repository_name stringlengths 7 58 | func_path_in_repository stringlengths 18 194 | func_name stringlengths 6 111 | whole_func_string stringlengths 80 3.8k | language stringclasses 1
value | func_code_string stringlengths 80 3.8k | func_code_tokens listlengths 20 697 | func_documentation_string stringlengths 61 2k | func_documentation_tokens listlengths 1 434 | split_name stringclasses 1
value | func_code_url stringlengths 111 308 |
|---|---|---|---|---|---|---|---|---|---|---|
box/box-android-sdk | box-content-sdk/src/main/java/com/box/androidsdk/content/BoxApiFile.java | BoxApiFile.getCopyRequest | public BoxRequestsFile.CopyFile getCopyRequest(String id, String parentId) {
BoxRequestsFile.CopyFile request = new BoxRequestsFile.CopyFile(id, parentId, getFileCopyUrl(id), mSession);
return request;
} | java | public BoxRequestsFile.CopyFile getCopyRequest(String id, String parentId) {
BoxRequestsFile.CopyFile request = new BoxRequestsFile.CopyFile(id, parentId, getFileCopyUrl(id), mSession);
return request;
} | [
"public",
"BoxRequestsFile",
".",
"CopyFile",
"getCopyRequest",
"(",
"String",
"id",
",",
"String",
"parentId",
")",
"{",
"BoxRequestsFile",
".",
"CopyFile",
"request",
"=",
"new",
"BoxRequestsFile",
".",
"CopyFile",
"(",
"id",
",",
"parentId",
",",
"getFileCopy... | Gets a request that copies a file
@param id id of the file to copy
@param parentId id of the parent folder to copy the file into
@return request to copy a file | [
"Gets",
"a",
"request",
"that",
"copies",
"a",
"file"
] | train | https://github.com/box/box-android-sdk/blob/a621ad5ddebf23067fec27529130d72718fc0e88/box-content-sdk/src/main/java/com/box/androidsdk/content/BoxApiFile.java#L209-L212 |
exoplatform/jcr | exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/dataflow/persistent/LinkedWorkspaceStorageCacheImpl.java | LinkedWorkspaceStorageCacheImpl.removeChildProperty | protected PropertyData removeChildProperty(final String parentIdentifier, final String childIdentifier)
{
final List<PropertyData> childProperties = propertiesCache.get(parentIdentifier);
if (childProperties != null)
{
synchronized (childProperties)
{ // [PN] 17.01.07
for (Iterator<PropertyData> i = childProperties.iterator(); i.hasNext();)
{
PropertyData cn = i.next();
if (cn.getIdentifier().equals(childIdentifier))
{
i.remove();
if (childProperties.size() <= 0)
{
propertiesCache.remove(parentIdentifier);
}
return cn;
}
}
}
}
return null;
} | java | protected PropertyData removeChildProperty(final String parentIdentifier, final String childIdentifier)
{
final List<PropertyData> childProperties = propertiesCache.get(parentIdentifier);
if (childProperties != null)
{
synchronized (childProperties)
{ // [PN] 17.01.07
for (Iterator<PropertyData> i = childProperties.iterator(); i.hasNext();)
{
PropertyData cn = i.next();
if (cn.getIdentifier().equals(childIdentifier))
{
i.remove();
if (childProperties.size() <= 0)
{
propertiesCache.remove(parentIdentifier);
}
return cn;
}
}
}
}
return null;
} | [
"protected",
"PropertyData",
"removeChildProperty",
"(",
"final",
"String",
"parentIdentifier",
",",
"final",
"String",
"childIdentifier",
")",
"{",
"final",
"List",
"<",
"PropertyData",
">",
"childProperties",
"=",
"propertiesCache",
".",
"get",
"(",
"parentIdentifie... | Remove property by id if parent properties are cached in CP.
@param parentIdentifier
- parent id
@param childIdentifier
- property id
@return removed property or null if property not cached or parent properties are not cached | [
"Remove",
"property",
"by",
"id",
"if",
"parent",
"properties",
"are",
"cached",
"in",
"CP",
"."
] | train | https://github.com/exoplatform/jcr/blob/3e7f9ee1b5683640d73a4316fb4b0ad5eac5b8a2/exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/dataflow/persistent/LinkedWorkspaceStorageCacheImpl.java#L2065-L2088 |
ansell/restlet-utils | src/main/java/com/github/ansell/restletutils/RestletUtilSesameRealm.java | RestletUtilSesameRealm.buildSparqlQueryToFindUser | protected String buildSparqlQueryToFindUser(final String userIdentifier, boolean findAllUsers)
{
if(!findAllUsers && userIdentifier == null)
{
throw new NullPointerException("User identifier was null");
}
final StringBuilder query = new StringBuilder();
query.append(" SELECT ?userIdentifier ?userUri ?userSecret ?userFirstName ?userLastName ?userEmail ");
query.append(" WHERE ");
query.append(" { ");
query.append(" ?userUri a ");
query.append(RenderUtils.getSPARQLQueryString(SesameRealmConstants.OAS_USER));
query.append(" . ");
query.append(" ?userUri ");
query.append(RenderUtils.getSPARQLQueryString(SesameRealmConstants.OAS_USERIDENTIFIER));
query.append(" ?userIdentifier . ");
query.append(" OPTIONAL{ ?userUri ");
query.append(RenderUtils.getSPARQLQueryString(SesameRealmConstants.OAS_USERSECRET));
query.append(" ?userSecret . } ");
query.append(" OPTIONAL{ ?userUri ");
query.append(RenderUtils.getSPARQLQueryString(SesameRealmConstants.OAS_USERFIRSTNAME));
query.append(" ?userFirstName . } ");
query.append(" OPTIONAL{ ?userUri ");
query.append(RenderUtils.getSPARQLQueryString(SesameRealmConstants.OAS_USERLASTNAME));
query.append(" ?userLastName . } ");
query.append(" OPTIONAL{ ?userUri ");
query.append(RenderUtils.getSPARQLQueryString(SesameRealmConstants.OAS_USEREMAIL));
query.append(" ?userEmail . } ");
if(!findAllUsers)
{
query.append(" FILTER(str(?userIdentifier) = \"" + RenderUtils.escape(userIdentifier) + "\") ");
}
query.append(" } ");
return query.toString();
} | java | protected String buildSparqlQueryToFindUser(final String userIdentifier, boolean findAllUsers)
{
if(!findAllUsers && userIdentifier == null)
{
throw new NullPointerException("User identifier was null");
}
final StringBuilder query = new StringBuilder();
query.append(" SELECT ?userIdentifier ?userUri ?userSecret ?userFirstName ?userLastName ?userEmail ");
query.append(" WHERE ");
query.append(" { ");
query.append(" ?userUri a ");
query.append(RenderUtils.getSPARQLQueryString(SesameRealmConstants.OAS_USER));
query.append(" . ");
query.append(" ?userUri ");
query.append(RenderUtils.getSPARQLQueryString(SesameRealmConstants.OAS_USERIDENTIFIER));
query.append(" ?userIdentifier . ");
query.append(" OPTIONAL{ ?userUri ");
query.append(RenderUtils.getSPARQLQueryString(SesameRealmConstants.OAS_USERSECRET));
query.append(" ?userSecret . } ");
query.append(" OPTIONAL{ ?userUri ");
query.append(RenderUtils.getSPARQLQueryString(SesameRealmConstants.OAS_USERFIRSTNAME));
query.append(" ?userFirstName . } ");
query.append(" OPTIONAL{ ?userUri ");
query.append(RenderUtils.getSPARQLQueryString(SesameRealmConstants.OAS_USERLASTNAME));
query.append(" ?userLastName . } ");
query.append(" OPTIONAL{ ?userUri ");
query.append(RenderUtils.getSPARQLQueryString(SesameRealmConstants.OAS_USEREMAIL));
query.append(" ?userEmail . } ");
if(!findAllUsers)
{
query.append(" FILTER(str(?userIdentifier) = \"" + RenderUtils.escape(userIdentifier) + "\") ");
}
query.append(" } ");
return query.toString();
} | [
"protected",
"String",
"buildSparqlQueryToFindUser",
"(",
"final",
"String",
"userIdentifier",
",",
"boolean",
"findAllUsers",
")",
"{",
"if",
"(",
"!",
"findAllUsers",
"&&",
"userIdentifier",
"==",
"null",
")",
"{",
"throw",
"new",
"NullPointerException",
"(",
"\... | Builds a SPARQL query to retrieve details of a RestletUtilUser. This method could be
overridden to search for other information regarding a user.
@param userIdentifier
The unique identifier of the User to search for.
@param findAllUsers True to find all users, and false to only find the specified user.
@return A String representation of the SPARQL Select query | [
"Builds",
"a",
"SPARQL",
"query",
"to",
"retrieve",
"details",
"of",
"a",
"RestletUtilUser",
".",
"This",
"method",
"could",
"be",
"overridden",
"to",
"search",
"for",
"other",
"information",
"regarding",
"a",
"user",
"."
] | train | https://github.com/ansell/restlet-utils/blob/6c39a3e91aa8295936af1dbfccd6ba27230c40a9/src/main/java/com/github/ansell/restletutils/RestletUtilSesameRealm.java#L630-L666 |
OpenLiberty/open-liberty | dev/com.ibm.ws.ejbcontainer.core/src/com/ibm/ejs/container/BeanO.java | BeanO.getEJBHome | @Override
public EJBHome getEJBHome()
{
try
{
EJSWrapper wrapper = home.getWrapper().getRemoteWrapper();
Object wrapperRef = container.getEJBRuntime().getRemoteReference(wrapper);
// The EJB spec does not require us to narrow to the actual home
// interface, but since we have to narrow to EJBHome anyway, we
// might as well narrow to the specific interface. It seems like it
// might be an oversight anyway given that the spec does require
// SessionContext.getEJBObject to narrow.
return (EJBHome) PortableRemoteObject.narrow(wrapperRef, home.beanMetaData.homeInterfaceClass);
} catch (IllegalStateException ise) { // d116480
// FFDC not logged for this spec required scenario
throw ise;
} catch (Exception ex) {
// p97440 - start of change
// This should never happen. Something is wrong.
// Need to throw a runtime exception since this is a
// Java EE architected interface that does not allow a checked
// exceptions to be thrown. So, throw ContainerEJBException.
FFDCFilter.processException(ex, CLASS_NAME + ".getEJBHome", "522", this);
ContainerEJBException ex2 = new ContainerEJBException("Failed to get the wrapper for home.", ex);
Tr.error(tc
, "CAUGHT_EXCEPTION_THROWING_NEW_EXCEPTION_CNTR0035E"
, new Object[] { ex, ex2.toString() }); // d194031
throw ex2;
// p97440 - end of change
}
} | java | @Override
public EJBHome getEJBHome()
{
try
{
EJSWrapper wrapper = home.getWrapper().getRemoteWrapper();
Object wrapperRef = container.getEJBRuntime().getRemoteReference(wrapper);
// The EJB spec does not require us to narrow to the actual home
// interface, but since we have to narrow to EJBHome anyway, we
// might as well narrow to the specific interface. It seems like it
// might be an oversight anyway given that the spec does require
// SessionContext.getEJBObject to narrow.
return (EJBHome) PortableRemoteObject.narrow(wrapperRef, home.beanMetaData.homeInterfaceClass);
} catch (IllegalStateException ise) { // d116480
// FFDC not logged for this spec required scenario
throw ise;
} catch (Exception ex) {
// p97440 - start of change
// This should never happen. Something is wrong.
// Need to throw a runtime exception since this is a
// Java EE architected interface that does not allow a checked
// exceptions to be thrown. So, throw ContainerEJBException.
FFDCFilter.processException(ex, CLASS_NAME + ".getEJBHome", "522", this);
ContainerEJBException ex2 = new ContainerEJBException("Failed to get the wrapper for home.", ex);
Tr.error(tc
, "CAUGHT_EXCEPTION_THROWING_NEW_EXCEPTION_CNTR0035E"
, new Object[] { ex, ex2.toString() }); // d194031
throw ex2;
// p97440 - end of change
}
} | [
"@",
"Override",
"public",
"EJBHome",
"getEJBHome",
"(",
")",
"{",
"try",
"{",
"EJSWrapper",
"wrapper",
"=",
"home",
".",
"getWrapper",
"(",
")",
".",
"getRemoteWrapper",
"(",
")",
";",
"Object",
"wrapperRef",
"=",
"container",
".",
"getEJBRuntime",
"(",
"... | Return <code>EJBHome</code> instance associated with
this <code>BeanO</code>. <p> | [
"Return",
"<code",
">",
"EJBHome<",
"/",
"code",
">",
"instance",
"associated",
"with",
"this",
"<code",
">",
"BeanO<",
"/",
"code",
">",
".",
"<p",
">"
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.ejbcontainer.core/src/com/ibm/ejs/container/BeanO.java#L724-L760 |
threerings/narya | core/src/main/java/com/threerings/admin/client/DSetEditor.java | DSetEditor.setAccessor | public void setAccessor (Accessor<E> accessor)
{
removeAll();
_accessor = accessor;
_table = new ObjectEditorTable(_entryClass, _editableFields, _accessor.getInterp(_interp),
_displayFields);
add(new JScrollPane(_table), BorderLayout.CENTER);
} | java | public void setAccessor (Accessor<E> accessor)
{
removeAll();
_accessor = accessor;
_table = new ObjectEditorTable(_entryClass, _editableFields, _accessor.getInterp(_interp),
_displayFields);
add(new JScrollPane(_table), BorderLayout.CENTER);
} | [
"public",
"void",
"setAccessor",
"(",
"Accessor",
"<",
"E",
">",
"accessor",
")",
"{",
"removeAll",
"(",
")",
";",
"_accessor",
"=",
"accessor",
";",
"_table",
"=",
"new",
"ObjectEditorTable",
"(",
"_entryClass",
",",
"_editableFields",
",",
"_accessor",
"."... | Sets the logic for how this editor interacts with its underlying data. | [
"Sets",
"the",
"logic",
"for",
"how",
"this",
"editor",
"interacts",
"with",
"its",
"underlying",
"data",
"."
] | train | https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/admin/client/DSetEditor.java#L147-L154 |
nohana/Amalgam | amalgam/src/main/java/com/amalgam/widget/ToastUtils.java | ToastUtils.showOnUiThread | public static void showOnUiThread(Context applicationContext, int stringResId, int duration, Handler handler) {
showOnUiThread(applicationContext, applicationContext.getString(stringResId), duration, handler);
} | java | public static void showOnUiThread(Context applicationContext, int stringResId, int duration, Handler handler) {
showOnUiThread(applicationContext, applicationContext.getString(stringResId), duration, handler);
} | [
"public",
"static",
"void",
"showOnUiThread",
"(",
"Context",
"applicationContext",
",",
"int",
"stringResId",
",",
"int",
"duration",
",",
"Handler",
"handler",
")",
"{",
"showOnUiThread",
"(",
"applicationContext",
",",
"applicationContext",
".",
"getString",
"(",... | Show toast on the UI thread.
@param applicationContext the application context.
@param stringResId to show.
@param duration the display duration.
@param handler the main handler. | [
"Show",
"toast",
"on",
"the",
"UI",
"thread",
"."
] | train | https://github.com/nohana/Amalgam/blob/57809ddbfe7897e979cf507982ce0b3aa5e0ed8a/amalgam/src/main/java/com/amalgam/widget/ToastUtils.java#L51-L53 |
liferay/com-liferay-commerce | commerce-product-service/src/main/java/com/liferay/commerce/product/service/persistence/impl/CPFriendlyURLEntryPersistenceImpl.java | CPFriendlyURLEntryPersistenceImpl.fetchByUUID_G | @Override
public CPFriendlyURLEntry fetchByUUID_G(String uuid, long groupId) {
return fetchByUUID_G(uuid, groupId, true);
} | java | @Override
public CPFriendlyURLEntry fetchByUUID_G(String uuid, long groupId) {
return fetchByUUID_G(uuid, groupId, true);
} | [
"@",
"Override",
"public",
"CPFriendlyURLEntry",
"fetchByUUID_G",
"(",
"String",
"uuid",
",",
"long",
"groupId",
")",
"{",
"return",
"fetchByUUID_G",
"(",
"uuid",
",",
"groupId",
",",
"true",
")",
";",
"}"
] | Returns the cp friendly url entry where uuid = ? and groupId = ? or returns <code>null</code> if it could not be found. Uses the finder cache.
@param uuid the uuid
@param groupId the group ID
@return the matching cp friendly url entry, or <code>null</code> if a matching cp friendly url entry could not be found | [
"Returns",
"the",
"cp",
"friendly",
"url",
"entry",
"where",
"uuid",
"=",
"?",
";",
"and",
"groupId",
"=",
"?",
";",
"or",
"returns",
"<code",
">",
"null<",
"/",
"code",
">",
"if",
"it",
"could",
"not",
"be",
"found",
".",
"Uses",
"the",
"finde... | train | https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-product-service/src/main/java/com/liferay/commerce/product/service/persistence/impl/CPFriendlyURLEntryPersistenceImpl.java#L706-L709 |
SonarSource/sonarqube | server/sonar-db-dao/src/main/java/org/sonar/db/DaoUtils.java | DaoUtils.buildLikeValue | public static String buildLikeValue(String value, WildcardPosition wildcardPosition) {
String escapedValue = escapePercentAndUnderscore(value);
String wildcard = "%";
switch (wildcardPosition) {
case BEFORE:
escapedValue = wildcard + escapedValue;
break;
case AFTER:
escapedValue += wildcard;
break;
case BEFORE_AND_AFTER:
escapedValue = wildcard + escapedValue + wildcard;
break;
default:
throw new UnsupportedOperationException("Unhandled WildcardPosition: " + wildcardPosition);
}
return escapedValue;
} | java | public static String buildLikeValue(String value, WildcardPosition wildcardPosition) {
String escapedValue = escapePercentAndUnderscore(value);
String wildcard = "%";
switch (wildcardPosition) {
case BEFORE:
escapedValue = wildcard + escapedValue;
break;
case AFTER:
escapedValue += wildcard;
break;
case BEFORE_AND_AFTER:
escapedValue = wildcard + escapedValue + wildcard;
break;
default:
throw new UnsupportedOperationException("Unhandled WildcardPosition: " + wildcardPosition);
}
return escapedValue;
} | [
"public",
"static",
"String",
"buildLikeValue",
"(",
"String",
"value",
",",
"WildcardPosition",
"wildcardPosition",
")",
"{",
"String",
"escapedValue",
"=",
"escapePercentAndUnderscore",
"(",
"value",
")",
";",
"String",
"wildcard",
"=",
"\"%\"",
";",
"switch",
"... | Returns an escaped value in parameter, with the desired wildcards. Suitable to be used in a like sql query<br />
Escapes the "/", "%" and "_" characters.<br/>
You <strong>must</strong> add "ESCAPE '/'" after your like query. It defines '/' as the escape character. | [
"Returns",
"an",
"escaped",
"value",
"in",
"parameter",
"with",
"the",
"desired",
"wildcards",
".",
"Suitable",
"to",
"be",
"used",
"in",
"a",
"like",
"sql",
"query<br",
"/",
">",
"Escapes",
"the",
"/",
"%",
"and",
"_",
"characters",
".",
"<br",
"/",
"... | train | https://github.com/SonarSource/sonarqube/blob/2fffa4c2f79ae3714844d7742796e82822b6a98a/server/sonar-db-dao/src/main/java/org/sonar/db/DaoUtils.java#L34-L52 |
orbisgis/h2gis | h2gis-functions/src/main/java/org/h2gis/functions/spatial/volume/GeometryExtrude.java | GeometryExtrude.extrudePolygonAsGeometry | public static GeometryCollection extrudePolygonAsGeometry(Polygon polygon, double height){
GeometryFactory factory = polygon.getFactory();
Geometry[] geometries = new Geometry[3];
//Extract floor
//We process the exterior ring
final LineString shell = getClockWise(polygon.getExteriorRing());
ArrayList<Polygon> walls = new ArrayList<Polygon>();
for (int i = 1; i < shell.getNumPoints(); i++) {
walls.add(extrudeEdge(shell.getCoordinateN(i - 1), shell.getCoordinateN(i), height, factory));
}
final int nbOfHoles = polygon.getNumInteriorRing();
final LinearRing[] holes = new LinearRing[nbOfHoles];
for (int i = 0; i < nbOfHoles; i++) {
final LineString hole = getCounterClockWise(polygon.getInteriorRingN(i));
for (int j = 1; j < hole.getNumPoints(); j++) {
walls.add(extrudeEdge(hole.getCoordinateN(j - 1),
hole.getCoordinateN(j), height, factory));
}
holes[i] = factory.createLinearRing(hole.getCoordinateSequence());
}
geometries[0]= factory.createPolygon(factory.createLinearRing(shell.getCoordinateSequence()), holes);
geometries[1]= factory.createMultiPolygon(walls.toArray(new Polygon[0]));
geometries[2]= extractRoof(polygon, height);
return polygon.getFactory().createGeometryCollection(geometries);
} | java | public static GeometryCollection extrudePolygonAsGeometry(Polygon polygon, double height){
GeometryFactory factory = polygon.getFactory();
Geometry[] geometries = new Geometry[3];
//Extract floor
//We process the exterior ring
final LineString shell = getClockWise(polygon.getExteriorRing());
ArrayList<Polygon> walls = new ArrayList<Polygon>();
for (int i = 1; i < shell.getNumPoints(); i++) {
walls.add(extrudeEdge(shell.getCoordinateN(i - 1), shell.getCoordinateN(i), height, factory));
}
final int nbOfHoles = polygon.getNumInteriorRing();
final LinearRing[] holes = new LinearRing[nbOfHoles];
for (int i = 0; i < nbOfHoles; i++) {
final LineString hole = getCounterClockWise(polygon.getInteriorRingN(i));
for (int j = 1; j < hole.getNumPoints(); j++) {
walls.add(extrudeEdge(hole.getCoordinateN(j - 1),
hole.getCoordinateN(j), height, factory));
}
holes[i] = factory.createLinearRing(hole.getCoordinateSequence());
}
geometries[0]= factory.createPolygon(factory.createLinearRing(shell.getCoordinateSequence()), holes);
geometries[1]= factory.createMultiPolygon(walls.toArray(new Polygon[0]));
geometries[2]= extractRoof(polygon, height);
return polygon.getFactory().createGeometryCollection(geometries);
} | [
"public",
"static",
"GeometryCollection",
"extrudePolygonAsGeometry",
"(",
"Polygon",
"polygon",
",",
"double",
"height",
")",
"{",
"GeometryFactory",
"factory",
"=",
"polygon",
".",
"getFactory",
"(",
")",
";",
"Geometry",
"[",
"]",
"geometries",
"=",
"new",
"G... | Extrude the polygon as a collection of geometries
The output geometryCollection contains the floor, the walls and the roof.
@param polygon
@param height
@return | [
"Extrude",
"the",
"polygon",
"as",
"a",
"collection",
"of",
"geometries",
"The",
"output",
"geometryCollection",
"contains",
"the",
"floor",
"the",
"walls",
"and",
"the",
"roof",
"."
] | train | https://github.com/orbisgis/h2gis/blob/9cd70b447e6469cecbc2fc64b16774b59491df3b/h2gis-functions/src/main/java/org/h2gis/functions/spatial/volume/GeometryExtrude.java#L49-L75 |
diffplug/durian | src/com/diffplug/common/base/FieldsAndGetters.java | FieldsAndGetters.fieldsAndGetters | public static Stream<Map.Entry<String, Object>> fieldsAndGetters(Object obj) {
return fieldsAndGetters(obj, Predicates.alwaysTrue());
} | java | public static Stream<Map.Entry<String, Object>> fieldsAndGetters(Object obj) {
return fieldsAndGetters(obj, Predicates.alwaysTrue());
} | [
"public",
"static",
"Stream",
"<",
"Map",
".",
"Entry",
"<",
"String",
",",
"Object",
">",
">",
"fieldsAndGetters",
"(",
"Object",
"obj",
")",
"{",
"return",
"fieldsAndGetters",
"(",
"obj",
",",
"Predicates",
".",
"alwaysTrue",
"(",
")",
")",
";",
"}"
] | Returns a {@code Stream} of all public fields and getter methods and their values for the given object.
@see #getters(Object, Predicate) | [
"Returns",
"a",
"{",
"@code",
"Stream",
"}",
"of",
"all",
"public",
"fields",
"and",
"getter",
"methods",
"and",
"their",
"values",
"for",
"the",
"given",
"object",
"."
] | train | https://github.com/diffplug/durian/blob/10631a3480e5491eb6eb6ee06e752d8596914232/src/com/diffplug/common/base/FieldsAndGetters.java#L132-L134 |
ravendb/ravendb-jvm-client | src/main/java/net/ravendb/client/documents/conventions/DocumentConventions.java | DocumentConventions.registerIdConvention | @SuppressWarnings("unchecked")
public <TEntity> DocumentConventions registerIdConvention(Class<TEntity> clazz, BiFunction<String, TEntity, String> function) {
assertNotFrozen();
_listOfRegisteredIdConventions.stream()
.filter(x -> x.first.equals(clazz))
.findFirst()
.ifPresent(x -> _listOfRegisteredIdConventions.remove(x));
int index;
for (index = 0; index < _listOfRegisteredIdConventions.size(); index++) {
Tuple<Class, BiFunction<String, Object, String>> entry = _listOfRegisteredIdConventions.get(index);
if (entry.first.isAssignableFrom(clazz)) {
break;
}
}
_listOfRegisteredIdConventions.add(index, Tuple.create(clazz, (BiFunction<String, Object, String>) function));
return this;
} | java | @SuppressWarnings("unchecked")
public <TEntity> DocumentConventions registerIdConvention(Class<TEntity> clazz, BiFunction<String, TEntity, String> function) {
assertNotFrozen();
_listOfRegisteredIdConventions.stream()
.filter(x -> x.first.equals(clazz))
.findFirst()
.ifPresent(x -> _listOfRegisteredIdConventions.remove(x));
int index;
for (index = 0; index < _listOfRegisteredIdConventions.size(); index++) {
Tuple<Class, BiFunction<String, Object, String>> entry = _listOfRegisteredIdConventions.get(index);
if (entry.first.isAssignableFrom(clazz)) {
break;
}
}
_listOfRegisteredIdConventions.add(index, Tuple.create(clazz, (BiFunction<String, Object, String>) function));
return this;
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"public",
"<",
"TEntity",
">",
"DocumentConventions",
"registerIdConvention",
"(",
"Class",
"<",
"TEntity",
">",
"clazz",
",",
"BiFunction",
"<",
"String",
",",
"TEntity",
",",
"String",
">",
"function",
")",
... | Register an id convention for a single type (and all of its derived types.
Note that you can still fall back to the DocumentIdGenerator if you want.
@param <TEntity> Entity class
@param clazz Class
@param function Function to use
@return document conventions | [
"Register",
"an",
"id",
"convention",
"for",
"a",
"single",
"type",
"(",
"and",
"all",
"of",
"its",
"derived",
"types",
".",
"Note",
"that",
"you",
"can",
"still",
"fall",
"back",
"to",
"the",
"DocumentIdGenerator",
"if",
"you",
"want",
"."
] | train | https://github.com/ravendb/ravendb-jvm-client/blob/5a45727de507b541d1571e79ddd97c7d88bee787/src/main/java/net/ravendb/client/documents/conventions/DocumentConventions.java#L375-L395 |
Clivern/Racter | src/main/java/com/clivern/racter/senders/templates/ButtonTemplate.java | ButtonTemplate.setButton | public void setButton(String type, String title, String url, String payload)
{
HashMap<String, String> button = new HashMap<String, String>();
button.put("type", type);
button.put("title", title);
button.put("url", url);
button.put("payload", payload);
this.buttons.add(button);
} | java | public void setButton(String type, String title, String url, String payload)
{
HashMap<String, String> button = new HashMap<String, String>();
button.put("type", type);
button.put("title", title);
button.put("url", url);
button.put("payload", payload);
this.buttons.add(button);
} | [
"public",
"void",
"setButton",
"(",
"String",
"type",
",",
"String",
"title",
",",
"String",
"url",
",",
"String",
"payload",
")",
"{",
"HashMap",
"<",
"String",
",",
"String",
">",
"button",
"=",
"new",
"HashMap",
"<",
"String",
",",
"String",
">",
"(... | Set Button
@param type the button type
@param title the button title
@param url the button url
@param payload the button payload | [
"Set",
"Button"
] | train | https://github.com/Clivern/Racter/blob/bbde02f0c2a8a80653ad6b1607376d8408acd71c/src/main/java/com/clivern/racter/senders/templates/ButtonTemplate.java#L64-L72 |
salesforce/Argus | ArgusCore/src/main/java/com/salesforce/dva/argus/entity/PrincipalUser.java | PrincipalUser.createAdminUser | private static PrincipalUser createAdminUser() {
PrincipalUser result = new PrincipalUser("admin", "argus-admin@salesforce.com");
result.id = BigInteger.ONE;
result.setPrivileged(true);
return result;
} | java | private static PrincipalUser createAdminUser() {
PrincipalUser result = new PrincipalUser("admin", "argus-admin@salesforce.com");
result.id = BigInteger.ONE;
result.setPrivileged(true);
return result;
} | [
"private",
"static",
"PrincipalUser",
"createAdminUser",
"(",
")",
"{",
"PrincipalUser",
"result",
"=",
"new",
"PrincipalUser",
"(",
"\"admin\"",
",",
"\"argus-admin@salesforce.com\"",
")",
";",
"result",
".",
"id",
"=",
"BigInteger",
".",
"ONE",
";",
"result",
... | /* Method provided to be called using reflection to discretely create the admin user if needed. | [
"/",
"*",
"Method",
"provided",
"to",
"be",
"called",
"using",
"reflection",
"to",
"discretely",
"create",
"the",
"admin",
"user",
"if",
"needed",
"."
] | train | https://github.com/salesforce/Argus/blob/121b59a268da264316cded6a3e9271366a23cd86/ArgusCore/src/main/java/com/salesforce/dva/argus/entity/PrincipalUser.java#L272-L278 |
jasminb/jsonapi-converter | src/main/java/com/github/jasminb/jsonapi/ResourceConverter.java | ResourceConverter.writeDocument | public byte [] writeDocument(JSONAPIDocument<?> document, SerializationSettings settings)
throws DocumentSerializationException {
try {
resourceCache.init();
Map<String, ObjectNode> includedDataMap = new HashMap<>();
ObjectNode result = objectMapper.createObjectNode();
// Serialize data if present
if (document.get() != null) {
ObjectNode dataNode = getDataNode(document.get(), includedDataMap, settings);
result.set(DATA, dataNode);
// It is possible that relationships point back to top-level resource, in this case remove it from
// included section since it is already present (as a top level resource)
String identifier = String.valueOf(getIdValue(document.get()))
.concat(configuration.getTypeName(document.get().getClass()));
includedDataMap.remove(identifier);
result = addIncludedSection(result, includedDataMap);
}
// Serialize errors if present
if (document.getErrors() != null) {
ArrayNode errorsNode = objectMapper.createArrayNode();
for (Error error : document.getErrors()) {
errorsNode.add(objectMapper.valueToTree(error));
}
result.set(ERRORS, errorsNode);
}
// Serialize global links and meta
serializeMeta(document, result, settings);
serializeLinks(document, result, settings);
return objectMapper.writeValueAsBytes(result);
} catch (Exception e) {
throw new DocumentSerializationException(e);
} finally {
resourceCache.clear();
}
} | java | public byte [] writeDocument(JSONAPIDocument<?> document, SerializationSettings settings)
throws DocumentSerializationException {
try {
resourceCache.init();
Map<String, ObjectNode> includedDataMap = new HashMap<>();
ObjectNode result = objectMapper.createObjectNode();
// Serialize data if present
if (document.get() != null) {
ObjectNode dataNode = getDataNode(document.get(), includedDataMap, settings);
result.set(DATA, dataNode);
// It is possible that relationships point back to top-level resource, in this case remove it from
// included section since it is already present (as a top level resource)
String identifier = String.valueOf(getIdValue(document.get()))
.concat(configuration.getTypeName(document.get().getClass()));
includedDataMap.remove(identifier);
result = addIncludedSection(result, includedDataMap);
}
// Serialize errors if present
if (document.getErrors() != null) {
ArrayNode errorsNode = objectMapper.createArrayNode();
for (Error error : document.getErrors()) {
errorsNode.add(objectMapper.valueToTree(error));
}
result.set(ERRORS, errorsNode);
}
// Serialize global links and meta
serializeMeta(document, result, settings);
serializeLinks(document, result, settings);
return objectMapper.writeValueAsBytes(result);
} catch (Exception e) {
throw new DocumentSerializationException(e);
} finally {
resourceCache.clear();
}
} | [
"public",
"byte",
"[",
"]",
"writeDocument",
"(",
"JSONAPIDocument",
"<",
"?",
">",
"document",
",",
"SerializationSettings",
"settings",
")",
"throws",
"DocumentSerializationException",
"{",
"try",
"{",
"resourceCache",
".",
"init",
"(",
")",
";",
"Map",
"<",
... | Serializes provided {@link JSONAPIDocument} into JSON API Spec compatible byte representation.
@param document {@link JSONAPIDocument} document to serialize
@param settings {@link SerializationSettings} settings that override global serialization settings
@return serialized content in bytes
@throws DocumentSerializationException thrown in case serialization fails | [
"Serializes",
"provided",
"{",
"@link",
"JSONAPIDocument",
"}",
"into",
"JSON",
"API",
"Spec",
"compatible",
"byte",
"representation",
"."
] | train | https://github.com/jasminb/jsonapi-converter/blob/73b41c3b9274e70e62b3425071ca8afdc7bddaf6/src/main/java/com/github/jasminb/jsonapi/ResourceConverter.java#L690-L731 |
Carbonado/Carbonado | src/main/java/com/amazon/carbonado/raw/GenericEncodingStrategy.java | GenericEncodingStrategy.buildSerialEncoding | public LocalVariable buildSerialEncoding(CodeAssembler assembler,
StorableProperty<S>[] properties)
throws SupportException
{
properties = ensureAllProperties(properties);
return buildEncoding
(Mode.SERIAL, assembler, properties, null, null, null, false, -1, null, null);
} | java | public LocalVariable buildSerialEncoding(CodeAssembler assembler,
StorableProperty<S>[] properties)
throws SupportException
{
properties = ensureAllProperties(properties);
return buildEncoding
(Mode.SERIAL, assembler, properties, null, null, null, false, -1, null, null);
} | [
"public",
"LocalVariable",
"buildSerialEncoding",
"(",
"CodeAssembler",
"assembler",
",",
"StorableProperty",
"<",
"S",
">",
"[",
"]",
"properties",
")",
"throws",
"SupportException",
"{",
"properties",
"=",
"ensureAllProperties",
"(",
"properties",
")",
";",
"retur... | Generates bytecode instructions to encode properties and their
states. This encoding is suitable for short-term serialization only.
@param assembler code assembler to receive bytecode instructions
@param properties specific properties to decode, defaults to all
properties if null
@return local variable referencing a byte array with encoded data
@throws SupportException if any property type is not supported
@since 1.2 | [
"Generates",
"bytecode",
"instructions",
"to",
"encode",
"properties",
"and",
"their",
"states",
".",
"This",
"encoding",
"is",
"suitable",
"for",
"short",
"-",
"term",
"serialization",
"only",
"."
] | train | https://github.com/Carbonado/Carbonado/blob/eee29b365a61c8f03e1a1dc6bed0692e6b04b1db/src/main/java/com/amazon/carbonado/raw/GenericEncodingStrategy.java#L324-L331 |
DataSketches/sketches-core | src/main/java/com/yahoo/sketches/quantiles/Util.java | Util.lowestZeroBitStartingAt | static int lowestZeroBitStartingAt(final long bits, final int startingBit) {
int pos = startingBit & 0X3F;
long myBits = bits >>> pos;
while ((myBits & 1L) != 0) {
myBits = myBits >>> 1;
pos++;
}
return pos;
} | java | static int lowestZeroBitStartingAt(final long bits, final int startingBit) {
int pos = startingBit & 0X3F;
long myBits = bits >>> pos;
while ((myBits & 1L) != 0) {
myBits = myBits >>> 1;
pos++;
}
return pos;
} | [
"static",
"int",
"lowestZeroBitStartingAt",
"(",
"final",
"long",
"bits",
",",
"final",
"int",
"startingBit",
")",
"{",
"int",
"pos",
"=",
"startingBit",
"&",
"0X3F",
";",
"long",
"myBits",
"=",
"bits",
">>>",
"pos",
";",
"while",
"(",
"(",
"myBits",
"&"... | Returns the zero-based bit position of the lowest zero bit of <i>bits</i> starting at
<i>startingBit</i>. If input is all ones, this returns 64.
@param bits the input bits as a long
@param startingBit the zero-based starting bit position. Only the low 6 bits are used.
@return the zero-based bit position of the lowest zero bit starting at <i>startingBit</i>. | [
"Returns",
"the",
"zero",
"-",
"based",
"bit",
"position",
"of",
"the",
"lowest",
"zero",
"bit",
"of",
"<i",
">",
"bits<",
"/",
"i",
">",
"starting",
"at",
"<i",
">",
"startingBit<",
"/",
"i",
">",
".",
"If",
"input",
"is",
"all",
"ones",
"this",
"... | train | https://github.com/DataSketches/sketches-core/blob/900c8c9668a1e2f1d54d453e956caad54702e540/src/main/java/com/yahoo/sketches/quantiles/Util.java#L425-L434 |
liferay/com-liferay-commerce | commerce-tax-service/src/main/java/com/liferay/commerce/tax/service/persistence/impl/CommerceTaxMethodPersistenceImpl.java | CommerceTaxMethodPersistenceImpl.findAll | @Override
public List<CommerceTaxMethod> findAll() {
return findAll(QueryUtil.ALL_POS, QueryUtil.ALL_POS, null);
} | java | @Override
public List<CommerceTaxMethod> findAll() {
return findAll(QueryUtil.ALL_POS, QueryUtil.ALL_POS, null);
} | [
"@",
"Override",
"public",
"List",
"<",
"CommerceTaxMethod",
">",
"findAll",
"(",
")",
"{",
"return",
"findAll",
"(",
"QueryUtil",
".",
"ALL_POS",
",",
"QueryUtil",
".",
"ALL_POS",
",",
"null",
")",
";",
"}"
] | Returns all the commerce tax methods.
@return the commerce tax methods | [
"Returns",
"all",
"the",
"commerce",
"tax",
"methods",
"."
] | train | https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-tax-service/src/main/java/com/liferay/commerce/tax/service/persistence/impl/CommerceTaxMethodPersistenceImpl.java#L1989-L1992 |
jayantk/jklol | src/com/jayantkrish/jklol/util/AllAssignmentIterator.java | AllAssignmentIterator.initializeValueIterator | private static Iterator<int[]> initializeValueIterator(VariableNumMap vars) {
int[] dimensionSizes = new int[vars.size()];
List<DiscreteVariable> discreteVars = vars.getDiscreteVariables();
for (int i = 0; i < discreteVars.size(); i++) {
dimensionSizes[i] = discreteVars.get(i).numValues();
}
return new IntegerArrayIterator(dimensionSizes, new int[0]);
} | java | private static Iterator<int[]> initializeValueIterator(VariableNumMap vars) {
int[] dimensionSizes = new int[vars.size()];
List<DiscreteVariable> discreteVars = vars.getDiscreteVariables();
for (int i = 0; i < discreteVars.size(); i++) {
dimensionSizes[i] = discreteVars.get(i).numValues();
}
return new IntegerArrayIterator(dimensionSizes, new int[0]);
} | [
"private",
"static",
"Iterator",
"<",
"int",
"[",
"]",
">",
"initializeValueIterator",
"(",
"VariableNumMap",
"vars",
")",
"{",
"int",
"[",
"]",
"dimensionSizes",
"=",
"new",
"int",
"[",
"vars",
".",
"size",
"(",
")",
"]",
";",
"List",
"<",
"DiscreteVari... | /*
Initializes the variable values controlling the iteration position. | [
"/",
"*",
"Initializes",
"the",
"variable",
"values",
"controlling",
"the",
"iteration",
"position",
"."
] | train | https://github.com/jayantk/jklol/blob/d27532ca83e212d51066cf28f52621acc3fd44cc/src/com/jayantkrish/jklol/util/AllAssignmentIterator.java#L32-L40 |
ngageoint/geopackage-core-java | src/main/java/mil/nga/geopackage/tiles/TileBoundingBoxUtils.java | TileBoundingBoxUtils.getBoundingBox | public static BoundingBox getBoundingBox(BoundingBox totalBox,
TileMatrix tileMatrix, TileGrid tileGrid) {
return getBoundingBox(totalBox, tileMatrix.getMatrixWidth(),
tileMatrix.getMatrixHeight(), tileGrid);
} | java | public static BoundingBox getBoundingBox(BoundingBox totalBox,
TileMatrix tileMatrix, TileGrid tileGrid) {
return getBoundingBox(totalBox, tileMatrix.getMatrixWidth(),
tileMatrix.getMatrixHeight(), tileGrid);
} | [
"public",
"static",
"BoundingBox",
"getBoundingBox",
"(",
"BoundingBox",
"totalBox",
",",
"TileMatrix",
"tileMatrix",
",",
"TileGrid",
"tileGrid",
")",
"{",
"return",
"getBoundingBox",
"(",
"totalBox",
",",
"tileMatrix",
".",
"getMatrixWidth",
"(",
")",
",",
"tile... | Get the bounding box of the tile grid in the tile matrix using the total
bounding box with constant units
@param totalBox
total bounding box
@param tileMatrix
tile matrix
@param tileGrid
tile grid
@return bounding box
@since 1.2.0 | [
"Get",
"the",
"bounding",
"box",
"of",
"the",
"tile",
"grid",
"in",
"the",
"tile",
"matrix",
"using",
"the",
"total",
"bounding",
"box",
"with",
"constant",
"units"
] | train | https://github.com/ngageoint/geopackage-core-java/blob/6431c3b041a45b7f3802904ea4156b4082a72daa/src/main/java/mil/nga/geopackage/tiles/TileBoundingBoxUtils.java#L960-L964 |
kohsuke/com4j | runtime/src/main/java/com4j/COM4J.java | COM4J.getActiveObject | public static <T extends Com4jObject> T getActiveObject(Class<T> primaryInterface, GUID clsid ) {
return new GetActiveObjectTask<T>(clsid,primaryInterface).execute();
} | java | public static <T extends Com4jObject> T getActiveObject(Class<T> primaryInterface, GUID clsid ) {
return new GetActiveObjectTask<T>(clsid,primaryInterface).execute();
} | [
"public",
"static",
"<",
"T",
"extends",
"Com4jObject",
">",
"T",
"getActiveObject",
"(",
"Class",
"<",
"T",
">",
"primaryInterface",
",",
"GUID",
"clsid",
")",
"{",
"return",
"new",
"GetActiveObjectTask",
"<",
"T",
">",
"(",
"clsid",
",",
"primaryInterface"... | Gets an already running object from the running object table.
@param <T> the type of the return value and the type parameter of the class object of primaryInterface
@param primaryInterface The returned COM object is returned as this interface.
Must be non-null. Passing in {@link Com4jObject} allows
the caller to create a new instance without knowing
its primary interface.
@param clsid The CLSID of the object to be retrieved.
@return the retrieved object
@throws ComException if the retrieval fails.
@see <a href="http://msdn2.microsoft.com/en-us/library/ms221467.aspx">MSDN documentation</a> | [
"Gets",
"an",
"already",
"running",
"object",
"from",
"the",
"running",
"object",
"table",
"."
] | train | https://github.com/kohsuke/com4j/blob/1e690b805fb0e4e9ef61560e20a56335aecb0b24/runtime/src/main/java/com4j/COM4J.java#L162-L164 |
azkaban/azkaban | az-hadoop-jobtype-plugin/src/main/java/azkaban/jobtype/HadoopConfigurationInjector.java | HadoopConfigurationInjector.prepareResourcesToInject | public static void prepareResourcesToInject(Props props, String workingDir) {
try {
Configuration conf = new Configuration(false);
// First, inject a series of Azkaban links. These are equivalent to
// CommonJobProperties.[EXECUTION,WORKFLOW,JOB,JOBEXEC,ATTEMPT]_LINK
addHadoopProperties(props);
// Next, automatically inject any properties that begin with the
// designated injection prefix.
Map<String, String> confProperties = props.getMapByPrefix(INJECT_PREFIX);
for (Map.Entry<String, String> entry : confProperties.entrySet()) {
String confKey = entry.getKey().replace(INJECT_PREFIX, "");
String confVal = entry.getValue();
if (confVal != null) {
conf.set(confKey, confVal);
}
}
// Now write out the configuration file to inject.
File file = getConfFile(props, workingDir, INJECT_FILE);
OutputStream xmlOut = new FileOutputStream(file);
conf.writeXml(xmlOut);
xmlOut.close();
} catch (Throwable e) {
_logger.error("Encountered error while preparing the Hadoop configuration resource file", e);
}
} | java | public static void prepareResourcesToInject(Props props, String workingDir) {
try {
Configuration conf = new Configuration(false);
// First, inject a series of Azkaban links. These are equivalent to
// CommonJobProperties.[EXECUTION,WORKFLOW,JOB,JOBEXEC,ATTEMPT]_LINK
addHadoopProperties(props);
// Next, automatically inject any properties that begin with the
// designated injection prefix.
Map<String, String> confProperties = props.getMapByPrefix(INJECT_PREFIX);
for (Map.Entry<String, String> entry : confProperties.entrySet()) {
String confKey = entry.getKey().replace(INJECT_PREFIX, "");
String confVal = entry.getValue();
if (confVal != null) {
conf.set(confKey, confVal);
}
}
// Now write out the configuration file to inject.
File file = getConfFile(props, workingDir, INJECT_FILE);
OutputStream xmlOut = new FileOutputStream(file);
conf.writeXml(xmlOut);
xmlOut.close();
} catch (Throwable e) {
_logger.error("Encountered error while preparing the Hadoop configuration resource file", e);
}
} | [
"public",
"static",
"void",
"prepareResourcesToInject",
"(",
"Props",
"props",
",",
"String",
"workingDir",
")",
"{",
"try",
"{",
"Configuration",
"conf",
"=",
"new",
"Configuration",
"(",
"false",
")",
";",
"// First, inject a series of Azkaban links. These are equival... | Writes out the XML configuration file that will be injected by the client
as a configuration resource.
<p>
This file will include a series of links injected by Azkaban as well as
any job properties that begin with the designated injection prefix.
@param props The Azkaban properties
@param workingDir The Azkaban job working directory | [
"Writes",
"out",
"the",
"XML",
"configuration",
"file",
"that",
"will",
"be",
"injected",
"by",
"the",
"client",
"as",
"a",
"configuration",
"resource",
".",
"<p",
">",
"This",
"file",
"will",
"include",
"a",
"series",
"of",
"links",
"injected",
"by",
"Azk... | train | https://github.com/azkaban/azkaban/blob/d258ea7d6e66807c6eff79c5325d6d3443618dff/az-hadoop-jobtype-plugin/src/main/java/azkaban/jobtype/HadoopConfigurationInjector.java#L82-L110 |
kuali/ojb-1.0.4 | src/java/org/apache/ojb/broker/core/PersistenceBrokerImpl.java | PersistenceBrokerImpl.storeCollections | private void storeCollections(Object obj, ClassDescriptor cld, boolean insert) throws PersistenceBrokerException
{
// get all members of obj that are collections and store all their elements
Collection listCods = cld.getCollectionDescriptors();
// return if nothing to do
if (listCods.size() == 0)
{
return;
}
Iterator i = listCods.iterator();
while (i.hasNext())
{
CollectionDescriptor cod = (CollectionDescriptor) i.next();
// if CASCADE_NONE was set, do nothing with referenced objects
if (cod.getCascadingStore() != ObjectReferenceDescriptor.CASCADE_NONE)
{
Object referencedObjects = cod.getPersistentField().get(obj);
if (cod.isMtoNRelation())
{
storeAndLinkMtoN(false, obj, cod, referencedObjects, insert);
}
else
{
storeAndLinkOneToMany(false, obj, cod, referencedObjects, insert);
}
// BRJ: only when auto-update = object (CASCADE_OBJECT)
//
if ((cod.getCascadingStore() == ObjectReferenceDescriptor.CASCADE_OBJECT)
&& (referencedObjects instanceof ManageableCollection))
{
((ManageableCollection) referencedObjects).afterStore(this);
}
}
}
} | java | private void storeCollections(Object obj, ClassDescriptor cld, boolean insert) throws PersistenceBrokerException
{
// get all members of obj that are collections and store all their elements
Collection listCods = cld.getCollectionDescriptors();
// return if nothing to do
if (listCods.size() == 0)
{
return;
}
Iterator i = listCods.iterator();
while (i.hasNext())
{
CollectionDescriptor cod = (CollectionDescriptor) i.next();
// if CASCADE_NONE was set, do nothing with referenced objects
if (cod.getCascadingStore() != ObjectReferenceDescriptor.CASCADE_NONE)
{
Object referencedObjects = cod.getPersistentField().get(obj);
if (cod.isMtoNRelation())
{
storeAndLinkMtoN(false, obj, cod, referencedObjects, insert);
}
else
{
storeAndLinkOneToMany(false, obj, cod, referencedObjects, insert);
}
// BRJ: only when auto-update = object (CASCADE_OBJECT)
//
if ((cod.getCascadingStore() == ObjectReferenceDescriptor.CASCADE_OBJECT)
&& (referencedObjects instanceof ManageableCollection))
{
((ManageableCollection) referencedObjects).afterStore(this);
}
}
}
} | [
"private",
"void",
"storeCollections",
"(",
"Object",
"obj",
",",
"ClassDescriptor",
"cld",
",",
"boolean",
"insert",
")",
"throws",
"PersistenceBrokerException",
"{",
"// get all members of obj that are collections and store all their elements",
"Collection",
"listCods",
"=",
... | Store/Link collections of objects poiting to <b>obj</b>.
More info please see comments in source.
@param obj real object which we will store collections for
@throws PersistenceBrokerException if some goes wrong - please see the error message for details | [
"Store",
"/",
"Link",
"collections",
"of",
"objects",
"poiting",
"to",
"<b",
">",
"obj<",
"/",
"b",
">",
".",
"More",
"info",
"please",
"see",
"comments",
"in",
"source",
"."
] | train | https://github.com/kuali/ojb-1.0.4/blob/9a544372f67ce965f662cdc71609dd03683c8f04/src/java/org/apache/ojb/broker/core/PersistenceBrokerImpl.java#L1028-L1064 |
ManfredTremmel/gwt-bean-validators | gwt-bean-validators/src/main/super/de/knightsoftnet/validators/supersource/java/io/IOUtils.java | IOUtils.checkOffsetAndCount | private static void checkOffsetAndCount(final int length, final int offset, final int count) {
if (offset < 0 || count < 0 || offset + count > length) {
throw new IndexOutOfBoundsException();
}
} | java | private static void checkOffsetAndCount(final int length, final int offset, final int count) {
if (offset < 0 || count < 0 || offset + count > length) {
throw new IndexOutOfBoundsException();
}
} | [
"private",
"static",
"void",
"checkOffsetAndCount",
"(",
"final",
"int",
"length",
",",
"final",
"int",
"offset",
",",
"final",
"int",
"count",
")",
"{",
"if",
"(",
"offset",
"<",
"0",
"||",
"count",
"<",
"0",
"||",
"offset",
"+",
"count",
">",
"length... | Validates the offset and the byte count for the given array length.
@param length Length of the array to be checked.
@param offset Starting offset in the array.
@param count Total number of elements to be accessed.
@throws IndexOutOfBoundsException if {@code offset} is negative, {@code count} is negative or
their sum exceeds the given {@code length}. | [
"Validates",
"the",
"offset",
"and",
"the",
"byte",
"count",
"for",
"the",
"given",
"array",
"length",
"."
] | train | https://github.com/ManfredTremmel/gwt-bean-validators/blob/cff7a2c3d68c2d17bf9d3cc57c79cc16fa8b4d5c/gwt-bean-validators/src/main/super/de/knightsoftnet/validators/supersource/java/io/IOUtils.java#L76-L80 |
carewebframework/carewebframework-core | org.carewebframework.mvn-parent/org.carewebframework.mvn.plugin-parent/org.carewebframework.mvn.plugin.helpconverter/src/main/java/org/carewebframework/maven/plugin/help/chm/BinaryTransform.java | BinaryTransform.getString | protected String getString(byte[] data, int offset) {
if (offset < 0) {
return "";
}
int i = offset;
while (data[i++] != 0x00) {
;
}
return getString(data, offset, i - offset - 1);
} | java | protected String getString(byte[] data, int offset) {
if (offset < 0) {
return "";
}
int i = offset;
while (data[i++] != 0x00) {
;
}
return getString(data, offset, i - offset - 1);
} | [
"protected",
"String",
"getString",
"(",
"byte",
"[",
"]",
"data",
",",
"int",
"offset",
")",
"{",
"if",
"(",
"offset",
"<",
"0",
")",
"{",
"return",
"\"\"",
";",
"}",
"int",
"i",
"=",
"offset",
";",
"while",
"(",
"data",
"[",
"i",
"++",
"]",
"... | Returns a string value from a zero-terminated byte array at the specified offset.
@param data The source data.
@param offset The byte offset.
@return A string. | [
"Returns",
"a",
"string",
"value",
"from",
"a",
"zero",
"-",
"terminated",
"byte",
"array",
"at",
"the",
"specified",
"offset",
"."
] | train | https://github.com/carewebframework/carewebframework-core/blob/fa3252d4f7541dbe151b92c3d4f6f91433cd1673/org.carewebframework.mvn-parent/org.carewebframework.mvn.plugin-parent/org.carewebframework.mvn.plugin.helpconverter/src/main/java/org/carewebframework/maven/plugin/help/chm/BinaryTransform.java#L119-L129 |
alkacon/opencms-core | src/org/opencms/db/CmsDriverManager.java | CmsDriverManager.readResource | public I_CmsHistoryResource readResource(CmsDbContext dbc, CmsResource resource, int version) throws CmsException {
Iterator<I_CmsHistoryResource> itVersions = getHistoryDriver(dbc).readAllAvailableVersions(
dbc,
resource.getStructureId()).iterator();
while (itVersions.hasNext()) {
I_CmsHistoryResource histRes = itVersions.next();
if (histRes.getVersion() == version) {
return histRes;
}
}
throw new CmsVfsResourceNotFoundException(
org.opencms.db.generic.Messages.get().container(
org.opencms.db.generic.Messages.ERR_HISTORY_FILE_NOT_FOUND_1,
resource.getStructureId()));
} | java | public I_CmsHistoryResource readResource(CmsDbContext dbc, CmsResource resource, int version) throws CmsException {
Iterator<I_CmsHistoryResource> itVersions = getHistoryDriver(dbc).readAllAvailableVersions(
dbc,
resource.getStructureId()).iterator();
while (itVersions.hasNext()) {
I_CmsHistoryResource histRes = itVersions.next();
if (histRes.getVersion() == version) {
return histRes;
}
}
throw new CmsVfsResourceNotFoundException(
org.opencms.db.generic.Messages.get().container(
org.opencms.db.generic.Messages.ERR_HISTORY_FILE_NOT_FOUND_1,
resource.getStructureId()));
} | [
"public",
"I_CmsHistoryResource",
"readResource",
"(",
"CmsDbContext",
"dbc",
",",
"CmsResource",
"resource",
",",
"int",
"version",
")",
"throws",
"CmsException",
"{",
"Iterator",
"<",
"I_CmsHistoryResource",
">",
"itVersions",
"=",
"getHistoryDriver",
"(",
"dbc",
... | Reads an historical resource entry for the given resource and with the given version number.<p>
@param dbc the current db context
@param resource the resource to be read
@param version the version number to retrieve
@return the resource that was read
@throws CmsException if the resource could not be read for any reason
@see CmsObject#restoreResourceVersion(CmsUUID, int)
@see CmsObject#readResource(CmsUUID, int) | [
"Reads",
"an",
"historical",
"resource",
"entry",
"for",
"the",
"given",
"resource",
"and",
"with",
"the",
"given",
"version",
"number",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/db/CmsDriverManager.java#L7614-L7629 |
apache/flink | flink-connectors/flink-connector-kafka-base/src/main/java/org/apache/flink/streaming/connectors/kafka/FlinkKafkaConsumerBase.java | FlinkKafkaConsumerBase.adjustAutoCommitConfig | static void adjustAutoCommitConfig(Properties properties, OffsetCommitMode offsetCommitMode) {
if (offsetCommitMode == OffsetCommitMode.ON_CHECKPOINTS || offsetCommitMode == OffsetCommitMode.DISABLED) {
properties.setProperty(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "false");
}
} | java | static void adjustAutoCommitConfig(Properties properties, OffsetCommitMode offsetCommitMode) {
if (offsetCommitMode == OffsetCommitMode.ON_CHECKPOINTS || offsetCommitMode == OffsetCommitMode.DISABLED) {
properties.setProperty(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "false");
}
} | [
"static",
"void",
"adjustAutoCommitConfig",
"(",
"Properties",
"properties",
",",
"OffsetCommitMode",
"offsetCommitMode",
")",
"{",
"if",
"(",
"offsetCommitMode",
"==",
"OffsetCommitMode",
".",
"ON_CHECKPOINTS",
"||",
"offsetCommitMode",
"==",
"OffsetCommitMode",
".",
"... | Make sure that auto commit is disabled when our offset commit mode is ON_CHECKPOINTS.
This overwrites whatever setting the user configured in the properties.
@param properties - Kafka configuration properties to be adjusted
@param offsetCommitMode offset commit mode | [
"Make",
"sure",
"that",
"auto",
"commit",
"is",
"disabled",
"when",
"our",
"offset",
"commit",
"mode",
"is",
"ON_CHECKPOINTS",
".",
"This",
"overwrites",
"whatever",
"setting",
"the",
"user",
"configured",
"in",
"the",
"properties",
"."
] | train | https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-connectors/flink-connector-kafka-base/src/main/java/org/apache/flink/streaming/connectors/kafka/FlinkKafkaConsumerBase.java#L263-L267 |
LearnLib/automatalib | util/src/main/java/net/automatalib/util/automata/minimizer/hopcroft/HopcroftMinimization.java | HopcroftMinimization.minimizeDFA | public static <I> CompactDFA<I> minimizeDFA(DFA<?, I> dfa, Alphabet<I> alphabet, PruningMode pruningMode) {
return doMinimizeDFA(dfa, alphabet, new CompactDFA.Creator<>(), pruningMode);
} | java | public static <I> CompactDFA<I> minimizeDFA(DFA<?, I> dfa, Alphabet<I> alphabet, PruningMode pruningMode) {
return doMinimizeDFA(dfa, alphabet, new CompactDFA.Creator<>(), pruningMode);
} | [
"public",
"static",
"<",
"I",
">",
"CompactDFA",
"<",
"I",
">",
"minimizeDFA",
"(",
"DFA",
"<",
"?",
",",
"I",
">",
"dfa",
",",
"Alphabet",
"<",
"I",
">",
"alphabet",
",",
"PruningMode",
"pruningMode",
")",
"{",
"return",
"doMinimizeDFA",
"(",
"dfa",
... | Minimizes the given DFA. The result is returned in the form of a {@link CompactDFA}.
@param dfa
the DFA to minimize
@param alphabet
the input alphabet (this will be the input alphabet of the returned DFA)
@param pruningMode
the pruning mode (see above)
@return a minimized version of the specified DFA | [
"Minimizes",
"the",
"given",
"DFA",
".",
"The",
"result",
"is",
"returned",
"in",
"the",
"form",
"of",
"a",
"{",
"@link",
"CompactDFA",
"}",
"."
] | train | https://github.com/LearnLib/automatalib/blob/8a462ec52f6eaab9f8996e344f2163a72cb8aa6e/util/src/main/java/net/automatalib/util/automata/minimizer/hopcroft/HopcroftMinimization.java#L176-L178 |
b3dgs/lionengine | lionengine-game/src/main/java/com/b3dgs/lionengine/game/feature/tile/map/pathfinding/PathfindableModel.java | PathfindableModel.assignObjectId | private void assignObjectId(int dtx, int dty)
{
final int tw = transformable.getWidth() / map.getTileWidth();
final int th = transformable.getHeight() / map.getTileHeight();
for (int tx = dtx; tx < dtx + tw; tx++)
{
for (int ty = dty; ty < dty + th; ty++)
{
mapPath.addObjectId(tx, ty, id);
}
}
} | java | private void assignObjectId(int dtx, int dty)
{
final int tw = transformable.getWidth() / map.getTileWidth();
final int th = transformable.getHeight() / map.getTileHeight();
for (int tx = dtx; tx < dtx + tw; tx++)
{
for (int ty = dty; ty < dty + th; ty++)
{
mapPath.addObjectId(tx, ty, id);
}
}
} | [
"private",
"void",
"assignObjectId",
"(",
"int",
"dtx",
",",
"int",
"dty",
")",
"{",
"final",
"int",
"tw",
"=",
"transformable",
".",
"getWidth",
"(",
")",
"/",
"map",
".",
"getTileWidth",
"(",
")",
";",
"final",
"int",
"th",
"=",
"transformable",
".",... | Assign the map object id of the pathfindable.
@param dtx The tile horizontal destination.
@param dty The tile vertical destination. | [
"Assign",
"the",
"map",
"object",
"id",
"of",
"the",
"pathfindable",
"."
] | train | https://github.com/b3dgs/lionengine/blob/cac3d5578532cf11724a737b9f09e71bf9995ab2/lionengine-game/src/main/java/com/b3dgs/lionengine/game/feature/tile/map/pathfinding/PathfindableModel.java#L167-L179 |
haifengl/smile | math/src/main/java/smile/math/matrix/BiconjugateGradient.java | BiconjugateGradient.snorm | private static double snorm(double[] x, int itol) {
int n = x.length;
if (itol <= 3) {
double ans = 0.0;
for (int i = 0; i < n; i++) {
ans += x[i] * x[i];
}
return Math.sqrt(ans);
} else {
int isamax = 0;
for (int i = 0; i < n; i++) {
if (Math.abs(x[i]) > Math.abs(x[isamax])) {
isamax = i;
}
}
return Math.abs(x[isamax]);
}
} | java | private static double snorm(double[] x, int itol) {
int n = x.length;
if (itol <= 3) {
double ans = 0.0;
for (int i = 0; i < n; i++) {
ans += x[i] * x[i];
}
return Math.sqrt(ans);
} else {
int isamax = 0;
for (int i = 0; i < n; i++) {
if (Math.abs(x[i]) > Math.abs(x[isamax])) {
isamax = i;
}
}
return Math.abs(x[isamax]);
}
} | [
"private",
"static",
"double",
"snorm",
"(",
"double",
"[",
"]",
"x",
",",
"int",
"itol",
")",
"{",
"int",
"n",
"=",
"x",
".",
"length",
";",
"if",
"(",
"itol",
"<=",
"3",
")",
"{",
"double",
"ans",
"=",
"0.0",
";",
"for",
"(",
"int",
"i",
"=... | Compute L2 or L-infinity norms for a vector x, as signaled by itol. | [
"Compute",
"L2",
"or",
"L",
"-",
"infinity",
"norms",
"for",
"a",
"vector",
"x",
"as",
"signaled",
"by",
"itol",
"."
] | train | https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/math/src/main/java/smile/math/matrix/BiconjugateGradient.java#L291-L310 |
lestard/advanced-bindings | src/main/java/eu/lestard/advanced_bindings/api/NumberBindings.java | NumberBindings.divideSafe | public static IntegerBinding divideSafe(ObservableIntegerValue dividend, ObservableIntegerValue divisor, ObservableIntegerValue defaultValue) {
return Bindings.createIntegerBinding(() -> {
if (divisor.intValue() == 0) {
return defaultValue.get();
} else {
return dividend.intValue() / divisor.intValue();
}
}, dividend, divisor);
} | java | public static IntegerBinding divideSafe(ObservableIntegerValue dividend, ObservableIntegerValue divisor, ObservableIntegerValue defaultValue) {
return Bindings.createIntegerBinding(() -> {
if (divisor.intValue() == 0) {
return defaultValue.get();
} else {
return dividend.intValue() / divisor.intValue();
}
}, dividend, divisor);
} | [
"public",
"static",
"IntegerBinding",
"divideSafe",
"(",
"ObservableIntegerValue",
"dividend",
",",
"ObservableIntegerValue",
"divisor",
",",
"ObservableIntegerValue",
"defaultValue",
")",
"{",
"return",
"Bindings",
".",
"createIntegerBinding",
"(",
"(",
")",
"->",
"{",... | An integer binding of a division that won't throw an {@link java.lang.ArithmeticException}
when a division by zero happens. See {@link #divideSafe(javafx.beans.value.ObservableIntegerValue,
javafx.beans.value.ObservableIntegerValue)}
for more information.
@param dividend the observable value used as dividend
@param divisor the observable value used as divisor
@param defaultValue the observable value that is used as default value. The binding will have this value when a
division by zero happens.
@return the resulting integer binding | [
"An",
"integer",
"binding",
"of",
"a",
"division",
"that",
"won",
"t",
"throw",
"an",
"{",
"@link",
"java",
".",
"lang",
".",
"ArithmeticException",
"}",
"when",
"a",
"division",
"by",
"zero",
"happens",
".",
"See",
"{",
"@link",
"#divideSafe",
"(",
"jav... | train | https://github.com/lestard/advanced-bindings/blob/054a5dde261c29f862b971765fa3da3704a13ab4/src/main/java/eu/lestard/advanced_bindings/api/NumberBindings.java#L221-L231 |
beangle/beangle3 | commons/model/src/main/java/org/beangle/commons/entity/util/EntityUtils.java | EntityUtils.extractIdSeq | public static <T extends Entity<?>> String extractIdSeq(Collection<T> entities) {
if (null == entities || entities.isEmpty()) { return ""; }
StringBuilder idBuf = new StringBuilder(",");
for (Iterator<T> iter = entities.iterator(); iter.hasNext();) {
T element = iter.next();
try {
idBuf.append(String.valueOf(PropertyUtils.getProperty(element, "id")));
idBuf.append(',');
} catch (Exception e) {
throw new RuntimeException(e.getMessage());
}
}
return idBuf.toString();
} | java | public static <T extends Entity<?>> String extractIdSeq(Collection<T> entities) {
if (null == entities || entities.isEmpty()) { return ""; }
StringBuilder idBuf = new StringBuilder(",");
for (Iterator<T> iter = entities.iterator(); iter.hasNext();) {
T element = iter.next();
try {
idBuf.append(String.valueOf(PropertyUtils.getProperty(element, "id")));
idBuf.append(',');
} catch (Exception e) {
throw new RuntimeException(e.getMessage());
}
}
return idBuf.toString();
} | [
"public",
"static",
"<",
"T",
"extends",
"Entity",
"<",
"?",
">",
">",
"String",
"extractIdSeq",
"(",
"Collection",
"<",
"T",
">",
"entities",
")",
"{",
"if",
"(",
"null",
"==",
"entities",
"||",
"entities",
".",
"isEmpty",
"(",
")",
")",
"{",
"retur... | <p>
extractIdSeq.
</p>
@param entities a {@link java.util.Collection} object.
@param <T> a T object.
@return a {@link java.lang.String} object. | [
"<p",
">",
"extractIdSeq",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/beangle/beangle3/blob/33df2873a5f38e28ac174a1d3b8144eb2f808e64/commons/model/src/main/java/org/beangle/commons/entity/util/EntityUtils.java#L132-L145 |
orbisgis/h2gis | h2gis-functions/src/main/java/org/h2gis/functions/spatial/edit/ST_Reverse3DLine.java | ST_Reverse3DLine.reverse3D | private static LineString reverse3D(LineString lineString, String order) {
CoordinateSequence seq = lineString.getCoordinateSequence();
double startZ = seq.getCoordinate(0).z;
double endZ = seq.getCoordinate(seq.size() - 1).z;
if (order.equalsIgnoreCase("desc")) {
if (!Double.isNaN(startZ) && !Double.isNaN(endZ) && startZ < endZ) {
CoordinateSequences.reverse(seq);
return FACTORY.createLineString(seq);
}
} else if (order.equalsIgnoreCase("asc")) {
if (!Double.isNaN(startZ) && !Double.isNaN(endZ) && startZ > endZ) {
CoordinateSequences.reverse(seq);
return FACTORY.createLineString(seq);
}
}
else {
throw new IllegalArgumentException("Supported order values are asc or desc.");
}
return lineString;
} | java | private static LineString reverse3D(LineString lineString, String order) {
CoordinateSequence seq = lineString.getCoordinateSequence();
double startZ = seq.getCoordinate(0).z;
double endZ = seq.getCoordinate(seq.size() - 1).z;
if (order.equalsIgnoreCase("desc")) {
if (!Double.isNaN(startZ) && !Double.isNaN(endZ) && startZ < endZ) {
CoordinateSequences.reverse(seq);
return FACTORY.createLineString(seq);
}
} else if (order.equalsIgnoreCase("asc")) {
if (!Double.isNaN(startZ) && !Double.isNaN(endZ) && startZ > endZ) {
CoordinateSequences.reverse(seq);
return FACTORY.createLineString(seq);
}
}
else {
throw new IllegalArgumentException("Supported order values are asc or desc.");
}
return lineString;
} | [
"private",
"static",
"LineString",
"reverse3D",
"(",
"LineString",
"lineString",
",",
"String",
"order",
")",
"{",
"CoordinateSequence",
"seq",
"=",
"lineString",
".",
"getCoordinateSequence",
"(",
")",
";",
"double",
"startZ",
"=",
"seq",
".",
"getCoordinate",
... | Reverses a LineString according to the z value. The z of the first point
must be lower than the z of the end point.
@param lineString
@return | [
"Reverses",
"a",
"LineString",
"according",
"to",
"the",
"z",
"value",
".",
"The",
"z",
"of",
"the",
"first",
"point",
"must",
"be",
"lower",
"than",
"the",
"z",
"of",
"the",
"end",
"point",
"."
] | train | https://github.com/orbisgis/h2gis/blob/9cd70b447e6469cecbc2fc64b16774b59491df3b/h2gis-functions/src/main/java/org/h2gis/functions/spatial/edit/ST_Reverse3DLine.java#L87-L106 |
mlhartme/mork | src/main/java/net/oneandone/mork/classfile/ClassRef.java | ClassRef.writeClasses | public static void writeClasses(ObjectOutput out, Class<?>[] types)
throws java.io.IOException {
int i;
if (types.length > Byte.MAX_VALUE) {
throw new RuntimeException("to many dimensions");
}
out.writeByte((byte) types.length);
for (i = 0; i < types.length; i++) {
write(out, types[i]);
}
} | java | public static void writeClasses(ObjectOutput out, Class<?>[] types)
throws java.io.IOException {
int i;
if (types.length > Byte.MAX_VALUE) {
throw new RuntimeException("to many dimensions");
}
out.writeByte((byte) types.length);
for (i = 0; i < types.length; i++) {
write(out, types[i]);
}
} | [
"public",
"static",
"void",
"writeClasses",
"(",
"ObjectOutput",
"out",
",",
"Class",
"<",
"?",
">",
"[",
"]",
"types",
")",
"throws",
"java",
".",
"io",
".",
"IOException",
"{",
"int",
"i",
";",
"if",
"(",
"types",
".",
"length",
">",
"Byte",
".",
... | Writes an array of Class objects.
@param out target to write to
@param types Classes to be written | [
"Writes",
"an",
"array",
"of",
"Class",
"objects",
"."
] | train | https://github.com/mlhartme/mork/blob/a069b087750c4133bfeebaf1f599c3bc96762113/src/main/java/net/oneandone/mork/classfile/ClassRef.java#L460-L471 |
ops4j/org.ops4j.pax.swissbox | pax-swissbox-tracker/src/main/java/org/ops4j/pax/swissbox/tracker/ServiceLookup.java | ServiceLookup.getServiceByFilter | public static Object getServiceByFilter( BundleContext bc, String ldapFilter, long timeout )
{
try
{
Filter filter = bc.createFilter( ldapFilter );
ServiceTracker tracker = new ServiceTracker( bc, filter, null );
tracker.open();
Object svc = tracker.waitForService( timeout );
if( svc == null )
{
throw new ServiceLookupException( "gave up waiting for service " + ldapFilter );
}
// increment the service use count to keep it valid after the ServiceTracker is closed
return bc.getService( tracker.getServiceReference() );
}
catch ( InvalidSyntaxException exc )
{
throw new ServiceLookupException( exc );
}
catch ( InterruptedException exc )
{
throw new ServiceLookupException( exc );
}
} | java | public static Object getServiceByFilter( BundleContext bc, String ldapFilter, long timeout )
{
try
{
Filter filter = bc.createFilter( ldapFilter );
ServiceTracker tracker = new ServiceTracker( bc, filter, null );
tracker.open();
Object svc = tracker.waitForService( timeout );
if( svc == null )
{
throw new ServiceLookupException( "gave up waiting for service " + ldapFilter );
}
// increment the service use count to keep it valid after the ServiceTracker is closed
return bc.getService( tracker.getServiceReference() );
}
catch ( InvalidSyntaxException exc )
{
throw new ServiceLookupException( exc );
}
catch ( InterruptedException exc )
{
throw new ServiceLookupException( exc );
}
} | [
"public",
"static",
"Object",
"getServiceByFilter",
"(",
"BundleContext",
"bc",
",",
"String",
"ldapFilter",
",",
"long",
"timeout",
")",
"{",
"try",
"{",
"Filter",
"filter",
"=",
"bc",
".",
"createFilter",
"(",
"ldapFilter",
")",
";",
"ServiceTracker",
"track... | Returns a service matching the given filter.
@param bc bundle context for accessing the OSGi registry
@param ldapFilter LDAP filter to be matched by the service. The class name must be part of the
filter.
@param timeout maximum wait period in milliseconds
@return matching service (not null)
@throws ServiceLookupException when no matching service has been found after the timeout | [
"Returns",
"a",
"service",
"matching",
"the",
"given",
"filter",
"."
] | train | https://github.com/ops4j/org.ops4j.pax.swissbox/blob/00b0ee16cdbe8017984a4d7ba808b10d985c5b5c/pax-swissbox-tracker/src/main/java/org/ops4j/pax/swissbox/tracker/ServiceLookup.java#L328-L351 |
Alluxio/alluxio | core/server/master/src/main/java/alluxio/master/file/meta/InodeLockList.java | InodeLockList.downgradeLastInode | public void downgradeLastInode() {
Preconditions.checkState(endsInInode());
Preconditions.checkState(!mEntries.isEmpty());
Preconditions.checkState(mLockMode == LockMode.WRITE);
InodeEntry last = (InodeEntry) mEntries.get(mEntries.size() - 1);
LockResource lock = mInodeLockManager.lockInode(last.getInode(), LockMode.READ);
last.getLock().close();
mEntries.set(mEntries.size() - 1, new InodeEntry(lock, last.mInode));
mLockMode = LockMode.READ;
} | java | public void downgradeLastInode() {
Preconditions.checkState(endsInInode());
Preconditions.checkState(!mEntries.isEmpty());
Preconditions.checkState(mLockMode == LockMode.WRITE);
InodeEntry last = (InodeEntry) mEntries.get(mEntries.size() - 1);
LockResource lock = mInodeLockManager.lockInode(last.getInode(), LockMode.READ);
last.getLock().close();
mEntries.set(mEntries.size() - 1, new InodeEntry(lock, last.mInode));
mLockMode = LockMode.READ;
} | [
"public",
"void",
"downgradeLastInode",
"(",
")",
"{",
"Preconditions",
".",
"checkState",
"(",
"endsInInode",
"(",
")",
")",
";",
"Preconditions",
".",
"checkState",
"(",
"!",
"mEntries",
".",
"isEmpty",
"(",
")",
")",
";",
"Preconditions",
".",
"checkState... | Downgrades the last inode from a write lock to a read lock. The read lock is acquired before
releasing the write lock. | [
"Downgrades",
"the",
"last",
"inode",
"from",
"a",
"write",
"lock",
"to",
"a",
"read",
"lock",
".",
"The",
"read",
"lock",
"is",
"acquired",
"before",
"releasing",
"the",
"write",
"lock",
"."
] | train | https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/server/master/src/main/java/alluxio/master/file/meta/InodeLockList.java#L207-L217 |
looly/hutool | hutool-core/src/main/java/cn/hutool/core/util/ArrayUtil.java | ArrayUtil.get | @SuppressWarnings("unchecked")
public static <T> T get(Object array, int index) {
if(null == array) {
return null;
}
if (index < 0) {
index += Array.getLength(array);
}
try {
return (T) Array.get(array, index);
} catch (ArrayIndexOutOfBoundsException e) {
return null;
}
} | java | @SuppressWarnings("unchecked")
public static <T> T get(Object array, int index) {
if(null == array) {
return null;
}
if (index < 0) {
index += Array.getLength(array);
}
try {
return (T) Array.get(array, index);
} catch (ArrayIndexOutOfBoundsException e) {
return null;
}
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"public",
"static",
"<",
"T",
">",
"T",
"get",
"(",
"Object",
"array",
",",
"int",
"index",
")",
"{",
"if",
"(",
"null",
"==",
"array",
")",
"{",
"return",
"null",
";",
"}",
"if",
"(",
"index",
"<... | 获取数组对象中指定index的值,支持负数,例如-1表示倒数第一个值<br>
如果数组下标越界,返回null
@param <T> 数组元素类型
@param array 数组对象
@param index 下标,支持负数
@return 值
@since 4.0.6 | [
"获取数组对象中指定index的值,支持负数,例如",
"-",
"1表示倒数第一个值<br",
">",
"如果数组下标越界,返回null"
] | train | https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/util/ArrayUtil.java#L1810-L1824 |
lessthanoptimal/ejml | main/ejml-ddense/src/org/ejml/dense/row/MatrixFeatures_DDRM.java | MatrixFeatures_DDRM.isConstantVal | public static boolean isConstantVal(DMatrixRMaj mat , double val , double tol )
{
// see if the result is an identity matrix
int index = 0;
for( int i = 0; i < mat.numRows; i++ ) {
for( int j = 0; j < mat.numCols; j++ ) {
if( !(Math.abs(mat.get(index++)-val) <= tol) )
return false;
}
}
return true;
} | java | public static boolean isConstantVal(DMatrixRMaj mat , double val , double tol )
{
// see if the result is an identity matrix
int index = 0;
for( int i = 0; i < mat.numRows; i++ ) {
for( int j = 0; j < mat.numCols; j++ ) {
if( !(Math.abs(mat.get(index++)-val) <= tol) )
return false;
}
}
return true;
} | [
"public",
"static",
"boolean",
"isConstantVal",
"(",
"DMatrixRMaj",
"mat",
",",
"double",
"val",
",",
"double",
"tol",
")",
"{",
"// see if the result is an identity matrix",
"int",
"index",
"=",
"0",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"... | Checks to see if every value in the matrix is the specified value.
@param mat The matrix being tested. Not modified.
@param val Checks to see if every element in the matrix has this value.
@param tol True if all the elements are within this tolerance.
@return true if the test passes. | [
"Checks",
"to",
"see",
"if",
"every",
"value",
"in",
"the",
"matrix",
"is",
"the",
"specified",
"value",
"."
] | train | https://github.com/lessthanoptimal/ejml/blob/1444680cc487af5e866730e62f48f5f9636850d9/main/ejml-ddense/src/org/ejml/dense/row/MatrixFeatures_DDRM.java#L552-L565 |
UrielCh/ovh-java-sdk | ovh-java-sdk-domain/src/main/java/net/minidev/ovh/api/ApiOvhDomain.java | ApiOvhDomain.zone_zoneName_record_id_GET | public OvhRecord zone_zoneName_record_id_GET(String zoneName, Long id) throws IOException {
String qPath = "/domain/zone/{zoneName}/record/{id}";
StringBuilder sb = path(qPath, zoneName, id);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, OvhRecord.class);
} | java | public OvhRecord zone_zoneName_record_id_GET(String zoneName, Long id) throws IOException {
String qPath = "/domain/zone/{zoneName}/record/{id}";
StringBuilder sb = path(qPath, zoneName, id);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, OvhRecord.class);
} | [
"public",
"OvhRecord",
"zone_zoneName_record_id_GET",
"(",
"String",
"zoneName",
",",
"Long",
"id",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/domain/zone/{zoneName}/record/{id}\"",
";",
"StringBuilder",
"sb",
"=",
"path",
"(",
"qPath",
",",
"zon... | Get this object properties
REST: GET /domain/zone/{zoneName}/record/{id}
@param zoneName [required] The internal name of your zone
@param id [required] Id of the object | [
"Get",
"this",
"object",
"properties"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-domain/src/main/java/net/minidev/ovh/api/ApiOvhDomain.java#L888-L893 |
raydac/java-comment-preprocessor | jcp/src/main/java/com/igormaznitsa/meta/common/exceptions/MetaErrorListeners.java | MetaErrorListeners.fireError | @Weight(Weight.Unit.VARIABLE)
public static void fireError(@Nonnull final String text, @Nonnull final Throwable error) {
for (final MetaErrorListener p : ERROR_LISTENERS) {
p.onDetectedError(text, error);
}
} | java | @Weight(Weight.Unit.VARIABLE)
public static void fireError(@Nonnull final String text, @Nonnull final Throwable error) {
for (final MetaErrorListener p : ERROR_LISTENERS) {
p.onDetectedError(text, error);
}
} | [
"@",
"Weight",
"(",
"Weight",
".",
"Unit",
".",
"VARIABLE",
")",
"public",
"static",
"void",
"fireError",
"(",
"@",
"Nonnull",
"final",
"String",
"text",
",",
"@",
"Nonnull",
"final",
"Throwable",
"error",
")",
"{",
"for",
"(",
"final",
"MetaErrorListener"... | Send notifications to all listeners.
@param text message text
@param error error object
@since 1.0 | [
"Send",
"notifications",
"to",
"all",
"listeners",
"."
] | train | https://github.com/raydac/java-comment-preprocessor/blob/83ac87b575ac084914d77695a8c8673de3b8300c/jcp/src/main/java/com/igormaznitsa/meta/common/exceptions/MetaErrorListeners.java#L92-L97 |
SonarSource/sonarqube | server/sonar-db-dao/src/main/java/org/sonar/db/user/UserDao.java | UserDao.selectByUuids | public List<UserDto> selectByUuids(DbSession session, Collection<String> uuids) {
return executeLargeInputs(uuids, mapper(session)::selectByUuids);
} | java | public List<UserDto> selectByUuids(DbSession session, Collection<String> uuids) {
return executeLargeInputs(uuids, mapper(session)::selectByUuids);
} | [
"public",
"List",
"<",
"UserDto",
">",
"selectByUuids",
"(",
"DbSession",
"session",
",",
"Collection",
"<",
"String",
">",
"uuids",
")",
"{",
"return",
"executeLargeInputs",
"(",
"uuids",
",",
"mapper",
"(",
"session",
")",
"::",
"selectByUuids",
")",
";",
... | Select users by uuids, including disabled users. An empty list is returned
if list of uuids is empty, without any db round trips. | [
"Select",
"users",
"by",
"uuids",
"including",
"disabled",
"users",
".",
"An",
"empty",
"list",
"is",
"returned",
"if",
"list",
"of",
"uuids",
"is",
"empty",
"without",
"any",
"db",
"round",
"trips",
"."
] | train | https://github.com/SonarSource/sonarqube/blob/2fffa4c2f79ae3714844d7742796e82822b6a98a/server/sonar-db-dao/src/main/java/org/sonar/db/user/UserDao.java#L93-L95 |
cdapio/tigon | tigon-sql/src/main/java/co/cask/tigon/sql/util/MetaInformationParser.java | MetaInformationParser.getSchemaMap | public static Map<String, StreamSchema> getSchemaMap(File fileLocation) throws IOException {
FileInputStream fis = new FileInputStream(new File(fileLocation, Constants.OUTPUT_SPEC));
BufferedReader reader = new BufferedReader(new InputStreamReader(fis));
String line;
while ((line = reader.readLine()) != null) {
schemaNames.add(line.split(",")[0]);
}
fis.close();
Document qtree = getQTree(fileLocation);
NodeList lfta = qtree.getElementsByTagName("LFTA");
NodeList hfta = qtree.getElementsByTagName("HFTA");
Map<String, StreamSchema> schemaMap = Maps.newHashMap();
addSchema(lfta, schemaMap);
addSchema(hfta, schemaMap);
return schemaMap;
} | java | public static Map<String, StreamSchema> getSchemaMap(File fileLocation) throws IOException {
FileInputStream fis = new FileInputStream(new File(fileLocation, Constants.OUTPUT_SPEC));
BufferedReader reader = new BufferedReader(new InputStreamReader(fis));
String line;
while ((line = reader.readLine()) != null) {
schemaNames.add(line.split(",")[0]);
}
fis.close();
Document qtree = getQTree(fileLocation);
NodeList lfta = qtree.getElementsByTagName("LFTA");
NodeList hfta = qtree.getElementsByTagName("HFTA");
Map<String, StreamSchema> schemaMap = Maps.newHashMap();
addSchema(lfta, schemaMap);
addSchema(hfta, schemaMap);
return schemaMap;
} | [
"public",
"static",
"Map",
"<",
"String",
",",
"StreamSchema",
">",
"getSchemaMap",
"(",
"File",
"fileLocation",
")",
"throws",
"IOException",
"{",
"FileInputStream",
"fis",
"=",
"new",
"FileInputStream",
"(",
"new",
"File",
"(",
"fileLocation",
",",
"Constants"... | This function generates the {@link co.cask.tigon.sql.flowlet.StreamSchema} for each query specified by the user
@param fileLocation Directory that contains the qtree.xml file & the output_spec.cfg
@return A map of query names and the associated {@link co.cask.tigon.sql.flowlet.StreamSchema}
@throws IOException | [
"This",
"function",
"generates",
"the",
"{"
] | train | https://github.com/cdapio/tigon/blob/5be6dffd7c79519d1211bb08f75be7dcfbbad392/tigon-sql/src/main/java/co/cask/tigon/sql/util/MetaInformationParser.java#L128-L143 |
Microsoft/malmo | Minecraft/src/main/java/com/microsoft/Malmo/Utils/MinecraftTypeHelper.java | MinecraftTypeHelper.applyVariant | static IBlockState applyVariant(IBlockState state, Variation variant)
{
// Try the variant property first - if that fails, look for other properties that match the supplied variant.
boolean relaxRequirements = false;
for (int i = 0; i < 2; i++)
{
for (IProperty prop : state.getProperties().keySet())
{
if ((prop.getName().equals("variant") || relaxRequirements) && prop.getValueClass().isEnum())
{
Object[] values = prop.getValueClass().getEnumConstants();
for (Object obj : values)
{
if (obj != null && obj.toString().equalsIgnoreCase(variant.getValue()))
{
return state.withProperty(prop, (Comparable) obj);
}
}
}
}
relaxRequirements = true; // Failed to set the variant, so try again with other properties.
}
return state;
} | java | static IBlockState applyVariant(IBlockState state, Variation variant)
{
// Try the variant property first - if that fails, look for other properties that match the supplied variant.
boolean relaxRequirements = false;
for (int i = 0; i < 2; i++)
{
for (IProperty prop : state.getProperties().keySet())
{
if ((prop.getName().equals("variant") || relaxRequirements) && prop.getValueClass().isEnum())
{
Object[] values = prop.getValueClass().getEnumConstants();
for (Object obj : values)
{
if (obj != null && obj.toString().equalsIgnoreCase(variant.getValue()))
{
return state.withProperty(prop, (Comparable) obj);
}
}
}
}
relaxRequirements = true; // Failed to set the variant, so try again with other properties.
}
return state;
} | [
"static",
"IBlockState",
"applyVariant",
"(",
"IBlockState",
"state",
",",
"Variation",
"variant",
")",
"{",
"// Try the variant property first - if that fails, look for other properties that match the supplied variant.",
"boolean",
"relaxRequirements",
"=",
"false",
";",
"for",
... | Select the request variant of the Minecraft block, if applicable
@param state The block to be varied
@param colour The new variation
@return A new blockstate which is the requested variant of the original, if such a variant exists; otherwise it returns the original block. | [
"Select",
"the",
"request",
"variant",
"of",
"the",
"Minecraft",
"block",
"if",
"applicable"
] | train | https://github.com/Microsoft/malmo/blob/4139cd6f3e52f6e893a931a1d4b70d35f8e70e5a/Minecraft/src/main/java/com/microsoft/Malmo/Utils/MinecraftTypeHelper.java#L530-L553 |
OpenLiberty/open-liberty | dev/com.ibm.ws.transport.http/src/com/ibm/ws/http/channel/internal/inbound/HttpInboundLink.java | HttpInboundLink.checkForH2MagicString | private boolean checkForH2MagicString(HttpInboundServiceContextImpl isc) {
boolean hasMagicString = false;
WsByteBuffer buffer;
if (myTSC == null || myTSC.getReadInterface() == null ||
(buffer = myTSC.getReadInterface().getBuffer()) == null) {
return hasMagicString;
}
// read the buffer, flip it, and if there is a backing array pull that out
buffer = buffer.duplicate();
buffer.flip();
byte[] bufferArray = null;
if (buffer.hasArray()) {
bufferArray = buffer.array();
}
// return true if the read buffer starts with the magic string
if (bufferArray != null && bufferArray.length >= 24) {
String bufferString = new String(bufferArray, 0, 24);
if (bufferString.startsWith(HttpConstants.HTTP2PrefaceString)) {
hasMagicString = true;
}
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
Tr.exit(tc, "checkForH2MagicString: returning " + hasMagicString);
}
buffer.release();
return hasMagicString;
} | java | private boolean checkForH2MagicString(HttpInboundServiceContextImpl isc) {
boolean hasMagicString = false;
WsByteBuffer buffer;
if (myTSC == null || myTSC.getReadInterface() == null ||
(buffer = myTSC.getReadInterface().getBuffer()) == null) {
return hasMagicString;
}
// read the buffer, flip it, and if there is a backing array pull that out
buffer = buffer.duplicate();
buffer.flip();
byte[] bufferArray = null;
if (buffer.hasArray()) {
bufferArray = buffer.array();
}
// return true if the read buffer starts with the magic string
if (bufferArray != null && bufferArray.length >= 24) {
String bufferString = new String(bufferArray, 0, 24);
if (bufferString.startsWith(HttpConstants.HTTP2PrefaceString)) {
hasMagicString = true;
}
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
Tr.exit(tc, "checkForH2MagicString: returning " + hasMagicString);
}
buffer.release();
return hasMagicString;
} | [
"private",
"boolean",
"checkForH2MagicString",
"(",
"HttpInboundServiceContextImpl",
"isc",
")",
"{",
"boolean",
"hasMagicString",
"=",
"false",
";",
"WsByteBuffer",
"buffer",
";",
"if",
"(",
"myTSC",
"==",
"null",
"||",
"myTSC",
".",
"getReadInterface",
"(",
")",... | Check the beginning of the current read buffer for the http/2 preface string
@param isc the HttpInboundServiceContextImpl to use
@return true if the magic string was found | [
"Check",
"the",
"beginning",
"of",
"the",
"current",
"read",
"buffer",
"for",
"the",
"http",
"/",
"2",
"preface",
"string"
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.transport.http/src/com/ibm/ws/http/channel/internal/inbound/HttpInboundLink.java#L991-L1021 |
biojava/biojava | biojava-structure/src/main/java/org/biojava/nbio/structure/cluster/SubunitClustererParameters.java | SubunitClustererParameters.isHighConfidenceScores | public boolean isHighConfidenceScores(double sequenceIdentity, double sequenceCoverage) {
if (useGlobalMetrics)
return sequenceIdentity>=hcSequenceIdentityGlobal;
else
return sequenceIdentity>=hcSequenceIdentityLocal && sequenceCoverage >= hcSequenceCoverageLocal;
} | java | public boolean isHighConfidenceScores(double sequenceIdentity, double sequenceCoverage) {
if (useGlobalMetrics)
return sequenceIdentity>=hcSequenceIdentityGlobal;
else
return sequenceIdentity>=hcSequenceIdentityLocal && sequenceCoverage >= hcSequenceCoverageLocal;
} | [
"public",
"boolean",
"isHighConfidenceScores",
"(",
"double",
"sequenceIdentity",
",",
"double",
"sequenceCoverage",
")",
"{",
"if",
"(",
"useGlobalMetrics",
")",
"return",
"sequenceIdentity",
">=",
"hcSequenceIdentityGlobal",
";",
"else",
"return",
"sequenceIdentity",
... | Whether the subunits can be considered "identical" by sequence alignment.
For local sequence alignment (normalized by the number of aligned pairs)
this means 0.95 or higher identity and 0.75 or higher coverage.
For global sequence alignment (normalised by the alignment length)
this means 0.85 or higher sequence identity.
@param sequenceIdentity
@param sequenceCoverage
@return true if the sequence alignment scores are equal to
or better than the "high confidence" scores, false otherwise. | [
"Whether",
"the",
"subunits",
"can",
"be",
"considered",
"identical",
"by",
"sequence",
"alignment",
".",
"For",
"local",
"sequence",
"alignment",
"(",
"normalized",
"by",
"the",
"number",
"of",
"aligned",
"pairs",
")",
"this",
"means",
"0",
".",
"95",
"or",... | train | https://github.com/biojava/biojava/blob/a1c71a8e3d40cc32104b1d387a3d3b560b43356e/biojava-structure/src/main/java/org/biojava/nbio/structure/cluster/SubunitClustererParameters.java#L502-L507 |
samskivert/samskivert | src/main/java/com/samskivert/util/IntIntMap.java | IntIntMap.removeOrElse | public int removeOrElse (int key, int defval)
{
_modCount++;
int removed = removeImpl(key, defval);
checkShrink();
return removed;
} | java | public int removeOrElse (int key, int defval)
{
_modCount++;
int removed = removeImpl(key, defval);
checkShrink();
return removed;
} | [
"public",
"int",
"removeOrElse",
"(",
"int",
"key",
",",
"int",
"defval",
")",
"{",
"_modCount",
"++",
";",
"int",
"removed",
"=",
"removeImpl",
"(",
"key",
",",
"defval",
")",
";",
"checkShrink",
"(",
")",
";",
"return",
"removed",
";",
"}"
] | Removes the value mapped for the specified key.
@return the value to which the key was mapped or the supplied default value if there was no
mapping for that key. | [
"Removes",
"the",
"value",
"mapped",
"for",
"the",
"specified",
"key",
"."
] | train | https://github.com/samskivert/samskivert/blob/a64d9ef42b69819bdb2c66bddac6a64caef928b6/src/main/java/com/samskivert/util/IntIntMap.java#L179-L185 |
awslabs/jsii | packages/jsii-java-runtime/project/src/main/java/software/amazon/jsii/JsiiObject.java | JsiiObject.jsiiStaticSet | protected static void jsiiStaticSet(final Class<?> nativeClass, final String property, @Nullable final Object value) {
String fqn = engine.loadModuleForClass(nativeClass);
engine.getClient().setStaticPropertyValue(fqn, property, JsiiObjectMapper.valueToTree(value));
} | java | protected static void jsiiStaticSet(final Class<?> nativeClass, final String property, @Nullable final Object value) {
String fqn = engine.loadModuleForClass(nativeClass);
engine.getClient().setStaticPropertyValue(fqn, property, JsiiObjectMapper.valueToTree(value));
} | [
"protected",
"static",
"void",
"jsiiStaticSet",
"(",
"final",
"Class",
"<",
"?",
">",
"nativeClass",
",",
"final",
"String",
"property",
",",
"@",
"Nullable",
"final",
"Object",
"value",
")",
"{",
"String",
"fqn",
"=",
"engine",
".",
"loadModuleForClass",
"(... | Sets a value for a static property.
@param nativeClass The java class.
@param property The name of the property
@param value The value | [
"Sets",
"a",
"value",
"for",
"a",
"static",
"property",
"."
] | train | https://github.com/awslabs/jsii/blob/6bbf743f5f65e98e5199ad31c93961533ffc40e5/packages/jsii-java-runtime/project/src/main/java/software/amazon/jsii/JsiiObject.java#L139-L142 |
b3dgs/lionengine | lionengine-game/src/main/java/com/b3dgs/lionengine/game/feature/FeaturableConfig.java | FeaturableConfig.getClass | @SuppressWarnings("unchecked")
private static <T> Class<T> getClass(String className)
{
if (CLASS_CACHE.containsKey(className))
{
return (Class<T>) CLASS_CACHE.get(className);
}
try
{
final Class<?> clazz = LOADER.loadClass(className);
CLASS_CACHE.put(className, clazz);
return (Class<T>) clazz;
}
catch (final ClassNotFoundException exception)
{
throw new LionEngineException(exception, ERROR_CLASS_PRESENCE + className);
}
} | java | @SuppressWarnings("unchecked")
private static <T> Class<T> getClass(String className)
{
if (CLASS_CACHE.containsKey(className))
{
return (Class<T>) CLASS_CACHE.get(className);
}
try
{
final Class<?> clazz = LOADER.loadClass(className);
CLASS_CACHE.put(className, clazz);
return (Class<T>) clazz;
}
catch (final ClassNotFoundException exception)
{
throw new LionEngineException(exception, ERROR_CLASS_PRESENCE + className);
}
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"private",
"static",
"<",
"T",
">",
"Class",
"<",
"T",
">",
"getClass",
"(",
"String",
"className",
")",
"{",
"if",
"(",
"CLASS_CACHE",
".",
"containsKey",
"(",
"className",
")",
")",
"{",
"return",
"("... | Get the class reference from its name using cache.
@param <T> The class type.
@param className The class name.
@return The typed class instance.
@throws LionEngineException If invalid class. | [
"Get",
"the",
"class",
"reference",
"from",
"its",
"name",
"using",
"cache",
"."
] | train | https://github.com/b3dgs/lionengine/blob/cac3d5578532cf11724a737b9f09e71bf9995ab2/lionengine-game/src/main/java/com/b3dgs/lionengine/game/feature/FeaturableConfig.java#L192-L209 |
xdcrafts/flower | flower-tools/src/main/java/com/github/xdcrafts/flower/tools/map/MapApi.java | MapApi.getUnsafe | public static <T> T getUnsafe(final Map map, final Class<T> clazz, final Object... path) {
return get(map, clazz, path).orElseThrow(() -> new IllegalAccessError(
"Map "
+ map
+ " does not have value of type "
+ clazz.getName()
+ " by "
+ Arrays.stream(path).map(Object::toString).collect(Collectors.joining(".")))
);
} | java | public static <T> T getUnsafe(final Map map, final Class<T> clazz, final Object... path) {
return get(map, clazz, path).orElseThrow(() -> new IllegalAccessError(
"Map "
+ map
+ " does not have value of type "
+ clazz.getName()
+ " by "
+ Arrays.stream(path).map(Object::toString).collect(Collectors.joining(".")))
);
} | [
"public",
"static",
"<",
"T",
">",
"T",
"getUnsafe",
"(",
"final",
"Map",
"map",
",",
"final",
"Class",
"<",
"T",
">",
"clazz",
",",
"final",
"Object",
"...",
"path",
")",
"{",
"return",
"get",
"(",
"map",
",",
"clazz",
",",
"path",
")",
".",
"or... | Walks by map's nodes and extracts optional value of type T.
@param <T> value type
@param clazz type of value
@param map subject
@param path nodes to walk in map
@return optional value of type T | [
"Walks",
"by",
"map",
"s",
"nodes",
"and",
"extracts",
"optional",
"value",
"of",
"type",
"T",
"."
] | train | https://github.com/xdcrafts/flower/blob/96a8e49102fea434bd383a3c7852f0ee9545f999/flower-tools/src/main/java/com/github/xdcrafts/flower/tools/map/MapApi.java#L120-L129 |
apache/groovy | subprojects/groovy-servlet/src/main/java/groovy/servlet/AbstractHttpServlet.java | AbstractHttpServlet.getResourceConnection | public URLConnection getResourceConnection (String name) throws ResourceException {
name = removeNamePrefix(name).replace('\\', '/');
//remove the leading / as we are trying with a leading / now
if (name.startsWith("WEB-INF/groovy/")) {
name = name.substring(15);//just for uniformity
} else if (name.startsWith("/")) {
name = name.substring(1);
}
/*
* Try to locate the resource and return an opened connection to it.
*/
try {
URL url = servletContext.getResource('/' + name);
if (url == null) {
url = servletContext.getResource("/WEB-INF/groovy/" + name);
}
if (url == null) {
throw new ResourceException("Resource \"" + name + "\" not found!");
}
return url.openConnection();
} catch (IOException e) {
throw new ResourceException("Problems getting resource named \"" + name + "\"!", e);
}
} | java | public URLConnection getResourceConnection (String name) throws ResourceException {
name = removeNamePrefix(name).replace('\\', '/');
//remove the leading / as we are trying with a leading / now
if (name.startsWith("WEB-INF/groovy/")) {
name = name.substring(15);//just for uniformity
} else if (name.startsWith("/")) {
name = name.substring(1);
}
/*
* Try to locate the resource and return an opened connection to it.
*/
try {
URL url = servletContext.getResource('/' + name);
if (url == null) {
url = servletContext.getResource("/WEB-INF/groovy/" + name);
}
if (url == null) {
throw new ResourceException("Resource \"" + name + "\" not found!");
}
return url.openConnection();
} catch (IOException e) {
throw new ResourceException("Problems getting resource named \"" + name + "\"!", e);
}
} | [
"public",
"URLConnection",
"getResourceConnection",
"(",
"String",
"name",
")",
"throws",
"ResourceException",
"{",
"name",
"=",
"removeNamePrefix",
"(",
"name",
")",
".",
"replace",
"(",
"'",
"'",
",",
"'",
"'",
")",
";",
"//remove the leading / as we are trying ... | Interface method for ResourceContainer. This is used by the GroovyScriptEngine. | [
"Interface",
"method",
"for",
"ResourceContainer",
".",
"This",
"is",
"used",
"by",
"the",
"GroovyScriptEngine",
"."
] | train | https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/subprojects/groovy-servlet/src/main/java/groovy/servlet/AbstractHttpServlet.java#L206-L231 |
JCTools/JCTools | jctools-core/src/main/java/org/jctools/maps/NonBlockingHashMap.java | NonBlockingHashMap.replace | @Override
public boolean replace ( TypeK key, TypeV oldValue, TypeV newValue ) {
return Objects.equals(putIfMatch( key, newValue, oldValue ), oldValue);
} | java | @Override
public boolean replace ( TypeK key, TypeV oldValue, TypeV newValue ) {
return Objects.equals(putIfMatch( key, newValue, oldValue ), oldValue);
} | [
"@",
"Override",
"public",
"boolean",
"replace",
"(",
"TypeK",
"key",
",",
"TypeV",
"oldValue",
",",
"TypeV",
"newValue",
")",
"{",
"return",
"Objects",
".",
"equals",
"(",
"putIfMatch",
"(",
"key",
",",
"newValue",
",",
"oldValue",
")",
",",
"oldValue",
... | Atomically do a <code>put(key,newValue)</code> if-and-only-if the key is
mapped a value which is <code>equals</code> to <code>oldValue</code>.
@throws NullPointerException if the specified key or value is null | [
"Atomically",
"do",
"a",
"<code",
">",
"put",
"(",
"key",
"newValue",
")",
"<",
"/",
"code",
">",
"if",
"-",
"and",
"-",
"only",
"-",
"if",
"the",
"key",
"is",
"mapped",
"a",
"value",
"which",
"is",
"<code",
">",
"equals<",
"/",
"code",
">",
"to"... | train | https://github.com/JCTools/JCTools/blob/9250fe316ec84209cbba0a41682f341256df781e/jctools-core/src/main/java/org/jctools/maps/NonBlockingHashMap.java#L352-L355 |
hibernate/hibernate-ogm | core/src/main/java/org/hibernate/ogm/datastore/map/impl/MapDatastoreProvider.java | MapDatastoreProvider.writeLock | public void writeLock(EntityKey key, int timeout) {
ReadWriteLock lock = getLock( key );
Lock writeLock = lock.writeLock();
acquireLock( key, timeout, writeLock );
} | java | public void writeLock(EntityKey key, int timeout) {
ReadWriteLock lock = getLock( key );
Lock writeLock = lock.writeLock();
acquireLock( key, timeout, writeLock );
} | [
"public",
"void",
"writeLock",
"(",
"EntityKey",
"key",
",",
"int",
"timeout",
")",
"{",
"ReadWriteLock",
"lock",
"=",
"getLock",
"(",
"key",
")",
";",
"Lock",
"writeLock",
"=",
"lock",
".",
"writeLock",
"(",
")",
";",
"acquireLock",
"(",
"key",
",",
"... | Acquires a write lock on a specific key.
@param key The key to lock
@param timeout in milliseconds; -1 means wait indefinitely, 0 means no wait. | [
"Acquires",
"a",
"write",
"lock",
"on",
"a",
"specific",
"key",
"."
] | train | https://github.com/hibernate/hibernate-ogm/blob/9ea971df7c27277029006a6f748d8272fb1d69d2/core/src/main/java/org/hibernate/ogm/datastore/map/impl/MapDatastoreProvider.java#L94-L98 |
BlueBrain/bluima | modules/bluima_typesystem/src/main/java/ch/epfl/bbp/uima/types/DocumentLine.java | DocumentLine.setBeginnings | public void setBeginnings(int i, float v) {
if (DocumentLine_Type.featOkTst && ((DocumentLine_Type)jcasType).casFeat_beginnings == null)
jcasType.jcas.throwFeatMissing("beginnings", "ch.epfl.bbp.uima.types.DocumentLine");
jcasType.jcas.checkArrayBounds(jcasType.ll_cas.ll_getRefValue(addr, ((DocumentLine_Type)jcasType).casFeatCode_beginnings), i);
jcasType.ll_cas.ll_setFloatArrayValue(jcasType.ll_cas.ll_getRefValue(addr, ((DocumentLine_Type)jcasType).casFeatCode_beginnings), i, v);} | java | public void setBeginnings(int i, float v) {
if (DocumentLine_Type.featOkTst && ((DocumentLine_Type)jcasType).casFeat_beginnings == null)
jcasType.jcas.throwFeatMissing("beginnings", "ch.epfl.bbp.uima.types.DocumentLine");
jcasType.jcas.checkArrayBounds(jcasType.ll_cas.ll_getRefValue(addr, ((DocumentLine_Type)jcasType).casFeatCode_beginnings), i);
jcasType.ll_cas.ll_setFloatArrayValue(jcasType.ll_cas.ll_getRefValue(addr, ((DocumentLine_Type)jcasType).casFeatCode_beginnings), i, v);} | [
"public",
"void",
"setBeginnings",
"(",
"int",
"i",
",",
"float",
"v",
")",
"{",
"if",
"(",
"DocumentLine_Type",
".",
"featOkTst",
"&&",
"(",
"(",
"DocumentLine_Type",
")",
"jcasType",
")",
".",
"casFeat_beginnings",
"==",
"null",
")",
"jcasType",
".",
"jc... | indexed setter for beginnings - sets an indexed value -
@generated
@param i index in the array to set
@param v value to set into the array | [
"indexed",
"setter",
"for",
"beginnings",
"-",
"sets",
"an",
"indexed",
"value",
"-"
] | train | https://github.com/BlueBrain/bluima/blob/793ea3f46761dce72094e057a56cddfa677156ae/modules/bluima_typesystem/src/main/java/ch/epfl/bbp/uima/types/DocumentLine.java#L160-L164 |
elki-project/elki | elki/src/main/java/de/lmu/ifi/dbs/elki/algorithm/projection/SNE.java | SNE.computeGradient | protected void computeGradient(AffinityMatrix pij, double[][] qij, double qij_isum, double[][] sol, double[] meta) {
final int dim3 = dim * 3;
int size = pij.size();
for(int i = 0, off = 0; i < size; i++, off += dim3) {
final double[] sol_i = sol[i], qij_i = qij[i];
Arrays.fill(meta, off, off + dim, 0.); // Clear gradient only
for(int j = 0; j < size; j++) {
if(i == j) {
continue;
}
final double[] sol_j = sol[j];
final double qij_ij = qij_i[j];
// Qij after scaling!
final double q = MathUtil.max(qij_ij * qij_isum, MIN_QIJ);
double a = 4 * (pij.get(i, j) - q); // SNE gradient
for(int k = 0; k < dim; k++) {
meta[off + k] += a * (sol_i[k] - sol_j[k]);
}
}
}
} | java | protected void computeGradient(AffinityMatrix pij, double[][] qij, double qij_isum, double[][] sol, double[] meta) {
final int dim3 = dim * 3;
int size = pij.size();
for(int i = 0, off = 0; i < size; i++, off += dim3) {
final double[] sol_i = sol[i], qij_i = qij[i];
Arrays.fill(meta, off, off + dim, 0.); // Clear gradient only
for(int j = 0; j < size; j++) {
if(i == j) {
continue;
}
final double[] sol_j = sol[j];
final double qij_ij = qij_i[j];
// Qij after scaling!
final double q = MathUtil.max(qij_ij * qij_isum, MIN_QIJ);
double a = 4 * (pij.get(i, j) - q); // SNE gradient
for(int k = 0; k < dim; k++) {
meta[off + k] += a * (sol_i[k] - sol_j[k]);
}
}
}
} | [
"protected",
"void",
"computeGradient",
"(",
"AffinityMatrix",
"pij",
",",
"double",
"[",
"]",
"[",
"]",
"qij",
",",
"double",
"qij_isum",
",",
"double",
"[",
"]",
"[",
"]",
"sol",
",",
"double",
"[",
"]",
"meta",
")",
"{",
"final",
"int",
"dim3",
"=... | Compute the gradients.
@param pij Desired affinity matrix
@param qij Projected affinity matrix
@param qij_isum Normalization factor
@param sol Current solution coordinates
@param meta Point metadata | [
"Compute",
"the",
"gradients",
"."
] | train | https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki/src/main/java/de/lmu/ifi/dbs/elki/algorithm/projection/SNE.java#L295-L315 |
Azure/azure-sdk-for-java | appservice/resource-manager/v2018_02_01/src/main/java/com/microsoft/azure/management/appservice/v2018_02_01/implementation/DomainsInner.java | DomainsInner.updateOwnershipIdentifier | public DomainOwnershipIdentifierInner updateOwnershipIdentifier(String resourceGroupName, String domainName, String name, DomainOwnershipIdentifierInner domainOwnershipIdentifier) {
return updateOwnershipIdentifierWithServiceResponseAsync(resourceGroupName, domainName, name, domainOwnershipIdentifier).toBlocking().single().body();
} | java | public DomainOwnershipIdentifierInner updateOwnershipIdentifier(String resourceGroupName, String domainName, String name, DomainOwnershipIdentifierInner domainOwnershipIdentifier) {
return updateOwnershipIdentifierWithServiceResponseAsync(resourceGroupName, domainName, name, domainOwnershipIdentifier).toBlocking().single().body();
} | [
"public",
"DomainOwnershipIdentifierInner",
"updateOwnershipIdentifier",
"(",
"String",
"resourceGroupName",
",",
"String",
"domainName",
",",
"String",
"name",
",",
"DomainOwnershipIdentifierInner",
"domainOwnershipIdentifier",
")",
"{",
"return",
"updateOwnershipIdentifierWithS... | Creates an ownership identifier for a domain or updates identifier details for an existing identifer.
Creates an ownership identifier for a domain or updates identifier details for an existing identifer.
@param resourceGroupName Name of the resource group to which the resource belongs.
@param domainName Name of domain.
@param name Name of identifier.
@param domainOwnershipIdentifier A JSON representation of the domain ownership properties.
@throws IllegalArgumentException thrown if parameters fail the validation
@throws DefaultErrorResponseException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the DomainOwnershipIdentifierInner object if successful. | [
"Creates",
"an",
"ownership",
"identifier",
"for",
"a",
"domain",
"or",
"updates",
"identifier",
"details",
"for",
"an",
"existing",
"identifer",
".",
"Creates",
"an",
"ownership",
"identifier",
"for",
"a",
"domain",
"or",
"updates",
"identifier",
"details",
"fo... | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/appservice/resource-manager/v2018_02_01/src/main/java/com/microsoft/azure/management/appservice/v2018_02_01/implementation/DomainsInner.java#L1723-L1725 |
phax/ph-web | ph-servlet/src/main/java/com/helger/servlet/response/UnifiedResponse.java | UnifiedResponse.setContentAndCharset | @Nonnull
public final UnifiedResponse setContentAndCharset (@Nonnull final String sContent, @Nonnull final Charset aCharset)
{
ValueEnforcer.notNull (sContent, "Content");
setCharset (aCharset);
setContent (sContent.getBytes (aCharset));
return this;
} | java | @Nonnull
public final UnifiedResponse setContentAndCharset (@Nonnull final String sContent, @Nonnull final Charset aCharset)
{
ValueEnforcer.notNull (sContent, "Content");
setCharset (aCharset);
setContent (sContent.getBytes (aCharset));
return this;
} | [
"@",
"Nonnull",
"public",
"final",
"UnifiedResponse",
"setContentAndCharset",
"(",
"@",
"Nonnull",
"final",
"String",
"sContent",
",",
"@",
"Nonnull",
"final",
"Charset",
"aCharset",
")",
"{",
"ValueEnforcer",
".",
"notNull",
"(",
"sContent",
",",
"\"Content\"",
... | Utility method to set content and charset at once.
@param sContent
The response content string. May not be <code>null</code>.
@param aCharset
The charset to use. May not be <code>null</code>.
@return this | [
"Utility",
"method",
"to",
"set",
"content",
"and",
"charset",
"at",
"once",
"."
] | train | https://github.com/phax/ph-web/blob/d445fd25184605b62682c93c9782409acf0ae813/ph-servlet/src/main/java/com/helger/servlet/response/UnifiedResponse.java#L415-L422 |
elibom/jogger | src/main/java/com/elibom/jogger/middleware/router/RouterMiddleware.java | RouterMiddleware.addRoute | public void addRoute(HttpMethod httpMethod, String path, Object controller, String methodName) throws NoSuchMethodException {
Preconditions.notNull(controller, "no controller provided");
Method method = controller.getClass().getMethod(methodName, Request.class, Response.class);
addRoute(httpMethod, path, controller, method);
} | java | public void addRoute(HttpMethod httpMethod, String path, Object controller, String methodName) throws NoSuchMethodException {
Preconditions.notNull(controller, "no controller provided");
Method method = controller.getClass().getMethod(methodName, Request.class, Response.class);
addRoute(httpMethod, path, controller, method);
} | [
"public",
"void",
"addRoute",
"(",
"HttpMethod",
"httpMethod",
",",
"String",
"path",
",",
"Object",
"controller",
",",
"String",
"methodName",
")",
"throws",
"NoSuchMethodException",
"{",
"Preconditions",
".",
"notNull",
"(",
"controller",
",",
"\"no controller pro... | Creates a {@link Route} object from the received arguments and adds it to the list of routes.
@param httpMethod the HTTP method to which this route is going to respond.
@param path the path to which this route is going to respond.
@param controller the object that will be invoked when this route matches.
@param methodName the name of the method in the <code>controller</code> object that will be invoked when this
route matches.
@throws NoSuchMethodException if the <code>methodName</code> is not found or doesn't have the right signature. | [
"Creates",
"a",
"{",
"@link",
"Route",
"}",
"object",
"from",
"the",
"received",
"arguments",
"and",
"adds",
"it",
"to",
"the",
"list",
"of",
"routes",
"."
] | train | https://github.com/elibom/jogger/blob/d5892ff45e76328d444a68b5a38c26e7bdd0692b/src/main/java/com/elibom/jogger/middleware/router/RouterMiddleware.java#L180-L184 |
doanduyhai/Achilles | achilles-core/src/main/java/info/archinnov/achilles/internals/apt/AptUtils.java | AptUtils.getElementValueClassName | public static Name getElementValueClassName(AnnotationMirror anno, CharSequence name, boolean useDefaults) {
Type.ClassType ct = getElementValue(anno, name, Type.ClassType.class, useDefaults);
// TODO: Is it a problem that this returns the type parameters too? Should I cut them off?
return ct.asElement().getQualifiedName();
} | java | public static Name getElementValueClassName(AnnotationMirror anno, CharSequence name, boolean useDefaults) {
Type.ClassType ct = getElementValue(anno, name, Type.ClassType.class, useDefaults);
// TODO: Is it a problem that this returns the type parameters too? Should I cut them off?
return ct.asElement().getQualifiedName();
} | [
"public",
"static",
"Name",
"getElementValueClassName",
"(",
"AnnotationMirror",
"anno",
",",
"CharSequence",
"name",
",",
"boolean",
"useDefaults",
")",
"{",
"Type",
".",
"ClassType",
"ct",
"=",
"getElementValue",
"(",
"anno",
",",
"name",
",",
"Type",
".",
"... | Get the Name of the class that is referenced by attribute 'name'.
This is a convenience method for the most common use-case.
Like getElementValue(anno, name, ClassType.class).getQualifiedName(), but
this method ensures consistent use of the qualified name. | [
"Get",
"the",
"Name",
"of",
"the",
"class",
"that",
"is",
"referenced",
"by",
"attribute",
"name",
".",
"This",
"is",
"a",
"convenience",
"method",
"for",
"the",
"most",
"common",
"use",
"-",
"case",
".",
"Like",
"getElementValue",
"(",
"anno",
"name",
"... | train | https://github.com/doanduyhai/Achilles/blob/8281c33100e72c993e570592ae1a5306afac6813/achilles-core/src/main/java/info/archinnov/achilles/internals/apt/AptUtils.java#L297-L301 |
ThreeTen/threetenbp | src/main/java/org/threeten/bp/chrono/HijrahDate.java | HijrahDate.getGregorianEpochDay | private static long getGregorianEpochDay(int prolepticYear, int monthOfYear, int dayOfMonth) {
long day = yearToGregorianEpochDay(prolepticYear);
day += getMonthDays(monthOfYear - 1, prolepticYear);
day += dayOfMonth;
return day;
} | java | private static long getGregorianEpochDay(int prolepticYear, int monthOfYear, int dayOfMonth) {
long day = yearToGregorianEpochDay(prolepticYear);
day += getMonthDays(monthOfYear - 1, prolepticYear);
day += dayOfMonth;
return day;
} | [
"private",
"static",
"long",
"getGregorianEpochDay",
"(",
"int",
"prolepticYear",
",",
"int",
"monthOfYear",
",",
"int",
"dayOfMonth",
")",
"{",
"long",
"day",
"=",
"yearToGregorianEpochDay",
"(",
"prolepticYear",
")",
";",
"day",
"+=",
"getMonthDays",
"(",
"mon... | Return Gregorian epoch day from Hijrah year, month, and day.
@param prolepticYear the year to represent, caller calculated
@param monthOfYear the month-of-year to represent, caller calculated
@param dayOfMonth the day-of-month to represent, caller calculated
@return a julian day | [
"Return",
"Gregorian",
"epoch",
"day",
"from",
"Hijrah",
"year",
"month",
"and",
"day",
"."
] | train | https://github.com/ThreeTen/threetenbp/blob/5f05b649f89f205aabd96b2f83c36796ec616fe6/src/main/java/org/threeten/bp/chrono/HijrahDate.java#L851-L856 |
Impetus/Kundera | src/kundera-couchdb/src/main/java/com/impetus/client/couchdb/CouchDbDBClientProperties.java | CouchDbDBClientProperties.populateClientProperties | public void populateClientProperties(Client client, Map<String, Object> properties)
{
this.couchDBClient = (CouchDBClient) client;
if (properties != null)
{
for (String key : properties.keySet())
{
Object value = properties.get(key);
if (checkNull(key, value))
{
if (key.equals(BATCH_SIZE))
{
setBatchSize(value);
}
}
// Add more properties as needed
}
}
} | java | public void populateClientProperties(Client client, Map<String, Object> properties)
{
this.couchDBClient = (CouchDBClient) client;
if (properties != null)
{
for (String key : properties.keySet())
{
Object value = properties.get(key);
if (checkNull(key, value))
{
if (key.equals(BATCH_SIZE))
{
setBatchSize(value);
}
}
// Add more properties as needed
}
}
} | [
"public",
"void",
"populateClientProperties",
"(",
"Client",
"client",
",",
"Map",
"<",
"String",
",",
"Object",
">",
"properties",
")",
"{",
"this",
".",
"couchDBClient",
"=",
"(",
"CouchDBClient",
")",
"client",
";",
"if",
"(",
"properties",
"!=",
"null",
... | Populate client properties.
@param client
the client
@param properties
the properties | [
"Populate",
"client",
"properties",
"."
] | train | https://github.com/Impetus/Kundera/blob/268958ab1ec09d14ec4d9184f0c8ded7a9158908/src/kundera-couchdb/src/main/java/com/impetus/client/couchdb/CouchDbDBClientProperties.java#L49-L68 |
forge/core | ui/impl/src/main/java/org/jboss/forge/addon/ui/impl/controller/WizardCommandControllerImpl.java | WizardCommandControllerImpl.refreshFlow | private synchronized void refreshFlow()
{
try
{
initialize();
}
catch (Exception e)
{
throw new IllegalStateException("Error while initializing wizard", e);
}
int currentFlowPointer = this.flowPointer;
try
{
this.flowPointer = 0;
while (canMoveToNextStep())
{
try
{
next().initialize();
}
catch (Exception e)
{
throw new IllegalStateException("Error while moving to the next wizard step", e);
}
}
cleanSubsequentStalePages();
}
finally
{
this.flowPointer = currentFlowPointer;
}
} | java | private synchronized void refreshFlow()
{
try
{
initialize();
}
catch (Exception e)
{
throw new IllegalStateException("Error while initializing wizard", e);
}
int currentFlowPointer = this.flowPointer;
try
{
this.flowPointer = 0;
while (canMoveToNextStep())
{
try
{
next().initialize();
}
catch (Exception e)
{
throw new IllegalStateException("Error while moving to the next wizard step", e);
}
}
cleanSubsequentStalePages();
}
finally
{
this.flowPointer = currentFlowPointer;
}
} | [
"private",
"synchronized",
"void",
"refreshFlow",
"(",
")",
"{",
"try",
"{",
"initialize",
"(",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"throw",
"new",
"IllegalStateException",
"(",
"\"Error while initializing wizard\"",
",",
"e",
")",
";",
... | Refreshes the current flow so it's possible to eagerly fetch all the steps | [
"Refreshes",
"the",
"current",
"flow",
"so",
"it",
"s",
"possible",
"to",
"eagerly",
"fetch",
"all",
"the",
"steps"
] | train | https://github.com/forge/core/blob/e140eb03bbe2b3409478ad70c86c3edbef6d9a0c/ui/impl/src/main/java/org/jboss/forge/addon/ui/impl/controller/WizardCommandControllerImpl.java#L92-L123 |
joniles/mpxj | src/main/java/net/sf/mpxj/ResourceAssignment.java | ResourceAssignment.setFinish | public void setFinish(int index, Date value)
{
set(selectField(AssignmentFieldLists.CUSTOM_FINISH, index), value);
} | java | public void setFinish(int index, Date value)
{
set(selectField(AssignmentFieldLists.CUSTOM_FINISH, index), value);
} | [
"public",
"void",
"setFinish",
"(",
"int",
"index",
",",
"Date",
"value",
")",
"{",
"set",
"(",
"selectField",
"(",
"AssignmentFieldLists",
".",
"CUSTOM_FINISH",
",",
"index",
")",
",",
"value",
")",
";",
"}"
] | Set a finish value.
@param index finish index (1-10)
@param value finish value | [
"Set",
"a",
"finish",
"value",
"."
] | train | https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/ResourceAssignment.java#L1562-L1565 |
astrapi69/jaulp-wicket | jaulp-wicket-base/src/main/java/de/alpharogroup/wicket/base/util/WicketImageExtensions.java | WicketImageExtensions.getImage | public static Image getImage(final String wicketId, final String contentType, final byte[] data)
{
return new Image(wicketId, new DatabaseImageResource(contentType, data));
} | java | public static Image getImage(final String wicketId, final String contentType, final byte[] data)
{
return new Image(wicketId, new DatabaseImageResource(contentType, data));
} | [
"public",
"static",
"Image",
"getImage",
"(",
"final",
"String",
"wicketId",
",",
"final",
"String",
"contentType",
",",
"final",
"byte",
"[",
"]",
"data",
")",
"{",
"return",
"new",
"Image",
"(",
"wicketId",
",",
"new",
"DatabaseImageResource",
"(",
"conten... | Gets the image.
@param wicketId
the id from the image for the html template.
@param contentType
the content type
@param data
the data
@return the image | [
"Gets",
"the",
"image",
"."
] | train | https://github.com/astrapi69/jaulp-wicket/blob/85d74368d00abd9bb97659b5794e38c0f8a013d4/jaulp-wicket-base/src/main/java/de/alpharogroup/wicket/base/util/WicketImageExtensions.java#L41-L44 |
facebook/fresco | drawee/src/main/java/com/facebook/drawee/view/SimpleDraweeView.java | SimpleDraweeView.setActualImageResource | public void setActualImageResource(@DrawableRes int resourceId, @Nullable Object callerContext) {
setImageURI(UriUtil.getUriForResourceId(resourceId), callerContext);
} | java | public void setActualImageResource(@DrawableRes int resourceId, @Nullable Object callerContext) {
setImageURI(UriUtil.getUriForResourceId(resourceId), callerContext);
} | [
"public",
"void",
"setActualImageResource",
"(",
"@",
"DrawableRes",
"int",
"resourceId",
",",
"@",
"Nullable",
"Object",
"callerContext",
")",
"{",
"setImageURI",
"(",
"UriUtil",
".",
"getUriForResourceId",
"(",
"resourceId",
")",
",",
"callerContext",
")",
";",
... | Sets the actual image resource to the given resource ID.
Similar to {@link #setImageResource(int)}, this sets the displayed image to the given resource.
However, {@link #setImageResource(int)} bypasses all Drawee functionality and makes the view
act as a normal {@link android.widget.ImageView}, whereas this method keeps all of the
Drawee functionality, including the {@link com.facebook.drawee.interfaces.DraweeHierarchy}.
@param resourceId the resource ID to use.
@param callerContext caller context | [
"Sets",
"the",
"actual",
"image",
"resource",
"to",
"the",
"given",
"resource",
"ID",
"."
] | train | https://github.com/facebook/fresco/blob/0b85879d51c5036d5e46e627a6651afefc0b971a/drawee/src/main/java/com/facebook/drawee/view/SimpleDraweeView.java#L208-L210 |
TheHortonMachine/hortonmachine | gears/src/main/java/org/hortonmachine/gears/io/dxfdwg/libs/dwg/utils/ByteUtils.java | ByteUtils.bytesToInt | public static final int bytesToInt( byte[] data, int[] offset ) {
/**
* TODO: We use network-order within OceanStore, but temporarily
* supporting intel-order to work with some JNI code until JNI code is
* set to interoperate with network-order.
*/
int result = 0;
for( int i = 0; i < SIZE_INT; ++i ) {
result <<= 8;
result |= byteToUnsignedInt(data[offset[0]++]);
}
return result;
} | java | public static final int bytesToInt( byte[] data, int[] offset ) {
/**
* TODO: We use network-order within OceanStore, but temporarily
* supporting intel-order to work with some JNI code until JNI code is
* set to interoperate with network-order.
*/
int result = 0;
for( int i = 0; i < SIZE_INT; ++i ) {
result <<= 8;
result |= byteToUnsignedInt(data[offset[0]++]);
}
return result;
} | [
"public",
"static",
"final",
"int",
"bytesToInt",
"(",
"byte",
"[",
"]",
"data",
",",
"int",
"[",
"]",
"offset",
")",
"{",
"/**\n * TODO: We use network-order within OceanStore, but temporarily\n * supporting intel-order to work with some JNI code until JNI code is\... | Return the <code>int</code> represented by the bytes in
<code>data</code> staring at offset <code>offset[0]</code>.
@param data the array from which to read
@param offset A single element array whose first element is the index in
data from which to begin reading on function entry, and which on
function exit has been incremented by the number of bytes read.
@return the value of the <code>int</code> decoded | [
"Return",
"the",
"<code",
">",
"int<",
"/",
"code",
">",
"represented",
"by",
"the",
"bytes",
"in",
"<code",
">",
"data<",
"/",
"code",
">",
"staring",
"at",
"offset",
"<code",
">",
"offset",
"[",
"0",
"]",
"<",
"/",
"code",
">",
"."
] | train | https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/org/hortonmachine/gears/io/dxfdwg/libs/dwg/utils/ByteUtils.java#L49-L63 |
jlinn/quartz-redis-jobstore | src/main/java/net/joelinn/quartz/jobstore/AbstractRedisStorage.java | AbstractRedisStorage.replaceTrigger | public boolean replaceTrigger(TriggerKey triggerKey, OperableTrigger newTrigger, T jedis) throws JobPersistenceException, ClassNotFoundException {
OperableTrigger oldTrigger = retrieveTrigger(triggerKey, jedis);
boolean found = oldTrigger != null;
if(found){
if(!oldTrigger.getJobKey().equals(newTrigger.getJobKey())){
throw new JobPersistenceException("New trigger is not related to the same job as the old trigger.");
}
removeTrigger(triggerKey, false, jedis);
storeTrigger(newTrigger, false, jedis);
}
return found;
} | java | public boolean replaceTrigger(TriggerKey triggerKey, OperableTrigger newTrigger, T jedis) throws JobPersistenceException, ClassNotFoundException {
OperableTrigger oldTrigger = retrieveTrigger(triggerKey, jedis);
boolean found = oldTrigger != null;
if(found){
if(!oldTrigger.getJobKey().equals(newTrigger.getJobKey())){
throw new JobPersistenceException("New trigger is not related to the same job as the old trigger.");
}
removeTrigger(triggerKey, false, jedis);
storeTrigger(newTrigger, false, jedis);
}
return found;
} | [
"public",
"boolean",
"replaceTrigger",
"(",
"TriggerKey",
"triggerKey",
",",
"OperableTrigger",
"newTrigger",
",",
"T",
"jedis",
")",
"throws",
"JobPersistenceException",
",",
"ClassNotFoundException",
"{",
"OperableTrigger",
"oldTrigger",
"=",
"retrieveTrigger",
"(",
"... | Remove (delete) the <code>{@link org.quartz.Trigger}</code> with the
given key, and store the new given one - which must be associated
with the same job.
@param triggerKey the key of the trigger to be replaced
@param newTrigger the replacement trigger
@param jedis a thread-safe Redis connection
@return true if the target trigger was found, removed, and replaced | [
"Remove",
"(",
"delete",
")",
"the",
"<code",
">",
"{"
] | train | https://github.com/jlinn/quartz-redis-jobstore/blob/be9a52ee776d8a09866fe99fd9718bc13a0cb992/src/main/java/net/joelinn/quartz/jobstore/AbstractRedisStorage.java#L258-L269 |
google/closure-compiler | src/com/google/javascript/refactoring/Matchers.java | Matchers.functionCall | public static Matcher functionCall(final String name) {
return new Matcher() {
@Override
public boolean matches(Node node, NodeMetadata metadata) {
// TODO(mknichel): Handle the case when functions are applied through .call or .apply.
return node.isCall() && propertyAccess(name).matches(node.getFirstChild(), metadata);
}
};
} | java | public static Matcher functionCall(final String name) {
return new Matcher() {
@Override
public boolean matches(Node node, NodeMetadata metadata) {
// TODO(mknichel): Handle the case when functions are applied through .call or .apply.
return node.isCall() && propertyAccess(name).matches(node.getFirstChild(), metadata);
}
};
} | [
"public",
"static",
"Matcher",
"functionCall",
"(",
"final",
"String",
"name",
")",
"{",
"return",
"new",
"Matcher",
"(",
")",
"{",
"@",
"Override",
"public",
"boolean",
"matches",
"(",
"Node",
"node",
",",
"NodeMetadata",
"metadata",
")",
"{",
"// TODO(mkni... | Returns a Matcher that matches all nodes that are function calls that match the provided name.
@param name The name of the function to match. For non-static functions, this must be the fully
qualified name that includes the type of the object. For instance: {@code
ns.AppContext.prototype.get} will match {@code appContext.get} and {@code this.get} when
called from the AppContext class. | [
"Returns",
"a",
"Matcher",
"that",
"matches",
"all",
"nodes",
"that",
"are",
"function",
"calls",
"that",
"match",
"the",
"provided",
"name",
"."
] | train | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/refactoring/Matchers.java#L178-L186 |
landawn/AbacusUtil | src/com/landawn/abacus/util/StringUtil.java | StringUtil.removeStart | public static String removeStart(final String str, final String removeStr) {
if (N.isNullOrEmpty(str) || N.isNullOrEmpty(removeStr)) {
return str;
}
if (str.startsWith(removeStr)) {
return str.substring(removeStr.length());
}
return str;
} | java | public static String removeStart(final String str, final String removeStr) {
if (N.isNullOrEmpty(str) || N.isNullOrEmpty(removeStr)) {
return str;
}
if (str.startsWith(removeStr)) {
return str.substring(removeStr.length());
}
return str;
} | [
"public",
"static",
"String",
"removeStart",
"(",
"final",
"String",
"str",
",",
"final",
"String",
"removeStr",
")",
"{",
"if",
"(",
"N",
".",
"isNullOrEmpty",
"(",
"str",
")",
"||",
"N",
".",
"isNullOrEmpty",
"(",
"removeStr",
")",
")",
"{",
"return",
... | <p>
Removes a substring only if it is at the beginning of a source string,
otherwise returns the source string.
</p>
<p>
A {@code null} source string will return {@code null}. An empty ("")
source string will return the empty string. A {@code null} search string
will return the source string.
</p>
<pre>
N.removeStart(null, *) = null
N.removeStart("", *) = ""
N.removeStart(*, null) = *
N.removeStart("www.domain.com", "www.") = "domain.com"
N.removeStart("domain.com", "www.") = "domain.com"
N.removeStart("www.domain.com", "domain") = "www.domain.com"
N.removeStart("abc", "") = "abc"
</pre>
@param str
the source String to search, may be null
@param removeStr
the String to search for and remove, may be null
@return the substring with the string removed if found, {@code null} if
null String input
@since 2.1 | [
"<p",
">",
"Removes",
"a",
"substring",
"only",
"if",
"it",
"is",
"at",
"the",
"beginning",
"of",
"a",
"source",
"string",
"otherwise",
"returns",
"the",
"source",
"string",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/landawn/AbacusUtil/blob/544b7720175d15e9329f83dd22a8cc5fa4515e12/src/com/landawn/abacus/util/StringUtil.java#L1147-L1157 |
looly/hutool | hutool-core/src/main/java/cn/hutool/core/io/BufferUtil.java | BufferUtil.create | public static ByteBuffer create(CharSequence data, Charset charset) {
return create(StrUtil.bytes(data, charset));
} | java | public static ByteBuffer create(CharSequence data, Charset charset) {
return create(StrUtil.bytes(data, charset));
} | [
"public",
"static",
"ByteBuffer",
"create",
"(",
"CharSequence",
"data",
",",
"Charset",
"charset",
")",
"{",
"return",
"create",
"(",
"StrUtil",
".",
"bytes",
"(",
"data",
",",
"charset",
")",
")",
";",
"}"
] | 从字符串创建新Buffer
@param data 数据
@param charset 编码
@return {@link ByteBuffer}
@since 4.5.0 | [
"从字符串创建新Buffer"
] | train | https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/io/BufferUtil.java#L237-L239 |
opencb/biodata | biodata-tools/src/main/java/org/opencb/biodata/tools/feature/WigUtils.java | WigUtils.getStart | public static int getStart(String headerLine) throws InvalidObjectException {
String str = getHeaderInfo("start", headerLine);
if (str == null) {
throw new InvalidObjectException("WigFile format, it could not find 'start' in the header line");
}
return Integer.parseInt(str);
} | java | public static int getStart(String headerLine) throws InvalidObjectException {
String str = getHeaderInfo("start", headerLine);
if (str == null) {
throw new InvalidObjectException("WigFile format, it could not find 'start' in the header line");
}
return Integer.parseInt(str);
} | [
"public",
"static",
"int",
"getStart",
"(",
"String",
"headerLine",
")",
"throws",
"InvalidObjectException",
"{",
"String",
"str",
"=",
"getHeaderInfo",
"(",
"\"start\"",
",",
"headerLine",
")",
";",
"if",
"(",
"str",
"==",
"null",
")",
"{",
"throw",
"new",
... | Extract the 'start' value from the given Wig header line.
@param headerLine Header line where to look for the 'start'
@return Start value | [
"Extract",
"the",
"start",
"value",
"from",
"the",
"given",
"Wig",
"header",
"line",
"."
] | train | https://github.com/opencb/biodata/blob/21b3d51d71f578efab908422aca4bab7a73097b1/biodata-tools/src/main/java/org/opencb/biodata/tools/feature/WigUtils.java#L169-L175 |
RKumsher/utils | src/main/java/com/github/rkumsher/date/RandomDateUtils.java | RandomDateUtils.randomInstant | public static Instant randomInstant(Instant startInclusive, Instant endExclusive) {
checkArgument(startInclusive != null, "Start must be non-null");
checkArgument(endExclusive != null, "End must be non-null");
checkArgument(!startInclusive.isAfter(endExclusive), "End must be on or after start");
checkArgument(
startInclusive.equals(MIN_INSTANT) || startInclusive.isAfter(MIN_INSTANT),
"Start must be on or after %s",
MIN_INSTANT);
checkArgument(
endExclusive.equals(MAX_INSTANT) || endExclusive.isBefore(MAX_INSTANT),
"End must be on or before %s",
MAX_INSTANT);
return Instant.ofEpochMilli(
RandomUtils.nextLong(startInclusive.toEpochMilli(), endExclusive.toEpochMilli()));
} | java | public static Instant randomInstant(Instant startInclusive, Instant endExclusive) {
checkArgument(startInclusive != null, "Start must be non-null");
checkArgument(endExclusive != null, "End must be non-null");
checkArgument(!startInclusive.isAfter(endExclusive), "End must be on or after start");
checkArgument(
startInclusive.equals(MIN_INSTANT) || startInclusive.isAfter(MIN_INSTANT),
"Start must be on or after %s",
MIN_INSTANT);
checkArgument(
endExclusive.equals(MAX_INSTANT) || endExclusive.isBefore(MAX_INSTANT),
"End must be on or before %s",
MAX_INSTANT);
return Instant.ofEpochMilli(
RandomUtils.nextLong(startInclusive.toEpochMilli(), endExclusive.toEpochMilli()));
} | [
"public",
"static",
"Instant",
"randomInstant",
"(",
"Instant",
"startInclusive",
",",
"Instant",
"endExclusive",
")",
"{",
"checkArgument",
"(",
"startInclusive",
"!=",
"null",
",",
"\"Start must be non-null\"",
")",
";",
"checkArgument",
"(",
"endExclusive",
"!=",
... | Returns a random {@link Instant} within the specified range.
@param startInclusive the earliest {@link Instant} that can be returned
@param endExclusive the upper bound (not included)
@return the random {@link Instant}
@throws IllegalArgumentException if startInclusive or endExclusive are null or if endExclusive
is earlier than startInclusive | [
"Returns",
"a",
"random",
"{",
"@link",
"Instant",
"}",
"within",
"the",
"specified",
"range",
"."
] | train | https://github.com/RKumsher/utils/blob/fcdb190569cd0288249bf4b46fd418f8c01d1caf/src/main/java/com/github/rkumsher/date/RandomDateUtils.java#L454-L468 |
kirgor/enklib | rest/src/main/java/com/kirgor/enklib/rest/RESTClient.java | RESTClient.deleteWithListResult | public <T> EntityResponse<List<T>> deleteWithListResult(Class<T> entityClass, String path, Map<String, String> headers) throws IOException, RESTException {
return parseListEntityResponse(entityClass, getHttpResponse(new HttpDelete(baseUrl + path), headers));
} | java | public <T> EntityResponse<List<T>> deleteWithListResult(Class<T> entityClass, String path, Map<String, String> headers) throws IOException, RESTException {
return parseListEntityResponse(entityClass, getHttpResponse(new HttpDelete(baseUrl + path), headers));
} | [
"public",
"<",
"T",
">",
"EntityResponse",
"<",
"List",
"<",
"T",
">",
">",
"deleteWithListResult",
"(",
"Class",
"<",
"T",
">",
"entityClass",
",",
"String",
"path",
",",
"Map",
"<",
"String",
",",
"String",
">",
"headers",
")",
"throws",
"IOException",... | Performs DELETE request, while expected response entity is a list of specified type.
@param entityClass Class, which contains expected response entity fields.
@param path Request path.
@param headers Map of HTTP request headers.
@param <T> Type of class, which contains expected response entity fields.
@throws IOException If error during HTTP connection or entity parsing occurs.
@throws RESTException If HTTP response code is non OK. | [
"Performs",
"DELETE",
"request",
"while",
"expected",
"response",
"entity",
"is",
"a",
"list",
"of",
"specified",
"type",
"."
] | train | https://github.com/kirgor/enklib/blob/8a24db296dc43db5d8fe509cf64ace0a0c7be8f2/rest/src/main/java/com/kirgor/enklib/rest/RESTClient.java#L554-L556 |
jparsec/jparsec | jparsec/src/main/java/org/jparsec/ParseContext.java | ParseContext.enableTrace | final void enableTrace(final String rootName) {
this.trace = new ParserTrace() {
private TreeNode current = new TreeNode(rootName, getIndex());
@Override public void push(String name) {
this.current = current.addChild(name, getIndex());
}
@Override public void pop() {
current.setEndIndex(getIndex());
this.current = current.parent();
}
@Override public TreeNode getCurrentNode() {
return current;
}
@Override public void setCurrentResult(Object result) {
current.setResult(result);
}
@Override public TreeNode getLatestChild() {
return current.latestChild;
}
@Override public void setLatestChild(TreeNode latest) {
checkState(latest == null || latest.parent() == current,
"Trying to set a child node not owned by the parent node");
current.latestChild = latest;
}
@Override public void startFresh(ParseContext context) {
context.enableTrace(rootName);
}
@Override public void setStateAs(ParserTrace that) {
current = that.getCurrentNode();
}
};
} | java | final void enableTrace(final String rootName) {
this.trace = new ParserTrace() {
private TreeNode current = new TreeNode(rootName, getIndex());
@Override public void push(String name) {
this.current = current.addChild(name, getIndex());
}
@Override public void pop() {
current.setEndIndex(getIndex());
this.current = current.parent();
}
@Override public TreeNode getCurrentNode() {
return current;
}
@Override public void setCurrentResult(Object result) {
current.setResult(result);
}
@Override public TreeNode getLatestChild() {
return current.latestChild;
}
@Override public void setLatestChild(TreeNode latest) {
checkState(latest == null || latest.parent() == current,
"Trying to set a child node not owned by the parent node");
current.latestChild = latest;
}
@Override public void startFresh(ParseContext context) {
context.enableTrace(rootName);
}
@Override public void setStateAs(ParserTrace that) {
current = that.getCurrentNode();
}
};
} | [
"final",
"void",
"enableTrace",
"(",
"final",
"String",
"rootName",
")",
"{",
"this",
".",
"trace",
"=",
"new",
"ParserTrace",
"(",
")",
"{",
"private",
"TreeNode",
"current",
"=",
"new",
"TreeNode",
"(",
"rootName",
",",
"getIndex",
"(",
")",
")",
";",
... | Enables parse tree tracing with {@code rootName} as the name of the root node. | [
"Enables",
"parse",
"tree",
"tracing",
"with",
"{"
] | train | https://github.com/jparsec/jparsec/blob/df1280259f5da9eb5ffc537437569dddba66cb94/jparsec/src/main/java/org/jparsec/ParseContext.java#L347-L379 |
UrielCh/ovh-java-sdk | ovh-java-sdk-price/src/main/java/net/minidev/ovh/api/ApiOvhPrice.java | ApiOvhPrice.hpcspot_consumption_job_reference_GET | public OvhPrice hpcspot_consumption_job_reference_GET(net.minidev.ovh.api.price.hpcspot.consumption.OvhJobEnum reference) throws IOException {
String qPath = "/price/hpcspot/consumption/job/{reference}";
StringBuilder sb = path(qPath, reference);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, OvhPrice.class);
} | java | public OvhPrice hpcspot_consumption_job_reference_GET(net.minidev.ovh.api.price.hpcspot.consumption.OvhJobEnum reference) throws IOException {
String qPath = "/price/hpcspot/consumption/job/{reference}";
StringBuilder sb = path(qPath, reference);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, OvhPrice.class);
} | [
"public",
"OvhPrice",
"hpcspot_consumption_job_reference_GET",
"(",
"net",
".",
"minidev",
".",
"ovh",
".",
"api",
".",
"price",
".",
"hpcspot",
".",
"consumption",
".",
"OvhJobEnum",
"reference",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/pr... | Get the price of a JOB consumption for 1 hour
REST: GET /price/hpcspot/consumption/job/{reference}
@param reference [required] The reference of the JOB consumption | [
"Get",
"the",
"price",
"of",
"a",
"JOB",
"consumption",
"for",
"1",
"hour"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-price/src/main/java/net/minidev/ovh/api/ApiOvhPrice.java#L180-L185 |
stevespringett/Alpine | alpine/src/main/java/alpine/persistence/AlpineQueryManager.java | AlpineQueryManager.hasPermission | public boolean hasPermission(final Team team, String permissionName) {
final Query query = pm.newQuery(Permission.class, "name == :permissionName && teams.contains(:team)");
query.setResult("count(id)");
return (Long) query.execute(permissionName, team) > 0;
} | java | public boolean hasPermission(final Team team, String permissionName) {
final Query query = pm.newQuery(Permission.class, "name == :permissionName && teams.contains(:team)");
query.setResult("count(id)");
return (Long) query.execute(permissionName, team) > 0;
} | [
"public",
"boolean",
"hasPermission",
"(",
"final",
"Team",
"team",
",",
"String",
"permissionName",
")",
"{",
"final",
"Query",
"query",
"=",
"pm",
".",
"newQuery",
"(",
"Permission",
".",
"class",
",",
"\"name == :permissionName && teams.contains(:team)\"",
")",
... | Determines if the specified Team has been assigned the specified permission.
@param team the Team to query
@param permissionName the name of the permission
@return true if the team has the permission assigned, false if not
@since 1.0.0 | [
"Determines",
"if",
"the",
"specified",
"Team",
"has",
"been",
"assigned",
"the",
"specified",
"permission",
"."
] | train | https://github.com/stevespringett/Alpine/blob/6c5ef5e1ba4f38922096f1307d3950c09edb3093/alpine/src/main/java/alpine/persistence/AlpineQueryManager.java#L557-L561 |
wcm-io/wcm-io-handler | media/src/main/java/io/wcm/handler/media/markup/AbstractImageMediaMarkupBuilder.java | AbstractImageMediaMarkupBuilder.setAdditionalAttributes | protected void setAdditionalAttributes(@Nullable HtmlElement<?> mediaElement, @NotNull Media media) {
if (mediaElement == null) {
return;
}
MediaArgs mediaArgs = media.getMediaRequest().getMediaArgs();
for (Entry<String, Object> entry : mediaArgs.getProperties().entrySet()) {
if (StringUtils.equals(entry.getKey(), MediaNameConstants.PROP_CSS_CLASS)) {
mediaElement.addCssClass(entry.getValue().toString());
}
else {
mediaElement.setAttribute(entry.getKey(), entry.getValue().toString());
}
}
} | java | protected void setAdditionalAttributes(@Nullable HtmlElement<?> mediaElement, @NotNull Media media) {
if (mediaElement == null) {
return;
}
MediaArgs mediaArgs = media.getMediaRequest().getMediaArgs();
for (Entry<String, Object> entry : mediaArgs.getProperties().entrySet()) {
if (StringUtils.equals(entry.getKey(), MediaNameConstants.PROP_CSS_CLASS)) {
mediaElement.addCssClass(entry.getValue().toString());
}
else {
mediaElement.setAttribute(entry.getKey(), entry.getValue().toString());
}
}
} | [
"protected",
"void",
"setAdditionalAttributes",
"(",
"@",
"Nullable",
"HtmlElement",
"<",
"?",
">",
"mediaElement",
",",
"@",
"NotNull",
"Media",
"media",
")",
"{",
"if",
"(",
"mediaElement",
"==",
"null",
")",
"{",
"return",
";",
"}",
"MediaArgs",
"mediaArg... | Set additional attributes on the media element from the MediaArgs properties.
@param mediaElement Media element
@param media Media | [
"Set",
"additional",
"attributes",
"on",
"the",
"media",
"element",
"from",
"the",
"MediaArgs",
"properties",
"."
] | train | https://github.com/wcm-io/wcm-io-handler/blob/b0fc1c11a3ceb89efb73826dcfd480d6a00c19af/media/src/main/java/io/wcm/handler/media/markup/AbstractImageMediaMarkupBuilder.java#L102-L115 |
threerings/nenya | core/src/main/java/com/threerings/resource/ResourceManager.java | ResourceManager.loadImage | protected static BufferedImage loadImage (File file, boolean useFastIO)
throws IOException
{
if (file == null) {
return null;
} else if (useFastIO) {
return FastImageIO.read(file);
}
return ImageIO.read(file);
} | java | protected static BufferedImage loadImage (File file, boolean useFastIO)
throws IOException
{
if (file == null) {
return null;
} else if (useFastIO) {
return FastImageIO.read(file);
}
return ImageIO.read(file);
} | [
"protected",
"static",
"BufferedImage",
"loadImage",
"(",
"File",
"file",
",",
"boolean",
"useFastIO",
")",
"throws",
"IOException",
"{",
"if",
"(",
"file",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"else",
"if",
"(",
"useFastIO",
")",
"{",
"re... | Loads an image from the supplied file. Supports {@link FastImageIO} files and formats
supported by {@link ImageIO} and will load the appropriate one based on the useFastIO param. | [
"Loads",
"an",
"image",
"from",
"the",
"supplied",
"file",
".",
"Supports",
"{"
] | train | https://github.com/threerings/nenya/blob/3165a012fd859009db3367f87bd2a5b820cc760a/core/src/main/java/com/threerings/resource/ResourceManager.java#L880-L889 |
CloudSlang/cs-actions | cs-amazon/src/main/java/io/cloudslang/content/amazon/actions/lambda/InvokeLambdaAction.java | InvokeLambdaAction.execute | @Action(name = "Invoke AWS Lambda Function",
outputs = {
@Output(Outputs.RETURN_CODE),
@Output(Outputs.RETURN_RESULT),
@Output(Outputs.EXCEPTION)
},
responses = {
@Response(text = Outputs.SUCCESS, field = Outputs.RETURN_CODE, value = Outputs.SUCCESS_RETURN_CODE,
matchType = MatchType.COMPARE_EQUAL, responseType = ResponseType.RESOLVED),
@Response(text = Outputs.FAILURE, field = Outputs.RETURN_CODE, value = Outputs.FAILURE_RETURN_CODE,
matchType = MatchType.COMPARE_EQUAL, responseType = ResponseType.ERROR)
}
)
public Map<String, String> execute(
@Param(value = IDENTITY, required = true) String identity,
@Param(value = CREDENTIAL, required = true, encrypted = true) String credential,
@Param(value = REGION, required = true) String region,
@Param(value = PROXY_HOST) String proxyHost,
@Param(value = PROXY_PORT) String proxyPort,
@Param(value = PROXY_USERNAME) String proxyUsername,
@Param(value = PROXY_PASSWORD) String proxyPassword,
@Param(value = FUNCTION_NAME, required = true) String function,
@Param(value = FUNCTION_QUALIFIER) String qualifier,
@Param(value = FUNCTION_PAYLOAD) String payload,
@Param(value = CONNECT_TIMEOUT) String connectTimeoutMs,
@Param(value = EXECUTION_TIMEOUT) String execTimeoutMs) {
proxyPort = defaultIfEmpty(proxyPort, DefaultValues.PROXY_PORT);
connectTimeoutMs = defaultIfEmpty(connectTimeoutMs, DefaultValues.CONNECT_TIMEOUT);
execTimeoutMs = defaultIfBlank(execTimeoutMs, DefaultValues.EXEC_TIMEOUT);
qualifier = defaultIfBlank(qualifier, DefaultValues.DEFAULT_FUNCTION_QUALIFIER);
ClientConfiguration lambdaClientConf = AmazonWebServiceClientUtil.getClientConfiguration(proxyHost, proxyPort, proxyUsername, proxyPassword, connectTimeoutMs, execTimeoutMs);
AWSLambdaAsyncClient client = (AWSLambdaAsyncClient) AWSLambdaAsyncClientBuilder.standard()
.withClientConfiguration(lambdaClientConf)
.withCredentials(new AWSStaticCredentialsProvider(new BasicAWSCredentials(identity, credential)))
.withRegion(region)
.build();
InvokeRequest invokeRequest = new InvokeRequest()
.withFunctionName(function)
.withQualifier(qualifier)
.withPayload(payload)
.withSdkClientExecutionTimeout(Integer.parseInt(execTimeoutMs));
try {
InvokeResult invokeResult = client.invoke(invokeRequest);
return OutputUtilities.getSuccessResultsMap(new String(invokeResult.getPayload().array()));
} catch (Exception e) {
return OutputUtilities.getFailureResultsMap(e);
}
} | java | @Action(name = "Invoke AWS Lambda Function",
outputs = {
@Output(Outputs.RETURN_CODE),
@Output(Outputs.RETURN_RESULT),
@Output(Outputs.EXCEPTION)
},
responses = {
@Response(text = Outputs.SUCCESS, field = Outputs.RETURN_CODE, value = Outputs.SUCCESS_RETURN_CODE,
matchType = MatchType.COMPARE_EQUAL, responseType = ResponseType.RESOLVED),
@Response(text = Outputs.FAILURE, field = Outputs.RETURN_CODE, value = Outputs.FAILURE_RETURN_CODE,
matchType = MatchType.COMPARE_EQUAL, responseType = ResponseType.ERROR)
}
)
public Map<String, String> execute(
@Param(value = IDENTITY, required = true) String identity,
@Param(value = CREDENTIAL, required = true, encrypted = true) String credential,
@Param(value = REGION, required = true) String region,
@Param(value = PROXY_HOST) String proxyHost,
@Param(value = PROXY_PORT) String proxyPort,
@Param(value = PROXY_USERNAME) String proxyUsername,
@Param(value = PROXY_PASSWORD) String proxyPassword,
@Param(value = FUNCTION_NAME, required = true) String function,
@Param(value = FUNCTION_QUALIFIER) String qualifier,
@Param(value = FUNCTION_PAYLOAD) String payload,
@Param(value = CONNECT_TIMEOUT) String connectTimeoutMs,
@Param(value = EXECUTION_TIMEOUT) String execTimeoutMs) {
proxyPort = defaultIfEmpty(proxyPort, DefaultValues.PROXY_PORT);
connectTimeoutMs = defaultIfEmpty(connectTimeoutMs, DefaultValues.CONNECT_TIMEOUT);
execTimeoutMs = defaultIfBlank(execTimeoutMs, DefaultValues.EXEC_TIMEOUT);
qualifier = defaultIfBlank(qualifier, DefaultValues.DEFAULT_FUNCTION_QUALIFIER);
ClientConfiguration lambdaClientConf = AmazonWebServiceClientUtil.getClientConfiguration(proxyHost, proxyPort, proxyUsername, proxyPassword, connectTimeoutMs, execTimeoutMs);
AWSLambdaAsyncClient client = (AWSLambdaAsyncClient) AWSLambdaAsyncClientBuilder.standard()
.withClientConfiguration(lambdaClientConf)
.withCredentials(new AWSStaticCredentialsProvider(new BasicAWSCredentials(identity, credential)))
.withRegion(region)
.build();
InvokeRequest invokeRequest = new InvokeRequest()
.withFunctionName(function)
.withQualifier(qualifier)
.withPayload(payload)
.withSdkClientExecutionTimeout(Integer.parseInt(execTimeoutMs));
try {
InvokeResult invokeResult = client.invoke(invokeRequest);
return OutputUtilities.getSuccessResultsMap(new String(invokeResult.getPayload().array()));
} catch (Exception e) {
return OutputUtilities.getFailureResultsMap(e);
}
} | [
"@",
"Action",
"(",
"name",
"=",
"\"Invoke AWS Lambda Function\"",
",",
"outputs",
"=",
"{",
"@",
"Output",
"(",
"Outputs",
".",
"RETURN_CODE",
")",
",",
"@",
"Output",
"(",
"Outputs",
".",
"RETURN_RESULT",
")",
",",
"@",
"Output",
"(",
"Outputs",
".",
"... | Invokes an AWS Lambda Function in sync mode using AWS Java SDK
@param identity Access key associated with your Amazon AWS or IAM account.
Example: "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY"
@param credential Secret access key ID associated with your Amazon AWS or IAM account.
@param proxyHost Optional - proxy server used to connect to Amazon API. If empty no proxy will be used.
Default: ""
@param proxyPort Optional - proxy server port. You must either specify values for both proxyHost and
proxyPort inputs or leave them both empty.
Default: ""
@param proxyUsername Optional - proxy server user name.
Default: ""
@param proxyPassword Optional - proxy server password associated with the proxyUsername input value.
Default: ""
@param function Lambda function name to call
Example: "helloWord"
@param qualifier Optional - Lambda function version or alias
Example: ":1"
Default: "$LATEST"
@param payload Optional - Lambda function payload in JSON format
Example: "{"key1":"value1", "key1":"value2"}"
Default: null
@return A map with strings as keys and strings as values that contains: outcome of the action, returnCode of the
operation, or failure message and the exception if there is one | [
"Invokes",
"an",
"AWS",
"Lambda",
"Function",
"in",
"sync",
"mode",
"using",
"AWS",
"Java",
"SDK"
] | train | https://github.com/CloudSlang/cs-actions/blob/9a1be1e99ad88286a6c153d5f2275df6ae1a57a1/cs-amazon/src/main/java/io/cloudslang/content/amazon/actions/lambda/InvokeLambdaAction.java#L71-L123 |
phax/ph-commons | ph-commons/src/main/java/com/helger/commons/text/codepoint/CodepointHelper.java | CodepointHelper.verifyNot | public static void verifyNot (final ICodepointIterator aIter, @Nonnull final ECodepointProfile eProfile)
{
final CodepointIteratorRestricted rci = aIter.restrict (eProfile.getFilter (), false, true);
while (rci.hasNext ())
rci.next ();
} | java | public static void verifyNot (final ICodepointIterator aIter, @Nonnull final ECodepointProfile eProfile)
{
final CodepointIteratorRestricted rci = aIter.restrict (eProfile.getFilter (), false, true);
while (rci.hasNext ())
rci.next ();
} | [
"public",
"static",
"void",
"verifyNot",
"(",
"final",
"ICodepointIterator",
"aIter",
",",
"@",
"Nonnull",
"final",
"ECodepointProfile",
"eProfile",
")",
"{",
"final",
"CodepointIteratorRestricted",
"rci",
"=",
"aIter",
".",
"restrict",
"(",
"eProfile",
".",
"getF... | Verifies a sequence of codepoints using the specified profile
@param aIter
Codepoint iterator
@param eProfile
profile to use | [
"Verifies",
"a",
"sequence",
"of",
"codepoints",
"using",
"the",
"specified",
"profile"
] | train | https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-commons/src/main/java/com/helger/commons/text/codepoint/CodepointHelper.java#L818-L823 |
kiegroup/drools | drools-decisiontables/src/main/java/org/drools/decisiontable/parser/RuleSheetParserUtil.java | RuleSheetParserUtil.getImportList | public static List<Import> getImportList(final List<String> importCells) {
final List<Import> importList = new ArrayList<Import>();
if ( importCells == null ) return importList;
for( String importCell: importCells ){
final StringTokenizer tokens = new StringTokenizer( importCell, "," );
while ( tokens.hasMoreTokens() ) {
final Import imp = new Import();
imp.setClassName( tokens.nextToken().trim() );
importList.add( imp );
}
}
return importList;
} | java | public static List<Import> getImportList(final List<String> importCells) {
final List<Import> importList = new ArrayList<Import>();
if ( importCells == null ) return importList;
for( String importCell: importCells ){
final StringTokenizer tokens = new StringTokenizer( importCell, "," );
while ( tokens.hasMoreTokens() ) {
final Import imp = new Import();
imp.setClassName( tokens.nextToken().trim() );
importList.add( imp );
}
}
return importList;
} | [
"public",
"static",
"List",
"<",
"Import",
">",
"getImportList",
"(",
"final",
"List",
"<",
"String",
">",
"importCells",
")",
"{",
"final",
"List",
"<",
"Import",
">",
"importList",
"=",
"new",
"ArrayList",
"<",
"Import",
">",
"(",
")",
";",
"if",
"("... | Create a list of Import model objects from cell contents.
@param importCells The cells containing text for all the classes to import.
@return A list of Import classes, which can be added to the ruleset. | [
"Create",
"a",
"list",
"of",
"Import",
"model",
"objects",
"from",
"cell",
"contents",
"."
] | train | https://github.com/kiegroup/drools/blob/22b0275d6dbe93070b8090948502cf46eda543c4/drools-decisiontables/src/main/java/org/drools/decisiontable/parser/RuleSheetParserUtil.java#L52-L65 |
belaban/JGroups | src/org/jgroups/util/Bits.java | Bits.readInt | public static int readInt(ByteBuffer buf) {
byte len=buf.get();
if(len == 0)
return 0;
return makeInt(buf, len);
} | java | public static int readInt(ByteBuffer buf) {
byte len=buf.get();
if(len == 0)
return 0;
return makeInt(buf, len);
} | [
"public",
"static",
"int",
"readInt",
"(",
"ByteBuffer",
"buf",
")",
"{",
"byte",
"len",
"=",
"buf",
".",
"get",
"(",
")",
";",
"if",
"(",
"len",
"==",
"0",
")",
"return",
"0",
";",
"return",
"makeInt",
"(",
"buf",
",",
"len",
")",
";",
"}"
] | Reads an int from a buffer.
@param buf the buffer
@return the int read from the buffer | [
"Reads",
"an",
"int",
"from",
"a",
"buffer",
"."
] | train | https://github.com/belaban/JGroups/blob/bd3ca786aa57fed41dfbc10a94b1281e388be03b/src/org/jgroups/util/Bits.java#L137-L142 |
mercadopago/dx-java | src/main/java/com/mercadopago/core/MPCache.java | MPCache.getMapCache | private static HashMap<String, MPApiResponse> getMapCache() {
if (cache == null || cache.get() == null) {
cache = new SoftReference(new HashMap<String, MPApiResponse>());
}
return cache.get();
} | java | private static HashMap<String, MPApiResponse> getMapCache() {
if (cache == null || cache.get() == null) {
cache = new SoftReference(new HashMap<String, MPApiResponse>());
}
return cache.get();
} | [
"private",
"static",
"HashMap",
"<",
"String",
",",
"MPApiResponse",
">",
"getMapCache",
"(",
")",
"{",
"if",
"(",
"cache",
"==",
"null",
"||",
"cache",
".",
"get",
"(",
")",
"==",
"null",
")",
"{",
"cache",
"=",
"new",
"SoftReference",
"(",
"new",
"... | Auxiliar method. It returns a Map with cached responses from the soft references variable.
If the map does not exists, its instantiated and then returned.
@return HashMap object | [
"Auxiliar",
"method",
".",
"It",
"returns",
"a",
"Map",
"with",
"cached",
"responses",
"from",
"the",
"soft",
"references",
"variable",
".",
"If",
"the",
"map",
"does",
"not",
"exists",
"its",
"instantiated",
"and",
"then",
"returned",
"."
] | train | https://github.com/mercadopago/dx-java/blob/9df65a6bfb4db0c1fddd7699a5b109643961b03f/src/main/java/com/mercadopago/core/MPCache.java#L22-L27 |
ocelotds/ocelot | ocelot-processor/src/main/java/org/ocelotds/processors/visitors/DataServiceVisitorJsBuilder.java | DataServiceVisitorJsBuilder.writeJavadocComment | void writeJavadocComment(String methodComment, Writer writer) throws IOException {
// From javadoc
if (methodComment != null) {
methodComment = methodComment.split("@")[0];
int lastIndexOf = methodComment.lastIndexOf("\n");
if (lastIndexOf >= 0) {
methodComment = methodComment.substring(0, lastIndexOf);
}
String comment = methodComment.replaceAll("\n", CR+TAB2+" *");
writer.append(TAB2).append(" *").append(comment).append(CR);
}
} | java | void writeJavadocComment(String methodComment, Writer writer) throws IOException {
// From javadoc
if (methodComment != null) {
methodComment = methodComment.split("@")[0];
int lastIndexOf = methodComment.lastIndexOf("\n");
if (lastIndexOf >= 0) {
methodComment = methodComment.substring(0, lastIndexOf);
}
String comment = methodComment.replaceAll("\n", CR+TAB2+" *");
writer.append(TAB2).append(" *").append(comment).append(CR);
}
} | [
"void",
"writeJavadocComment",
"(",
"String",
"methodComment",
",",
"Writer",
"writer",
")",
"throws",
"IOException",
"{",
"// From javadoc\r",
"if",
"(",
"methodComment",
"!=",
"null",
")",
"{",
"methodComment",
"=",
"methodComment",
".",
"split",
"(",
"\"@\"",
... | write js documentation from javadoc
@param methodComment
@param writer
@throws IOException | [
"write",
"js",
"documentation",
"from",
"javadoc"
] | train | https://github.com/ocelotds/ocelot/blob/5f0ac37afd8fa4dc9f7234a2aac8abbb522128e7/ocelot-processor/src/main/java/org/ocelotds/processors/visitors/DataServiceVisitorJsBuilder.java#L154-L165 |
Erudika/para | para-client/src/main/java/com/erudika/para/client/ParaClient.java | ParaClient.noSpaces | public String noSpaces(String str, String replaceWith) {
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
params.putSingle("string", str);
params.putSingle("replacement", replaceWith);
return getEntity(invokeGet("utils/nospaces", params), String.class);
} | java | public String noSpaces(String str, String replaceWith) {
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
params.putSingle("string", str);
params.putSingle("replacement", replaceWith);
return getEntity(invokeGet("utils/nospaces", params), String.class);
} | [
"public",
"String",
"noSpaces",
"(",
"String",
"str",
",",
"String",
"replaceWith",
")",
"{",
"MultivaluedMap",
"<",
"String",
",",
"String",
">",
"params",
"=",
"new",
"MultivaluedHashMap",
"<>",
"(",
")",
";",
"params",
".",
"putSingle",
"(",
"\"string\"",... | Converts spaces to dashes.
@param str a string with spaces
@param replaceWith a string to replace spaces with
@return a string with dashes | [
"Converts",
"spaces",
"to",
"dashes",
"."
] | train | https://github.com/Erudika/para/blob/5ba096c477042ea7b18e9a0e8b5b1ee0f5bd6ce9/para-client/src/main/java/com/erudika/para/client/ParaClient.java#L1209-L1214 |
QSFT/Doradus | doradus-server/src/main/java/com/dell/doradus/service/spider/SpiderTransaction.java | SpiderTransaction.deleteAllObjectsColumn | public void deleteAllObjectsColumn(TableDefinition tableDef, String objID, int shardNo) {
String rowKey = ALL_OBJECTS_ROW_KEY;
if (shardNo > 0) {
rowKey = shardNo + "/" + ALL_OBJECTS_ROW_KEY;
}
deleteColumn(SpiderService.termsStoreName(tableDef), rowKey, objID);
} | java | public void deleteAllObjectsColumn(TableDefinition tableDef, String objID, int shardNo) {
String rowKey = ALL_OBJECTS_ROW_KEY;
if (shardNo > 0) {
rowKey = shardNo + "/" + ALL_OBJECTS_ROW_KEY;
}
deleteColumn(SpiderService.termsStoreName(tableDef), rowKey, objID);
} | [
"public",
"void",
"deleteAllObjectsColumn",
"(",
"TableDefinition",
"tableDef",
",",
"String",
"objID",
",",
"int",
"shardNo",
")",
"{",
"String",
"rowKey",
"=",
"ALL_OBJECTS_ROW_KEY",
";",
"if",
"(",
"shardNo",
">",
"0",
")",
"{",
"rowKey",
"=",
"shardNo",
... | Delete the "all objects" column with the given object ID from the given table.
@param tableDef {@link TableDefinition} of object's owning table.
@param objID ID of object being deleted.
@param shardNo Shard number of object being deleted.
@see #addAllObjectsColumn(TableDefinition, String, int) | [
"Delete",
"the",
"all",
"objects",
"column",
"with",
"the",
"given",
"object",
"ID",
"from",
"the",
"given",
"table",
"."
] | train | https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-server/src/main/java/com/dell/doradus/service/spider/SpiderTransaction.java#L381-L387 |
xvik/generics-resolver | src/main/java/ru/vyarus/java/generics/resolver/util/GenericsResolutionUtils.java | GenericsResolutionUtils.fillOuterGenerics | public static LinkedHashMap<String, Type> fillOuterGenerics(
final Type type,
final LinkedHashMap<String, Type> generics,
final Map<Class<?>, LinkedHashMap<String, Type>> knownGenerics) {
final LinkedHashMap<String, Type> res;
final Type outer = TypeUtils.getOuter(type);
if (outer == null) {
// not inner class
res = generics;
} else {
final LinkedHashMap<String, Type> outerGenerics;
if (outer instanceof ParameterizedType) {
// outer generics declared in field definition (ignorance required because provided type
// may contain unknown outer generics (Outer<B>.Inner field))
outerGenerics = resolveGenerics(outer, new IgnoreGenericsMap(generics));
} else {
final Class<?> outerType = GenericsUtils.resolveClass(outer, generics);
// either use known generics for outer class or resolve by upper bound
outerGenerics = knownGenerics != null && knownGenerics.containsKey(outerType)
? new LinkedHashMap<String, Type>(knownGenerics.get(outerType))
: resolveRawGenerics(outerType);
}
// class may declare generics with the same name and they must not be overridden
for (TypeVariable var : GenericsUtils.resolveClass(type, generics).getTypeParameters()) {
outerGenerics.remove(var.getName());
}
if (generics instanceof EmptyGenericsMap) {
// if outer map is empty then it was assumed that empty map could be returned
// (outerGenerics could be empty map too)
res = outerGenerics;
} else {
generics.putAll(outerGenerics);
res = generics;
}
}
return res;
} | java | public static LinkedHashMap<String, Type> fillOuterGenerics(
final Type type,
final LinkedHashMap<String, Type> generics,
final Map<Class<?>, LinkedHashMap<String, Type>> knownGenerics) {
final LinkedHashMap<String, Type> res;
final Type outer = TypeUtils.getOuter(type);
if (outer == null) {
// not inner class
res = generics;
} else {
final LinkedHashMap<String, Type> outerGenerics;
if (outer instanceof ParameterizedType) {
// outer generics declared in field definition (ignorance required because provided type
// may contain unknown outer generics (Outer<B>.Inner field))
outerGenerics = resolveGenerics(outer, new IgnoreGenericsMap(generics));
} else {
final Class<?> outerType = GenericsUtils.resolveClass(outer, generics);
// either use known generics for outer class or resolve by upper bound
outerGenerics = knownGenerics != null && knownGenerics.containsKey(outerType)
? new LinkedHashMap<String, Type>(knownGenerics.get(outerType))
: resolveRawGenerics(outerType);
}
// class may declare generics with the same name and they must not be overridden
for (TypeVariable var : GenericsUtils.resolveClass(type, generics).getTypeParameters()) {
outerGenerics.remove(var.getName());
}
if (generics instanceof EmptyGenericsMap) {
// if outer map is empty then it was assumed that empty map could be returned
// (outerGenerics could be empty map too)
res = outerGenerics;
} else {
generics.putAll(outerGenerics);
res = generics;
}
}
return res;
} | [
"public",
"static",
"LinkedHashMap",
"<",
"String",
",",
"Type",
">",
"fillOuterGenerics",
"(",
"final",
"Type",
"type",
",",
"final",
"LinkedHashMap",
"<",
"String",
",",
"Type",
">",
"generics",
",",
"final",
"Map",
"<",
"Class",
"<",
"?",
">",
",",
"L... | Inner class could reference outer class generics and so this generics must be included into class context.
<p>
Outer generics could be included into declaration like {@code Outer<String>.Inner field}. In this case
incoming type should be {@link ParameterizedType} with generified owner.
<p>
When provided type is simply a class (or anything resolvable to class), then outer class generics are resolved
as upper bound (by declaration). Class may declare the same generic name and, in this case, outer generic
will be ignored (as not visible).
<p>
During inlying context resolution, if outer generic is not declared in type we can try to guess it:
we know outer context, and, if outer class is in outer context hierarchy, we could assume that it's actual
parent class and so we could use more specific generics. This will be true for most sane cases (often inner
class is used inside owner), but other cases are still possible (anyway, the chance that inner class will
appear in two different hierarchies of outer class is quite small).
<p>
It is very important to use returned map instead of passed in map because, incoming empty map is always replaced
to avoid modifications of shared empty maps.
@param type context type
@param generics resolved type generics
@param knownGenerics map of known middle generics and possibly known outer context (outer context may contain
outer class generics declarations). May be null.
@return actual generics map (incoming map may be default empty map and in this case it must be replaced) | [
"Inner",
"class",
"could",
"reference",
"outer",
"class",
"generics",
"and",
"so",
"this",
"generics",
"must",
"be",
"included",
"into",
"class",
"context",
".",
"<p",
">",
"Outer",
"generics",
"could",
"be",
"included",
"into",
"declaration",
"like",
"{",
"... | train | https://github.com/xvik/generics-resolver/blob/d7d9d2783265df1178230e8f0b7cb6d853b67a7b/src/main/java/ru/vyarus/java/generics/resolver/util/GenericsResolutionUtils.java#L298-L335 |
alkacon/opencms-core | src/org/opencms/xml/CmsXmlEntityResolver.java | CmsXmlEntityResolver.getCacheKeyForCurrentProject | private String getCacheKeyForCurrentProject(String systemId) {
// check the project
boolean project = (m_cms != null) ? m_cms.getRequestContext().getCurrentProject().isOnlineProject() : false;
// remove opencms:// prefix
if (systemId.startsWith(OPENCMS_SCHEME)) {
systemId = systemId.substring(OPENCMS_SCHEME.length() - 1);
}
return getCacheKey(systemId, project);
} | java | private String getCacheKeyForCurrentProject(String systemId) {
// check the project
boolean project = (m_cms != null) ? m_cms.getRequestContext().getCurrentProject().isOnlineProject() : false;
// remove opencms:// prefix
if (systemId.startsWith(OPENCMS_SCHEME)) {
systemId = systemId.substring(OPENCMS_SCHEME.length() - 1);
}
return getCacheKey(systemId, project);
} | [
"private",
"String",
"getCacheKeyForCurrentProject",
"(",
"String",
"systemId",
")",
"{",
"// check the project",
"boolean",
"project",
"=",
"(",
"m_cms",
"!=",
"null",
")",
"?",
"m_cms",
".",
"getRequestContext",
"(",
")",
".",
"getCurrentProject",
"(",
")",
".... | Returns a cache key for the given system id (filename) based on the status
of the internal CmsObject.<p>
@param systemId the system id (filename) to get the cache key for
@return the cache key for the system id | [
"Returns",
"a",
"cache",
"key",
"for",
"the",
"given",
"system",
"id",
"(",
"filename",
")",
"based",
"on",
"the",
"status",
"of",
"the",
"internal",
"CmsObject",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/xml/CmsXmlEntityResolver.java#L525-L536 |
OpenLiberty/open-liberty | dev/com.ibm.ws.config/src/com/ibm/ws/config/xml/internal/ConfigEvaluator.java | ConfigEvaluator.resolveStringValue | private String resolveStringValue(Object rawValue, ExtendedAttributeDefinition attrDef, EvaluationContext context, boolean ignoreWarnings) throws ConfigEvaluatorException {
if (rawValue instanceof String) {
return processString((String) rawValue, attrDef, context, ignoreWarnings);
} else if (rawValue instanceof ConfigElement) {
// Like convertConfigElementToSingleValue, handle elements with
// attributes: <top><bool attr="ignored">true></bool></top>
return processString(((ConfigElement) rawValue).getElementValue(), attrDef, context, ignoreWarnings);
} else {
throw new IllegalStateException("Attribute type mismatch. Expected String type, got " + rawValue);
}
} | java | private String resolveStringValue(Object rawValue, ExtendedAttributeDefinition attrDef, EvaluationContext context, boolean ignoreWarnings) throws ConfigEvaluatorException {
if (rawValue instanceof String) {
return processString((String) rawValue, attrDef, context, ignoreWarnings);
} else if (rawValue instanceof ConfigElement) {
// Like convertConfigElementToSingleValue, handle elements with
// attributes: <top><bool attr="ignored">true></bool></top>
return processString(((ConfigElement) rawValue).getElementValue(), attrDef, context, ignoreWarnings);
} else {
throw new IllegalStateException("Attribute type mismatch. Expected String type, got " + rawValue);
}
} | [
"private",
"String",
"resolveStringValue",
"(",
"Object",
"rawValue",
",",
"ExtendedAttributeDefinition",
"attrDef",
",",
"EvaluationContext",
"context",
",",
"boolean",
"ignoreWarnings",
")",
"throws",
"ConfigEvaluatorException",
"{",
"if",
"(",
"rawValue",
"instanceof",... | Resolve a raw value to a String, and process it so that it can be evaluated. | [
"Resolve",
"a",
"raw",
"value",
"to",
"a",
"String",
"and",
"process",
"it",
"so",
"that",
"it",
"can",
"be",
"evaluated",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.config/src/com/ibm/ws/config/xml/internal/ConfigEvaluator.java#L916-L926 |
j-a-w-r/jawr-main-repo | jawr/jawr-core/src/main/java/net/jawr/web/resource/bundle/locale/LocaleUtils.java | LocaleUtils.matchesFilter | public static boolean matchesFilter(String key, List<String> filters) {
boolean rets = (null == filters);
if (!rets) {
for (Iterator<String> it = filters.iterator(); it.hasNext() && !rets;)
rets = key.startsWith(it.next());
}
return rets;
} | java | public static boolean matchesFilter(String key, List<String> filters) {
boolean rets = (null == filters);
if (!rets) {
for (Iterator<String> it = filters.iterator(); it.hasNext() && !rets;)
rets = key.startsWith(it.next());
}
return rets;
} | [
"public",
"static",
"boolean",
"matchesFilter",
"(",
"String",
"key",
",",
"List",
"<",
"String",
">",
"filters",
")",
"{",
"boolean",
"rets",
"=",
"(",
"null",
"==",
"filters",
")",
";",
"if",
"(",
"!",
"rets",
")",
"{",
"for",
"(",
"Iterator",
"<",... | Determines whether a key matches any of the set filters.
@param key
the property key
@param filters
@return true if the key matches any of the set filters. | [
"Determines",
"whether",
"a",
"key",
"matches",
"any",
"of",
"the",
"set",
"filters",
"."
] | train | https://github.com/j-a-w-r/jawr-main-repo/blob/5381f6acf461cd2502593c67a77bd6ef9eab848d/jawr/jawr-core/src/main/java/net/jawr/web/resource/bundle/locale/LocaleUtils.java#L55-L63 |
atomix/copycat | server/src/main/java/io/atomix/copycat/server/storage/system/MetaStore.java | MetaStore.deleteConfigurationFromMetadataBuffer | private FileBuffer deleteConfigurationFromMetadataBuffer(File metaFile, FileBuffer buffer)
{
long term = buffer.readLong(0);
int vote = buffer.readInt(8);
buffer.close();
try {
Files.delete(metaFile.toPath());
} catch (IOException ex) {
throw new RuntimeException(String.format("Failed to delete [%s].", metaFile), ex);
}
FileBuffer truncatedBuffer = FileBuffer.allocate(metaFile, 12);
truncatedBuffer.writeLong(0, term).flush();
truncatedBuffer.writeInt(8, vote).flush();
return truncatedBuffer;
} | java | private FileBuffer deleteConfigurationFromMetadataBuffer(File metaFile, FileBuffer buffer)
{
long term = buffer.readLong(0);
int vote = buffer.readInt(8);
buffer.close();
try {
Files.delete(metaFile.toPath());
} catch (IOException ex) {
throw new RuntimeException(String.format("Failed to delete [%s].", metaFile), ex);
}
FileBuffer truncatedBuffer = FileBuffer.allocate(metaFile, 12);
truncatedBuffer.writeLong(0, term).flush();
truncatedBuffer.writeInt(8, vote).flush();
return truncatedBuffer;
} | [
"private",
"FileBuffer",
"deleteConfigurationFromMetadataBuffer",
"(",
"File",
"metaFile",
",",
"FileBuffer",
"buffer",
")",
"{",
"long",
"term",
"=",
"buffer",
".",
"readLong",
"(",
"0",
")",
";",
"int",
"vote",
"=",
"buffer",
".",
"readInt",
"(",
"8",
")",... | Note: used in backward compatibility code with pre 1.2.6 release. This can be removed in later releases. | [
"Note",
":",
"used",
"in",
"backward",
"compatibility",
"code",
"with",
"pre",
"1",
".",
"2",
".",
"6",
"release",
".",
"This",
"can",
"be",
"removed",
"in",
"later",
"releases",
"."
] | train | https://github.com/atomix/copycat/blob/c90b88ccd5c63d6ea0b49fb77c25e2f3272a7b10/server/src/main/java/io/atomix/copycat/server/storage/system/MetaStore.java#L97-L114 |
alkacon/opencms-core | src/org/opencms/jsp/util/CmsJspCategoryAccessBean.java | CmsJspCategoryAccessBean.getSubCategories | public Map<String, CmsJspCategoryAccessBean> getSubCategories() {
if (m_subCategories == null) {
m_subCategories = CmsCollectionsGenericWrapper.createLazyMap(new Transformer() {
@SuppressWarnings("synthetic-access")
public Object transform(Object pathPrefix) {
return new CmsJspCategoryAccessBean(m_cms, m_categories, (String)pathPrefix);
}
});
}
return m_subCategories;
} | java | public Map<String, CmsJspCategoryAccessBean> getSubCategories() {
if (m_subCategories == null) {
m_subCategories = CmsCollectionsGenericWrapper.createLazyMap(new Transformer() {
@SuppressWarnings("synthetic-access")
public Object transform(Object pathPrefix) {
return new CmsJspCategoryAccessBean(m_cms, m_categories, (String)pathPrefix);
}
});
}
return m_subCategories;
} | [
"public",
"Map",
"<",
"String",
",",
"CmsJspCategoryAccessBean",
">",
"getSubCategories",
"(",
")",
"{",
"if",
"(",
"m_subCategories",
"==",
"null",
")",
"{",
"m_subCategories",
"=",
"CmsCollectionsGenericWrapper",
".",
"createLazyMap",
"(",
"new",
"Transformer",
... | Returns a map from a category path to the wrapper of all the sub-categories of the category with the path given as key.
@return a map from a category path to all sub-categories of the path's category. | [
"Returns",
"a",
"map",
"from",
"a",
"category",
"path",
"to",
"the",
"wrapper",
"of",
"all",
"the",
"sub",
"-",
"categories",
"of",
"the",
"category",
"with",
"the",
"path",
"given",
"as",
"key",
"."
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/jsp/util/CmsJspCategoryAccessBean.java#L178-L192 |
wisdom-framework/wisdom | core/wisdom-maven-plugin/src/main/java/org/wisdom/maven/utils/ChameleonInstanceHolder.java | ChameleonInstanceHolder.fixLoggingSystem | public static void fixLoggingSystem(File basedir) {
ILoggerFactory factory = LoggerFactory.getILoggerFactory();
if (factory instanceof LoggerContext) {
// We know that we are using logback from here.
LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
ch.qos.logback.classic.Logger logbackLogger = lc.getLogger(Logger.ROOT_LOGGER_NAME);
if (logbackLogger == null) {
return;
}
Iterator<Appender<ILoggingEvent>> iterator = logbackLogger.iteratorForAppenders();
while (iterator.hasNext()) {
Appender<ILoggingEvent> appender = iterator.next();
if (appender instanceof AsyncAppender) {
appender = ((AsyncAppender) appender).getAppender("FILE");
}
if (appender instanceof RollingFileAppender) {
RollingFileAppender<ILoggingEvent> fileAppender =
(RollingFileAppender<ILoggingEvent>) appender;
String file = new File(basedir, "logs/wisdom.log").getAbsolutePath();
fileAppender.stop();
// Remove the created log directory.
// We do that afterwards because on Windows the file cannot be deleted while we still have a logger
// using it.
FileUtils.deleteQuietly(new File("logs"));
fileAppender.setFile(file);
fileAppender.setContext(lc);
fileAppender.start();
}
}
}
} | java | public static void fixLoggingSystem(File basedir) {
ILoggerFactory factory = LoggerFactory.getILoggerFactory();
if (factory instanceof LoggerContext) {
// We know that we are using logback from here.
LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
ch.qos.logback.classic.Logger logbackLogger = lc.getLogger(Logger.ROOT_LOGGER_NAME);
if (logbackLogger == null) {
return;
}
Iterator<Appender<ILoggingEvent>> iterator = logbackLogger.iteratorForAppenders();
while (iterator.hasNext()) {
Appender<ILoggingEvent> appender = iterator.next();
if (appender instanceof AsyncAppender) {
appender = ((AsyncAppender) appender).getAppender("FILE");
}
if (appender instanceof RollingFileAppender) {
RollingFileAppender<ILoggingEvent> fileAppender =
(RollingFileAppender<ILoggingEvent>) appender;
String file = new File(basedir, "logs/wisdom.log").getAbsolutePath();
fileAppender.stop();
// Remove the created log directory.
// We do that afterwards because on Windows the file cannot be deleted while we still have a logger
// using it.
FileUtils.deleteQuietly(new File("logs"));
fileAppender.setFile(file);
fileAppender.setContext(lc);
fileAppender.start();
}
}
}
} | [
"public",
"static",
"void",
"fixLoggingSystem",
"(",
"File",
"basedir",
")",
"{",
"ILoggerFactory",
"factory",
"=",
"LoggerFactory",
".",
"getILoggerFactory",
"(",
")",
";",
"if",
"(",
"factory",
"instanceof",
"LoggerContext",
")",
"{",
"// We know that we are using... | Fixes the Chameleon logging configuration to write the logs in the logs/wisdom.log file instead of chameleon.log
file.
@param basedir the base directory of the chameleon | [
"Fixes",
"the",
"Chameleon",
"logging",
"configuration",
"to",
"write",
"the",
"logs",
"in",
"the",
"logs",
"/",
"wisdom",
".",
"log",
"file",
"instead",
"of",
"chameleon",
".",
"log",
"file",
"."
] | train | https://github.com/wisdom-framework/wisdom/blob/a35b6431200fec56b178c0ff60837ed73fd7874d/core/wisdom-maven-plugin/src/main/java/org/wisdom/maven/utils/ChameleonInstanceHolder.java#L128-L161 |
prestodb/presto | presto-accumulo/src/main/java/com/facebook/presto/accumulo/index/ColumnCardinalityCache.java | ColumnCardinalityCache.getColumnCardinality | public long getColumnCardinality(String schema, String table, Authorizations auths, String family, String qualifier, Collection<Range> colValues)
throws ExecutionException
{
LOG.debug("Getting cardinality for %s:%s", family, qualifier);
// Collect all exact Accumulo Ranges, i.e. single value entries vs. a full scan
Collection<CacheKey> exactRanges = colValues.stream()
.filter(ColumnCardinalityCache::isExact)
.map(range -> new CacheKey(schema, table, family, qualifier, range, auths))
.collect(Collectors.toList());
LOG.debug("Column values contain %s exact ranges of %s", exactRanges.size(), colValues.size());
// Sum the cardinalities for the exact-value Ranges
// This is where the reach-out to Accumulo occurs for all Ranges that have not
// previously been fetched
long sum = cache.getAll(exactRanges).values().stream().mapToLong(Long::longValue).sum();
// If these collection sizes are not equal,
// then there is at least one non-exact range
if (exactRanges.size() != colValues.size()) {
// for each range in the column value
for (Range range : colValues) {
// if this range is not exact
if (!isExact(range)) {
// Then get the value for this range using the single-value cache lookup
sum += cache.get(new CacheKey(schema, table, family, qualifier, range, auths));
}
}
}
return sum;
} | java | public long getColumnCardinality(String schema, String table, Authorizations auths, String family, String qualifier, Collection<Range> colValues)
throws ExecutionException
{
LOG.debug("Getting cardinality for %s:%s", family, qualifier);
// Collect all exact Accumulo Ranges, i.e. single value entries vs. a full scan
Collection<CacheKey> exactRanges = colValues.stream()
.filter(ColumnCardinalityCache::isExact)
.map(range -> new CacheKey(schema, table, family, qualifier, range, auths))
.collect(Collectors.toList());
LOG.debug("Column values contain %s exact ranges of %s", exactRanges.size(), colValues.size());
// Sum the cardinalities for the exact-value Ranges
// This is where the reach-out to Accumulo occurs for all Ranges that have not
// previously been fetched
long sum = cache.getAll(exactRanges).values().stream().mapToLong(Long::longValue).sum();
// If these collection sizes are not equal,
// then there is at least one non-exact range
if (exactRanges.size() != colValues.size()) {
// for each range in the column value
for (Range range : colValues) {
// if this range is not exact
if (!isExact(range)) {
// Then get the value for this range using the single-value cache lookup
sum += cache.get(new CacheKey(schema, table, family, qualifier, range, auths));
}
}
}
return sum;
} | [
"public",
"long",
"getColumnCardinality",
"(",
"String",
"schema",
",",
"String",
"table",
",",
"Authorizations",
"auths",
",",
"String",
"family",
",",
"String",
"qualifier",
",",
"Collection",
"<",
"Range",
">",
"colValues",
")",
"throws",
"ExecutionException",
... | Gets the column cardinality for all of the given range values. May reach out to the
metrics table in Accumulo to retrieve new cache elements.
@param schema Table schema
@param table Table name
@param auths Scan authorizations
@param family Accumulo column family
@param qualifier Accumulo column qualifier
@param colValues All range values to summarize for the cardinality
@return The cardinality of the column | [
"Gets",
"the",
"column",
"cardinality",
"for",
"all",
"of",
"the",
"given",
"range",
"values",
".",
"May",
"reach",
"out",
"to",
"the",
"metrics",
"table",
"in",
"Accumulo",
"to",
"retrieve",
"new",
"cache",
"elements",
"."
] | train | https://github.com/prestodb/presto/blob/89de5e379d8f85e139d292b0add8c537a2a01a88/presto-accumulo/src/main/java/com/facebook/presto/accumulo/index/ColumnCardinalityCache.java#L188-L220 |
RestComm/sip-servlets | sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/core/session/SipApplicationSessionImpl.java | SipApplicationSessionImpl.removeServletTimer | public void removeServletTimer(ServletTimer servletTimer, boolean updateAppSessionReadyToInvalidateState){
if(servletTimers != null) {
servletTimers.remove(servletTimer.getId());
}
if(updateAppSessionReadyToInvalidateState) {
updateReadyToInvalidateState();
}
} | java | public void removeServletTimer(ServletTimer servletTimer, boolean updateAppSessionReadyToInvalidateState){
if(servletTimers != null) {
servletTimers.remove(servletTimer.getId());
}
if(updateAppSessionReadyToInvalidateState) {
updateReadyToInvalidateState();
}
} | [
"public",
"void",
"removeServletTimer",
"(",
"ServletTimer",
"servletTimer",
",",
"boolean",
"updateAppSessionReadyToInvalidateState",
")",
"{",
"if",
"(",
"servletTimers",
"!=",
"null",
")",
"{",
"servletTimers",
".",
"remove",
"(",
"servletTimer",
".",
"getId",
"(... | Remove a servlet timer from this application session
@param servletTimer the servlet timer to remove | [
"Remove",
"a",
"servlet",
"timer",
"from",
"this",
"application",
"session"
] | train | https://github.com/RestComm/sip-servlets/blob/fd7011d2803ab1d205b140768a760c8c69e0c997/sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/core/session/SipApplicationSessionImpl.java#L609-L616 |
finmath/finmath-lib | src/main/java6/net/finmath/marketdata/products/SwapAnnuity.java | SwapAnnuity.getSwapAnnuity | public static double getSwapAnnuity(ScheduleInterface schedule, DiscountCurveInterface discountCurve) {
double evaluationTime = 0.0; // Consider only payment time > 0
return getSwapAnnuity(evaluationTime, schedule, discountCurve, null);
} | java | public static double getSwapAnnuity(ScheduleInterface schedule, DiscountCurveInterface discountCurve) {
double evaluationTime = 0.0; // Consider only payment time > 0
return getSwapAnnuity(evaluationTime, schedule, discountCurve, null);
} | [
"public",
"static",
"double",
"getSwapAnnuity",
"(",
"ScheduleInterface",
"schedule",
",",
"DiscountCurveInterface",
"discountCurve",
")",
"{",
"double",
"evaluationTime",
"=",
"0.0",
";",
"// Consider only payment time > 0",
"return",
"getSwapAnnuity",
"(",
"evaluationTime... | Function to calculate an (idealized) swap annuity for a given schedule and discount curve.
Note: This method will consider evaluationTime being 0, see {@link net.finmath.marketdata.products.SwapAnnuity#getSwapAnnuity(double, ScheduleInterface, DiscountCurveInterface, AnalyticModelInterface)}.
@param schedule The schedule discretization, i.e., the period start and end dates. End dates are considered payment dates and start of the next period.
@param discountCurve The discount curve.
@return The swap annuity. | [
"Function",
"to",
"calculate",
"an",
"(",
"idealized",
")",
"swap",
"annuity",
"for",
"a",
"given",
"schedule",
"and",
"discount",
"curve",
"."
] | train | https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java6/net/finmath/marketdata/products/SwapAnnuity.java#L83-L86 |
arquillian/arquillian-algeron | common/git/src/main/java/org/arquillian/algeron/git/GitOperations.java | GitOperations.cloneRepository | public Git cloneRepository(String remoteUrl, Path localPath) {
try {
return Git.cloneRepository()
.setURI(remoteUrl)
.setDirectory(localPath.toFile())
.call();
} catch (GitAPIException e) {
throw new IllegalStateException(e);
}
} | java | public Git cloneRepository(String remoteUrl, Path localPath) {
try {
return Git.cloneRepository()
.setURI(remoteUrl)
.setDirectory(localPath.toFile())
.call();
} catch (GitAPIException e) {
throw new IllegalStateException(e);
}
} | [
"public",
"Git",
"cloneRepository",
"(",
"String",
"remoteUrl",
",",
"Path",
"localPath",
")",
"{",
"try",
"{",
"return",
"Git",
".",
"cloneRepository",
"(",
")",
".",
"setURI",
"(",
"remoteUrl",
")",
".",
"setDirectory",
"(",
"localPath",
".",
"toFile",
"... | Clones a public remote git repository. Caller is responsible of closing git repository.
@param remoteUrl
to connect.
@param localPath
where to clone the repo.
@return Git instance. Caller is responsible to close the connection. | [
"Clones",
"a",
"public",
"remote",
"git",
"repository",
".",
"Caller",
"is",
"responsible",
"of",
"closing",
"git",
"repository",
"."
] | train | https://github.com/arquillian/arquillian-algeron/blob/ec79372defdafe99ab2f7bb696f1c1eabdbbacb6/common/git/src/main/java/org/arquillian/algeron/git/GitOperations.java#L471-L480 |
couchbase/couchbase-lite-java-core | src/main/java/com/couchbase/lite/replicator/Replication.java | Replication.setHeaders | @InterfaceAudience.Public
public void setHeaders(Map<String, Object> requestHeadersParam) {
// Fix - https://github.com/couchbase/couchbase-lite-java-core/issues/1617
storeCookiesIntoCookieJar(requestHeadersParam);
properties.put(ReplicationField.REQUEST_HEADERS, requestHeadersParam);
replicationInternal.setHeaders(requestHeadersParam);
} | java | @InterfaceAudience.Public
public void setHeaders(Map<String, Object> requestHeadersParam) {
// Fix - https://github.com/couchbase/couchbase-lite-java-core/issues/1617
storeCookiesIntoCookieJar(requestHeadersParam);
properties.put(ReplicationField.REQUEST_HEADERS, requestHeadersParam);
replicationInternal.setHeaders(requestHeadersParam);
} | [
"@",
"InterfaceAudience",
".",
"Public",
"public",
"void",
"setHeaders",
"(",
"Map",
"<",
"String",
",",
"Object",
">",
"requestHeadersParam",
")",
"{",
"// Fix - https://github.com/couchbase/couchbase-lite-java-core/issues/1617",
"storeCookiesIntoCookieJar",
"(",
"requestHea... | Set Extra HTTP headers to be sent in all requests to the remote server. | [
"Set",
"Extra",
"HTTP",
"headers",
"to",
"be",
"sent",
"in",
"all",
"requests",
"to",
"the",
"remote",
"server",
"."
] | train | https://github.com/couchbase/couchbase-lite-java-core/blob/3b275642e2d2f231fd155ad9def9c5e9eff3118e/src/main/java/com/couchbase/lite/replicator/Replication.java#L900-L907 |
Jsondb/jsondb-core | src/main/java/io/jsondb/crypto/CryptoUtil.java | CryptoUtil.generate128BitKey | public static String generate128BitKey(String password, String salt)
throws NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeySpecException {
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
KeySpec spec = new PBEKeySpec(password.toCharArray(), salt.getBytes(), 65536, 128);
SecretKey key = factory.generateSecret(spec);
byte[] keybyte = key.getEncoded();
return Base64.getEncoder().encodeToString(keybyte);
} | java | public static String generate128BitKey(String password, String salt)
throws NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeySpecException {
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
KeySpec spec = new PBEKeySpec(password.toCharArray(), salt.getBytes(), 65536, 128);
SecretKey key = factory.generateSecret(spec);
byte[] keybyte = key.getEncoded();
return Base64.getEncoder().encodeToString(keybyte);
} | [
"public",
"static",
"String",
"generate128BitKey",
"(",
"String",
"password",
",",
"String",
"salt",
")",
"throws",
"NoSuchAlgorithmException",
",",
"UnsupportedEncodingException",
",",
"InvalidKeySpecException",
"{",
"SecretKeyFactory",
"factory",
"=",
"SecretKeyFactory",
... | Utility method to help generate a strong 128 bit Key to be used for the DefaultAESCBCCipher.
Note: This function is only provided as a utility to generate strong password it should
be used statically to generate a key and then the key should be captured and used in your program.
This function defaults to using 65536 iterations and 128 bits for key size. If you wish to use 256 bits key size
then ensure that you have Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy installed
and change the last argument to {@link javax.crypto.spec.PBEKeySpec} below to 256
@param password A password which acts as a seed for generation of the key
@param salt A salt used in combination with the password for the generation of the key
@return A Base64 Encoded string representing the 128 bit key
@throws NoSuchAlgorithmException if the KeyFactory algorithm is not found in available crypto providers
@throws UnsupportedEncodingException if the char encoding of the salt is not known.
@throws InvalidKeySpecException invalid generated key | [
"Utility",
"method",
"to",
"help",
"generate",
"a",
"strong",
"128",
"bit",
"Key",
"to",
"be",
"used",
"for",
"the",
"DefaultAESCBCCipher",
"."
] | train | https://github.com/Jsondb/jsondb-core/blob/c49654d1eee2ace4d5ca5be19730652a966ce7f4/src/main/java/io/jsondb/crypto/CryptoUtil.java#L131-L140 |
BigBadaboom/androidsvg | androidsvg/src/main/java/com/caverock/androidsvg/SVG.java | SVG.renderViewToCanvas | @SuppressWarnings({"WeakerAccess", "unused"})
public void renderViewToCanvas(String viewId, Canvas canvas, RectF viewPort)
{
RenderOptions renderOptions = RenderOptions.create().view(viewId);
if (viewPort != null) {
renderOptions.viewPort(viewPort.left, viewPort.top, viewPort.width(), viewPort.height());
}
renderToCanvas(canvas, renderOptions);
} | java | @SuppressWarnings({"WeakerAccess", "unused"})
public void renderViewToCanvas(String viewId, Canvas canvas, RectF viewPort)
{
RenderOptions renderOptions = RenderOptions.create().view(viewId);
if (viewPort != null) {
renderOptions.viewPort(viewPort.left, viewPort.top, viewPort.width(), viewPort.height());
}
renderToCanvas(canvas, renderOptions);
} | [
"@",
"SuppressWarnings",
"(",
"{",
"\"WeakerAccess\"",
",",
"\"unused\"",
"}",
")",
"public",
"void",
"renderViewToCanvas",
"(",
"String",
"viewId",
",",
"Canvas",
"canvas",
",",
"RectF",
"viewPort",
")",
"{",
"RenderOptions",
"renderOptions",
"=",
"RenderOptions"... | Renders this SVG document to a Canvas using the specified view defined in the document.
<p>
A View is an special element in a SVG documents that describes a rectangular area in the document.
Calling this method with a {@code viewId} will result in the specified view being positioned and scaled
to the viewport. In other words, use {@link #renderToPicture()} to render the whole document, or use this
method instead to render just a part of it.
<p>
If the {@code <view>} could not be found, nothing will be drawn.
@param viewId the id of a view element in the document that defines which section of the document is to be visible.
@param canvas the canvas to which the document should be rendered.
@param viewPort the bounds of the area on the canvas you want the SVG rendered, or null for the whole canvas. | [
"Renders",
"this",
"SVG",
"document",
"to",
"a",
"Canvas",
"using",
"the",
"specified",
"view",
"defined",
"in",
"the",
"document",
".",
"<p",
">",
"A",
"View",
"is",
"an",
"special",
"element",
"in",
"a",
"SVG",
"documents",
"that",
"describes",
"a",
"r... | train | https://github.com/BigBadaboom/androidsvg/blob/0d1614dd1a4da10ea4afe3b0cea1361a4ac6b45a/androidsvg/src/main/java/com/caverock/androidsvg/SVG.java#L578-L588 |
sagiegurari/fax4j | src/main/java/org/fax4j/bridge/http/SimpleHTTPRequestParser.java | SimpleHTTPRequestParser.getFileInfoFromRequestImpl | protected FileInfo getFileInfoFromRequestImpl(HTTPRequest request,Map<String,String> queryStringMap)
{
//get file name
String name=queryStringMap.get("file");
if(name==null)
{
throw new FaxException("File name not provided in query string.");
}
//get content
byte[] content=null;
ContentType contentType=request.getContentType();
switch(contentType)
{
case BINARY:
content=request.getContentAsBinary();
break;
case STRING:
String contentString=request.getContentAsString();
content=IOHelper.convertStringToBinary(contentString,null);
break;
default:
throw new FaxException("Unsupported content type: "+contentType);
}
if((content==null)||(content.length==0))
{
throw new FaxException("File content not provided in request payload.");
}
//create file info
FileInfo fileInfo=new FileInfo(name,content);
return fileInfo;
} | java | protected FileInfo getFileInfoFromRequestImpl(HTTPRequest request,Map<String,String> queryStringMap)
{
//get file name
String name=queryStringMap.get("file");
if(name==null)
{
throw new FaxException("File name not provided in query string.");
}
//get content
byte[] content=null;
ContentType contentType=request.getContentType();
switch(contentType)
{
case BINARY:
content=request.getContentAsBinary();
break;
case STRING:
String contentString=request.getContentAsString();
content=IOHelper.convertStringToBinary(contentString,null);
break;
default:
throw new FaxException("Unsupported content type: "+contentType);
}
if((content==null)||(content.length==0))
{
throw new FaxException("File content not provided in request payload.");
}
//create file info
FileInfo fileInfo=new FileInfo(name,content);
return fileInfo;
} | [
"protected",
"FileInfo",
"getFileInfoFromRequestImpl",
"(",
"HTTPRequest",
"request",
",",
"Map",
"<",
"String",
",",
"String",
">",
"queryStringMap",
")",
"{",
"//get file name",
"String",
"name",
"=",
"queryStringMap",
".",
"get",
"(",
"\"file\"",
")",
";",
"i... | This function returns the file info from the request data.
@param request
The HTTP request
@param queryStringMap
The query string as key/value map
@return The file info | [
"This",
"function",
"returns",
"the",
"file",
"info",
"from",
"the",
"request",
"data",
"."
] | train | https://github.com/sagiegurari/fax4j/blob/42fa51acabe7bf279e27ab3dd1cf76146b27955f/src/main/java/org/fax4j/bridge/http/SimpleHTTPRequestParser.java#L166-L199 |
facebook/fresco | samples/scrollperf/src/main/java/com/facebook/samples/scrollperf/data/impl/ContentProviderSimpleAdapter.java | ContentProviderSimpleAdapter.getExternalPhotoSimpleAdapter | public static ContentProviderSimpleAdapter getExternalPhotoSimpleAdapter(Context context) {
return new ContentProviderSimpleAdapter(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, context);
} | java | public static ContentProviderSimpleAdapter getExternalPhotoSimpleAdapter(Context context) {
return new ContentProviderSimpleAdapter(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, context);
} | [
"public",
"static",
"ContentProviderSimpleAdapter",
"getExternalPhotoSimpleAdapter",
"(",
"Context",
"context",
")",
"{",
"return",
"new",
"ContentProviderSimpleAdapter",
"(",
"MediaStore",
".",
"Images",
".",
"Media",
".",
"EXTERNAL_CONTENT_URI",
",",
"context",
")",
"... | Creates and returns a SimpleAdapter for External Photos
@param context The Context
@return The SimpleAdapter for local photo | [
"Creates",
"and",
"returns",
"a",
"SimpleAdapter",
"for",
"External",
"Photos"
] | train | https://github.com/facebook/fresco/blob/0b85879d51c5036d5e46e627a6651afefc0b971a/samples/scrollperf/src/main/java/com/facebook/samples/scrollperf/data/impl/ContentProviderSimpleAdapter.java#L57-L59 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.