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 |
|---|---|---|---|---|---|---|---|---|---|---|
Impetus/Kundera | src/kundera-cassandra/cassandra-core/src/main/java/com/impetus/client/cassandra/thrift/CQLTranslator.java | CQLTranslator.ensureCase | public StringBuilder ensureCase(StringBuilder builder, String fieldName, boolean useToken)
{
if (useToken)
{
builder.append(TOKEN);
}
builder.append(Constants.ESCAPE_QUOTE);
builder.append(fieldName);
builder.append(Constants.ESCAPE_QUOTE);
if (useToken)
{
builder.append(CLOSE_BRACKET);
}
return builder;
} | java | public StringBuilder ensureCase(StringBuilder builder, String fieldName, boolean useToken)
{
if (useToken)
{
builder.append(TOKEN);
}
builder.append(Constants.ESCAPE_QUOTE);
builder.append(fieldName);
builder.append(Constants.ESCAPE_QUOTE);
if (useToken)
{
builder.append(CLOSE_BRACKET);
}
return builder;
} | [
"public",
"StringBuilder",
"ensureCase",
"(",
"StringBuilder",
"builder",
",",
"String",
"fieldName",
",",
"boolean",
"useToken",
")",
"{",
"if",
"(",
"useToken",
")",
"{",
"builder",
".",
"append",
"(",
"TOKEN",
")",
";",
"}",
"builder",
".",
"append",
"(... | Ensures case for corresponding column name.
@param builder
column name builder.
@param fieldName
column name.
@param useToken
the use token
@return builder object with appended column name. | [
"Ensures",
"case",
"for",
"corresponding",
"column",
"name",
"."
] | train | https://github.com/Impetus/Kundera/blob/268958ab1ec09d14ec4d9184f0c8ded7a9158908/src/kundera-cassandra/cassandra-core/src/main/java/com/impetus/client/cassandra/thrift/CQLTranslator.java#L1003-L1018 |
Azure/azure-sdk-for-java | sql/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sql/v2017_03_01_preview/implementation/JobAgentsInner.java | JobAgentsInner.listByServerAsync | public Observable<Page<JobAgentInner>> listByServerAsync(final String resourceGroupName, final String serverName) {
return listByServerWithServiceResponseAsync(resourceGroupName, serverName)
.map(new Func1<ServiceResponse<Page<JobAgentInner>>, Page<JobAgentInner>>() {
@Override
public Page<JobAgentInner> call(ServiceResponse<Page<JobAgentInner>> response) {
return response.body();
}
});
} | java | public Observable<Page<JobAgentInner>> listByServerAsync(final String resourceGroupName, final String serverName) {
return listByServerWithServiceResponseAsync(resourceGroupName, serverName)
.map(new Func1<ServiceResponse<Page<JobAgentInner>>, Page<JobAgentInner>>() {
@Override
public Page<JobAgentInner> call(ServiceResponse<Page<JobAgentInner>> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"Page",
"<",
"JobAgentInner",
">",
">",
"listByServerAsync",
"(",
"final",
"String",
"resourceGroupName",
",",
"final",
"String",
"serverName",
")",
"{",
"return",
"listByServerWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"ser... | Gets a list of job agents in a server.
@param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal.
@param serverName The name of the server.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the PagedList<JobAgentInner> object | [
"Gets",
"a",
"list",
"of",
"job",
"agents",
"in",
"a",
"server",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/sql/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sql/v2017_03_01_preview/implementation/JobAgentsInner.java#L154-L162 |
Red5/red5-server-common | src/main/java/org/red5/server/net/rtmp/RTMPHandshake.java | RTMPHandshake.getDigestOffset2 | protected int getDigestOffset2(byte[] handshake, int bufferOffset) {
bufferOffset += 772;
int offset = handshake[bufferOffset] & 0xff; // & 0x0ff;
bufferOffset++;
offset += handshake[bufferOffset] & 0xff;
bufferOffset++;
offset += handshake[bufferOffset] & 0xff;
bufferOffset++;
offset += handshake[bufferOffset] & 0xff;
int res = Math.abs((offset % 728) + 776);
if (res + DIGEST_LENGTH > 1535) {
log.error("Invalid digest offset calc: {}", res);
}
return res;
} | java | protected int getDigestOffset2(byte[] handshake, int bufferOffset) {
bufferOffset += 772;
int offset = handshake[bufferOffset] & 0xff; // & 0x0ff;
bufferOffset++;
offset += handshake[bufferOffset] & 0xff;
bufferOffset++;
offset += handshake[bufferOffset] & 0xff;
bufferOffset++;
offset += handshake[bufferOffset] & 0xff;
int res = Math.abs((offset % 728) + 776);
if (res + DIGEST_LENGTH > 1535) {
log.error("Invalid digest offset calc: {}", res);
}
return res;
} | [
"protected",
"int",
"getDigestOffset2",
"(",
"byte",
"[",
"]",
"handshake",
",",
"int",
"bufferOffset",
")",
"{",
"bufferOffset",
"+=",
"772",
";",
"int",
"offset",
"=",
"handshake",
"[",
"bufferOffset",
"]",
"&",
"0xff",
";",
"// & 0x0ff;\r",
"bufferOffset",
... | Returns a digest byte offset.
@param handshake handshake sequence
@param bufferOffset buffer offset
@return digest offset | [
"Returns",
"a",
"digest",
"byte",
"offset",
"."
] | train | https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/net/rtmp/RTMPHandshake.java#L531-L545 |
Carbonado/Carbonado | src/main/java/com/amazon/carbonado/filter/Filter.java | Filter.orExists | public final Filter<S> orExists(String propertyName, Filter<?> subFilter) {
ChainedProperty<S> prop = new FilterParser<S>(mType, propertyName).parseChainedProperty();
return or(ExistsFilter.build(prop, subFilter, false));
} | java | public final Filter<S> orExists(String propertyName, Filter<?> subFilter) {
ChainedProperty<S> prop = new FilterParser<S>(mType, propertyName).parseChainedProperty();
return or(ExistsFilter.build(prop, subFilter, false));
} | [
"public",
"final",
"Filter",
"<",
"S",
">",
"orExists",
"(",
"String",
"propertyName",
",",
"Filter",
"<",
"?",
">",
"subFilter",
")",
"{",
"ChainedProperty",
"<",
"S",
">",
"prop",
"=",
"new",
"FilterParser",
"<",
"S",
">",
"(",
"mType",
",",
"propert... | Returns a combined filter instance that accepts records which are
accepted either by this filter or the "exists" test applied to a join.
@param propertyName one-to-many join property name, which may be a chained property
@param subFilter sub-filter to apply to join, which may be null to test
for any existing
@return canonical Filter instance
@throws IllegalArgumentException if property is not found
@since 1.2 | [
"Returns",
"a",
"combined",
"filter",
"instance",
"that",
"accepts",
"records",
"which",
"are",
"accepted",
"either",
"by",
"this",
"filter",
"or",
"the",
"exists",
"test",
"applied",
"to",
"a",
"join",
"."
] | train | https://github.com/Carbonado/Carbonado/blob/eee29b365a61c8f03e1a1dc6bed0692e6b04b1db/src/main/java/com/amazon/carbonado/filter/Filter.java#L394-L397 |
looly/hutool | hutool-poi/src/main/java/cn/hutool/poi/excel/style/StyleUtil.java | StyleUtil.cloneCellStyle | public static CellStyle cloneCellStyle(Workbook workbook, CellStyle cellStyle) {
final CellStyle newCellStyle = workbook.createCellStyle();
newCellStyle.cloneStyleFrom(cellStyle);
return newCellStyle;
} | java | public static CellStyle cloneCellStyle(Workbook workbook, CellStyle cellStyle) {
final CellStyle newCellStyle = workbook.createCellStyle();
newCellStyle.cloneStyleFrom(cellStyle);
return newCellStyle;
} | [
"public",
"static",
"CellStyle",
"cloneCellStyle",
"(",
"Workbook",
"workbook",
",",
"CellStyle",
"cellStyle",
")",
"{",
"final",
"CellStyle",
"newCellStyle",
"=",
"workbook",
".",
"createCellStyle",
"(",
")",
";",
"newCellStyle",
".",
"cloneStyleFrom",
"(",
"cell... | 克隆新的{@link CellStyle}
@param workbook 工作簿
@param cellStyle 被复制的样式
@return {@link CellStyle} | [
"克隆新的",
"{",
"@link",
"CellStyle",
"}"
] | train | https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-poi/src/main/java/cn/hutool/poi/excel/style/StyleUtil.java#L41-L45 |
Azure/azure-sdk-for-java | compute/resource-manager/v2017_03_30/src/main/java/com/microsoft/azure/management/compute/v2017_03_30/implementation/VirtualMachinesInner.java | VirtualMachinesInner.runCommand | public RunCommandResultInner runCommand(String resourceGroupName, String vmName, RunCommandInput parameters) {
return runCommandWithServiceResponseAsync(resourceGroupName, vmName, parameters).toBlocking().last().body();
} | java | public RunCommandResultInner runCommand(String resourceGroupName, String vmName, RunCommandInput parameters) {
return runCommandWithServiceResponseAsync(resourceGroupName, vmName, parameters).toBlocking().last().body();
} | [
"public",
"RunCommandResultInner",
"runCommand",
"(",
"String",
"resourceGroupName",
",",
"String",
"vmName",
",",
"RunCommandInput",
"parameters",
")",
"{",
"return",
"runCommandWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"vmName",
",",
"parameters",
")",
... | Run command on the VM.
@param resourceGroupName The name of the resource group.
@param vmName The name of the virtual machine.
@param parameters Parameters supplied to the Run command operation.
@throws IllegalArgumentException thrown if parameters fail the validation
@throws CloudException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the RunCommandResultInner object if successful. | [
"Run",
"command",
"on",
"the",
"VM",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/compute/resource-manager/v2017_03_30/src/main/java/com/microsoft/azure/management/compute/v2017_03_30/implementation/VirtualMachinesInner.java#L2626-L2628 |
RestComm/Restcomm-Connect | restcomm/restcomm.dao/src/main/java/org/restcomm/connect/dao/mybatis/MybatisApplicationsDao.java | MybatisApplicationsDao.populateApplicationWithNumber | private void populateApplicationWithNumber(Application application, final Map<String, Object> map, String field_prefix) {
// first create the number
ApplicationNumberSummary number = new ApplicationNumberSummary(
readString(map.get(field_prefix + "sid")),
readString(map.get(field_prefix + "friendly_name")),
readString(map.get(field_prefix + "phone_number")),
readString(map.get(field_prefix + "voice_application_sid")),
readString(map.get(field_prefix + "sms_application_sid")),
readString(map.get(field_prefix + "ussd_application_sid")),
readString(map.get(field_prefix + "refer_application_sid"))
);
List<ApplicationNumberSummary> numbers = application.getNumbers();
if (numbers == null) {
numbers = new ArrayList<ApplicationNumberSummary>();
application.setNumbers(numbers);
}
numbers.add(number);
} | java | private void populateApplicationWithNumber(Application application, final Map<String, Object> map, String field_prefix) {
// first create the number
ApplicationNumberSummary number = new ApplicationNumberSummary(
readString(map.get(field_prefix + "sid")),
readString(map.get(field_prefix + "friendly_name")),
readString(map.get(field_prefix + "phone_number")),
readString(map.get(field_prefix + "voice_application_sid")),
readString(map.get(field_prefix + "sms_application_sid")),
readString(map.get(field_prefix + "ussd_application_sid")),
readString(map.get(field_prefix + "refer_application_sid"))
);
List<ApplicationNumberSummary> numbers = application.getNumbers();
if (numbers == null) {
numbers = new ArrayList<ApplicationNumberSummary>();
application.setNumbers(numbers);
}
numbers.add(number);
} | [
"private",
"void",
"populateApplicationWithNumber",
"(",
"Application",
"application",
",",
"final",
"Map",
"<",
"String",
",",
"Object",
">",
"map",
",",
"String",
"field_prefix",
")",
"{",
"// first create the number",
"ApplicationNumberSummary",
"number",
"=",
"new... | Populates application.numbers field with information of one or more numbers. The 'numbers' list is created if
already null and an IncomingPhoneNumber is added into it based on information from the map. Invoking the same method
several times to add more numbers to the same list is possible.
@param application
@param map
@param field_prefix
@return | [
"Populates",
"application",
".",
"numbers",
"field",
"with",
"information",
"of",
"one",
"or",
"more",
"numbers",
".",
"The",
"numbers",
"list",
"is",
"created",
"if",
"already",
"null",
"and",
"an",
"IncomingPhoneNumber",
"is",
"added",
"into",
"it",
"based",... | train | https://github.com/RestComm/Restcomm-Connect/blob/2194dee4fc524cdfd0af77a218ba5f212f97f7c5/restcomm/restcomm.dao/src/main/java/org/restcomm/connect/dao/mybatis/MybatisApplicationsDao.java#L200-L217 |
openengsb/openengsb | components/ekb/persistence-persist-edb/src/main/java/org/openengsb/core/ekb/persistence/persist/edb/internal/ModelDiff.java | ModelDiff.addDifference | public void addDifference(Field field, Object before, Object after) {
ModelDiffEntry entry = new ModelDiffEntry();
entry.setBefore(before);
entry.setAfter(after);
entry.setField(field);
differences.put(field, entry);
} | java | public void addDifference(Field field, Object before, Object after) {
ModelDiffEntry entry = new ModelDiffEntry();
entry.setBefore(before);
entry.setAfter(after);
entry.setField(field);
differences.put(field, entry);
} | [
"public",
"void",
"addDifference",
"(",
"Field",
"field",
",",
"Object",
"before",
",",
"Object",
"after",
")",
"{",
"ModelDiffEntry",
"entry",
"=",
"new",
"ModelDiffEntry",
"(",
")",
";",
"entry",
".",
"setBefore",
"(",
"before",
")",
";",
"entry",
".",
... | Adds a difference to the list of differences of this ModelDiff instance. | [
"Adds",
"a",
"difference",
"to",
"the",
"list",
"of",
"differences",
"of",
"this",
"ModelDiff",
"instance",
"."
] | train | https://github.com/openengsb/openengsb/blob/d39058000707f617cd405629f9bc7f17da7b414a/components/ekb/persistence-persist-edb/src/main/java/org/openengsb/core/ekb/persistence/persist/edb/internal/ModelDiff.java#L100-L106 |
aws/aws-sdk-java | aws-java-sdk-inspector/src/main/java/com/amazonaws/services/inspector/model/DescribeExclusionsResult.java | DescribeExclusionsResult.withFailedItems | public DescribeExclusionsResult withFailedItems(java.util.Map<String, FailedItemDetails> failedItems) {
setFailedItems(failedItems);
return this;
} | java | public DescribeExclusionsResult withFailedItems(java.util.Map<String, FailedItemDetails> failedItems) {
setFailedItems(failedItems);
return this;
} | [
"public",
"DescribeExclusionsResult",
"withFailedItems",
"(",
"java",
".",
"util",
".",
"Map",
"<",
"String",
",",
"FailedItemDetails",
">",
"failedItems",
")",
"{",
"setFailedItems",
"(",
"failedItems",
")",
";",
"return",
"this",
";",
"}"
] | <p>
Exclusion details that cannot be described. An error code is provided for each failed item.
</p>
@param failedItems
Exclusion details that cannot be described. An error code is provided for each failed item.
@return Returns a reference to this object so that method calls can be chained together. | [
"<p",
">",
"Exclusion",
"details",
"that",
"cannot",
"be",
"described",
".",
"An",
"error",
"code",
"is",
"provided",
"for",
"each",
"failed",
"item",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-inspector/src/main/java/com/amazonaws/services/inspector/model/DescribeExclusionsResult.java#L135-L138 |
VoltDB/voltdb | src/hsqldb19b3/org/hsqldb_voltpatches/FunctionSQL.java | FunctionSQL.getValue | @Override
public Object getValue(Session session) {
Object[] data = new Object[nodes.length];
for (int i = 0; i < nodes.length; i++) {
Expression e = nodes[i];
if (e != null) {
data[i] = e.getValue(session, e.dataType);
}
}
return getValue(session, data);
} | java | @Override
public Object getValue(Session session) {
Object[] data = new Object[nodes.length];
for (int i = 0; i < nodes.length; i++) {
Expression e = nodes[i];
if (e != null) {
data[i] = e.getValue(session, e.dataType);
}
}
return getValue(session, data);
} | [
"@",
"Override",
"public",
"Object",
"getValue",
"(",
"Session",
"session",
")",
"{",
"Object",
"[",
"]",
"data",
"=",
"new",
"Object",
"[",
"nodes",
".",
"length",
"]",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"nodes",
".",
"length",
... | Evaluates and returns this Function in the context of the session.<p> | [
"Evaluates",
"and",
"returns",
"this",
"Function",
"in",
"the",
"context",
"of",
"the",
"session",
".",
"<p",
">"
] | train | https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/hsqldb19b3/org/hsqldb_voltpatches/FunctionSQL.java#L677-L691 |
gallandarakhneorg/afc | advanced/gis/giscore/src/main/java/org/arakhne/afc/gis/mapelement/MapCircle.java | MapCircle.getDistance | @Override
@Pure
public double getDistance(Point2D<?, ?> point) {
double dist = super.getDistance(point);
dist -= this.radius;
return dist;
} | java | @Override
@Pure
public double getDistance(Point2D<?, ?> point) {
double dist = super.getDistance(point);
dist -= this.radius;
return dist;
} | [
"@",
"Override",
"@",
"Pure",
"public",
"double",
"getDistance",
"(",
"Point2D",
"<",
"?",
",",
"?",
">",
"point",
")",
"{",
"double",
"dist",
"=",
"super",
".",
"getDistance",
"(",
"point",
")",
";",
"dist",
"-=",
"this",
".",
"radius",
";",
"return... | Replies the distance between this MapCircle and
point.
@param point the point to compute the distance to.
@return the distance. Should be negative if the point is inside the circle. | [
"Replies",
"the",
"distance",
"between",
"this",
"MapCircle",
"and",
"point",
"."
] | train | https://github.com/gallandarakhneorg/afc/blob/0c7d2e1ddefd4167ef788416d970a6c1ef6f8bbb/advanced/gis/giscore/src/main/java/org/arakhne/afc/gis/mapelement/MapCircle.java#L309-L315 |
docusign/docusign-java-client | src/main/java/com/docusign/esign/api/FoldersApi.java | FoldersApi.listItems | public FolderItemsResponse listItems(String accountId, String folderId) throws ApiException {
return listItems(accountId, folderId, null);
} | java | public FolderItemsResponse listItems(String accountId, String folderId) throws ApiException {
return listItems(accountId, folderId, null);
} | [
"public",
"FolderItemsResponse",
"listItems",
"(",
"String",
"accountId",
",",
"String",
"folderId",
")",
"throws",
"ApiException",
"{",
"return",
"listItems",
"(",
"accountId",
",",
"folderId",
",",
"null",
")",
";",
"}"
] | Gets a list of the envelopes in the specified folder.
Retrieves a list of the envelopes in the specified folder. You can narrow the query by specifying search criteria in the query string parameters.
@param accountId The external account number (int) or account ID Guid. (required)
@param folderId The ID of the folder being accessed. (required)
@return FolderItemsResponse | [
"Gets",
"a",
"list",
"of",
"the",
"envelopes",
"in",
"the",
"specified",
"folder",
".",
"Retrieves",
"a",
"list",
"of",
"the",
"envelopes",
"in",
"the",
"specified",
"folder",
".",
"You",
"can",
"narrow",
"the",
"query",
"by",
"specifying",
"search",
"crit... | train | https://github.com/docusign/docusign-java-client/blob/17ae82ace0f023e98edf813be832950568212e34/src/main/java/com/docusign/esign/api/FoldersApi.java#L238-L240 |
GoogleCloudPlatform/app-maven-plugin | src/main/java/com/google/cloud/tools/maven/cloudsdk/ConfigReader.java | ConfigReader.getProjectId | public String getProjectId() {
try {
String gcloudProject = gcloud.getConfig().getProject();
if (gcloudProject == null || gcloudProject.trim().isEmpty()) {
throw new RuntimeException("Project was not found in gcloud config");
}
return gcloudProject;
} catch (CloudSdkNotFoundException
| CloudSdkOutOfDateException
| CloudSdkVersionFileException
| IOException
| ProcessHandlerException ex) {
throw new RuntimeException("Failed to read project from gcloud config", ex);
}
} | java | public String getProjectId() {
try {
String gcloudProject = gcloud.getConfig().getProject();
if (gcloudProject == null || gcloudProject.trim().isEmpty()) {
throw new RuntimeException("Project was not found in gcloud config");
}
return gcloudProject;
} catch (CloudSdkNotFoundException
| CloudSdkOutOfDateException
| CloudSdkVersionFileException
| IOException
| ProcessHandlerException ex) {
throw new RuntimeException("Failed to read project from gcloud config", ex);
}
} | [
"public",
"String",
"getProjectId",
"(",
")",
"{",
"try",
"{",
"String",
"gcloudProject",
"=",
"gcloud",
".",
"getConfig",
"(",
")",
".",
"getProject",
"(",
")",
";",
"if",
"(",
"gcloudProject",
"==",
"null",
"||",
"gcloudProject",
".",
"trim",
"(",
")",... | Return gcloud config property for project, or error out if not found. | [
"Return",
"gcloud",
"config",
"property",
"for",
"project",
"or",
"error",
"out",
"if",
"not",
"found",
"."
] | train | https://github.com/GoogleCloudPlatform/app-maven-plugin/blob/1f31bb8e963ce189e9ed6b88923a1853533485ff/src/main/java/com/google/cloud/tools/maven/cloudsdk/ConfigReader.java#L38-L52 |
carewebframework/carewebframework-core | org.carewebframework.ui-parent/org.carewebframework.ui.core/src/main/java/org/carewebframework/ui/util/TreeUtil.java | TreeUtil.findNode | public static Treenode findNode(Treeview tree, String path, boolean create) {
return findNode(tree, path, create, Treenode.class);
} | java | public static Treenode findNode(Treeview tree, String path, boolean create) {
return findNode(tree, path, create, Treenode.class);
} | [
"public",
"static",
"Treenode",
"findNode",
"(",
"Treeview",
"tree",
",",
"String",
"path",
",",
"boolean",
"create",
")",
"{",
"return",
"findNode",
"(",
"tree",
",",
"path",
",",
"create",
",",
"Treenode",
".",
"class",
")",
";",
"}"
] | Returns the tree item associated with the specified \-delimited path.
@param tree Tree to search. Search is not case sensitive.
@param path \-delimited path to search.
@param create If true, tree nodes are created if they do not already exist.
@return The tree item corresponding to the specified path, or null if not found. | [
"Returns",
"the",
"tree",
"item",
"associated",
"with",
"the",
"specified",
"\\",
"-",
"delimited",
"path",
"."
] | train | https://github.com/carewebframework/carewebframework-core/blob/fa3252d4f7541dbe151b92c3d4f6f91433cd1673/org.carewebframework.ui-parent/org.carewebframework.ui.core/src/main/java/org/carewebframework/ui/util/TreeUtil.java#L107-L109 |
hazelcast/hazelcast | hazelcast/src/main/java/com/hazelcast/cache/CacheUtil.java | CacheUtil.getDistributedObjectName | public static String getDistributedObjectName(String cacheName, URI uri, ClassLoader classLoader) {
return HazelcastCacheManager.CACHE_MANAGER_PREFIX + getPrefixedCacheName(cacheName, uri, classLoader);
} | java | public static String getDistributedObjectName(String cacheName, URI uri, ClassLoader classLoader) {
return HazelcastCacheManager.CACHE_MANAGER_PREFIX + getPrefixedCacheName(cacheName, uri, classLoader);
} | [
"public",
"static",
"String",
"getDistributedObjectName",
"(",
"String",
"cacheName",
",",
"URI",
"uri",
",",
"ClassLoader",
"classLoader",
")",
"{",
"return",
"HazelcastCacheManager",
".",
"CACHE_MANAGER_PREFIX",
"+",
"getPrefixedCacheName",
"(",
"cacheName",
",",
"u... | Convenience method to obtain the name of Hazelcast distributed object corresponding to the cache identified
by the given arguments. The distributed object name returned by this method can be used to obtain the cache as
a Hazelcast {@link ICache} as shown in this example:
<pre>
HazelcastInstance hz = Hazelcast.newHazelcastInstance();
// Obtain Cache via JSR-107 API
CachingProvider hazelcastCachingProvider = Caching.getCachingProvider(
"com.hazelcast.cache.HazelcastCachingProvider",
HazelcastCachingProvider.class.getClassLoader());
CacheManager cacheManager = hazelcastCachingProvider.getCacheManager();
Cache testCache = cacheManager.createCache("test", new MutableConfiguration<String, String>());
// URI and ClassLoader are null, since we created this cache with the default CacheManager,
// otherwise we should pass the owning CacheManager's URI & ClassLoader as arguments.
String distributedObjectName = CacheUtil.asDistributedObjectName("test", null, null);
// Obtain a reference to the backing ICache via HazelcastInstance.getDistributedObject.
// You may invoke this on any member of the cluster.
ICache<String, String> distributedObjectCache = (ICache) hz.getDistributedObject(
ICacheService.SERVICE_NAME,
distributedObjectName);
</pre>
@param cacheName the simple name of the cache without any prefix
@param uri an implementation specific URI for the
Hazelcast's {@link javax.cache.CacheManager} (null means use
Hazelcast's {@link javax.cache.spi.CachingProvider#getDefaultURI()})
@param classLoader the {@link ClassLoader} to use for the
Hazelcast's {@link javax.cache.CacheManager} (null means use
Hazelcast's {@link javax.cache.spi.CachingProvider#getDefaultClassLoader()})
@return the name of the {@link ICache} distributed object corresponding to given arguments. | [
"Convenience",
"method",
"to",
"obtain",
"the",
"name",
"of",
"Hazelcast",
"distributed",
"object",
"corresponding",
"to",
"the",
"cache",
"identified",
"by",
"the",
"given",
"arguments",
".",
"The",
"distributed",
"object",
"name",
"returned",
"by",
"this",
"me... | train | https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/cache/CacheUtil.java#L131-L133 |
alkacon/opencms-core | src/org/opencms/workplace/explorer/CmsResourceUtil.java | CmsResourceUtil.getNoEditReason | public String getNoEditReason(Locale locale, boolean ignoreExpiration) throws CmsException {
String reason = "";
if (m_resource instanceof I_CmsHistoryResource) {
reason = Messages.get().getBundle(locale).key(Messages.GUI_NO_EDIT_REASON_HISTORY_0);
} else if (!m_cms.hasPermissions(
m_resource,
CmsPermissionSet.ACCESS_WRITE,
false,
ignoreExpiration ? CmsResourceFilter.IGNORE_EXPIRATION : CmsResourceFilter.DEFAULT) || !isEditable()) {
reason = Messages.get().getBundle(locale).key(Messages.GUI_NO_EDIT_REASON_PERMISSION_0);
} else if (!getLock().isLockableBy(m_cms.getRequestContext().getCurrentUser())) {
if (getLock().getSystemLock().isPublish()) {
reason = Messages.get().getBundle(locale).key(Messages.GUI_PUBLISH_TOOLTIP_0);
} else {
reason = Messages.get().getBundle(locale).key(Messages.GUI_NO_EDIT_REASON_LOCK_1, getLockedByName());
}
}
return reason;
} | java | public String getNoEditReason(Locale locale, boolean ignoreExpiration) throws CmsException {
String reason = "";
if (m_resource instanceof I_CmsHistoryResource) {
reason = Messages.get().getBundle(locale).key(Messages.GUI_NO_EDIT_REASON_HISTORY_0);
} else if (!m_cms.hasPermissions(
m_resource,
CmsPermissionSet.ACCESS_WRITE,
false,
ignoreExpiration ? CmsResourceFilter.IGNORE_EXPIRATION : CmsResourceFilter.DEFAULT) || !isEditable()) {
reason = Messages.get().getBundle(locale).key(Messages.GUI_NO_EDIT_REASON_PERMISSION_0);
} else if (!getLock().isLockableBy(m_cms.getRequestContext().getCurrentUser())) {
if (getLock().getSystemLock().isPublish()) {
reason = Messages.get().getBundle(locale).key(Messages.GUI_PUBLISH_TOOLTIP_0);
} else {
reason = Messages.get().getBundle(locale).key(Messages.GUI_NO_EDIT_REASON_LOCK_1, getLockedByName());
}
}
return reason;
} | [
"public",
"String",
"getNoEditReason",
"(",
"Locale",
"locale",
",",
"boolean",
"ignoreExpiration",
")",
"throws",
"CmsException",
"{",
"String",
"reason",
"=",
"\"\"",
";",
"if",
"(",
"m_resource",
"instanceof",
"I_CmsHistoryResource",
")",
"{",
"reason",
"=",
... | Checks is the current resource can be edited by the current user.<p>
@param locale the locale to use for the messages
@param ignoreExpiration <code>true</code> to ignore resource release and expiration date
@return an empty string if editable, or a localized string with the reason
@throws CmsException if something goes wrong | [
"Checks",
"is",
"the",
"current",
"resource",
"can",
"be",
"edited",
"by",
"the",
"current",
"user",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/workplace/explorer/CmsResourceUtil.java#L751-L770 |
OpenLiberty/open-liberty | dev/com.ibm.ws.threading/src/com/ibm/ws/threading/internal/ThroughputDistribution.java | ThroughputDistribution.addDataPoint | synchronized void addDataPoint(double value, int updated) {
// 8/10/2012: Force the standard deviation to 1/3 of the first data point
// 8/11:2012: Force it to 1/6th of the first data point (more accurate)
if (ewmaVariance == Double.NEGATIVE_INFINITY) {
reset(value, updated);
return;
}
double delta = value - ewma;
double increment = ALPHA * delta;
ewma += increment;
ewmaVariance = (1 - ALPHA) * (ewmaVariance + delta * increment);
ewmaStddev = Math.sqrt(ewmaVariance);
lastUpdate = updated;
} | java | synchronized void addDataPoint(double value, int updated) {
// 8/10/2012: Force the standard deviation to 1/3 of the first data point
// 8/11:2012: Force it to 1/6th of the first data point (more accurate)
if (ewmaVariance == Double.NEGATIVE_INFINITY) {
reset(value, updated);
return;
}
double delta = value - ewma;
double increment = ALPHA * delta;
ewma += increment;
ewmaVariance = (1 - ALPHA) * (ewmaVariance + delta * increment);
ewmaStddev = Math.sqrt(ewmaVariance);
lastUpdate = updated;
} | [
"synchronized",
"void",
"addDataPoint",
"(",
"double",
"value",
",",
"int",
"updated",
")",
"{",
"// 8/10/2012: Force the standard deviation to 1/3 of the first data point",
"// 8/11:2012: Force it to 1/6th of the first data point (more accurate)",
"if",
"(",
"ewmaVariance",
"==",
... | Add a throughput observation to the distribution, setting lastUpdate
@param value the observed throughput | [
"Add",
"a",
"throughput",
"observation",
"to",
"the",
"distribution",
"setting",
"lastUpdate"
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.threading/src/com/ibm/ws/threading/internal/ThroughputDistribution.java#L143-L159 |
google/closure-compiler | src/com/google/javascript/jscomp/ControlFlowAnalysis.java | ControlFlowAnalysis.isBreakStructure | static boolean isBreakStructure(Node n, boolean labeled) {
switch (n.getToken()) {
case FOR:
case FOR_IN:
case FOR_OF:
case FOR_AWAIT_OF:
case DO:
case WHILE:
case SWITCH:
return true;
case BLOCK:
case ROOT:
case IF:
case TRY:
return labeled;
default:
return false;
}
} | java | static boolean isBreakStructure(Node n, boolean labeled) {
switch (n.getToken()) {
case FOR:
case FOR_IN:
case FOR_OF:
case FOR_AWAIT_OF:
case DO:
case WHILE:
case SWITCH:
return true;
case BLOCK:
case ROOT:
case IF:
case TRY:
return labeled;
default:
return false;
}
} | [
"static",
"boolean",
"isBreakStructure",
"(",
"Node",
"n",
",",
"boolean",
"labeled",
")",
"{",
"switch",
"(",
"n",
".",
"getToken",
"(",
")",
")",
"{",
"case",
"FOR",
":",
"case",
"FOR_IN",
":",
"case",
"FOR_OF",
":",
"case",
"FOR_AWAIT_OF",
":",
"cas... | Determines whether the given node can be terminated with a BREAK node. | [
"Determines",
"whether",
"the",
"given",
"node",
"can",
"be",
"terminated",
"with",
"a",
"BREAK",
"node",
"."
] | train | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/ControlFlowAnalysis.java#L994-L1012 |
alkacon/opencms-core | src/org/opencms/db/CmsDriverManager.java | CmsDriverManager.writeOrganizationalUnit | public void writeOrganizationalUnit(CmsDbContext dbc, CmsOrganizationalUnit organizationalUnit)
throws CmsException {
m_monitor.uncacheOrgUnit(organizationalUnit);
getUserDriver(dbc).writeOrganizationalUnit(dbc, organizationalUnit);
// create a publish list for the 'virtual' publish event
CmsResource ouRes = readResource(dbc, organizationalUnit.getId(), CmsResourceFilter.DEFAULT);
CmsPublishList pl = new CmsPublishList(ouRes, false);
pl.add(ouRes, false);
getProjectDriver(dbc).writePublishHistory(
dbc,
pl.getPublishHistoryId(),
new CmsPublishedResource(ouRes, -1, CmsResourceState.STATE_NEW));
// fire the 'virtual' publish event
Map<String, Object> eventData = new HashMap<String, Object>();
eventData.put(I_CmsEventListener.KEY_PUBLISHID, pl.getPublishHistoryId().toString());
eventData.put(I_CmsEventListener.KEY_PROJECTID, dbc.currentProject().getUuid());
eventData.put(I_CmsEventListener.KEY_DBCONTEXT, dbc);
CmsEvent afterPublishEvent = new CmsEvent(I_CmsEventListener.EVENT_PUBLISH_PROJECT, eventData);
OpenCms.fireCmsEvent(afterPublishEvent);
m_monitor.cacheOrgUnit(organizationalUnit);
} | java | public void writeOrganizationalUnit(CmsDbContext dbc, CmsOrganizationalUnit organizationalUnit)
throws CmsException {
m_monitor.uncacheOrgUnit(organizationalUnit);
getUserDriver(dbc).writeOrganizationalUnit(dbc, organizationalUnit);
// create a publish list for the 'virtual' publish event
CmsResource ouRes = readResource(dbc, organizationalUnit.getId(), CmsResourceFilter.DEFAULT);
CmsPublishList pl = new CmsPublishList(ouRes, false);
pl.add(ouRes, false);
getProjectDriver(dbc).writePublishHistory(
dbc,
pl.getPublishHistoryId(),
new CmsPublishedResource(ouRes, -1, CmsResourceState.STATE_NEW));
// fire the 'virtual' publish event
Map<String, Object> eventData = new HashMap<String, Object>();
eventData.put(I_CmsEventListener.KEY_PUBLISHID, pl.getPublishHistoryId().toString());
eventData.put(I_CmsEventListener.KEY_PROJECTID, dbc.currentProject().getUuid());
eventData.put(I_CmsEventListener.KEY_DBCONTEXT, dbc);
CmsEvent afterPublishEvent = new CmsEvent(I_CmsEventListener.EVENT_PUBLISH_PROJECT, eventData);
OpenCms.fireCmsEvent(afterPublishEvent);
m_monitor.cacheOrgUnit(organizationalUnit);
} | [
"public",
"void",
"writeOrganizationalUnit",
"(",
"CmsDbContext",
"dbc",
",",
"CmsOrganizationalUnit",
"organizationalUnit",
")",
"throws",
"CmsException",
"{",
"m_monitor",
".",
"uncacheOrgUnit",
"(",
"organizationalUnit",
")",
";",
"getUserDriver",
"(",
"dbc",
")",
... | Writes an already existing organizational unit.<p>
The organizational unit id has to be a valid OpenCms organizational unit id.<br>
The organizational unit with the given id will be completely overridden
by the given data.<p>
@param dbc the current db context
@param organizationalUnit the organizational unit that should be written
@throws CmsException if operation was not successful
@see org.opencms.security.CmsOrgUnitManager#writeOrganizationalUnit(CmsObject, CmsOrganizationalUnit) | [
"Writes",
"an",
"already",
"existing",
"organizational",
"unit",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/db/CmsDriverManager.java#L9905-L9930 |
ksclarke/freelib-utils | src/main/java/info/freelibrary/util/FileUtils.java | FileUtils.listFiles | public static File[] listFiles(final File aDir, final FilenameFilter aFilter) throws FileNotFoundException {
return listFiles(aDir, aFilter, false, (String[]) null);
} | java | public static File[] listFiles(final File aDir, final FilenameFilter aFilter) throws FileNotFoundException {
return listFiles(aDir, aFilter, false, (String[]) null);
} | [
"public",
"static",
"File",
"[",
"]",
"listFiles",
"(",
"final",
"File",
"aDir",
",",
"final",
"FilenameFilter",
"aFilter",
")",
"throws",
"FileNotFoundException",
"{",
"return",
"listFiles",
"(",
"aDir",
",",
"aFilter",
",",
"false",
",",
"(",
"String",
"["... | An array of all the files in the supplied directory that match the supplied <code>FilenameFilter</code>.
@param aDir A directory from which a file listing should be returned
@param aFilter A file name filter which returned files should match
@return An array of matching files
@throws FileNotFoundException If the supplied directory doesn't exist | [
"An",
"array",
"of",
"all",
"the",
"files",
"in",
"the",
"supplied",
"directory",
"that",
"match",
"the",
"supplied",
"<code",
">",
"FilenameFilter<",
"/",
"code",
">",
"."
] | train | https://github.com/ksclarke/freelib-utils/blob/54e822ae4c11b3d74793fd82a1a535ffafffaf45/src/main/java/info/freelibrary/util/FileUtils.java#L342-L344 |
Esri/geometry-api-java | src/main/java/com/esri/core/geometry/Transformation2D.java | Transformation2D.flipY | public void flipY(double y0, double y1) {
yx = -yx;
yy = -yy;
yd = y0 + y1 - yd;
} | java | public void flipY(double y0, double y1) {
yx = -yx;
yy = -yy;
yd = y0 + y1 - yd;
} | [
"public",
"void",
"flipY",
"(",
"double",
"y0",
",",
"double",
"y1",
")",
"{",
"yx",
"=",
"-",
"yx",
";",
"yy",
"=",
"-",
"yy",
";",
"yd",
"=",
"y0",
"+",
"y1",
"-",
"yd",
";",
"}"
] | Flips the transformation around the Y axis.
@param y0
The Y coordinate to flip.
@param y1
The Y coordinate to flip to. | [
"Flips",
"the",
"transformation",
"around",
"the",
"Y",
"axis",
"."
] | train | https://github.com/Esri/geometry-api-java/blob/494da8ec953d76e7c6072afbc081abfe48ff07cf/src/main/java/com/esri/core/geometry/Transformation2D.java#L812-L816 |
LMAX-Exchange/disruptor | src/main/java/com/lmax/disruptor/dsl/Disruptor.java | Disruptor.publishEvent | public <A> void publishEvent(final EventTranslatorOneArg<T, A> eventTranslator, final A arg)
{
ringBuffer.publishEvent(eventTranslator, arg);
} | java | public <A> void publishEvent(final EventTranslatorOneArg<T, A> eventTranslator, final A arg)
{
ringBuffer.publishEvent(eventTranslator, arg);
} | [
"public",
"<",
"A",
">",
"void",
"publishEvent",
"(",
"final",
"EventTranslatorOneArg",
"<",
"T",
",",
"A",
">",
"eventTranslator",
",",
"final",
"A",
"arg",
")",
"{",
"ringBuffer",
".",
"publishEvent",
"(",
"eventTranslator",
",",
"arg",
")",
";",
"}"
] | Publish an event to the ring buffer.
@param <A> Class of the user supplied argument.
@param eventTranslator the translator that will load data into the event.
@param arg A single argument to load into the event | [
"Publish",
"an",
"event",
"to",
"the",
"ring",
"buffer",
"."
] | train | https://github.com/LMAX-Exchange/disruptor/blob/4266d00c5250190313446fdd7c8aa7a4edb5c818/src/main/java/com/lmax/disruptor/dsl/Disruptor.java#L341-L344 |
jbundle/jbundle | base/message/trx/src/main/java/org/jbundle/base/message/trx/message/external/convert/BaseConvertToNative.java | BaseConvertToNative.setPayloadProperties | public void setPayloadProperties(BaseMessage message, Object msg)
{
MessageDataDesc messageDataDesc = message.getMessageDataDesc(null); // Top level only
if (messageDataDesc != null)
{
Map<String,Class<?>> mapPropertyNames = messageDataDesc.getPayloadPropertyNames(null);
if (mapPropertyNames != null)
{
for (String strKey : mapPropertyNames.keySet())
{
Class<?> classKey = mapPropertyNames.get(strKey);
this.setPayloadProperty(message, msg, strKey, classKey);
}
}
}
if (message.get("Version") == null)
this.setPayloadProperty(DEFAULT_VERSION, msg, "Version", Float.class);
this.setPayloadProperty(this.getTimeStamp(), msg, "TimeStamp", org.joda.time.DateTime.class); // Current timestamp
} | java | public void setPayloadProperties(BaseMessage message, Object msg)
{
MessageDataDesc messageDataDesc = message.getMessageDataDesc(null); // Top level only
if (messageDataDesc != null)
{
Map<String,Class<?>> mapPropertyNames = messageDataDesc.getPayloadPropertyNames(null);
if (mapPropertyNames != null)
{
for (String strKey : mapPropertyNames.keySet())
{
Class<?> classKey = mapPropertyNames.get(strKey);
this.setPayloadProperty(message, msg, strKey, classKey);
}
}
}
if (message.get("Version") == null)
this.setPayloadProperty(DEFAULT_VERSION, msg, "Version", Float.class);
this.setPayloadProperty(this.getTimeStamp(), msg, "TimeStamp", org.joda.time.DateTime.class); // Current timestamp
} | [
"public",
"void",
"setPayloadProperties",
"(",
"BaseMessage",
"message",
",",
"Object",
"msg",
")",
"{",
"MessageDataDesc",
"messageDataDesc",
"=",
"message",
".",
"getMessageDataDesc",
"(",
"null",
")",
";",
"// Top level only",
"if",
"(",
"messageDataDesc",
"!=",
... | Move the standard payload properties from the message to the xml.
@param message
@param msg | [
"Move",
"the",
"standard",
"payload",
"properties",
"from",
"the",
"message",
"to",
"the",
"xml",
"."
] | train | https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/base/message/trx/src/main/java/org/jbundle/base/message/trx/message/external/convert/BaseConvertToNative.java#L171-L189 |
Azure/azure-sdk-for-java | compute/resource-manager/v2017_12_01/src/main/java/com/microsoft/azure/management/compute/v2017_12_01/implementation/VirtualMachineScaleSetVMsInner.java | VirtualMachineScaleSetVMsInner.updateAsync | public Observable<VirtualMachineScaleSetVMInner> updateAsync(String resourceGroupName, String vmScaleSetName, String instanceId, VirtualMachineScaleSetVMInner parameters) {
return updateWithServiceResponseAsync(resourceGroupName, vmScaleSetName, instanceId, parameters).map(new Func1<ServiceResponse<VirtualMachineScaleSetVMInner>, VirtualMachineScaleSetVMInner>() {
@Override
public VirtualMachineScaleSetVMInner call(ServiceResponse<VirtualMachineScaleSetVMInner> response) {
return response.body();
}
});
} | java | public Observable<VirtualMachineScaleSetVMInner> updateAsync(String resourceGroupName, String vmScaleSetName, String instanceId, VirtualMachineScaleSetVMInner parameters) {
return updateWithServiceResponseAsync(resourceGroupName, vmScaleSetName, instanceId, parameters).map(new Func1<ServiceResponse<VirtualMachineScaleSetVMInner>, VirtualMachineScaleSetVMInner>() {
@Override
public VirtualMachineScaleSetVMInner call(ServiceResponse<VirtualMachineScaleSetVMInner> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"VirtualMachineScaleSetVMInner",
">",
"updateAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"vmScaleSetName",
",",
"String",
"instanceId",
",",
"VirtualMachineScaleSetVMInner",
"parameters",
")",
"{",
"return",
"updateWithServiceResp... | Updates a virtual machine of a VM scale set.
@param resourceGroupName The name of the resource group.
@param vmScaleSetName The name of the VM scale set where the extension should be create or updated.
@param instanceId The instance ID of the virtual machine.
@param parameters Parameters supplied to the Update Virtual Machine Scale Sets VM operation.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable for the request | [
"Updates",
"a",
"virtual",
"machine",
"of",
"a",
"VM",
"scale",
"set",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/compute/resource-manager/v2017_12_01/src/main/java/com/microsoft/azure/management/compute/v2017_12_01/implementation/VirtualMachineScaleSetVMsInner.java#L714-L721 |
molgenis/molgenis | molgenis-data-postgresql/src/main/java/org/molgenis/data/postgresql/PostgreSqlExceptionTranslator.java | PostgreSqlExceptionTranslator.translateReadonlyViolation | MolgenisValidationException translateReadonlyViolation(PSQLException pSqlException) {
Matcher matcher =
Pattern.compile(
"Updating read-only column \"?(.*?)\"? of table \"?(.*?)\"? with id \\[(.*?)] is not allowed")
.matcher(pSqlException.getServerErrorMessage().getMessage());
boolean matches = matcher.matches();
if (!matches) {
LOG.error(ERROR_TRANSLATING_POSTGRES_EXC_MSG, pSqlException);
throw new RuntimeException(ERROR_TRANSLATING_EXCEPTION_MSG, pSqlException);
}
String colName = matcher.group(1);
String tableName = matcher.group(2);
String id = matcher.group(3);
ConstraintViolation constraintViolation =
new ConstraintViolation(
format(
"Updating read-only attribute '%s' of entity '%s' with id '%s' is not allowed.",
tryGetAttributeName(tableName, colName).orElse(TOKEN_UNKNOWN),
tryGetEntityTypeName(tableName).orElse(TOKEN_UNKNOWN),
id));
return new MolgenisValidationException(singleton(constraintViolation));
} | java | MolgenisValidationException translateReadonlyViolation(PSQLException pSqlException) {
Matcher matcher =
Pattern.compile(
"Updating read-only column \"?(.*?)\"? of table \"?(.*?)\"? with id \\[(.*?)] is not allowed")
.matcher(pSqlException.getServerErrorMessage().getMessage());
boolean matches = matcher.matches();
if (!matches) {
LOG.error(ERROR_TRANSLATING_POSTGRES_EXC_MSG, pSqlException);
throw new RuntimeException(ERROR_TRANSLATING_EXCEPTION_MSG, pSqlException);
}
String colName = matcher.group(1);
String tableName = matcher.group(2);
String id = matcher.group(3);
ConstraintViolation constraintViolation =
new ConstraintViolation(
format(
"Updating read-only attribute '%s' of entity '%s' with id '%s' is not allowed.",
tryGetAttributeName(tableName, colName).orElse(TOKEN_UNKNOWN),
tryGetEntityTypeName(tableName).orElse(TOKEN_UNKNOWN),
id));
return new MolgenisValidationException(singleton(constraintViolation));
} | [
"MolgenisValidationException",
"translateReadonlyViolation",
"(",
"PSQLException",
"pSqlException",
")",
"{",
"Matcher",
"matcher",
"=",
"Pattern",
".",
"compile",
"(",
"\"Updating read-only column \\\"?(.*?)\\\"? of table \\\"?(.*?)\\\"? with id \\\\[(.*?)] is not allowed\"",
")",
"... | Package private for testability
@param pSqlException PostgreSQL exception
@return translated validation exception | [
"Package",
"private",
"for",
"testability"
] | train | https://github.com/molgenis/molgenis/blob/b4d0d6b27e6f6c8d7505a3863dc03b589601f987/molgenis-data-postgresql/src/main/java/org/molgenis/data/postgresql/PostgreSqlExceptionTranslator.java#L143-L164 |
Jasig/uPortal | uPortal-groups/uPortal-groups-core/src/main/java/org/apereo/portal/groups/RDBMEntityGroupStore.java | RDBMEntityGroupStore.primFind | private IEntityGroup primFind(String groupID, boolean lockable) throws GroupsException {
IEntityGroup eg = null;
Connection conn = null;
try {
conn = RDBMServices.getConnection();
String sql = getFindGroupSql();
PreparedStatement ps = conn.prepareStatement(sql);
try {
ps.setString(1, groupID);
if (LOG.isDebugEnabled())
LOG.debug("RDBMEntityGroupStore.find(): " + ps + " (" + groupID + ")");
ResultSet rs = ps.executeQuery();
try {
while (rs.next()) {
eg =
(lockable)
? lockableInstanceFromResultSet(rs)
: instanceFromResultSet(rs);
}
} finally {
rs.close();
}
} finally {
ps.close();
}
} catch (Exception e) {
LOG.error("RDBMEntityGroupStore.find(): ", e);
throw new GroupsException("Error retrieving " + groupID + ": ", e);
} finally {
RDBMServices.releaseConnection(conn);
}
return eg;
} | java | private IEntityGroup primFind(String groupID, boolean lockable) throws GroupsException {
IEntityGroup eg = null;
Connection conn = null;
try {
conn = RDBMServices.getConnection();
String sql = getFindGroupSql();
PreparedStatement ps = conn.prepareStatement(sql);
try {
ps.setString(1, groupID);
if (LOG.isDebugEnabled())
LOG.debug("RDBMEntityGroupStore.find(): " + ps + " (" + groupID + ")");
ResultSet rs = ps.executeQuery();
try {
while (rs.next()) {
eg =
(lockable)
? lockableInstanceFromResultSet(rs)
: instanceFromResultSet(rs);
}
} finally {
rs.close();
}
} finally {
ps.close();
}
} catch (Exception e) {
LOG.error("RDBMEntityGroupStore.find(): ", e);
throw new GroupsException("Error retrieving " + groupID + ": ", e);
} finally {
RDBMServices.releaseConnection(conn);
}
return eg;
} | [
"private",
"IEntityGroup",
"primFind",
"(",
"String",
"groupID",
",",
"boolean",
"lockable",
")",
"throws",
"GroupsException",
"{",
"IEntityGroup",
"eg",
"=",
"null",
";",
"Connection",
"conn",
"=",
"null",
";",
"try",
"{",
"conn",
"=",
"RDBMServices",
".",
... | Find and return an instance of the group.
@param groupID the group ID
@param lockable boolean
@return IEntityGroup | [
"Find",
"and",
"return",
"an",
"instance",
"of",
"the",
"group",
"."
] | train | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-groups/uPortal-groups-core/src/main/java/org/apereo/portal/groups/RDBMEntityGroupStore.java#L1114-L1147 |
pmwmedia/tinylog | tinylog-impl/src/main/java/org/tinylog/core/ConfigurationParser.java | ConfigurationParser.parse | private static Level parse(final String property, final Level defaultValue) {
if (property == null) {
return defaultValue;
} else {
try {
return Level.valueOf(property.toUpperCase(Locale.ROOT));
} catch (IllegalArgumentException ex) {
InternalLogger.log(Level.ERROR, "Illegal severity level: " + property);
return defaultValue;
}
}
} | java | private static Level parse(final String property, final Level defaultValue) {
if (property == null) {
return defaultValue;
} else {
try {
return Level.valueOf(property.toUpperCase(Locale.ROOT));
} catch (IllegalArgumentException ex) {
InternalLogger.log(Level.ERROR, "Illegal severity level: " + property);
return defaultValue;
}
}
} | [
"private",
"static",
"Level",
"parse",
"(",
"final",
"String",
"property",
",",
"final",
"Level",
"defaultValue",
")",
"{",
"if",
"(",
"property",
"==",
"null",
")",
"{",
"return",
"defaultValue",
";",
"}",
"else",
"{",
"try",
"{",
"return",
"Level",
"."... | Reads a severity level from configuration.
@param property
Key of property
@param defaultValue
Default value, if property doesn't exist or is invalid
@return Severity level | [
"Reads",
"a",
"severity",
"level",
"from",
"configuration",
"."
] | train | https://github.com/pmwmedia/tinylog/blob/d03d4ef84a1310155037e08ca8822a91697d1086/tinylog-impl/src/main/java/org/tinylog/core/ConfigurationParser.java#L223-L234 |
pravega/pravega | controller/src/main/java/io/pravega/controller/metrics/StreamMetrics.java | StreamMetrics.updateStreamFailed | public void updateStreamFailed(String scope, String streamName) {
DYNAMIC_LOGGER.incCounterValue(globalMetricName(UPDATE_STREAM_FAILED), 1);
DYNAMIC_LOGGER.incCounterValue(UPDATE_STREAM_FAILED, 1, streamTags(scope, streamName));
} | java | public void updateStreamFailed(String scope, String streamName) {
DYNAMIC_LOGGER.incCounterValue(globalMetricName(UPDATE_STREAM_FAILED), 1);
DYNAMIC_LOGGER.incCounterValue(UPDATE_STREAM_FAILED, 1, streamTags(scope, streamName));
} | [
"public",
"void",
"updateStreamFailed",
"(",
"String",
"scope",
",",
"String",
"streamName",
")",
"{",
"DYNAMIC_LOGGER",
".",
"incCounterValue",
"(",
"globalMetricName",
"(",
"UPDATE_STREAM_FAILED",
")",
",",
"1",
")",
";",
"DYNAMIC_LOGGER",
".",
"incCounterValue",
... | This method increments the counter of failed Stream update operations in the system as well as the failed
update attempts for this specific Stream.
@param scope Scope.
@param streamName Name of the Stream. | [
"This",
"method",
"increments",
"the",
"counter",
"of",
"failed",
"Stream",
"update",
"operations",
"in",
"the",
"system",
"as",
"well",
"as",
"the",
"failed",
"update",
"attempts",
"for",
"this",
"specific",
"Stream",
"."
] | train | https://github.com/pravega/pravega/blob/6e24df7470669b3956a07018f52b2c6b3c2a3503/controller/src/main/java/io/pravega/controller/metrics/StreamMetrics.java#L152-L155 |
FedericoPecora/meta-csp-framework | src/main/java/org/metacsp/multi/spatial/DE9IM/DE9IMRelation.java | DE9IMRelation.isRelation | public static boolean isRelation(GeometricShapeVariable gv1, GeometricShapeVariable gv2, DE9IMRelation.Type t) {
try {
String methodName = t.name().substring(0, 1).toLowerCase() + t.name().substring(1);
Method m = Geometry.class.getMethod(methodName, Geometry.class);
Geometry g1 = ((GeometricShapeDomain)gv1.getDomain()).getGeometry();
Geometry g2 = ((GeometricShapeDomain)gv2.getDomain()).getGeometry();
return ((Boolean)m.invoke(g1, g2));
}
catch (NoSuchMethodException e) { e.printStackTrace(); }
catch (SecurityException e) { e.printStackTrace(); }
catch (IllegalAccessException e) { e.printStackTrace(); }
catch (IllegalArgumentException e) { e.printStackTrace(); }
catch (InvocationTargetException e) { e.printStackTrace(); }
return false;
} | java | public static boolean isRelation(GeometricShapeVariable gv1, GeometricShapeVariable gv2, DE9IMRelation.Type t) {
try {
String methodName = t.name().substring(0, 1).toLowerCase() + t.name().substring(1);
Method m = Geometry.class.getMethod(methodName, Geometry.class);
Geometry g1 = ((GeometricShapeDomain)gv1.getDomain()).getGeometry();
Geometry g2 = ((GeometricShapeDomain)gv2.getDomain()).getGeometry();
return ((Boolean)m.invoke(g1, g2));
}
catch (NoSuchMethodException e) { e.printStackTrace(); }
catch (SecurityException e) { e.printStackTrace(); }
catch (IllegalAccessException e) { e.printStackTrace(); }
catch (IllegalArgumentException e) { e.printStackTrace(); }
catch (InvocationTargetException e) { e.printStackTrace(); }
return false;
} | [
"public",
"static",
"boolean",
"isRelation",
"(",
"GeometricShapeVariable",
"gv1",
",",
"GeometricShapeVariable",
"gv2",
",",
"DE9IMRelation",
".",
"Type",
"t",
")",
"{",
"try",
"{",
"String",
"methodName",
"=",
"t",
".",
"name",
"(",
")",
".",
"substring",
... | Check if the spatial relation between two {@link GeometricShapeVariable}s is of a given type.
@param gv1 The source {@link GeometricShapeVariable}.
@param gv2 The destination {@link GeometricShapeVariable}.
@param t The type of relation to check.
@return <code>true</code> iff the given variables are in the given relation. | [
"Check",
"if",
"the",
"spatial",
"relation",
"between",
"two",
"{"
] | train | https://github.com/FedericoPecora/meta-csp-framework/blob/42aaef2e2b76d0f738427f0dd9653c4f62b40517/src/main/java/org/metacsp/multi/spatial/DE9IM/DE9IMRelation.java#L78-L92 |
joniles/mpxj | src/main/java/net/sf/mpxj/mpp/MPPUtility.java | MPPUtility.getUnicodeStringLengthInBytes | private static final int getUnicodeStringLengthInBytes(byte[] data, int offset)
{
int result;
if (data == null || offset >= data.length)
{
result = 0;
}
else
{
result = data.length - offset;
for (int loop = offset; loop < (data.length - 1); loop += 2)
{
if (data[loop] == 0 && data[loop + 1] == 0)
{
result = loop - offset;
break;
}
}
}
return result;
} | java | private static final int getUnicodeStringLengthInBytes(byte[] data, int offset)
{
int result;
if (data == null || offset >= data.length)
{
result = 0;
}
else
{
result = data.length - offset;
for (int loop = offset; loop < (data.length - 1); loop += 2)
{
if (data[loop] == 0 && data[loop + 1] == 0)
{
result = loop - offset;
break;
}
}
}
return result;
} | [
"private",
"static",
"final",
"int",
"getUnicodeStringLengthInBytes",
"(",
"byte",
"[",
"]",
"data",
",",
"int",
"offset",
")",
"{",
"int",
"result",
";",
"if",
"(",
"data",
"==",
"null",
"||",
"offset",
">=",
"data",
".",
"length",
")",
"{",
"result",
... | Determine the length of a nul terminated UTF16LE string in bytes.
@param data string data
@param offset offset into string data
@return length in bytes | [
"Determine",
"the",
"length",
"of",
"a",
"nul",
"terminated",
"UTF16LE",
"string",
"in",
"bytes",
"."
] | train | https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/mpp/MPPUtility.java#L459-L480 |
nabedge/mixer2 | src/main/java/org/mixer2/xhtml/AbstractJaxb.java | AbstractJaxb.getDescendants | @SuppressWarnings("unchecked")
public <T extends AbstractJaxb> List<T> getDescendants(String clazz,
Class<T> tagType) {
return GetDescendantsUtil.getDescendants((T) this, new ArrayList<T>(),
clazz, tagType);
} | java | @SuppressWarnings("unchecked")
public <T extends AbstractJaxb> List<T> getDescendants(String clazz,
Class<T> tagType) {
return GetDescendantsUtil.getDescendants((T) this, new ArrayList<T>(),
clazz, tagType);
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"public",
"<",
"T",
"extends",
"AbstractJaxb",
">",
"List",
"<",
"T",
">",
"getDescendants",
"(",
"String",
"clazz",
",",
"Class",
"<",
"T",
">",
"tagType",
")",
"{",
"return",
"GetDescendantsUtil",
".",
... | <p>
scan descendant element that is specified tag type having specified class
attribute and return it as List.
</p>
<pre>
// usage:
// get all div objects having "foo" class
List<Div> divList = html.getDescendants("foo", Div.class);
// get all Table objects having "bar" class within <div id="foo">
List<Table> tbList = html.getById("foo", Div.class).getDescendants("bar",
Table.class);
</pre>
@param clazz
@param tagType
@return | [
"<p",
">",
"scan",
"descendant",
"element",
"that",
"is",
"specified",
"tag",
"type",
"having",
"specified",
"class",
"attribute",
"and",
"return",
"it",
"as",
"List",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/nabedge/mixer2/blob/8c2db27cfcd65bf0b1e0242ef9362ebd8033777c/src/main/java/org/mixer2/xhtml/AbstractJaxb.java#L224-L229 |
blackfizz/EazeGraph | EazeGraphLibrary/src/main/java/org/eazegraph/lib/charts/StackedBarChart.java | StackedBarChart.initializeGraph | @Override
protected void initializeGraph() {
super.initializeGraph();
mData = new ArrayList<>();
mSeperatorPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mSeperatorPaint.setStyle(Paint.Style.FILL_AND_STROKE);
mSeperatorPaint.setStrokeWidth(mSeparatorWidth);
mSeperatorPaint.setColor(0xFFFFFFFF);
mTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mTextPaint.setTextSize(mTextSize);
mTextPaint.setTextAlign(Paint.Align.CENTER);
mTextPaint.setColor(0xFFFFFFFF);
if(this.isInEditMode()) {
StackedBarModel s1 = new StackedBarModel();
s1.addBar(new BarModel(2.3f, 0xFF123456));
s1.addBar(new BarModel(2.f, 0xFF1EF556));
s1.addBar(new BarModel(3.3f, 0xFF1BA4E6));
StackedBarModel s2 = new StackedBarModel();
s2.addBar(new BarModel(1.1f, 0xFF123456));
s2.addBar(new BarModel(2.7f, 0xFF1EF556));
s2.addBar(new BarModel(0.7f, 0xFF1BA4E6));
addBar(s1);
addBar(s2);
}
} | java | @Override
protected void initializeGraph() {
super.initializeGraph();
mData = new ArrayList<>();
mSeperatorPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mSeperatorPaint.setStyle(Paint.Style.FILL_AND_STROKE);
mSeperatorPaint.setStrokeWidth(mSeparatorWidth);
mSeperatorPaint.setColor(0xFFFFFFFF);
mTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mTextPaint.setTextSize(mTextSize);
mTextPaint.setTextAlign(Paint.Align.CENTER);
mTextPaint.setColor(0xFFFFFFFF);
if(this.isInEditMode()) {
StackedBarModel s1 = new StackedBarModel();
s1.addBar(new BarModel(2.3f, 0xFF123456));
s1.addBar(new BarModel(2.f, 0xFF1EF556));
s1.addBar(new BarModel(3.3f, 0xFF1BA4E6));
StackedBarModel s2 = new StackedBarModel();
s2.addBar(new BarModel(1.1f, 0xFF123456));
s2.addBar(new BarModel(2.7f, 0xFF1EF556));
s2.addBar(new BarModel(0.7f, 0xFF1BA4E6));
addBar(s1);
addBar(s2);
}
} | [
"@",
"Override",
"protected",
"void",
"initializeGraph",
"(",
")",
"{",
"super",
".",
"initializeGraph",
"(",
")",
";",
"mData",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"mSeperatorPaint",
"=",
"new",
"Paint",
"(",
"Paint",
".",
"ANTI_ALIAS_FLAG",
")"... | This is the main entry point after the graph has been inflated. Used to initialize the graph
and its corresponding members. | [
"This",
"is",
"the",
"main",
"entry",
"point",
"after",
"the",
"graph",
"has",
"been",
"inflated",
".",
"Used",
"to",
"initialize",
"the",
"graph",
"and",
"its",
"corresponding",
"members",
"."
] | train | https://github.com/blackfizz/EazeGraph/blob/ce5e68ecc70e154f83bbb2fcce1a970db125c1e6/EazeGraphLibrary/src/main/java/org/eazegraph/lib/charts/StackedBarChart.java#L183-L213 |
cloudant/sync-android | cloudant-sync-datastore-core/src/main/java/com/cloudant/sync/internal/documentstore/DatabaseImpl.java | DatabaseImpl.forceInsert | public void forceInsert(final List<ForceInsertItem> items) throws DocumentException {
Misc.checkState(this.isOpen(), "Database is closed");
for (ForceInsertItem item : items) {
Misc.checkNotNull(item.rev, "Input document revision");
Misc.checkNotNull(item.revisionHistory, "Input revision history");
Misc.checkArgument(item.revisionHistory.size() > 0, "Input revision history " +
"must not be empty");
Misc.checkArgument(checkCurrentRevisionIsInRevisionHistory(item.rev, item
.revisionHistory), "Current revision must exist in revision history.");
Misc.checkArgument(checkRevisionIsInCorrectOrder(item.revisionHistory),
"Revision history must be in right order.");
CouchUtils.validateDocumentId(item.rev.getId());
CouchUtils.validateRevisionId(item.rev.getRevision());
}
try {
// for raising events after completing database transaction
List<DocumentModified> events = queue.submitTransaction(new ForceInsertCallable(items, attachmentsDir, attachmentStreamFactory)).get();
// if we got here, everything got written to the database successfully
// now raise any events we stored up
for (DocumentModified event : events) {
eventBus.post(event);
}
} catch (InterruptedException e) {
throw new RuntimeException(e);
} catch (ExecutionException e) {
throw new DocumentException(e);
}
} | java | public void forceInsert(final List<ForceInsertItem> items) throws DocumentException {
Misc.checkState(this.isOpen(), "Database is closed");
for (ForceInsertItem item : items) {
Misc.checkNotNull(item.rev, "Input document revision");
Misc.checkNotNull(item.revisionHistory, "Input revision history");
Misc.checkArgument(item.revisionHistory.size() > 0, "Input revision history " +
"must not be empty");
Misc.checkArgument(checkCurrentRevisionIsInRevisionHistory(item.rev, item
.revisionHistory), "Current revision must exist in revision history.");
Misc.checkArgument(checkRevisionIsInCorrectOrder(item.revisionHistory),
"Revision history must be in right order.");
CouchUtils.validateDocumentId(item.rev.getId());
CouchUtils.validateRevisionId(item.rev.getRevision());
}
try {
// for raising events after completing database transaction
List<DocumentModified> events = queue.submitTransaction(new ForceInsertCallable(items, attachmentsDir, attachmentStreamFactory)).get();
// if we got here, everything got written to the database successfully
// now raise any events we stored up
for (DocumentModified event : events) {
eventBus.post(event);
}
} catch (InterruptedException e) {
throw new RuntimeException(e);
} catch (ExecutionException e) {
throw new DocumentException(e);
}
} | [
"public",
"void",
"forceInsert",
"(",
"final",
"List",
"<",
"ForceInsertItem",
">",
"items",
")",
"throws",
"DocumentException",
"{",
"Misc",
".",
"checkState",
"(",
"this",
".",
"isOpen",
"(",
")",
",",
"\"Database is closed\"",
")",
";",
"for",
"(",
"Force... | <p>
Inserts one or more revisions of a document into the database. For efficiency, this is
performed as one database transaction.
</p>
<p>
Each revision is inserted at a point in the tree expressed by the path described in the
{@code revisionHistory} field. If any non-leaf revisions do not exist locally, then they are
created as "stub" revisions.
</p>
<p>
This method should only be called by the replicator. It is designed
to allow revisions from remote databases to be added to this
database during the replication process: the documents in the remote database already have
revision IDs that need to be preserved for the two databases to be in sync (otherwise it
would not be possible to tell that the two represent the same revision). This is analogous to
using the _new_edits false option in CouchDB
(see
<a target="_blank" href="https://wiki.apache.org/couchdb/HTTP_Bulk_Document_API#Posting_Existing_Revisions">
the CouchDB wiki</a> for more detail).
<p>
If the document was successfully inserted, a
{@link com.cloudant.sync.event.notifications.DocumentCreated DocumentCreated},
{@link com.cloudant.sync.event.notifications.DocumentModified DocumentModified}, or
{@link com.cloudant.sync.event.notifications.DocumentDeleted DocumentDeleted}
event is posted on the event bus. The event will depend on the nature
of the update made.
</p>
@param items one or more revisions to insert.
@see Database#getEventBus()
@throws DocumentException if there was an error inserting the revision or its attachments
into the database | [
"<p",
">",
"Inserts",
"one",
"or",
"more",
"revisions",
"of",
"a",
"document",
"into",
"the",
"database",
".",
"For",
"efficiency",
"this",
"is",
"performed",
"as",
"one",
"database",
"transaction",
".",
"<",
"/",
"p",
">",
"<p",
">",
"Each",
"revision",... | train | https://github.com/cloudant/sync-android/blob/5f1416ed1bd9ab05d7a4b8736480c8ae68bd7383/cloudant-sync-datastore-core/src/main/java/com/cloudant/sync/internal/documentstore/DatabaseImpl.java#L541-L574 |
Wadpam/guja | guja-core/src/main/java/com/wadpam/guja/oauth2/api/UserResource.java | UserResource.changeUsername | @POST
@Path("me/username")
@RolesAllowed({"ROLE_ADMIN", "ROLE_USER"})
public Response changeUsername(@Context HttpServletRequest request, UsernameRequest usernameRequest) {
Long userId = (Long) request.getAttribute(OAuth2Filter.NAME_USER_ID);
return changeUsername(userId, usernameRequest);
} | java | @POST
@Path("me/username")
@RolesAllowed({"ROLE_ADMIN", "ROLE_USER"})
public Response changeUsername(@Context HttpServletRequest request, UsernameRequest usernameRequest) {
Long userId = (Long) request.getAttribute(OAuth2Filter.NAME_USER_ID);
return changeUsername(userId, usernameRequest);
} | [
"@",
"POST",
"@",
"Path",
"(",
"\"me/username\"",
")",
"@",
"RolesAllowed",
"(",
"{",
"\"ROLE_ADMIN\"",
",",
"\"ROLE_USER\"",
"}",
")",
"public",
"Response",
"changeUsername",
"(",
"@",
"Context",
"HttpServletRequest",
"request",
",",
"UsernameRequest",
"usernameR... | Change current users username.
The username must be unique
@param usernameRequest new username
@return 200 if success
409 if username is not unique | [
"Change",
"current",
"users",
"username",
".",
"The",
"username",
"must",
"be",
"unique"
] | train | https://github.com/Wadpam/guja/blob/eb8ba8e6794a96ea0dd9744cada4f9ad9618f114/guja-core/src/main/java/com/wadpam/guja/oauth2/api/UserResource.java#L325-L331 |
Azure/azure-sdk-for-java | cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/ModelsImpl.java | ModelsImpl.getEntity | public EntityExtractor getEntity(UUID appId, String versionId, UUID entityId) {
return getEntityWithServiceResponseAsync(appId, versionId, entityId).toBlocking().single().body();
} | java | public EntityExtractor getEntity(UUID appId, String versionId, UUID entityId) {
return getEntityWithServiceResponseAsync(appId, versionId, entityId).toBlocking().single().body();
} | [
"public",
"EntityExtractor",
"getEntity",
"(",
"UUID",
"appId",
",",
"String",
"versionId",
",",
"UUID",
"entityId",
")",
"{",
"return",
"getEntityWithServiceResponseAsync",
"(",
"appId",
",",
"versionId",
",",
"entityId",
")",
".",
"toBlocking",
"(",
")",
".",
... | Gets information about the entity model.
@param appId The application ID.
@param versionId The version ID.
@param entityId The entity extractor ID.
@throws IllegalArgumentException thrown if parameters fail the validation
@throws ErrorResponseException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the EntityExtractor object if successful. | [
"Gets",
"information",
"about",
"the",
"entity",
"model",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/ModelsImpl.java#L3285-L3287 |
camunda/camunda-commons | logging/src/main/java/org/camunda/commons/logging/BaseLogger.java | BaseLogger.logDebug | protected void logDebug(String id, String messageTemplate, Object... parameters) {
if(delegateLogger.isDebugEnabled()) {
String msg = formatMessageTemplate(id, messageTemplate);
delegateLogger.debug(msg, parameters);
}
} | java | protected void logDebug(String id, String messageTemplate, Object... parameters) {
if(delegateLogger.isDebugEnabled()) {
String msg = formatMessageTemplate(id, messageTemplate);
delegateLogger.debug(msg, parameters);
}
} | [
"protected",
"void",
"logDebug",
"(",
"String",
"id",
",",
"String",
"messageTemplate",
",",
"Object",
"...",
"parameters",
")",
"{",
"if",
"(",
"delegateLogger",
".",
"isDebugEnabled",
"(",
")",
")",
"{",
"String",
"msg",
"=",
"formatMessageTemplate",
"(",
... | Logs a 'DEBUG' message
@param id the unique id of this log message
@param messageTemplate the message template to use
@param parameters a list of optional parameters | [
"Logs",
"a",
"DEBUG",
"message"
] | train | https://github.com/camunda/camunda-commons/blob/bd3195db47c92c25717288fe9e6735f8e882f247/logging/src/main/java/org/camunda/commons/logging/BaseLogger.java#L115-L120 |
soulwarelabs/jParley-Utility | src/main/java/com/soulwarelabs/jparley/utility/Manager.java | Manager.setupAll | public void setupAll(Connection connection, Statement statement)
throws SQLException {
for (Object key : mappings.keySet()) {
Parameter parameter = mappings.get(key);
if (parameter.getInput() != null) {
Object value = parameter.getInput().getValue();
Converter encoder = parameter.getEncoder();
if (encoder != null) {
value = encoder.perform(connection, value);
}
statement.in(key, value, parameter.getType());
}
if (parameter.getOutput() != null) {
Integer sqlType = parameter.getType();
String structName = parameter.getStruct();
statement.out(key, sqlType, structName);
}
}
} | java | public void setupAll(Connection connection, Statement statement)
throws SQLException {
for (Object key : mappings.keySet()) {
Parameter parameter = mappings.get(key);
if (parameter.getInput() != null) {
Object value = parameter.getInput().getValue();
Converter encoder = parameter.getEncoder();
if (encoder != null) {
value = encoder.perform(connection, value);
}
statement.in(key, value, parameter.getType());
}
if (parameter.getOutput() != null) {
Integer sqlType = parameter.getType();
String structName = parameter.getStruct();
statement.out(key, sqlType, structName);
}
}
} | [
"public",
"void",
"setupAll",
"(",
"Connection",
"connection",
",",
"Statement",
"statement",
")",
"throws",
"SQLException",
"{",
"for",
"(",
"Object",
"key",
":",
"mappings",
".",
"keySet",
"(",
")",
")",
"{",
"Parameter",
"parameter",
"=",
"mappings",
".",... | Set up all registered parameters to specified statement.
@param connection an SQL database connection.
@param statement an SQL callable statement.
@throws SQLException if error occurs while setting up parameters.
@see Connection
@see Statement
@since v1.0 | [
"Set",
"up",
"all",
"registered",
"parameters",
"to",
"specified",
"statement",
"."
] | train | https://github.com/soulwarelabs/jParley-Utility/blob/825d139b9d294ef4cf71dbce349be5cb3da1b3a9/src/main/java/com/soulwarelabs/jparley/utility/Manager.java#L200-L218 |
apereo/cas | core/cas-server-core-util-api/src/main/java/org/apereo/cas/util/crypto/CertUtils.java | CertUtils.readCertificate | public static X509Certificate readCertificate(final InputStreamSource resource) {
try (val in = resource.getInputStream()) {
return CertUtil.readCertificate(in);
} catch (final IOException e) {
throw new IllegalArgumentException("Error reading certificate " + resource, e);
}
} | java | public static X509Certificate readCertificate(final InputStreamSource resource) {
try (val in = resource.getInputStream()) {
return CertUtil.readCertificate(in);
} catch (final IOException e) {
throw new IllegalArgumentException("Error reading certificate " + resource, e);
}
} | [
"public",
"static",
"X509Certificate",
"readCertificate",
"(",
"final",
"InputStreamSource",
"resource",
")",
"{",
"try",
"(",
"val",
"in",
"=",
"resource",
".",
"getInputStream",
"(",
")",
")",
"{",
"return",
"CertUtil",
".",
"readCertificate",
"(",
"in",
")"... | Read certificate.
@param resource the resource to read the cert from
@return the x 509 certificate | [
"Read",
"certificate",
"."
] | train | https://github.com/apereo/cas/blob/b4b306433a8782cef803a39bea5b1f96740e0e9b/core/cas-server-core-util-api/src/main/java/org/apereo/cas/util/crypto/CertUtils.java#L65-L71 |
eclipse/xtext-lib | org.eclipse.xtext.xbase.lib/src/org/eclipse/xtext/xbase/lib/MapExtensions.java | MapExtensions.operator_add | @Inline(value = "$1.put($2.getKey(), $2.getValue())", statementExpression = true)
public static <K, V> V operator_add(Map<K, V> map, Pair<? extends K, ? extends V> entry) {
return map.put(entry.getKey(), entry.getValue());
} | java | @Inline(value = "$1.put($2.getKey(), $2.getValue())", statementExpression = true)
public static <K, V> V operator_add(Map<K, V> map, Pair<? extends K, ? extends V> entry) {
return map.put(entry.getKey(), entry.getValue());
} | [
"@",
"Inline",
"(",
"value",
"=",
"\"$1.put($2.getKey(), $2.getValue())\"",
",",
"statementExpression",
"=",
"true",
")",
"public",
"static",
"<",
"K",
",",
"V",
">",
"V",
"operator_add",
"(",
"Map",
"<",
"K",
",",
"V",
">",
"map",
",",
"Pair",
"<",
"?",... | Add the given pair into the map.
<p>
If the pair key already exists in the map, its value is replaced
by the value in the pair, and the old value in the map is returned.
</p>
@param <K> type of the map keys.
@param <V> type of the map values.
@param map the map to update.
@param entry the entry (key, value) to add into the map.
@return the value previously associated to the key, or <code>null</code>
if the key was not present in the map before the addition.
@since 2.15 | [
"Add",
"the",
"given",
"pair",
"into",
"the",
"map",
"."
] | train | https://github.com/eclipse/xtext-lib/blob/7063572e1f1bd713a3aa53bdf3a8dc60e25c169a/org.eclipse.xtext.xbase.lib/src/org/eclipse/xtext/xbase/lib/MapExtensions.java#L118-L121 |
mgormley/pacaya | src/main/java/edu/jhu/pacaya/gm/inf/BeliefPropagation.java | BeliefPropagation.getResidual | private double getResidual(VarTensor t1, VarTensor t2) {
assert s == t1.getAlgebra() && s == t2.getAlgebra();
Tensor.checkEqualSize(t1, t2);
Tensor.checkSameAlgebra(t1, t2);
double residual = Double.NEGATIVE_INFINITY;
for (int c=0; c<t1.size(); c++) {
double abs = Math.abs(s.toLogProb(t1.get(c)) - s.toLogProb(t2.get(c)));
if (abs > residual) {
residual = abs;
}
}
return residual;
} | java | private double getResidual(VarTensor t1, VarTensor t2) {
assert s == t1.getAlgebra() && s == t2.getAlgebra();
Tensor.checkEqualSize(t1, t2);
Tensor.checkSameAlgebra(t1, t2);
double residual = Double.NEGATIVE_INFINITY;
for (int c=0; c<t1.size(); c++) {
double abs = Math.abs(s.toLogProb(t1.get(c)) - s.toLogProb(t2.get(c)));
if (abs > residual) {
residual = abs;
}
}
return residual;
} | [
"private",
"double",
"getResidual",
"(",
"VarTensor",
"t1",
",",
"VarTensor",
"t2",
")",
"{",
"assert",
"s",
"==",
"t1",
".",
"getAlgebra",
"(",
")",
"&&",
"s",
"==",
"t2",
".",
"getAlgebra",
"(",
")",
";",
"Tensor",
".",
"checkEqualSize",
"(",
"t1",
... | Gets the residual for a new message, as the maximum error over all assignments.
Following the definition of Sutton & McCallum (2007), we compute the residual as the infinity
norm of the difference of the log of the message vectors.
Note: the returned value is NOT in the semiring / abstract algebra. It is the actual value
described above. | [
"Gets",
"the",
"residual",
"for",
"a",
"new",
"message",
"as",
"the",
"maximum",
"error",
"over",
"all",
"assignments",
"."
] | train | https://github.com/mgormley/pacaya/blob/786294cbac7cc65dbc32210c10acc32ed0c69233/src/main/java/edu/jhu/pacaya/gm/inf/BeliefPropagation.java#L485-L497 |
intuit/QuickBooks-V3-Java-SDK | oauth2-platform-api/src/main/java/com/intuit/oauth2/config/OAuth2Config.java | OAuth2Config.prepareUrl | public String prepareUrl(List<Scope> scopes, String redirectUri, String csrfToken) throws InvalidRequestException {
logger.debug("Enter OAuth2config::prepareUrl");
if(scopes == null || scopes.isEmpty() || redirectUri.isEmpty() || csrfToken.isEmpty()) {
logger.error("Invalid request for prepareUrl ");
throw new InvalidRequestException("Invalid request for prepareUrl");
}
try {
return intuitAuthorizationEndpoint
+ "?client_id=" + clientId
+ "&response_type=code&scope=" + URLEncoder.encode(buildScopeString(scopes), "UTF-8")
+ "&redirect_uri=" + URLEncoder.encode(redirectUri, "UTF-8")
+ "&state=" + csrfToken;
} catch (UnsupportedEncodingException e) {
logger.error("Exception while preparing url for redirect ", e);
throw new InvalidRequestException(e.getMessage(), e);
}
} | java | public String prepareUrl(List<Scope> scopes, String redirectUri, String csrfToken) throws InvalidRequestException {
logger.debug("Enter OAuth2config::prepareUrl");
if(scopes == null || scopes.isEmpty() || redirectUri.isEmpty() || csrfToken.isEmpty()) {
logger.error("Invalid request for prepareUrl ");
throw new InvalidRequestException("Invalid request for prepareUrl");
}
try {
return intuitAuthorizationEndpoint
+ "?client_id=" + clientId
+ "&response_type=code&scope=" + URLEncoder.encode(buildScopeString(scopes), "UTF-8")
+ "&redirect_uri=" + URLEncoder.encode(redirectUri, "UTF-8")
+ "&state=" + csrfToken;
} catch (UnsupportedEncodingException e) {
logger.error("Exception while preparing url for redirect ", e);
throw new InvalidRequestException(e.getMessage(), e);
}
} | [
"public",
"String",
"prepareUrl",
"(",
"List",
"<",
"Scope",
">",
"scopes",
",",
"String",
"redirectUri",
",",
"String",
"csrfToken",
")",
"throws",
"InvalidRequestException",
"{",
"logger",
".",
"debug",
"(",
"\"Enter OAuth2config::prepareUrl\"",
")",
";",
"if",
... | Prepares URL to call the OAuth2 authorization endpoint using Scope, CSRF and redirectURL that is supplied
@param scope
@param redirectUri
@param csrfToken
@return
@throws InvalidRequestException | [
"Prepares",
"URL",
"to",
"call",
"the",
"OAuth2",
"authorization",
"endpoint",
"using",
"Scope",
"CSRF",
"and",
"redirectURL",
"that",
"is",
"supplied"
] | train | https://github.com/intuit/QuickBooks-V3-Java-SDK/blob/59f988d0776d46620d0b34711c411b2b5b1da06b/oauth2-platform-api/src/main/java/com/intuit/oauth2/config/OAuth2Config.java#L188-L206 |
Azure/azure-sdk-for-java | recoveryservices.backup/resource-manager/v2017_07_01/src/main/java/com/microsoft/azure/management/recoveryservices/backup/v2017_07_01/implementation/BackupResourceStorageConfigsInner.java | BackupResourceStorageConfigsInner.getAsync | public Observable<BackupResourceConfigResourceInner> getAsync(String vaultName, String resourceGroupName) {
return getWithServiceResponseAsync(vaultName, resourceGroupName).map(new Func1<ServiceResponse<BackupResourceConfigResourceInner>, BackupResourceConfigResourceInner>() {
@Override
public BackupResourceConfigResourceInner call(ServiceResponse<BackupResourceConfigResourceInner> response) {
return response.body();
}
});
} | java | public Observable<BackupResourceConfigResourceInner> getAsync(String vaultName, String resourceGroupName) {
return getWithServiceResponseAsync(vaultName, resourceGroupName).map(new Func1<ServiceResponse<BackupResourceConfigResourceInner>, BackupResourceConfigResourceInner>() {
@Override
public BackupResourceConfigResourceInner call(ServiceResponse<BackupResourceConfigResourceInner> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"BackupResourceConfigResourceInner",
">",
"getAsync",
"(",
"String",
"vaultName",
",",
"String",
"resourceGroupName",
")",
"{",
"return",
"getWithServiceResponseAsync",
"(",
"vaultName",
",",
"resourceGroupName",
")",
".",
"map",
"(",
"new... | Fetches resource storage config.
@param vaultName The name of the recovery services vault.
@param resourceGroupName The name of the resource group where the recovery services vault is present.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the BackupResourceConfigResourceInner object | [
"Fetches",
"resource",
"storage",
"config",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/recoveryservices.backup/resource-manager/v2017_07_01/src/main/java/com/microsoft/azure/management/recoveryservices/backup/v2017_07_01/implementation/BackupResourceStorageConfigsInner.java#L102-L109 |
lucee/Lucee | core/src/main/java/lucee/transformer/bytecode/util/ASMUtil.java | ASMUtil.toType | public static Type toType(Class type, boolean axistype) throws PageException {
if (axistype) type = ((ConfigImpl) ThreadLocalPageContext.getConfig()).getWSHandler().toWSTypeClass(type);
return Type.getType(type);
} | java | public static Type toType(Class type, boolean axistype) throws PageException {
if (axistype) type = ((ConfigImpl) ThreadLocalPageContext.getConfig()).getWSHandler().toWSTypeClass(type);
return Type.getType(type);
} | [
"public",
"static",
"Type",
"toType",
"(",
"Class",
"type",
",",
"boolean",
"axistype",
")",
"throws",
"PageException",
"{",
"if",
"(",
"axistype",
")",
"type",
"=",
"(",
"(",
"ConfigImpl",
")",
"ThreadLocalPageContext",
".",
"getConfig",
"(",
")",
")",
".... | translate a string cfml type definition to a Type Object
@param cfType
@param axistype
@return
@throws PageException | [
"translate",
"a",
"string",
"cfml",
"type",
"definition",
"to",
"a",
"Type",
"Object"
] | train | https://github.com/lucee/Lucee/blob/29b153fc4e126e5edb97da937f2ee2e231b87593/core/src/main/java/lucee/transformer/bytecode/util/ASMUtil.java#L658-L661 |
opentable/otj-jaxrs | client/src/main/java/com/opentable/jaxrs/JaxRsClientFactory.java | JaxRsClientFactory.addFeatureMap | public synchronized JaxRsClientFactory addFeatureMap(Map<JaxRsFeatureGroup, Set<Feature>> map) {
map.forEach((g, fs) -> fs.forEach(f -> addFeatureToGroup(g, f)));
return this;
} | java | public synchronized JaxRsClientFactory addFeatureMap(Map<JaxRsFeatureGroup, Set<Feature>> map) {
map.forEach((g, fs) -> fs.forEach(f -> addFeatureToGroup(g, f)));
return this;
} | [
"public",
"synchronized",
"JaxRsClientFactory",
"addFeatureMap",
"(",
"Map",
"<",
"JaxRsFeatureGroup",
",",
"Set",
"<",
"Feature",
">",
">",
"map",
")",
"{",
"map",
".",
"forEach",
"(",
"(",
"g",
",",
"fs",
")",
"->",
"fs",
".",
"forEach",
"(",
"f",
"-... | Register many features at once. Mostly a convenience for DI environments. | [
"Register",
"many",
"features",
"at",
"once",
".",
"Mostly",
"a",
"convenience",
"for",
"DI",
"environments",
"."
] | train | https://github.com/opentable/otj-jaxrs/blob/384e7094fe5a56d41b2a9970bfd783fa85cbbcb8/client/src/main/java/com/opentable/jaxrs/JaxRsClientFactory.java#L115-L118 |
salesforce/Argus | ArgusCore/src/main/java/com/salesforce/dva/argus/service/jpa/DefaultJPAService.java | DefaultJPAService.findEntity | protected <E extends Identifiable> E findEntity(EntityManager em, BigInteger id, Class<E> type) {
requireArgument(em != null, "The entity manager cannot be null.");
requireArgument(id != null && id.compareTo(ZERO) > 0, "ID must be positive and non-zero");
requireArgument(type != null, "The entity cannot be null.");
em.getEntityManagerFactory().getCache().evictAll();
return em.find(type, id);
} | java | protected <E extends Identifiable> E findEntity(EntityManager em, BigInteger id, Class<E> type) {
requireArgument(em != null, "The entity manager cannot be null.");
requireArgument(id != null && id.compareTo(ZERO) > 0, "ID must be positive and non-zero");
requireArgument(type != null, "The entity cannot be null.");
em.getEntityManagerFactory().getCache().evictAll();
return em.find(type, id);
} | [
"protected",
"<",
"E",
"extends",
"Identifiable",
">",
"E",
"findEntity",
"(",
"EntityManager",
"em",
",",
"BigInteger",
"id",
",",
"Class",
"<",
"E",
">",
"type",
")",
"{",
"requireArgument",
"(",
"em",
"!=",
"null",
",",
"\"The entity manager cannot be null.... | Locates an entity based on it's primary key value.
@param <E> The type of the entity.
@param em The entity manager to use. Cannot be null.
@param id The primary key of the entity. Cannot be null and must be a positive non-zero number.
@param type The runtime type of the entity. Cannot be null.
@return The entity or null if no entity exists for the primary key. | [
"Locates",
"an",
"entity",
"based",
"on",
"it",
"s",
"primary",
"key",
"value",
"."
] | train | https://github.com/salesforce/Argus/blob/121b59a268da264316cded6a3e9271366a23cd86/ArgusCore/src/main/java/com/salesforce/dva/argus/service/jpa/DefaultJPAService.java#L137-L143 |
VoltDB/voltdb | third_party/java/src/com/google_voltpatches/common/math/IntMath.java | IntMath.checkedAdd | public static int checkedAdd(int a, int b) {
long result = (long) a + b;
checkNoOverflow(result == (int) result);
return (int) result;
} | java | public static int checkedAdd(int a, int b) {
long result = (long) a + b;
checkNoOverflow(result == (int) result);
return (int) result;
} | [
"public",
"static",
"int",
"checkedAdd",
"(",
"int",
"a",
",",
"int",
"b",
")",
"{",
"long",
"result",
"=",
"(",
"long",
")",
"a",
"+",
"b",
";",
"checkNoOverflow",
"(",
"result",
"==",
"(",
"int",
")",
"result",
")",
";",
"return",
"(",
"int",
"... | Returns the sum of {@code a} and {@code b}, provided it does not overflow.
@throws ArithmeticException if {@code a + b} overflows in signed {@code int} arithmetic | [
"Returns",
"the",
"sum",
"of",
"{",
"@code",
"a",
"}",
"and",
"{",
"@code",
"b",
"}",
"provided",
"it",
"does",
"not",
"overflow",
"."
] | train | https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/third_party/java/src/com/google_voltpatches/common/math/IntMath.java#L453-L457 |
elki-project/elki | elki-core-math/src/main/java/de/lmu/ifi/dbs/elki/math/geometry/SweepHullDelaunay2D.java | SweepHullDelaunay2D.flipTriangles | int flipTriangles(long[] flippedA, long[] flippedB) {
int numflips = 0;
BitsUtil.zeroI(flippedB);
for(int i = BitsUtil.nextSetBit(flippedA, 0); i > -1; i = BitsUtil.nextSetBit(flippedA, i + 1)) {
if(!BitsUtil.get(flippedB, i) && flipTriangle(i, flippedB) >= 0) {
numflips += 2;
}
}
if(LOG.isDebuggingFinest()) {
LOG.debugFinest("Flips: " + numflips);
}
return numflips;
} | java | int flipTriangles(long[] flippedA, long[] flippedB) {
int numflips = 0;
BitsUtil.zeroI(flippedB);
for(int i = BitsUtil.nextSetBit(flippedA, 0); i > -1; i = BitsUtil.nextSetBit(flippedA, i + 1)) {
if(!BitsUtil.get(flippedB, i) && flipTriangle(i, flippedB) >= 0) {
numflips += 2;
}
}
if(LOG.isDebuggingFinest()) {
LOG.debugFinest("Flips: " + numflips);
}
return numflips;
} | [
"int",
"flipTriangles",
"(",
"long",
"[",
"]",
"flippedA",
",",
"long",
"[",
"]",
"flippedB",
")",
"{",
"int",
"numflips",
"=",
"0",
";",
"BitsUtil",
".",
"zeroI",
"(",
"flippedB",
")",
";",
"for",
"(",
"int",
"i",
"=",
"BitsUtil",
".",
"nextSetBit",... | Flip triangles as necessary
@param flippedA Bit set for triangles to test
@param flippedB Bit set to mark triangles as done | [
"Flip",
"triangles",
"as",
"necessary"
] | train | https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-core-math/src/main/java/de/lmu/ifi/dbs/elki/math/geometry/SweepHullDelaunay2D.java#L480-L492 |
alkacon/opencms-core | src-gwt/org/opencms/gwt/client/ui/CmsNotification.java | CmsNotification.sendSticky | public CmsNotificationMessage sendSticky(Type type, String message) {
CmsNotificationMessage notificationMessage = new CmsNotificationMessage(Mode.STICKY, type, message);
m_messages.add(notificationMessage);
if (hasWidget()) {
m_widget.addMessage(notificationMessage);
}
return notificationMessage;
} | java | public CmsNotificationMessage sendSticky(Type type, String message) {
CmsNotificationMessage notificationMessage = new CmsNotificationMessage(Mode.STICKY, type, message);
m_messages.add(notificationMessage);
if (hasWidget()) {
m_widget.addMessage(notificationMessage);
}
return notificationMessage;
} | [
"public",
"CmsNotificationMessage",
"sendSticky",
"(",
"Type",
"type",
",",
"String",
"message",
")",
"{",
"CmsNotificationMessage",
"notificationMessage",
"=",
"new",
"CmsNotificationMessage",
"(",
"Mode",
".",
"STICKY",
",",
"type",
",",
"message",
")",
";",
"m_... | Sends a new sticky notification that can not be removed by the user.<p>
@param type the notification type
@param message the message
@return the message, use to hide the message | [
"Sends",
"a",
"new",
"sticky",
"notification",
"that",
"can",
"not",
"be",
"removed",
"by",
"the",
"user",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/gwt/client/ui/CmsNotification.java#L230-L238 |
code4everything/util | src/main/java/com/zhazhapan/util/Utils.java | Utils.loadJsonToBean | public static <T> T loadJsonToBean(String jsonPath, String encoding, Class<T> clazz) throws IOException {
JSONObject jsonObject = JSONObject.parseObject(FileExecutor.readFileToString(new File(jsonPath), encoding));
return JSONObject.toJavaObject(jsonObject, clazz);
} | java | public static <T> T loadJsonToBean(String jsonPath, String encoding, Class<T> clazz) throws IOException {
JSONObject jsonObject = JSONObject.parseObject(FileExecutor.readFileToString(new File(jsonPath), encoding));
return JSONObject.toJavaObject(jsonObject, clazz);
} | [
"public",
"static",
"<",
"T",
">",
"T",
"loadJsonToBean",
"(",
"String",
"jsonPath",
",",
"String",
"encoding",
",",
"Class",
"<",
"T",
">",
"clazz",
")",
"throws",
"IOException",
"{",
"JSONObject",
"jsonObject",
"=",
"JSONObject",
".",
"parseObject",
"(",
... | 加载JSON配置文件
@param jsonPath JSON文件路径
@param encoding 编码格式,为null时使用系统默认编码
@param clazz 类
@param <T> 类型值
@return Bean
@throws IOException 异常
@since 1.0.8 | [
"加载JSON配置文件"
] | train | https://github.com/code4everything/util/blob/1fc9f0ead1108f4d7208ba7c000df4244f708418/src/main/java/com/zhazhapan/util/Utils.java#L125-L128 |
vznet/mongo-jackson-mapper | src/main/java/net/vz/mongodb/jackson/DBUpdate.java | DBUpdate.pushAll | public static Builder pushAll(String field, Object... values) {
return new Builder().pushAll(field, values);
} | java | public static Builder pushAll(String field, Object... values) {
return new Builder().pushAll(field, values);
} | [
"public",
"static",
"Builder",
"pushAll",
"(",
"String",
"field",
",",
"Object",
"...",
"values",
")",
"{",
"return",
"new",
"Builder",
"(",
")",
".",
"pushAll",
"(",
"field",
",",
"values",
")",
";",
"}"
] | Add all of the given values to the array value at the specified field atomically
@param field The field to add the values to
@param values The values to add
@return this object | [
"Add",
"all",
"of",
"the",
"given",
"values",
"to",
"the",
"array",
"value",
"at",
"the",
"specified",
"field",
"atomically"
] | train | https://github.com/vznet/mongo-jackson-mapper/blob/ecd189aefa89636cddf70fb383f5d676be347976/src/main/java/net/vz/mongodb/jackson/DBUpdate.java#L101-L103 |
deeplearning4j/deeplearning4j | nd4j/nd4j-serde/nd4j-arrow/src/main/java/org/nd4j/arrow/ArrowSerde.java | ArrowSerde.addTypeTypeRelativeToNDArray | public static void addTypeTypeRelativeToNDArray(FlatBufferBuilder bufferBuilder,INDArray arr) {
switch(arr.data().dataType()) {
case LONG:
case INT:
Tensor.addTypeType(bufferBuilder,Type.Int);
break;
case FLOAT:
Tensor.addTypeType(bufferBuilder,Type.FloatingPoint);
break;
case DOUBLE:
Tensor.addTypeType(bufferBuilder,Type.Decimal);
break;
}
} | java | public static void addTypeTypeRelativeToNDArray(FlatBufferBuilder bufferBuilder,INDArray arr) {
switch(arr.data().dataType()) {
case LONG:
case INT:
Tensor.addTypeType(bufferBuilder,Type.Int);
break;
case FLOAT:
Tensor.addTypeType(bufferBuilder,Type.FloatingPoint);
break;
case DOUBLE:
Tensor.addTypeType(bufferBuilder,Type.Decimal);
break;
}
} | [
"public",
"static",
"void",
"addTypeTypeRelativeToNDArray",
"(",
"FlatBufferBuilder",
"bufferBuilder",
",",
"INDArray",
"arr",
")",
"{",
"switch",
"(",
"arr",
".",
"data",
"(",
")",
".",
"dataType",
"(",
")",
")",
"{",
"case",
"LONG",
":",
"case",
"INT",
"... | Convert the given {@link INDArray}
data type to the proper data type for the tensor.
@param bufferBuilder the buffer builder in use
@param arr the array to conver tthe data type for | [
"Convert",
"the",
"given",
"{"
] | train | https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/nd4j/nd4j-serde/nd4j-arrow/src/main/java/org/nd4j/arrow/ArrowSerde.java#L118-L131 |
intuit/QuickBooks-V3-Java-SDK | ipp-v3-java-devkit/src/main/java/com/intuit/ipp/serialization/IntuitResponseDeserializer.java | IntuitResponseDeserializer.registerModulesForCustomFieldDef | private void registerModulesForCustomFieldDef(ObjectMapper objectMapper) {
SimpleModule simpleModule = new SimpleModule("CustomFieldDefinition", new Version(1, 0, 0, null));
simpleModule.addDeserializer(CustomFieldDefinition.class, new CustomFieldDefinitionDeserializer());
objectMapper.registerModule(simpleModule);
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
} | java | private void registerModulesForCustomFieldDef(ObjectMapper objectMapper) {
SimpleModule simpleModule = new SimpleModule("CustomFieldDefinition", new Version(1, 0, 0, null));
simpleModule.addDeserializer(CustomFieldDefinition.class, new CustomFieldDefinitionDeserializer());
objectMapper.registerModule(simpleModule);
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
} | [
"private",
"void",
"registerModulesForCustomFieldDef",
"(",
"ObjectMapper",
"objectMapper",
")",
"{",
"SimpleModule",
"simpleModule",
"=",
"new",
"SimpleModule",
"(",
"\"CustomFieldDefinition\"",
",",
"new",
"Version",
"(",
"1",
",",
"0",
",",
"0",
",",
"null",
")... | Method to add custom deserializer for CustomFieldDefinition
@param objectMapper the Jackson object mapper | [
"Method",
"to",
"add",
"custom",
"deserializer",
"for",
"CustomFieldDefinition"
] | train | https://github.com/intuit/QuickBooks-V3-Java-SDK/blob/59f988d0776d46620d0b34711c411b2b5b1da06b/ipp-v3-java-devkit/src/main/java/com/intuit/ipp/serialization/IntuitResponseDeserializer.java#L389-L394 |
powermock/powermock | powermock-reflect/src/main/java/org/powermock/reflect/internal/WhiteboxImpl.java | WhiteboxImpl.findUniqueConstructorOrThrowException | public static Constructor<?> findUniqueConstructorOrThrowException(Class<?> type, Object... arguments) {
return new ConstructorFinder(type, arguments).findConstructor();
} | java | public static Constructor<?> findUniqueConstructorOrThrowException(Class<?> type, Object... arguments) {
return new ConstructorFinder(type, arguments).findConstructor();
} | [
"public",
"static",
"Constructor",
"<",
"?",
">",
"findUniqueConstructorOrThrowException",
"(",
"Class",
"<",
"?",
">",
"type",
",",
"Object",
"...",
"arguments",
")",
"{",
"return",
"new",
"ConstructorFinder",
"(",
"type",
",",
"arguments",
")",
".",
"findCon... | Finds and returns a certain constructor. If the constructor couldn't be
found this method delegates to
@param type The type where the constructor should be located.
@param arguments The arguments passed to the constructor.
@return The found constructor.
@throws ConstructorNotFoundException if no constructor was found.
@throws TooManyConstructorsFoundException if too constructors matched.
@throws IllegalArgumentException if {@code type} is null. | [
"Finds",
"and",
"returns",
"a",
"certain",
"constructor",
".",
"If",
"the",
"constructor",
"couldn",
"t",
"be",
"found",
"this",
"method",
"delegates",
"to"
] | train | https://github.com/powermock/powermock/blob/e8cd68026c284c6a7efe66959809eeebd8d1f9ad/powermock-reflect/src/main/java/org/powermock/reflect/internal/WhiteboxImpl.java#L1081-L1083 |
aws/aws-sdk-java | aws-java-sdk-pinpoint/src/main/java/com/amazonaws/services/pinpoint/model/WriteCampaignRequest.java | WriteCampaignRequest.withTags | public WriteCampaignRequest withTags(java.util.Map<String, String> tags) {
setTags(tags);
return this;
} | java | public WriteCampaignRequest withTags(java.util.Map<String, String> tags) {
setTags(tags);
return this;
} | [
"public",
"WriteCampaignRequest",
"withTags",
"(",
"java",
".",
"util",
".",
"Map",
"<",
"String",
",",
"String",
">",
"tags",
")",
"{",
"setTags",
"(",
"tags",
")",
";",
"return",
"this",
";",
"}"
] | The Tags for the campaign.
@param tags
The Tags for the campaign.
@return Returns a reference to this object so that method calls can be chained together. | [
"The",
"Tags",
"for",
"the",
"campaign",
"."
] | train | https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-pinpoint/src/main/java/com/amazonaws/services/pinpoint/model/WriteCampaignRequest.java#L510-L513 |
diffplug/durian | src/com/diffplug/common/base/FieldsAndGetters.java | FieldsAndGetters.tryCall | private static Object tryCall(String methodName, Throwing.Supplier<Object> supplier) {
try {
return supplier.get();
} catch (Throwable error) {
return new CallException(methodName, error);
}
} | java | private static Object tryCall(String methodName, Throwing.Supplier<Object> supplier) {
try {
return supplier.get();
} catch (Throwable error) {
return new CallException(methodName, error);
}
} | [
"private",
"static",
"Object",
"tryCall",
"(",
"String",
"methodName",
",",
"Throwing",
".",
"Supplier",
"<",
"Object",
">",
"supplier",
")",
"{",
"try",
"{",
"return",
"supplier",
".",
"get",
"(",
")",
";",
"}",
"catch",
"(",
"Throwable",
"error",
")",
... | Executes the given function, return any exceptions it might throw as wrapped values. | [
"Executes",
"the",
"given",
"function",
"return",
"any",
"exceptions",
"it",
"might",
"throw",
"as",
"wrapped",
"values",
"."
] | train | https://github.com/diffplug/durian/blob/10631a3480e5491eb6eb6ee06e752d8596914232/src/com/diffplug/common/base/FieldsAndGetters.java#L102-L108 |
biojava/biojava | biojava-structure/src/main/java/org/biojava/nbio/structure/contact/Grid.java | Grid.addCoords | public void addCoords(Point3d[] atoms, BoundingBox bounds) {
this.iAtoms = atoms;
this.iAtomObjects = null;
if (bounds!=null) {
this.ibounds = bounds;
} else {
this.ibounds = new BoundingBox(iAtoms);
}
this.jAtoms = null;
this.jAtomObjects = null;
this.jbounds = null;
fillGrid();
} | java | public void addCoords(Point3d[] atoms, BoundingBox bounds) {
this.iAtoms = atoms;
this.iAtomObjects = null;
if (bounds!=null) {
this.ibounds = bounds;
} else {
this.ibounds = new BoundingBox(iAtoms);
}
this.jAtoms = null;
this.jAtomObjects = null;
this.jbounds = null;
fillGrid();
} | [
"public",
"void",
"addCoords",
"(",
"Point3d",
"[",
"]",
"atoms",
",",
"BoundingBox",
"bounds",
")",
"{",
"this",
".",
"iAtoms",
"=",
"atoms",
";",
"this",
".",
"iAtomObjects",
"=",
"null",
";",
"if",
"(",
"bounds",
"!=",
"null",
")",
"{",
"this",
".... | Adds a set of coordinates, subsequent call to {@link #getIndicesContacts()} will produce the
contacts, i.e. the set of points within distance cutoff.
The bounds calculated elsewhere can be passed, or if null they are computed.
Subsequent calls to method {@link #getAtomContacts()} will produce a NullPointerException
since this only adds coordinates and no atom information.
@param atoms
@param bounds | [
"Adds",
"a",
"set",
"of",
"coordinates",
"subsequent",
"call",
"to",
"{"
] | train | https://github.com/biojava/biojava/blob/a1c71a8e3d40cc32104b1d387a3d3b560b43356e/biojava-structure/src/main/java/org/biojava/nbio/structure/contact/Grid.java#L267-L282 |
zaproxy/zaproxy | src/org/zaproxy/zap/spider/Spider.java | Spider.isDefaultPort | private static boolean isDefaultPort(String scheme, int port) {
if (port == -1) {
return true;
}
if ("http".equalsIgnoreCase(scheme)) {
return port == 80;
}
if ("https".equalsIgnoreCase(scheme)) {
return port == 443;
}
return false;
} | java | private static boolean isDefaultPort(String scheme, int port) {
if (port == -1) {
return true;
}
if ("http".equalsIgnoreCase(scheme)) {
return port == 80;
}
if ("https".equalsIgnoreCase(scheme)) {
return port == 443;
}
return false;
} | [
"private",
"static",
"boolean",
"isDefaultPort",
"(",
"String",
"scheme",
",",
"int",
"port",
")",
"{",
"if",
"(",
"port",
"==",
"-",
"1",
")",
"{",
"return",
"true",
";",
"}",
"if",
"(",
"\"http\"",
".",
"equalsIgnoreCase",
"(",
"scheme",
")",
")",
... | Tells whether or not the given port is the default for the given scheme.
<p>
Only intended to be used with HTTP/S schemes.
@param scheme the scheme.
@param port the port.
@return {@code true} if the given port is the default for the given scheme, {@code false} otherwise. | [
"Tells",
"whether",
"or",
"not",
"the",
"given",
"port",
"is",
"the",
"default",
"for",
"the",
"given",
"scheme",
".",
"<p",
">",
"Only",
"intended",
"to",
"be",
"used",
"with",
"HTTP",
"/",
"S",
"schemes",
"."
] | train | https://github.com/zaproxy/zaproxy/blob/0cbe5121f2ae1ecca222513d182759210c569bec/src/org/zaproxy/zap/spider/Spider.java#L350-L364 |
mabe02/lanterna | src/main/java/com/googlecode/lanterna/graphics/SimpleTheme.java | SimpleTheme.makeTheme | public static SimpleTheme makeTheme(
boolean activeIsBold,
TextColor baseForeground,
TextColor baseBackground,
TextColor editableForeground,
TextColor editableBackground,
TextColor selectedForeground,
TextColor selectedBackground,
TextColor guiBackground) {
SGR[] activeStyle = activeIsBold ? new SGR[]{SGR.BOLD} : new SGR[0];
SimpleTheme theme = new SimpleTheme(baseForeground, baseBackground);
theme.getDefaultDefinition().setSelected(baseBackground, baseForeground, activeStyle);
theme.getDefaultDefinition().setActive(selectedForeground, selectedBackground, activeStyle);
theme.addOverride(AbstractBorder.class, baseForeground, baseBackground)
.setSelected(baseForeground, baseBackground, activeStyle);
theme.addOverride(AbstractListBox.class, baseForeground, baseBackground)
.setSelected(selectedForeground, selectedBackground, activeStyle);
theme.addOverride(Button.class, baseForeground, baseBackground)
.setActive(selectedForeground, selectedBackground, activeStyle)
.setSelected(selectedForeground, selectedBackground, activeStyle);
theme.addOverride(CheckBox.class, baseForeground, baseBackground)
.setActive(selectedForeground, selectedBackground, activeStyle)
.setPreLight(selectedForeground, selectedBackground, activeStyle)
.setSelected(selectedForeground, selectedBackground, activeStyle);
theme.addOverride(CheckBoxList.class, baseForeground, baseBackground)
.setActive(selectedForeground, selectedBackground, activeStyle);
theme.addOverride(ComboBox.class, baseForeground, baseBackground)
.setActive(editableForeground, editableBackground, activeStyle)
.setPreLight(editableForeground, editableBackground);
theme.addOverride(DefaultWindowDecorationRenderer.class, baseForeground, baseBackground)
.setActive(baseForeground, baseBackground, activeStyle);
theme.addOverride(GUIBackdrop.class, baseForeground, guiBackground);
theme.addOverride(RadioBoxList.class, baseForeground, baseBackground)
.setActive(selectedForeground, selectedBackground, activeStyle);
theme.addOverride(Table.class, baseForeground, baseBackground)
.setActive(editableForeground, editableBackground, activeStyle)
.setSelected(baseForeground, baseBackground);
theme.addOverride(TextBox.class, editableForeground, editableBackground)
.setActive(editableForeground, editableBackground, activeStyle)
.setSelected(editableForeground, editableBackground, activeStyle);
theme.setWindowPostRenderer(new WindowShadowRenderer());
return theme;
} | java | public static SimpleTheme makeTheme(
boolean activeIsBold,
TextColor baseForeground,
TextColor baseBackground,
TextColor editableForeground,
TextColor editableBackground,
TextColor selectedForeground,
TextColor selectedBackground,
TextColor guiBackground) {
SGR[] activeStyle = activeIsBold ? new SGR[]{SGR.BOLD} : new SGR[0];
SimpleTheme theme = new SimpleTheme(baseForeground, baseBackground);
theme.getDefaultDefinition().setSelected(baseBackground, baseForeground, activeStyle);
theme.getDefaultDefinition().setActive(selectedForeground, selectedBackground, activeStyle);
theme.addOverride(AbstractBorder.class, baseForeground, baseBackground)
.setSelected(baseForeground, baseBackground, activeStyle);
theme.addOverride(AbstractListBox.class, baseForeground, baseBackground)
.setSelected(selectedForeground, selectedBackground, activeStyle);
theme.addOverride(Button.class, baseForeground, baseBackground)
.setActive(selectedForeground, selectedBackground, activeStyle)
.setSelected(selectedForeground, selectedBackground, activeStyle);
theme.addOverride(CheckBox.class, baseForeground, baseBackground)
.setActive(selectedForeground, selectedBackground, activeStyle)
.setPreLight(selectedForeground, selectedBackground, activeStyle)
.setSelected(selectedForeground, selectedBackground, activeStyle);
theme.addOverride(CheckBoxList.class, baseForeground, baseBackground)
.setActive(selectedForeground, selectedBackground, activeStyle);
theme.addOverride(ComboBox.class, baseForeground, baseBackground)
.setActive(editableForeground, editableBackground, activeStyle)
.setPreLight(editableForeground, editableBackground);
theme.addOverride(DefaultWindowDecorationRenderer.class, baseForeground, baseBackground)
.setActive(baseForeground, baseBackground, activeStyle);
theme.addOverride(GUIBackdrop.class, baseForeground, guiBackground);
theme.addOverride(RadioBoxList.class, baseForeground, baseBackground)
.setActive(selectedForeground, selectedBackground, activeStyle);
theme.addOverride(Table.class, baseForeground, baseBackground)
.setActive(editableForeground, editableBackground, activeStyle)
.setSelected(baseForeground, baseBackground);
theme.addOverride(TextBox.class, editableForeground, editableBackground)
.setActive(editableForeground, editableBackground, activeStyle)
.setSelected(editableForeground, editableBackground, activeStyle);
theme.setWindowPostRenderer(new WindowShadowRenderer());
return theme;
} | [
"public",
"static",
"SimpleTheme",
"makeTheme",
"(",
"boolean",
"activeIsBold",
",",
"TextColor",
"baseForeground",
",",
"TextColor",
"baseBackground",
",",
"TextColor",
"editableForeground",
",",
"TextColor",
"editableBackground",
",",
"TextColor",
"selectedForeground",
... | Helper method that will quickly setup a new theme with some sensible component overrides.
@param activeIsBold Should focused components also use bold SGR style?
@param baseForeground The base foreground color of the theme
@param baseBackground The base background color of the theme
@param editableForeground Foreground color for editable components, or editable areas of components
@param editableBackground Background color for editable components, or editable areas of components
@param selectedForeground Foreground color for the selection marker when a component has multiple selection states
@param selectedBackground Background color for the selection marker when a component has multiple selection states
@param guiBackground Background color of the GUI, if this theme is assigned to the {@link TextGUI}
@return Assembled {@link SimpleTheme} using the parameters from above | [
"Helper",
"method",
"that",
"will",
"quickly",
"setup",
"a",
"new",
"theme",
"with",
"some",
"sensible",
"component",
"overrides",
"."
] | train | https://github.com/mabe02/lanterna/blob/8dfd62206ff46ab10223b2ef2dbb0a2c51850954/src/main/java/com/googlecode/lanterna/graphics/SimpleTheme.java#L49-L96 |
lastaflute/lastaflute | src/main/java/org/lastaflute/web/login/TypicalLoginAssist.java | TypicalLoginAssist.doSaveRememberMeCookie | protected void doSaveRememberMeCookie(USER_ENTITY userEntity, USER_BEAN userBean, int expireDays, String cookieKey) {
logger.debug("...Saving remember-me key to cookie: key={}", cookieKey);
final String value = buildRememberMeCookieValue(userEntity, userBean, expireDays);
final int expireSeconds = expireDays * 60 * 60 * 24; // cookie's expire, same as access token
cookieManager.setCookieCiphered(cookieKey, value, expireSeconds);
} | java | protected void doSaveRememberMeCookie(USER_ENTITY userEntity, USER_BEAN userBean, int expireDays, String cookieKey) {
logger.debug("...Saving remember-me key to cookie: key={}", cookieKey);
final String value = buildRememberMeCookieValue(userEntity, userBean, expireDays);
final int expireSeconds = expireDays * 60 * 60 * 24; // cookie's expire, same as access token
cookieManager.setCookieCiphered(cookieKey, value, expireSeconds);
} | [
"protected",
"void",
"doSaveRememberMeCookie",
"(",
"USER_ENTITY",
"userEntity",
",",
"USER_BEAN",
"userBean",
",",
"int",
"expireDays",
",",
"String",
"cookieKey",
")",
"{",
"logger",
".",
"debug",
"(",
"\"...Saving remember-me key to cookie: key={}\"",
",",
"cookieKey... | Do save remember-me key to cookie.
@param userEntity The selected entity of login user. (NotNull)
@param userBean The user bean saved in session. (NotNull)
@param expireDays The expire days of both access token and cookie value.
@param cookieKey The key of the cookie. (NotNull) | [
"Do",
"save",
"remember",
"-",
"me",
"key",
"to",
"cookie",
"."
] | train | https://github.com/lastaflute/lastaflute/blob/17b56dda8322e4c6d79043532c1dda917d6b60a8/src/main/java/org/lastaflute/web/login/TypicalLoginAssist.java#L436-L441 |
BioPAX/Paxtools | paxtools-query/src/main/java/org/biopax/paxtools/query/algorithm/CycleBreaker.java | CycleBreaker.isSafe | public boolean isSafe(Node node, Edge edge)
{
initMaps();
setColor(node, BLACK);
setLabel(node, 0);
setLabel(edge, 0);
labelEquivRecursive(node, UPWARD, 0, false, false);
labelEquivRecursive(node, DOWNWARD, 0, false, false);
// Initialize dist and color of source set
Node neigh = edge.getTargetNode();
if (getColor(neigh) != WHITE) return false;
setColor(neigh, GRAY);
setLabel(neigh, 0);
queue.add(neigh);
labelEquivRecursive(neigh, UPWARD, 0, true, false);
labelEquivRecursive(neigh, DOWNWARD, 0, true, false);
// Process the queue
while (!queue.isEmpty())
{
Node current = queue.remove(0);
if (ST.contains(current)) return true;
boolean safe = processNode2(current);
if (safe) return true;
// Current node is processed
setColor(current, BLACK);
}
return false;
} | java | public boolean isSafe(Node node, Edge edge)
{
initMaps();
setColor(node, BLACK);
setLabel(node, 0);
setLabel(edge, 0);
labelEquivRecursive(node, UPWARD, 0, false, false);
labelEquivRecursive(node, DOWNWARD, 0, false, false);
// Initialize dist and color of source set
Node neigh = edge.getTargetNode();
if (getColor(neigh) != WHITE) return false;
setColor(neigh, GRAY);
setLabel(neigh, 0);
queue.add(neigh);
labelEquivRecursive(neigh, UPWARD, 0, true, false);
labelEquivRecursive(neigh, DOWNWARD, 0, true, false);
// Process the queue
while (!queue.isEmpty())
{
Node current = queue.remove(0);
if (ST.contains(current)) return true;
boolean safe = processNode2(current);
if (safe) return true;
// Current node is processed
setColor(current, BLACK);
}
return false;
} | [
"public",
"boolean",
"isSafe",
"(",
"Node",
"node",
",",
"Edge",
"edge",
")",
"{",
"initMaps",
"(",
")",
";",
"setColor",
"(",
"node",
",",
"BLACK",
")",
";",
"setLabel",
"(",
"node",
",",
"0",
")",
";",
"setLabel",
"(",
"edge",
",",
"0",
")",
";... | Checks whether an edge is on an unwanted cycle.
@param node Node that the edge is bound
@param edge The edge to check
@return True if no cycle is detected, false otherwise | [
"Checks",
"whether",
"an",
"edge",
"is",
"on",
"an",
"unwanted",
"cycle",
"."
] | train | https://github.com/BioPAX/Paxtools/blob/2f93afa94426bf8b5afc2e0e61cd4b269a83288d/paxtools-query/src/main/java/org/biopax/paxtools/query/algorithm/CycleBreaker.java#L72-L114 |
infinispan/infinispan | extended-statistics/src/main/java/org/infinispan/stats/CacheStatisticManager.java | CacheStatisticManager.onPrepareCommand | public final void onPrepareCommand(GlobalTransaction globalTransaction, boolean local) {
//NB: If I want to give up using the InboundInvocationHandler, I can create the remote transaction
//here, just overriding the handlePrepareCommand
TransactionStatistics txs = getTransactionStatistic(globalTransaction, local);
if (txs == null) {
log.prepareOnUnexistingTransaction(globalTransaction == null ? "null" : globalTransaction.globalId());
log.error("Trying to invoke onPrepareCommand() but no transaction is associated");
return;
}
txs.onPrepareCommand();
} | java | public final void onPrepareCommand(GlobalTransaction globalTransaction, boolean local) {
//NB: If I want to give up using the InboundInvocationHandler, I can create the remote transaction
//here, just overriding the handlePrepareCommand
TransactionStatistics txs = getTransactionStatistic(globalTransaction, local);
if (txs == null) {
log.prepareOnUnexistingTransaction(globalTransaction == null ? "null" : globalTransaction.globalId());
log.error("Trying to invoke onPrepareCommand() but no transaction is associated");
return;
}
txs.onPrepareCommand();
} | [
"public",
"final",
"void",
"onPrepareCommand",
"(",
"GlobalTransaction",
"globalTransaction",
",",
"boolean",
"local",
")",
"{",
"//NB: If I want to give up using the InboundInvocationHandler, I can create the remote transaction",
"//here, just overriding the handlePrepareCommand",
"Tran... | Invoked when a {@link org.infinispan.commands.tx.PrepareCommand} is received for a transaction.
@param globalTransaction the global transaction to be prepared.
@param local {@code true} if measurement occurred in a local context. | [
"Invoked",
"when",
"a",
"{",
"@link",
"org",
".",
"infinispan",
".",
"commands",
".",
"tx",
".",
"PrepareCommand",
"}",
"is",
"received",
"for",
"a",
"transaction",
"."
] | train | https://github.com/infinispan/infinispan/blob/7c62b94886c3febb4774ae8376acf2baa0265ab5/extended-statistics/src/main/java/org/infinispan/stats/CacheStatisticManager.java#L103-L113 |
deeplearning4j/deeplearning4j | nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/workspace/WorkspaceUtils.java | WorkspaceUtils.assertValidArray | public static void assertValidArray(INDArray array, String msg){
if(array == null || !array.isAttached()){
return;
}
val ws = array.data().getParentWorkspace();
if (ws.getWorkspaceType() != MemoryWorkspace.Type.CIRCULAR) {
if (!ws.isScopeActive()) {
throw new ND4JWorkspaceException( (msg == null ? "" : msg + ": ") + "Array uses leaked workspace pointer " +
"from workspace " + ws.getId() + "\nAll open workspaces: " + allOpenWorkspaces());
}
if (ws.getGenerationId() != array.data().getGenerationId()) {
throw new ND4JWorkspaceException( (msg == null ? "" : msg + ": ") + "Array outdated workspace pointer " +
"from workspace " + ws.getId() + " (array generation " + array.data().getGenerationId() +
", current workspace generation " + ws.getGenerationId() + ")\nAll open workspaces: " + allOpenWorkspaces());
}
}
} | java | public static void assertValidArray(INDArray array, String msg){
if(array == null || !array.isAttached()){
return;
}
val ws = array.data().getParentWorkspace();
if (ws.getWorkspaceType() != MemoryWorkspace.Type.CIRCULAR) {
if (!ws.isScopeActive()) {
throw new ND4JWorkspaceException( (msg == null ? "" : msg + ": ") + "Array uses leaked workspace pointer " +
"from workspace " + ws.getId() + "\nAll open workspaces: " + allOpenWorkspaces());
}
if (ws.getGenerationId() != array.data().getGenerationId()) {
throw new ND4JWorkspaceException( (msg == null ? "" : msg + ": ") + "Array outdated workspace pointer " +
"from workspace " + ws.getId() + " (array generation " + array.data().getGenerationId() +
", current workspace generation " + ws.getGenerationId() + ")\nAll open workspaces: " + allOpenWorkspaces());
}
}
} | [
"public",
"static",
"void",
"assertValidArray",
"(",
"INDArray",
"array",
",",
"String",
"msg",
")",
"{",
"if",
"(",
"array",
"==",
"null",
"||",
"!",
"array",
".",
"isAttached",
"(",
")",
")",
"{",
"return",
";",
"}",
"val",
"ws",
"=",
"array",
".",... | Assert that the specified array is valid, in terms of workspaces: i.e., if it is attached (and not in a circular
workspace), assert that the workspace is open, and that the data is not from an old generation.
@param array Array to check
@param msg Message (prefix) to include in the exception, if required. May be null | [
"Assert",
"that",
"the",
"specified",
"array",
"is",
"valid",
"in",
"terms",
"of",
"workspaces",
":",
"i",
".",
"e",
".",
"if",
"it",
"is",
"attached",
"(",
"and",
"not",
"in",
"a",
"circular",
"workspace",
")",
"assert",
"that",
"the",
"workspace",
"i... | train | https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/workspace/WorkspaceUtils.java#L109-L129 |
apache/incubator-druid | extensions-core/lookups-cached-global/src/main/java/org/apache/druid/server/lookup/namespace/cache/CacheScheduler.java | CacheScheduler.createVersionedCache | public VersionedCache createVersionedCache(@Nullable EntryImpl<? extends ExtractionNamespace> entryId, String version)
{
updatesStarted.incrementAndGet();
return new VersionedCache(String.valueOf(entryId), version);
} | java | public VersionedCache createVersionedCache(@Nullable EntryImpl<? extends ExtractionNamespace> entryId, String version)
{
updatesStarted.incrementAndGet();
return new VersionedCache(String.valueOf(entryId), version);
} | [
"public",
"VersionedCache",
"createVersionedCache",
"(",
"@",
"Nullable",
"EntryImpl",
"<",
"?",
"extends",
"ExtractionNamespace",
">",
"entryId",
",",
"String",
"version",
")",
"{",
"updatesStarted",
".",
"incrementAndGet",
"(",
")",
";",
"return",
"new",
"Versio... | This method should be used from {@link CacheGenerator#generateCache} implementations, to obtain a {@link
VersionedCache} to be returned.
@param entryId an object uniquely corresponding to the {@link CacheScheduler.Entry}, for which VersionedCache is
created
@param version version, associated with the cache | [
"This",
"method",
"should",
"be",
"used",
"from",
"{",
"@link",
"CacheGenerator#generateCache",
"}",
"implementations",
"to",
"obtain",
"a",
"{",
"@link",
"VersionedCache",
"}",
"to",
"be",
"returned",
"."
] | train | https://github.com/apache/incubator-druid/blob/f776b9408962b9006cfcfe4d6c1794751972cc8e/extensions-core/lookups-cached-global/src/main/java/org/apache/druid/server/lookup/namespace/cache/CacheScheduler.java#L469-L473 |
linkedin/linkedin-zookeeper | org.linkedin.zookeeper-impl/src/main/java/org/linkedin/zookeeper/tracker/ZooKeeperTreeTracker.java | ZooKeeperTreeTracker.waitForZkTxId | public long waitForZkTxId(long zkTxId, Object timeout)
throws TimeoutException, InterruptedException
{
long endTime = ClockUtils.toEndTime(clock, timeout);
synchronized(_lock)
{
while(_lastZkTxId < zkTxId)
{
ConcurrentUtils.awaitUntil(clock, _lock, endTime);
}
return _lastZkTxId;
}
} | java | public long waitForZkTxId(long zkTxId, Object timeout)
throws TimeoutException, InterruptedException
{
long endTime = ClockUtils.toEndTime(clock, timeout);
synchronized(_lock)
{
while(_lastZkTxId < zkTxId)
{
ConcurrentUtils.awaitUntil(clock, _lock, endTime);
}
return _lastZkTxId;
}
} | [
"public",
"long",
"waitForZkTxId",
"(",
"long",
"zkTxId",
",",
"Object",
"timeout",
")",
"throws",
"TimeoutException",
",",
"InterruptedException",
"{",
"long",
"endTime",
"=",
"ClockUtils",
".",
"toEndTime",
"(",
"clock",
",",
"timeout",
")",
";",
"synchronized... | Waits no longer than the timeout provided (or forever if <code>null</code>) for this tracker
to have seen at least the provided zookeeper transaction id
@return the last known zkTxId (guaranteed to be >= to zkTxId) | [
"Waits",
"no",
"longer",
"than",
"the",
"timeout",
"provided",
"(",
"or",
"forever",
"if",
"<code",
">",
"null<",
"/",
"code",
">",
")",
"for",
"this",
"tracker",
"to",
"have",
"seen",
"at",
"least",
"the",
"provided",
"zookeeper",
"transaction",
"id"
] | train | https://github.com/linkedin/linkedin-zookeeper/blob/600b1d01318594ed425ede566bbbdc94b026a53e/org.linkedin.zookeeper-impl/src/main/java/org/linkedin/zookeeper/tracker/ZooKeeperTreeTracker.java#L184-L198 |
hawtio/hawtio | hawtio-util/src/main/java/io/hawt/util/introspect/support/ClassScanner.java | ClassScanner.findClassNames | public SortedSet<String> findClassNames(String search, Integer limit) {
Map<Package, ClassLoader[]> packageMap = Packages.getPackageMap(getClassLoaders(), ignorePackages);
return findClassNamesInPackages(search, limit, packageMap);
} | java | public SortedSet<String> findClassNames(String search, Integer limit) {
Map<Package, ClassLoader[]> packageMap = Packages.getPackageMap(getClassLoaders(), ignorePackages);
return findClassNamesInPackages(search, limit, packageMap);
} | [
"public",
"SortedSet",
"<",
"String",
">",
"findClassNames",
"(",
"String",
"search",
",",
"Integer",
"limit",
")",
"{",
"Map",
"<",
"Package",
",",
"ClassLoader",
"[",
"]",
">",
"packageMap",
"=",
"Packages",
".",
"getPackageMap",
"(",
"getClassLoaders",
"(... | Searches for the available class names given the text search
@return all the class names found on the current classpath using the given text search filter | [
"Searches",
"for",
"the",
"available",
"class",
"names",
"given",
"the",
"text",
"search"
] | train | https://github.com/hawtio/hawtio/blob/d8b1c8f246307c0313ba297a494106d0859f3ffd/hawtio-util/src/main/java/io/hawt/util/introspect/support/ClassScanner.java#L95-L98 |
shrinkwrap/resolver | maven/api-maven/src/main/java/org/jboss/shrinkwrap/resolver/api/maven/coordinate/MavenDependencies.java | MavenDependencies.createExclusion | public static MavenDependencyExclusion createExclusion(final String groupId, final String artifactId)
throws IllegalArgumentException {
if (groupId == null || groupId.length() == 0) {
throw new IllegalArgumentException("groupId must be specified");
}
if (artifactId == null || artifactId.length() == 0) {
throw new IllegalArgumentException("groupId must be specified");
}
final MavenDependencyExclusion exclusion = new MavenDependencyExclusionImpl(groupId, artifactId);
return exclusion;
} | java | public static MavenDependencyExclusion createExclusion(final String groupId, final String artifactId)
throws IllegalArgumentException {
if (groupId == null || groupId.length() == 0) {
throw new IllegalArgumentException("groupId must be specified");
}
if (artifactId == null || artifactId.length() == 0) {
throw new IllegalArgumentException("groupId must be specified");
}
final MavenDependencyExclusion exclusion = new MavenDependencyExclusionImpl(groupId, artifactId);
return exclusion;
} | [
"public",
"static",
"MavenDependencyExclusion",
"createExclusion",
"(",
"final",
"String",
"groupId",
",",
"final",
"String",
"artifactId",
")",
"throws",
"IllegalArgumentException",
"{",
"if",
"(",
"groupId",
"==",
"null",
"||",
"groupId",
".",
"length",
"(",
")"... | Creates a new {@link MavenDependencyExclusion} instance from the specified, required arguments
@param groupId A groupId of the new {@link MavenDependencyExclusion} instance.
@param artifactId An artifactId of the new {@link MavenDependencyExclusion} instance.
@return The new {@link MavenDependencyExclusion} instance.
@throws IllegalArgumentException
If either argument is not specified | [
"Creates",
"a",
"new",
"{",
"@link",
"MavenDependencyExclusion",
"}",
"instance",
"from",
"the",
"specified",
"required",
"arguments"
] | train | https://github.com/shrinkwrap/resolver/blob/e881a84b8cff5b0a014f2a5ebf612be3eb9db01f/maven/api-maven/src/main/java/org/jboss/shrinkwrap/resolver/api/maven/coordinate/MavenDependencies.java#L168-L178 |
roboconf/roboconf-platform | miscellaneous/roboconf-dm-rest-client/src/main/java/net/roboconf/dm/rest/client/delegates/ManagementWsDelegate.java | ManagementWsDelegate.uploadZippedApplicationTemplate | public void uploadZippedApplicationTemplate( File applicationFile ) throws ManagementWsException, IOException {
if( applicationFile == null
|| ! applicationFile.exists()
|| ! applicationFile.isFile())
throw new IOException( "Expected an existing file as parameter." );
this.logger.finer( "Loading an application from " + applicationFile.getAbsolutePath() + "..." );
FormDataMultiPart part = new FormDataMultiPart();
part.bodyPart( new FileDataBodyPart( "file", applicationFile, MediaType.APPLICATION_OCTET_STREAM_TYPE));
WebResource path = this.resource.path( UrlConstants.APPLICATIONS ).path( "templates" );
ClientResponse response = this.wsClient.createBuilder( path )
.type( MediaType.MULTIPART_FORM_DATA_TYPE )
.post( ClientResponse.class, part );
if( Family.SUCCESSFUL != response.getStatusInfo().getFamily()) {
String value = response.getEntity( String.class );
this.logger.finer( response.getStatusInfo() + ": " + value );
throw new ManagementWsException( response.getStatusInfo().getStatusCode(), value );
}
this.logger.finer( String.valueOf( response.getStatusInfo()));
} | java | public void uploadZippedApplicationTemplate( File applicationFile ) throws ManagementWsException, IOException {
if( applicationFile == null
|| ! applicationFile.exists()
|| ! applicationFile.isFile())
throw new IOException( "Expected an existing file as parameter." );
this.logger.finer( "Loading an application from " + applicationFile.getAbsolutePath() + "..." );
FormDataMultiPart part = new FormDataMultiPart();
part.bodyPart( new FileDataBodyPart( "file", applicationFile, MediaType.APPLICATION_OCTET_STREAM_TYPE));
WebResource path = this.resource.path( UrlConstants.APPLICATIONS ).path( "templates" );
ClientResponse response = this.wsClient.createBuilder( path )
.type( MediaType.MULTIPART_FORM_DATA_TYPE )
.post( ClientResponse.class, part );
if( Family.SUCCESSFUL != response.getStatusInfo().getFamily()) {
String value = response.getEntity( String.class );
this.logger.finer( response.getStatusInfo() + ": " + value );
throw new ManagementWsException( response.getStatusInfo().getStatusCode(), value );
}
this.logger.finer( String.valueOf( response.getStatusInfo()));
} | [
"public",
"void",
"uploadZippedApplicationTemplate",
"(",
"File",
"applicationFile",
")",
"throws",
"ManagementWsException",
",",
"IOException",
"{",
"if",
"(",
"applicationFile",
"==",
"null",
"||",
"!",
"applicationFile",
".",
"exists",
"(",
")",
"||",
"!",
"app... | Uploads a ZIP file and loads its application template.
@param applicationFile a ZIP archive file
@throws ManagementWsException if a problem occurred with the applications management
@throws IOException if the file was not found or is invalid | [
"Uploads",
"a",
"ZIP",
"file",
"and",
"loads",
"its",
"application",
"template",
"."
] | train | https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/miscellaneous/roboconf-dm-rest-client/src/main/java/net/roboconf/dm/rest/client/delegates/ManagementWsDelegate.java#L81-L105 |
inkstand-io/scribble | scribble-jcr/src/main/java/io/inkstand/scribble/jcr/rules/util/XMLContentHandler.java | XMLContentHandler.startElementRootNode | private void startElementRootNode(final Attributes attributes) {
LOG.debug("Found rootNode");
try {
this.rootNode = this.newNode(null, attributes);
this.nodeStack.push(this.rootNode);
} catch (final RepositoryException e) {
throw new AssertionError("Could not create node", e);
}
} | java | private void startElementRootNode(final Attributes attributes) {
LOG.debug("Found rootNode");
try {
this.rootNode = this.newNode(null, attributes);
this.nodeStack.push(this.rootNode);
} catch (final RepositoryException e) {
throw new AssertionError("Could not create node", e);
}
} | [
"private",
"void",
"startElementRootNode",
"(",
"final",
"Attributes",
"attributes",
")",
"{",
"LOG",
".",
"debug",
"(",
"\"Found rootNode\"",
")",
";",
"try",
"{",
"this",
".",
"rootNode",
"=",
"this",
".",
"newNode",
"(",
"null",
",",
"attributes",
")",
... | Invoked on rootNode element.
@param attributes
the DOM attributes of the root node element | [
"Invoked",
"on",
"rootNode",
"element",
"."
] | train | https://github.com/inkstand-io/scribble/blob/66e67553bad4b1ff817e1715fd1d3dd833406744/scribble-jcr/src/main/java/io/inkstand/scribble/jcr/rules/util/XMLContentHandler.java#L334-L343 |
lucee/Lucee | core/src/main/java/lucee/runtime/schedule/StorageUtil.java | StorageUtil.setBoolean | public void setBoolean(Element el, String key, boolean value) {
el.setAttribute(key, String.valueOf(value));
} | java | public void setBoolean(Element el, String key, boolean value) {
el.setAttribute(key, String.valueOf(value));
} | [
"public",
"void",
"setBoolean",
"(",
"Element",
"el",
",",
"String",
"key",
",",
"boolean",
"value",
")",
"{",
"el",
".",
"setAttribute",
"(",
"key",
",",
"String",
".",
"valueOf",
"(",
"value",
")",
")",
";",
"}"
] | sets a boolean value to a XML Element
@param el Element to set value on it
@param key key to set
@param value value to set | [
"sets",
"a",
"boolean",
"value",
"to",
"a",
"XML",
"Element"
] | train | https://github.com/lucee/Lucee/blob/29b153fc4e126e5edb97da937f2ee2e231b87593/core/src/main/java/lucee/runtime/schedule/StorageUtil.java#L390-L392 |
pac4j/pac4j | pac4j-core/src/main/java/org/pac4j/core/util/CommonHelper.java | CommonHelper.areEqualsIgnoreCaseAndTrim | public static boolean areEqualsIgnoreCaseAndTrim(final String s1, final String s2) {
if (s1 == null && s2 == null) {
return true;
} else if (s1 != null && s2 != null) {
return s1.trim().equalsIgnoreCase(s2.trim());
} else {
return false;
}
} | java | public static boolean areEqualsIgnoreCaseAndTrim(final String s1, final String s2) {
if (s1 == null && s2 == null) {
return true;
} else if (s1 != null && s2 != null) {
return s1.trim().equalsIgnoreCase(s2.trim());
} else {
return false;
}
} | [
"public",
"static",
"boolean",
"areEqualsIgnoreCaseAndTrim",
"(",
"final",
"String",
"s1",
",",
"final",
"String",
"s2",
")",
"{",
"if",
"(",
"s1",
"==",
"null",
"&&",
"s2",
"==",
"null",
")",
"{",
"return",
"true",
";",
"}",
"else",
"if",
"(",
"s1",
... | Compare two String to see if they are equals ignoring the case and the blank spaces (both null is ok).
@param s1 string
@param s2 string
@return if two String are equals ignoring the case and the blank spaces | [
"Compare",
"two",
"String",
"to",
"see",
"if",
"they",
"are",
"equals",
"ignoring",
"the",
"case",
"and",
"the",
"blank",
"spaces",
"(",
"both",
"null",
"is",
"ok",
")",
"."
] | train | https://github.com/pac4j/pac4j/blob/d9cd029f8783792b31dd48bf1e32f80628f2c4a3/pac4j-core/src/main/java/org/pac4j/core/util/CommonHelper.java#L63-L71 |
infinispan/infinispan | extended-statistics/src/main/java/org/infinispan/stats/CacheStatisticManager.java | CacheStatisticManager.setTransactionOutcome | public final void setTransactionOutcome(boolean commit, GlobalTransaction globalTransaction, boolean local) {
TransactionStatistics txs = getTransactionStatistic(globalTransaction, local);
if (txs == null) {
log.outcomeOnUnexistingTransaction(globalTransaction == null ? "null" : globalTransaction.globalId(),
commit ? "COMMIT" : "ROLLBACK");
return;
}
txs.setOutcome(commit);
} | java | public final void setTransactionOutcome(boolean commit, GlobalTransaction globalTransaction, boolean local) {
TransactionStatistics txs = getTransactionStatistic(globalTransaction, local);
if (txs == null) {
log.outcomeOnUnexistingTransaction(globalTransaction == null ? "null" : globalTransaction.globalId(),
commit ? "COMMIT" : "ROLLBACK");
return;
}
txs.setOutcome(commit);
} | [
"public",
"final",
"void",
"setTransactionOutcome",
"(",
"boolean",
"commit",
",",
"GlobalTransaction",
"globalTransaction",
",",
"boolean",
"local",
")",
"{",
"TransactionStatistics",
"txs",
"=",
"getTransactionStatistic",
"(",
"globalTransaction",
",",
"local",
")",
... | Sets the transaction outcome to commit or rollback, depending if the transaction has commit successfully or not
respectively.
@param commit {@code true} if the transaction has committed successfully.
@param globalTransaction the terminated global transaction.
@param local {@code true} if measurement occurred in a local context. | [
"Sets",
"the",
"transaction",
"outcome",
"to",
"commit",
"or",
"rollback",
"depending",
"if",
"the",
"transaction",
"has",
"commit",
"successfully",
"or",
"not",
"respectively",
"."
] | train | https://github.com/infinispan/infinispan/blob/7c62b94886c3febb4774ae8376acf2baa0265ab5/extended-statistics/src/main/java/org/infinispan/stats/CacheStatisticManager.java#L123-L131 |
landawn/AbacusUtil | src/com/landawn/abacus/util/FileSystemUtil.java | FileSystemUtil.performCommand | List<String> performCommand(final String[] cmdAttribs, final int max, final long timeout) throws IOException {
// this method does what it can to avoid the 'Too many open files' error
// based on trial and error and these links:
// http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4784692
// http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4801027
// http://forum.java.sun.com/thread.jspa?threadID=533029&messageID=2572018
// however, its still not perfect as the JDK support is so poor
// (see commons-exec or Ant for a better multi-threaded multi-os solution)
final List<String> lines = new ArrayList<String>(20);
Process proc = null;
InputStream in = null;
OutputStream out = null;
InputStream err = null;
BufferedReader inr = null;
try {
final Thread monitor = ThreadMonitor.start(timeout);
proc = openProcess(cmdAttribs);
in = proc.getInputStream();
out = proc.getOutputStream();
err = proc.getErrorStream();
// default charset is most likely appropriate here
inr = new BufferedReader(new InputStreamReader(in, Charset.defaultCharset()));
String line = inr.readLine();
while (line != null && lines.size() < max) {
line = line.toLowerCase(Locale.ENGLISH).trim();
lines.add(line);
line = inr.readLine();
}
proc.waitFor();
ThreadMonitor.stop(monitor);
if (proc.exitValue() != 0) {
// os command problem, throw exception
throw new IOException("Command line returned OS error code '" + proc.exitValue() + "' for command " + Arrays.asList(cmdAttribs));
}
if (lines.isEmpty()) {
// unknown problem, throw exception
throw new IOException("Command line did not return any info " + "for command " + Arrays.asList(cmdAttribs));
}
return lines;
} catch (final InterruptedException ex) {
throw new IOException("Command line threw an InterruptedException " + "for command " + Arrays.asList(cmdAttribs) + " timeout=" + timeout, ex);
} finally {
IOUtil.closeQuietly(in);
IOUtil.closeQuietly(out);
IOUtil.closeQuietly(err);
IOUtil.closeQuietly(inr);
if (proc != null) {
proc.destroy();
}
}
} | java | List<String> performCommand(final String[] cmdAttribs, final int max, final long timeout) throws IOException {
// this method does what it can to avoid the 'Too many open files' error
// based on trial and error and these links:
// http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4784692
// http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4801027
// http://forum.java.sun.com/thread.jspa?threadID=533029&messageID=2572018
// however, its still not perfect as the JDK support is so poor
// (see commons-exec or Ant for a better multi-threaded multi-os solution)
final List<String> lines = new ArrayList<String>(20);
Process proc = null;
InputStream in = null;
OutputStream out = null;
InputStream err = null;
BufferedReader inr = null;
try {
final Thread monitor = ThreadMonitor.start(timeout);
proc = openProcess(cmdAttribs);
in = proc.getInputStream();
out = proc.getOutputStream();
err = proc.getErrorStream();
// default charset is most likely appropriate here
inr = new BufferedReader(new InputStreamReader(in, Charset.defaultCharset()));
String line = inr.readLine();
while (line != null && lines.size() < max) {
line = line.toLowerCase(Locale.ENGLISH).trim();
lines.add(line);
line = inr.readLine();
}
proc.waitFor();
ThreadMonitor.stop(monitor);
if (proc.exitValue() != 0) {
// os command problem, throw exception
throw new IOException("Command line returned OS error code '" + proc.exitValue() + "' for command " + Arrays.asList(cmdAttribs));
}
if (lines.isEmpty()) {
// unknown problem, throw exception
throw new IOException("Command line did not return any info " + "for command " + Arrays.asList(cmdAttribs));
}
return lines;
} catch (final InterruptedException ex) {
throw new IOException("Command line threw an InterruptedException " + "for command " + Arrays.asList(cmdAttribs) + " timeout=" + timeout, ex);
} finally {
IOUtil.closeQuietly(in);
IOUtil.closeQuietly(out);
IOUtil.closeQuietly(err);
IOUtil.closeQuietly(inr);
if (proc != null) {
proc.destroy();
}
}
} | [
"List",
"<",
"String",
">",
"performCommand",
"(",
"final",
"String",
"[",
"]",
"cmdAttribs",
",",
"final",
"int",
"max",
",",
"final",
"long",
"timeout",
")",
"throws",
"IOException",
"{",
"// this method does what it can to avoid the 'Too many open files' error\r",
... | Performs the os command.
@param cmdAttribs the command line parameters
@param max The maximum limit for the lines returned
@param timeout The timeout amount in milliseconds or no timeout if the value
is zero or less
@return the lines returned by the command, converted to lower-case
@throws IOException if an error occurs | [
"Performs",
"the",
"os",
"command",
"."
] | train | https://github.com/landawn/AbacusUtil/blob/544b7720175d15e9329f83dd22a8cc5fa4515e12/src/com/landawn/abacus/util/FileSystemUtil.java#L411-L468 |
Azure/azure-sdk-for-java | sql/resource-manager/v2015_05_01_preview/src/main/java/com/microsoft/azure/management/sql/v2015_05_01_preview/implementation/DatabaseAutomaticTuningsInner.java | DatabaseAutomaticTuningsInner.getAsync | public Observable<DatabaseAutomaticTuningInner> getAsync(String resourceGroupName, String serverName, String databaseName) {
return getWithServiceResponseAsync(resourceGroupName, serverName, databaseName).map(new Func1<ServiceResponse<DatabaseAutomaticTuningInner>, DatabaseAutomaticTuningInner>() {
@Override
public DatabaseAutomaticTuningInner call(ServiceResponse<DatabaseAutomaticTuningInner> response) {
return response.body();
}
});
} | java | public Observable<DatabaseAutomaticTuningInner> getAsync(String resourceGroupName, String serverName, String databaseName) {
return getWithServiceResponseAsync(resourceGroupName, serverName, databaseName).map(new Func1<ServiceResponse<DatabaseAutomaticTuningInner>, DatabaseAutomaticTuningInner>() {
@Override
public DatabaseAutomaticTuningInner call(ServiceResponse<DatabaseAutomaticTuningInner> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"DatabaseAutomaticTuningInner",
">",
"getAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"serverName",
",",
"String",
"databaseName",
")",
"{",
"return",
"getWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"serverName",
... | Gets a database's automatic tuning.
@param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal.
@param serverName The name of the server.
@param databaseName The name of the database.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the DatabaseAutomaticTuningInner object | [
"Gets",
"a",
"database",
"s",
"automatic",
"tuning",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/sql/resource-manager/v2015_05_01_preview/src/main/java/com/microsoft/azure/management/sql/v2015_05_01_preview/implementation/DatabaseAutomaticTuningsInner.java#L105-L112 |
facebookarchive/hive-dwrf | hive-dwrf/src/main/java/com/facebook/hive/orc/InStream.java | InStream.create | public static InStream create(String name, ByteBuffer input, CompressionCodec codec,
int bufferSize) throws IOException {
return create(name, input, codec, bufferSize, true);
} | java | public static InStream create(String name, ByteBuffer input, CompressionCodec codec,
int bufferSize) throws IOException {
return create(name, input, codec, bufferSize, true);
} | [
"public",
"static",
"InStream",
"create",
"(",
"String",
"name",
",",
"ByteBuffer",
"input",
",",
"CompressionCodec",
"codec",
",",
"int",
"bufferSize",
")",
"throws",
"IOException",
"{",
"return",
"create",
"(",
"name",
",",
"input",
",",
"codec",
",",
"buf... | This should only be used if the data happens to already be in memory, e.g. for tests | [
"This",
"should",
"only",
"be",
"used",
"if",
"the",
"data",
"happens",
"to",
"already",
"be",
"in",
"memory",
"e",
".",
"g",
".",
"for",
"tests"
] | train | https://github.com/facebookarchive/hive-dwrf/blob/a7b4fcf28a57e006a2fc041d40cf7e5ad16e6b45/hive-dwrf/src/main/java/com/facebook/hive/orc/InStream.java#L481-L484 |
wmdietl/jsr308-langtools | src/share/classes/com/sun/tools/doclets/internal/toolkit/builders/ConstantsSummaryBuilder.java | ConstantsSummaryBuilder.buildContents | public void buildContents(XMLNode node, Content contentTree) {
Content contentListTree = writer.getContentsHeader();
PackageDoc[] packages = configuration.packages;
printedPackageHeaders = new HashSet<String>();
for (int i = 0; i < packages.length; i++) {
if (hasConstantField(packages[i]) && ! hasPrintedPackageIndex(packages[i].name())) {
writer.addLinkToPackageContent(packages[i],
parsePackageName(packages[i].name()),
printedPackageHeaders, contentListTree);
}
}
contentTree.addContent(writer.getContentsList(contentListTree));
} | java | public void buildContents(XMLNode node, Content contentTree) {
Content contentListTree = writer.getContentsHeader();
PackageDoc[] packages = configuration.packages;
printedPackageHeaders = new HashSet<String>();
for (int i = 0; i < packages.length; i++) {
if (hasConstantField(packages[i]) && ! hasPrintedPackageIndex(packages[i].name())) {
writer.addLinkToPackageContent(packages[i],
parsePackageName(packages[i].name()),
printedPackageHeaders, contentListTree);
}
}
contentTree.addContent(writer.getContentsList(contentListTree));
} | [
"public",
"void",
"buildContents",
"(",
"XMLNode",
"node",
",",
"Content",
"contentTree",
")",
"{",
"Content",
"contentListTree",
"=",
"writer",
".",
"getContentsHeader",
"(",
")",
";",
"PackageDoc",
"[",
"]",
"packages",
"=",
"configuration",
".",
"packages",
... | Build the list of packages.
@param node the XML element that specifies which components to document
@param contentTree the content tree to which the content list will be added | [
"Build",
"the",
"list",
"of",
"packages",
"."
] | train | https://github.com/wmdietl/jsr308-langtools/blob/8812d28c20f4de070a0dd6de1b45602431379834/src/share/classes/com/sun/tools/doclets/internal/toolkit/builders/ConstantsSummaryBuilder.java#L152-L164 |
google/error-prone-javac | src/jdk.compiler/share/classes/com/sun/source/util/TreeScanner.java | TreeScanner.visitSynchronized | @Override
public R visitSynchronized(SynchronizedTree node, P p) {
R r = scan(node.getExpression(), p);
r = scanAndReduce(node.getBlock(), p, r);
return r;
} | java | @Override
public R visitSynchronized(SynchronizedTree node, P p) {
R r = scan(node.getExpression(), p);
r = scanAndReduce(node.getBlock(), p, r);
return r;
} | [
"@",
"Override",
"public",
"R",
"visitSynchronized",
"(",
"SynchronizedTree",
"node",
",",
"P",
"p",
")",
"{",
"R",
"r",
"=",
"scan",
"(",
"node",
".",
"getExpression",
"(",
")",
",",
"p",
")",
";",
"r",
"=",
"scanAndReduce",
"(",
"node",
".",
"getBl... | {@inheritDoc} This implementation scans the children in left to right order.
@param node {@inheritDoc}
@param p {@inheritDoc}
@return the result of scanning | [
"{",
"@inheritDoc",
"}",
"This",
"implementation",
"scans",
"the",
"children",
"in",
"left",
"to",
"right",
"order",
"."
] | train | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.compiler/share/classes/com/sun/source/util/TreeScanner.java#L357-L362 |
canoo/dolphin-platform | platform/dolphin-platform-remoting-server/src/main/java/com/canoo/dp/impl/server/gc/GarbageCollector.java | GarbageCollector.onRemovedFromList | public synchronized void onRemovedFromList(ObservableList list, Object value) {
if (!configuration.isUseGc()) {
return;
}
removeReferenceAndCheckForGC(list, value);
} | java | public synchronized void onRemovedFromList(ObservableList list, Object value) {
if (!configuration.isUseGc()) {
return;
}
removeReferenceAndCheckForGC(list, value);
} | [
"public",
"synchronized",
"void",
"onRemovedFromList",
"(",
"ObservableList",
"list",
",",
"Object",
"value",
")",
"{",
"if",
"(",
"!",
"configuration",
".",
"isUseGc",
"(",
")",
")",
"{",
"return",
";",
"}",
"removeReferenceAndCheckForGC",
"(",
"list",
",",
... | This method must be called for each item that is removed to a {@link ObservableList} that is part of a Dolphin bean (see {@link RemotingBean})
@param list the list
@param value the removed item | [
"This",
"method",
"must",
"be",
"called",
"for",
"each",
"item",
"that",
"is",
"removed",
"to",
"a",
"{",
"@link",
"ObservableList",
"}",
"that",
"is",
"part",
"of",
"a",
"Dolphin",
"bean",
"(",
"see",
"{",
"@link",
"RemotingBean",
"}",
")"
] | train | https://github.com/canoo/dolphin-platform/blob/fb99c1fab24df80d2fa094d8688b546140146874/platform/dolphin-platform-remoting-server/src/main/java/com/canoo/dp/impl/server/gc/GarbageCollector.java#L193-L198 |
Samsung/GearVRf | GVRf/Extensions/widgetLib/src/org/gearvrf/widgetlib/thread/ExecutionChain.java | ExecutionChain.runOnUIThread | public <T, U> ExecutionChain runOnUIThread(Task<T, U> task) {
runOnThread(Context.Type.UI, task);
return this;
} | java | public <T, U> ExecutionChain runOnUIThread(Task<T, U> task) {
runOnThread(Context.Type.UI, task);
return this;
} | [
"public",
"<",
"T",
",",
"U",
">",
"ExecutionChain",
"runOnUIThread",
"(",
"Task",
"<",
"T",
",",
"U",
">",
"task",
")",
"{",
"runOnThread",
"(",
"Context",
".",
"Type",
".",
"UI",
",",
"task",
")",
";",
"return",
"this",
";",
"}"
] | Add a {@link Task} to be run on Android's
{@link Activity#runOnUiThread(Runnable) UI thread}. It will be run after
all Tasks added prior to this call.
@param task
{@code Task} to run
@return Reference to the {@code ExecutionChain}.
@throws IllegalStateException
if the chain of execution has already been {@link #execute()
started}. | [
"Add",
"a",
"{",
"@link",
"Task",
"}",
"to",
"be",
"run",
"on",
"Android",
"s",
"{",
"@link",
"Activity#runOnUiThread",
"(",
"Runnable",
")",
"UI",
"thread",
"}",
".",
"It",
"will",
"be",
"run",
"after",
"all",
"Tasks",
"added",
"prior",
"to",
"this",
... | train | https://github.com/Samsung/GearVRf/blob/05034d465a7b0a494fabb9e9f2971ac19392f32d/GVRf/Extensions/widgetLib/src/org/gearvrf/widgetlib/thread/ExecutionChain.java#L251-L254 |
wcm-io/wcm-io-handler | media/src/main/java/io/wcm/handler/media/impl/ImageFileServlet.java | ImageFileServlet.getImageFileName | public static String getImageFileName(String originalFilename) {
String namePart = StringUtils.substringBeforeLast(originalFilename, ".");
String extensionPart = StringUtils.substringAfterLast(originalFilename, ".");
// use PNG format if original image is PNG, otherwise always use JPEG
if (StringUtils.equalsIgnoreCase(extensionPart, FileExtension.PNG)) {
extensionPart = FileExtension.PNG;
}
else {
extensionPart = FileExtension.JPEG;
}
return namePart + "." + extensionPart;
} | java | public static String getImageFileName(String originalFilename) {
String namePart = StringUtils.substringBeforeLast(originalFilename, ".");
String extensionPart = StringUtils.substringAfterLast(originalFilename, ".");
// use PNG format if original image is PNG, otherwise always use JPEG
if (StringUtils.equalsIgnoreCase(extensionPart, FileExtension.PNG)) {
extensionPart = FileExtension.PNG;
}
else {
extensionPart = FileExtension.JPEG;
}
return namePart + "." + extensionPart;
} | [
"public",
"static",
"String",
"getImageFileName",
"(",
"String",
"originalFilename",
")",
"{",
"String",
"namePart",
"=",
"StringUtils",
".",
"substringBeforeLast",
"(",
"originalFilename",
",",
"\".\"",
")",
";",
"String",
"extensionPart",
"=",
"StringUtils",
".",
... | Get image filename to be used for the URL with file extension matching the image format which is produced by this
servlet.
@param originalFilename Original filename of the image to render.
@return Filename to be used for URL. | [
"Get",
"image",
"filename",
"to",
"be",
"used",
"for",
"the",
"URL",
"with",
"file",
"extension",
"matching",
"the",
"image",
"format",
"which",
"is",
"produced",
"by",
"this",
"servlet",
"."
] | train | https://github.com/wcm-io/wcm-io-handler/blob/b0fc1c11a3ceb89efb73826dcfd480d6a00c19af/media/src/main/java/io/wcm/handler/media/impl/ImageFileServlet.java#L155-L167 |
sinetja/sinetja | src/main/java/sinetja/Response.java | Response.respondJsonPText | public ChannelFuture respondJsonPText(Object text, String function) throws Exception {
return respondJs(function + "(" + text + ");\r\n");
} | java | public ChannelFuture respondJsonPText(Object text, String function) throws Exception {
return respondJs(function + "(" + text + ");\r\n");
} | [
"public",
"ChannelFuture",
"respondJsonPText",
"(",
"Object",
"text",
",",
"String",
"function",
")",
"throws",
"Exception",
"{",
"return",
"respondJs",
"(",
"function",
"+",
"\"(\"",
"+",
"text",
"+",
"\");\\r\\n\"",
")",
";",
"}"
] | Wraps the text with the given JavaScript function name, and responds.
<p>
Content-Type header is set to "application/javascript". | [
"Wraps",
"the",
"text",
"with",
"the",
"given",
"JavaScript",
"function",
"name",
"and",
"responds",
".",
"<p",
">",
"Content",
"-",
"Type",
"header",
"is",
"set",
"to",
"application",
"/",
"javascript",
"."
] | train | https://github.com/sinetja/sinetja/blob/eec94dba55ec28263e3503fcdb33532282134775/src/main/java/sinetja/Response.java#L223-L225 |
Ordinastie/MalisisCore | src/main/java/net/malisis/core/block/component/ItemTransformComponent.java | ItemTransformComponent.getTransform | public Matrix4f getTransform(Item item, TransformType transformType)
{
switch (transformType)
{
case THIRD_PERSON_LEFT_HAND:
return thirdPersonLeftHand;
case THIRD_PERSON_RIGHT_HAND:
return thirdPersonRightHand;
case FIRST_PERSON_LEFT_HAND:
return firstPersonLeftHand;
case FIRST_PERSON_RIGHT_HAND:
return firstPersonRightHand;
case HEAD:
return head;
case GUI:
return gui;
case GROUND:
return ground;
case FIXED:
return fixed;
default:
return null;
}
} | java | public Matrix4f getTransform(Item item, TransformType transformType)
{
switch (transformType)
{
case THIRD_PERSON_LEFT_HAND:
return thirdPersonLeftHand;
case THIRD_PERSON_RIGHT_HAND:
return thirdPersonRightHand;
case FIRST_PERSON_LEFT_HAND:
return firstPersonLeftHand;
case FIRST_PERSON_RIGHT_HAND:
return firstPersonRightHand;
case HEAD:
return head;
case GUI:
return gui;
case GROUND:
return ground;
case FIXED:
return fixed;
default:
return null;
}
} | [
"public",
"Matrix4f",
"getTransform",
"(",
"Item",
"item",
",",
"TransformType",
"transformType",
")",
"{",
"switch",
"(",
"transformType",
")",
"{",
"case",
"THIRD_PERSON_LEFT_HAND",
":",
"return",
"thirdPersonLeftHand",
";",
"case",
"THIRD_PERSON_RIGHT_HAND",
":",
... | Gets the {@link Matrix4f transformation} for the specified {@link Item} and {@link TransformType}.
@param item the item
@param transformType the transform type
@return the transform | [
"Gets",
"the",
"{",
"@link",
"Matrix4f",
"transformation",
"}",
"for",
"the",
"specified",
"{",
"@link",
"Item",
"}",
"and",
"{",
"@link",
"TransformType",
"}",
"."
] | train | https://github.com/Ordinastie/MalisisCore/blob/4f8e1fa462d5c372fc23414482ba9f429881cc54/src/main/java/net/malisis/core/block/component/ItemTransformComponent.java#L142-L165 |
redisson/redisson | redisson/src/main/java/org/redisson/config/Config.java | Config.fromJSON | public static Config fromJSON(File file, ClassLoader classLoader) throws IOException {
ConfigSupport support = new ConfigSupport();
return support.fromJSON(file, Config.class, classLoader);
} | java | public static Config fromJSON(File file, ClassLoader classLoader) throws IOException {
ConfigSupport support = new ConfigSupport();
return support.fromJSON(file, Config.class, classLoader);
} | [
"public",
"static",
"Config",
"fromJSON",
"(",
"File",
"file",
",",
"ClassLoader",
"classLoader",
")",
"throws",
"IOException",
"{",
"ConfigSupport",
"support",
"=",
"new",
"ConfigSupport",
"(",
")",
";",
"return",
"support",
".",
"fromJSON",
"(",
"file",
",",... | Read config object stored in JSON format from <code>File</code>
@param file object
@param classLoader class loader
@return config
@throws IOException error | [
"Read",
"config",
"object",
"stored",
"in",
"JSON",
"format",
"from",
"<code",
">",
"File<",
"/",
"code",
">"
] | train | https://github.com/redisson/redisson/blob/d3acc0249b2d5d658d36d99e2c808ce49332ea44/redisson/src/main/java/org/redisson/config/Config.java#L581-L584 |
codeprimate-software/cp-elements | src/main/java/org/cp/elements/context/configure/AbstractConfiguration.java | AbstractConfiguration.getPropertyValueAs | @SuppressWarnings("unchecked")
public <T> T getPropertyValueAs(final String propertyName, final T defaultPropertyValue, final Class<T> type) {
try {
return ObjectUtils.defaultIfNull(convert(getPropertyValue(propertyName, NOT_REQUIRED), type),
defaultPropertyValue);
}
catch (ConversionException ignore) {
return defaultPropertyValue;
}
} | java | @SuppressWarnings("unchecked")
public <T> T getPropertyValueAs(final String propertyName, final T defaultPropertyValue, final Class<T> type) {
try {
return ObjectUtils.defaultIfNull(convert(getPropertyValue(propertyName, NOT_REQUIRED), type),
defaultPropertyValue);
}
catch (ConversionException ignore) {
return defaultPropertyValue;
}
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"public",
"<",
"T",
">",
"T",
"getPropertyValueAs",
"(",
"final",
"String",
"propertyName",
",",
"final",
"T",
"defaultPropertyValue",
",",
"final",
"Class",
"<",
"T",
">",
"type",
")",
"{",
"try",
"{",
"... | Gets the value of the configuration property identified by name as a value of the specified Class type.
The defaultPropertyValue parameter effectively overrides the required attribute indicating that the property
is not required to be declared or defined.
@param propertyName a String value indicating the name of the configuration property.
@param defaultPropertyValue the default value for the configuration property when the property is undeclared or
undefined.
@param type the expected Class type of the configuration property value.
@return the value of the configuration property identified by name, or the default property value if the property
was undeclared or undefined. | [
"Gets",
"the",
"value",
"of",
"the",
"configuration",
"property",
"identified",
"by",
"name",
"as",
"a",
"value",
"of",
"the",
"specified",
"Class",
"type",
".",
"The",
"defaultPropertyValue",
"parameter",
"effectively",
"overrides",
"the",
"required",
"attribute"... | train | https://github.com/codeprimate-software/cp-elements/blob/f2163c149fbbef05015e688132064ebcac7c49ab/src/main/java/org/cp/elements/context/configure/AbstractConfiguration.java#L274-L283 |
derari/cthul | objects/src/main/java/org/cthul/objects/Boxing.java | Boxing.boxAll | public static Object[] boxAll(Class<?> type, Object src, int srcPos, int len) {
switch (tId(type)) {
case I_BOOLEAN: return boxBooleans(src, srcPos, len);
case I_BYTE: return boxBytes(src, srcPos, len);
case I_CHARACTER: return boxCharacters(src, srcPos, len);
case I_DOUBLE: return boxDoubles(src, srcPos, len);
case I_FLOAT: return boxFloats(src, srcPos, len);
case I_INTEGER: return boxIntegers(src, srcPos, len);
case I_LONG: return boxLongs(src, srcPos, len);
case I_SHORT: return boxShorts(src, srcPos, len);
}
throw new IllegalArgumentException("No primitive/box: " + type);
} | java | public static Object[] boxAll(Class<?> type, Object src, int srcPos, int len) {
switch (tId(type)) {
case I_BOOLEAN: return boxBooleans(src, srcPos, len);
case I_BYTE: return boxBytes(src, srcPos, len);
case I_CHARACTER: return boxCharacters(src, srcPos, len);
case I_DOUBLE: return boxDoubles(src, srcPos, len);
case I_FLOAT: return boxFloats(src, srcPos, len);
case I_INTEGER: return boxIntegers(src, srcPos, len);
case I_LONG: return boxLongs(src, srcPos, len);
case I_SHORT: return boxShorts(src, srcPos, len);
}
throw new IllegalArgumentException("No primitive/box: " + type);
} | [
"public",
"static",
"Object",
"[",
"]",
"boxAll",
"(",
"Class",
"<",
"?",
">",
"type",
",",
"Object",
"src",
",",
"int",
"srcPos",
",",
"int",
"len",
")",
"{",
"switch",
"(",
"tId",
"(",
"type",
")",
")",
"{",
"case",
"I_BOOLEAN",
":",
"return",
... | Transforms a primitive array into an array of boxed values.
@param type target type
@param src source array
@param srcPos start position
@param len length
@return array | [
"Transforms",
"a",
"primitive",
"array",
"into",
"an",
"array",
"of",
"boxed",
"values",
"."
] | train | https://github.com/derari/cthul/blob/74a31e3cb6a94f5f25cc5253d1dbd42e19a17ebc/objects/src/main/java/org/cthul/objects/Boxing.java#L447-L459 |
khuxtable/seaglass | src/main/java/com/seaglasslookandfeel/painter/CheckBoxMenuItemPainter.java | CheckBoxMenuItemPainter.paintCheckIconSelectedAndMouseOver | private void paintCheckIconSelectedAndMouseOver(Graphics2D g, int width, int height) {
Shape s = shapeGenerator.createCheckMark(0, 0, width, height);
g.setPaint(iconSelectedMouseOver);
g.fill(s);
} | java | private void paintCheckIconSelectedAndMouseOver(Graphics2D g, int width, int height) {
Shape s = shapeGenerator.createCheckMark(0, 0, width, height);
g.setPaint(iconSelectedMouseOver);
g.fill(s);
} | [
"private",
"void",
"paintCheckIconSelectedAndMouseOver",
"(",
"Graphics2D",
"g",
",",
"int",
"width",
",",
"int",
"height",
")",
"{",
"Shape",
"s",
"=",
"shapeGenerator",
".",
"createCheckMark",
"(",
"0",
",",
"0",
",",
"width",
",",
"height",
")",
";",
"g... | Paint the check mark in mouse over state.
@param g the Graphics2D context to paint with.
@param width the width.
@param height the height. | [
"Paint",
"the",
"check",
"mark",
"in",
"mouse",
"over",
"state",
"."
] | train | https://github.com/khuxtable/seaglass/blob/f25ecba622923d7b29b64cb7d6068dd8005989b3/src/main/java/com/seaglasslookandfeel/painter/CheckBoxMenuItemPainter.java#L173-L178 |
Chorus-bdd/Chorus | interpreter/chorus-util/src/main/java/org/chorusbdd/chorus/util/assertion/ChorusAssert.java | ChorusAssert.assertEquals | static public void assertEquals(String message, char expected, char actual) {
assertEquals(message, new Character(expected), new Character(actual));
} | java | static public void assertEquals(String message, char expected, char actual) {
assertEquals(message, new Character(expected), new Character(actual));
} | [
"static",
"public",
"void",
"assertEquals",
"(",
"String",
"message",
",",
"char",
"expected",
",",
"char",
"actual",
")",
"{",
"assertEquals",
"(",
"message",
",",
"new",
"Character",
"(",
"expected",
")",
",",
"new",
"Character",
"(",
"actual",
")",
")",... | Asserts that two chars are equal. If they are not
an AssertionFailedError is thrown with the given message. | [
"Asserts",
"that",
"two",
"chars",
"are",
"equal",
".",
"If",
"they",
"are",
"not",
"an",
"AssertionFailedError",
"is",
"thrown",
"with",
"the",
"given",
"message",
"."
] | train | https://github.com/Chorus-bdd/Chorus/blob/1eea7ca858876bce821bb49b43fd5b6ba1737997/interpreter/chorus-util/src/main/java/org/chorusbdd/chorus/util/assertion/ChorusAssert.java#L202-L204 |
alkacon/opencms-core | src/org/opencms/ui/sitemap/CmsSitemapExtension.java | CmsSitemapExtension.openPropertyDialog | public void openPropertyDialog(CmsUUID sitemapEntryId, CmsUUID rootId) {
getRpcProxy(I_CmsSitemapClientRpc.class).openPropertyDialog("" + sitemapEntryId, "" + rootId);
} | java | public void openPropertyDialog(CmsUUID sitemapEntryId, CmsUUID rootId) {
getRpcProxy(I_CmsSitemapClientRpc.class).openPropertyDialog("" + sitemapEntryId, "" + rootId);
} | [
"public",
"void",
"openPropertyDialog",
"(",
"CmsUUID",
"sitemapEntryId",
",",
"CmsUUID",
"rootId",
")",
"{",
"getRpcProxy",
"(",
"I_CmsSitemapClientRpc",
".",
"class",
")",
".",
"openPropertyDialog",
"(",
"\"\"",
"+",
"sitemapEntryId",
",",
"\"\"",
"+",
"rootId",... | Opens the property dialog for the locale comparison view.<p>
@param sitemapEntryId the structure id for the sitemap entry to edit
@param rootId the structure id of the current tree's root | [
"Opens",
"the",
"property",
"dialog",
"for",
"the",
"locale",
"comparison",
"view",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ui/sitemap/CmsSitemapExtension.java#L345-L348 |
BranchMetrics/android-branch-deep-linking | Branch-SDK/src/io/branch/referral/Branch.java | Branch.getAutoInstance | @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
public static Branch getAutoInstance(@NonNull Context context, @NonNull String branchKey) {
isAutoSessionMode_ = true;
customReferrableSettings_ = CUSTOM_REFERRABLE_SETTINGS.USE_DEFAULT;
boolean isTest = BranchUtil.checkTestMode(context);
getBranchInstance(context, !isTest, branchKey);
if (branchKey.startsWith("key_")) {
boolean isNewBranchKeySet = branchReferral_.prefHelper_.setBranchKey(branchKey);
//on setting a new key clear link cache and pending requests
if (isNewBranchKeySet) {
branchReferral_.linkCache_.clear();
branchReferral_.requestQueue_.clear();
}
} else {
PrefHelper.Debug("Branch Key is invalid. Please check your BranchKey");
}
return branchReferral_;
} | java | @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
public static Branch getAutoInstance(@NonNull Context context, @NonNull String branchKey) {
isAutoSessionMode_ = true;
customReferrableSettings_ = CUSTOM_REFERRABLE_SETTINGS.USE_DEFAULT;
boolean isTest = BranchUtil.checkTestMode(context);
getBranchInstance(context, !isTest, branchKey);
if (branchKey.startsWith("key_")) {
boolean isNewBranchKeySet = branchReferral_.prefHelper_.setBranchKey(branchKey);
//on setting a new key clear link cache and pending requests
if (isNewBranchKeySet) {
branchReferral_.linkCache_.clear();
branchReferral_.requestQueue_.clear();
}
} else {
PrefHelper.Debug("Branch Key is invalid. Please check your BranchKey");
}
return branchReferral_;
} | [
"@",
"TargetApi",
"(",
"Build",
".",
"VERSION_CODES",
".",
"ICE_CREAM_SANDWICH",
")",
"public",
"static",
"Branch",
"getAutoInstance",
"(",
"@",
"NonNull",
"Context",
"context",
",",
"@",
"NonNull",
"String",
"branchKey",
")",
"{",
"isAutoSessionMode_",
"=",
"tr... | <p>Singleton method to return the pre-initialised, or newly initialise and return, a singleton
object of the type {@link Branch}.</p>
<p>Use this whenever you need to call a method directly on the {@link Branch} object.</p>
@param context A {@link Context} from which this call was made.
@param branchKey A {@link String} value used to initialize Branch.
@return An initialised {@link Branch} object, either fetched from a pre-initialised
instance within the singleton class, or a newly instantiated object where
one was not already requested during the current app lifecycle. | [
"<p",
">",
"Singleton",
"method",
"to",
"return",
"the",
"pre",
"-",
"initialised",
"or",
"newly",
"initialise",
"and",
"return",
"a",
"singleton",
"object",
"of",
"the",
"type",
"{",
"@link",
"Branch",
"}",
".",
"<",
"/",
"p",
">",
"<p",
">",
"Use",
... | train | https://github.com/BranchMetrics/android-branch-deep-linking/blob/e3bee2ccfcbf6d4bf1a5815b5b86666e4ff8f848/Branch-SDK/src/io/branch/referral/Branch.java#L735-L753 |
wisdom-framework/wisdom | core/wisdom-maven-plugin/src/main/java/org/wisdom/maven/utils/DefaultMaven2OsgiConverter.java | DefaultMaven2OsgiConverter.getBundleSymbolicName | public static String getBundleSymbolicName(String groupId, String artifactId) {
int i = groupId.lastIndexOf('.');
String lastSection = groupId.substring(++i);
if (artifactId.equals(lastSection)) {
return groupId;
}
if (artifactId.equals(groupId)
|| artifactId.startsWith(groupId + ".")) {
return artifactId;
}
if (artifactId.startsWith(lastSection)) {
artifactId = artifactId.substring(lastSection.length());
if (!Character.isLetterOrDigit(artifactId.charAt(0))) {
return (groupId + "." + artifactId.substring(1)).replace("-", ".");
}
// Else fall to the default case.
}
return (groupId + "." + artifactId).replace("-", ".");
} | java | public static String getBundleSymbolicName(String groupId, String artifactId) {
int i = groupId.lastIndexOf('.');
String lastSection = groupId.substring(++i);
if (artifactId.equals(lastSection)) {
return groupId;
}
if (artifactId.equals(groupId)
|| artifactId.startsWith(groupId + ".")) {
return artifactId;
}
if (artifactId.startsWith(lastSection)) {
artifactId = artifactId.substring(lastSection.length());
if (!Character.isLetterOrDigit(artifactId.charAt(0))) {
return (groupId + "." + artifactId.substring(1)).replace("-", ".");
}
// Else fall to the default case.
}
return (groupId + "." + artifactId).replace("-", ".");
} | [
"public",
"static",
"String",
"getBundleSymbolicName",
"(",
"String",
"groupId",
",",
"String",
"artifactId",
")",
"{",
"int",
"i",
"=",
"groupId",
".",
"lastIndexOf",
"(",
"'",
"'",
")",
";",
"String",
"lastSection",
"=",
"groupId",
".",
"substring",
"(",
... | Get the symbolic name as groupId + "." + artifactId, with the following exceptions. Unlike the original method
from the Maven Bundle Plugin, this method does not use the bundle inspection,
as the artifact's file does not exist when this method is called.
<ul>
<li>if artifactId is equal to last section of groupId then groupId is returned. eg.
org.apache.maven:maven -> org.apache.maven</li>
<li>if artifactId starts with last section of groupId that portion is removed. eg.
org.apache.maven:maven-core -> org.apache.maven.core</li>
<li>if artifactId starts with groupId then the artifactId is removed. eg.
org.apache:org.apache.maven.core -> org.apache.maven.core</li>
</ul>
@param groupId the groupId
@param artifactId the artifactId
@return the symbolic name for the given artifact coordinates | [
"Get",
"the",
"symbolic",
"name",
"as",
"groupId",
"+",
".",
"+",
"artifactId",
"with",
"the",
"following",
"exceptions",
".",
"Unlike",
"the",
"original",
"method",
"from",
"the",
"Maven",
"Bundle",
"Plugin",
"this",
"method",
"does",
"not",
"use",
"the",
... | train | https://github.com/wisdom-framework/wisdom/blob/a35b6431200fec56b178c0ff60837ed73fd7874d/core/wisdom-maven-plugin/src/main/java/org/wisdom/maven/utils/DefaultMaven2OsgiConverter.java#L112-L133 |
querydsl/querydsl | querydsl-lucene4/src/main/java/com/querydsl/lucene4/LuceneExpressions.java | LuceneExpressions.fuzzyLike | public static BooleanExpression fuzzyLike(Path<String> path, String value, int maxEdits) {
Term term = new Term(path.getMetadata().getName(), value);
return new QueryElement(new FuzzyQuery(term, maxEdits));
} | java | public static BooleanExpression fuzzyLike(Path<String> path, String value, int maxEdits) {
Term term = new Term(path.getMetadata().getName(), value);
return new QueryElement(new FuzzyQuery(term, maxEdits));
} | [
"public",
"static",
"BooleanExpression",
"fuzzyLike",
"(",
"Path",
"<",
"String",
">",
"path",
",",
"String",
"value",
",",
"int",
"maxEdits",
")",
"{",
"Term",
"term",
"=",
"new",
"Term",
"(",
"path",
".",
"getMetadata",
"(",
")",
".",
"getName",
"(",
... | Create a fuzzy query
@param path path
@param value value to match
@param maxEdits must be >= 0 and <= {@link LevenshteinAutomata#MAXIMUM_SUPPORTED_DISTANCE}.
@return condition | [
"Create",
"a",
"fuzzy",
"query"
] | train | https://github.com/querydsl/querydsl/blob/2bf234caf78549813a1e0f44d9c30ecc5ef734e3/querydsl-lucene4/src/main/java/com/querydsl/lucene4/LuceneExpressions.java#L52-L55 |
TheHortonMachine/hortonmachine | gears/src/main/java/oms3/ngmf/util/Validation.java | Validation.hexDigest | public static String hexDigest(String algorithm, File[] files) {
try {
MessageDigest md = MessageDigest.getInstance(algorithm);
byte[] buf = new byte[4096];
for (File f : files) {
FileInputStream in = new FileInputStream(f);
int nread = in.read(buf);
while (nread > 0) {
md.update(buf, 0, nread);
nread = in.read(buf);
}
in.close();
}
return toHex(md.digest(buf));
} catch (Exception ex) {
ex.printStackTrace(System.out);
}
return "<error>";
} | java | public static String hexDigest(String algorithm, File[] files) {
try {
MessageDigest md = MessageDigest.getInstance(algorithm);
byte[] buf = new byte[4096];
for (File f : files) {
FileInputStream in = new FileInputStream(f);
int nread = in.read(buf);
while (nread > 0) {
md.update(buf, 0, nread);
nread = in.read(buf);
}
in.close();
}
return toHex(md.digest(buf));
} catch (Exception ex) {
ex.printStackTrace(System.out);
}
return "<error>";
} | [
"public",
"static",
"String",
"hexDigest",
"(",
"String",
"algorithm",
",",
"File",
"[",
"]",
"files",
")",
"{",
"try",
"{",
"MessageDigest",
"md",
"=",
"MessageDigest",
".",
"getInstance",
"(",
"algorithm",
")",
";",
"byte",
"[",
"]",
"buf",
"=",
"new",... | Creates a hex encoded sha-256 hash of all files.
@param algorithm the algorithm to be used.
@param files the files to include for this hash.
@return the hexadecimal digest (length 64byte for sha-256). | [
"Creates",
"a",
"hex",
"encoded",
"sha",
"-",
"256",
"hash",
"of",
"all",
"files",
"."
] | train | https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/oms3/ngmf/util/Validation.java#L24-L42 |
xcesco/kripton | kripton-core/src/main/java/com/abubusoft/kripton/common/TypeAdapterUtils.java | TypeAdapterUtils.generateAdapter | @SuppressWarnings("rawtypes")
static <D extends TypeAdapter> D generateAdapter(HashMap<Class<? extends TypeAdapter>, TypeAdapter> cache, ReentrantLock lock, Class<D> clazz) {
D adapter = null;
try {
lock.lock();
adapter = clazz.newInstance();
cache.put(clazz, adapter);
} catch (Throwable e) {
throw (new KriptonRuntimeException(e));
} finally {
lock.unlock();
}
return adapter;
} | java | @SuppressWarnings("rawtypes")
static <D extends TypeAdapter> D generateAdapter(HashMap<Class<? extends TypeAdapter>, TypeAdapter> cache, ReentrantLock lock, Class<D> clazz) {
D adapter = null;
try {
lock.lock();
adapter = clazz.newInstance();
cache.put(clazz, adapter);
} catch (Throwable e) {
throw (new KriptonRuntimeException(e));
} finally {
lock.unlock();
}
return adapter;
} | [
"@",
"SuppressWarnings",
"(",
"\"rawtypes\"",
")",
"static",
"<",
"D",
"extends",
"TypeAdapter",
">",
"D",
"generateAdapter",
"(",
"HashMap",
"<",
"Class",
"<",
"?",
"extends",
"TypeAdapter",
">",
",",
"TypeAdapter",
">",
"cache",
",",
"ReentrantLock",
"lock",... | Generate adapter.
@param <D> the generic type
@param cache the cache
@param lock the lock
@param clazz the clazz
@return the d | [
"Generate",
"adapter",
"."
] | train | https://github.com/xcesco/kripton/blob/90de2c0523d39b99e81b8d38aa996898762f594a/kripton-core/src/main/java/com/abubusoft/kripton/common/TypeAdapterUtils.java#L86-L99 |
lesaint/damapping | core-parent/core/src/main/java/fr/javatronic/damapping/processor/sourcegenerator/MapperFactoryImplSourceGenerator.java | MapperFactoryImplSourceGenerator.appendProperties | private void appendProperties(List<DAParameter> mapperDependencyParameters, DAClassWriter<DAFileWriter> classWriter)
throws IOException {
for (DAParameter parameter : mapperDependencyParameters) {
classWriter.newProperty(parameter.getName().getName(), parameter.getType())
.withModifiers(DAModifier.PRIVATE, DAModifier.FINAL)
.withAnnotations(
from(parameter.getAnnotations()).filter(REMOVE_MAPPER_DEPENDENCY_ANNOTATION).toList()
)
.write();
}
} | java | private void appendProperties(List<DAParameter> mapperDependencyParameters, DAClassWriter<DAFileWriter> classWriter)
throws IOException {
for (DAParameter parameter : mapperDependencyParameters) {
classWriter.newProperty(parameter.getName().getName(), parameter.getType())
.withModifiers(DAModifier.PRIVATE, DAModifier.FINAL)
.withAnnotations(
from(parameter.getAnnotations()).filter(REMOVE_MAPPER_DEPENDENCY_ANNOTATION).toList()
)
.write();
}
} | [
"private",
"void",
"appendProperties",
"(",
"List",
"<",
"DAParameter",
">",
"mapperDependencyParameters",
",",
"DAClassWriter",
"<",
"DAFileWriter",
">",
"classWriter",
")",
"throws",
"IOException",
"{",
"for",
"(",
"DAParameter",
"parameter",
":",
"mapperDependencyP... | Creates a property for each DAParameter in the list of parameters identified as dependencies of the
MapperFactoryImpl class (same name, same type and same annotations except {@code MapperDependency}).
<p>
Dependencies of the MapperFactory interface are identified by the
{@link fr.javatronic.damapping.annotation.MapperDependency} annotation.
</p> | [
"Creates",
"a",
"property",
"for",
"each",
"DAParameter",
"in",
"the",
"list",
"of",
"parameters",
"identified",
"as",
"dependencies",
"of",
"the",
"MapperFactoryImpl",
"class",
"(",
"same",
"name",
"same",
"type",
"and",
"same",
"annotations",
"except",
"{"
] | train | https://github.com/lesaint/damapping/blob/357afa5866939fd2a18c09213975ffef4836f328/core-parent/core/src/main/java/fr/javatronic/damapping/processor/sourcegenerator/MapperFactoryImplSourceGenerator.java#L160-L171 |
aws/aws-sdk-java | aws-java-sdk-dynamodb/src/main/java/com/amazonaws/services/dynamodbv2/document/TableKeysAndAttributes.java | TableKeysAndAttributes.addHashOnlyPrimaryKey | public TableKeysAndAttributes addHashOnlyPrimaryKey(
String hashKeyName, Object hashKeyValue) {
this.addPrimaryKey(new PrimaryKey(hashKeyName, hashKeyValue));
return this;
} | java | public TableKeysAndAttributes addHashOnlyPrimaryKey(
String hashKeyName, Object hashKeyValue) {
this.addPrimaryKey(new PrimaryKey(hashKeyName, hashKeyValue));
return this;
} | [
"public",
"TableKeysAndAttributes",
"addHashOnlyPrimaryKey",
"(",
"String",
"hashKeyName",
",",
"Object",
"hashKeyValue",
")",
"{",
"this",
".",
"addPrimaryKey",
"(",
"new",
"PrimaryKey",
"(",
"hashKeyName",
",",
"hashKeyValue",
")",
")",
";",
"return",
"this",
";... | Adds a hash-only primary key to be included in the batch get-item
operation.
@param hashKeyName name of the hash key attribute name
@param hashKeyValue name of the hash key value
@return the current instance for method chaining purposes | [
"Adds",
"a",
"hash",
"-",
"only",
"primary",
"key",
"to",
"be",
"included",
"in",
"the",
"batch",
"get",
"-",
"item",
"operation",
"."
] | train | https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-dynamodb/src/main/java/com/amazonaws/services/dynamodbv2/document/TableKeysAndAttributes.java#L155-L159 |
xcesco/kripton | kripton-processor/src/main/java/com/abubusoft/kripton/processor/sharedprefs/transform/EnumPrefsTransform.java | EnumPrefsTransform.generateReadProperty | @Override
public void generateReadProperty(Builder methodBuilder, String preferenceName, TypeName beanClass, String beanName, PrefsProperty property, boolean readAll, ReadType readType) {
if (readAll) {
methodBuilder.beginControlFlow("");
}
methodBuilder.addStatement("String temp=$L.getString($S, null)", preferenceName, property.getPreferenceKey());
if (readAll) {
methodBuilder.addCode(setter(beanClass, beanName, property) + (!property.isPublicField() && beanName!=null ? "(" : "="));
}
switch (readType) {
case NONE:
break;
case RETURN:
methodBuilder.addCode("return ");
break;
case VALUE:
methodBuilder.addCode("$T _value=", property.getPropertyType().getTypeName());
break;
}
methodBuilder.addCode("($T.hasText(temp)) ? ", StringUtils.class);
methodBuilder.addCode("$T.valueOf(temp)", typeName);
methodBuilder.addCode(": $L", getter(DEFAULT_BEAN_NAME, beanClass, property));
if (readAll) {
methodBuilder.addCode(!property.isPublicField() && beanName!=null ? ")" : "");
}
methodBuilder.addCode(";\n");
if (readAll) {
methodBuilder.endControlFlow();
}
} | java | @Override
public void generateReadProperty(Builder methodBuilder, String preferenceName, TypeName beanClass, String beanName, PrefsProperty property, boolean readAll, ReadType readType) {
if (readAll) {
methodBuilder.beginControlFlow("");
}
methodBuilder.addStatement("String temp=$L.getString($S, null)", preferenceName, property.getPreferenceKey());
if (readAll) {
methodBuilder.addCode(setter(beanClass, beanName, property) + (!property.isPublicField() && beanName!=null ? "(" : "="));
}
switch (readType) {
case NONE:
break;
case RETURN:
methodBuilder.addCode("return ");
break;
case VALUE:
methodBuilder.addCode("$T _value=", property.getPropertyType().getTypeName());
break;
}
methodBuilder.addCode("($T.hasText(temp)) ? ", StringUtils.class);
methodBuilder.addCode("$T.valueOf(temp)", typeName);
methodBuilder.addCode(": $L", getter(DEFAULT_BEAN_NAME, beanClass, property));
if (readAll) {
methodBuilder.addCode(!property.isPublicField() && beanName!=null ? ")" : "");
}
methodBuilder.addCode(";\n");
if (readAll) {
methodBuilder.endControlFlow();
}
} | [
"@",
"Override",
"public",
"void",
"generateReadProperty",
"(",
"Builder",
"methodBuilder",
",",
"String",
"preferenceName",
",",
"TypeName",
"beanClass",
",",
"String",
"beanName",
",",
"PrefsProperty",
"property",
",",
"boolean",
"readAll",
",",
"ReadType",
"readT... | /* (non-Javadoc)
@see com.abubusoft.kripton.processor.sharedprefs.transform.PrefsTransform#generateReadProperty(com.squareup.javapoet.MethodSpec.Builder, java.lang.String, com.squareup.javapoet.TypeName, java.lang.String, com.abubusoft.kripton.processor.sharedprefs.model.PrefsProperty, boolean) | [
"/",
"*",
"(",
"non",
"-",
"Javadoc",
")"
] | train | https://github.com/xcesco/kripton/blob/90de2c0523d39b99e81b8d38aa996898762f594a/kripton-processor/src/main/java/com/abubusoft/kripton/processor/sharedprefs/transform/EnumPrefsTransform.java#L53-L89 |
cdapio/tephra | tephra-core/src/main/java/co/cask/tephra/util/TxUtils.java | TxUtils.getMaxTTL | private static long getMaxTTL(Map<byte[], Long> ttlByFamily) {
long maxTTL = 0;
for (Long familyTTL : ttlByFamily.values()) {
maxTTL = Math.max(familyTTL <= 0 ? Long.MAX_VALUE : familyTTL, maxTTL);
}
return maxTTL == 0 ? Long.MAX_VALUE : maxTTL;
} | java | private static long getMaxTTL(Map<byte[], Long> ttlByFamily) {
long maxTTL = 0;
for (Long familyTTL : ttlByFamily.values()) {
maxTTL = Math.max(familyTTL <= 0 ? Long.MAX_VALUE : familyTTL, maxTTL);
}
return maxTTL == 0 ? Long.MAX_VALUE : maxTTL;
} | [
"private",
"static",
"long",
"getMaxTTL",
"(",
"Map",
"<",
"byte",
"[",
"]",
",",
"Long",
">",
"ttlByFamily",
")",
"{",
"long",
"maxTTL",
"=",
"0",
";",
"for",
"(",
"Long",
"familyTTL",
":",
"ttlByFamily",
".",
"values",
"(",
")",
")",
"{",
"maxTTL",... | Returns the max TTL for the given TTL values. Returns Long.MAX_VALUE if any of the column families has no TTL set. | [
"Returns",
"the",
"max",
"TTL",
"for",
"the",
"given",
"TTL",
"values",
".",
"Returns",
"Long",
".",
"MAX_VALUE",
"if",
"any",
"of",
"the",
"column",
"families",
"has",
"no",
"TTL",
"set",
"."
] | train | https://github.com/cdapio/tephra/blob/082c56c15c6ece15002631ff6f89206a00d8915c/tephra-core/src/main/java/co/cask/tephra/util/TxUtils.java#L136-L142 |
Metatavu/edelphi | edelphi/src/main/java/fi/metatavu/edelphi/pages/panel/admin/report/thesis/ThesisScale1DQueryReportPage.java | ThesisScale1DQueryReportPage.appendQueryPageComments | private void appendQueryPageComments(RequestContext requestContext, final QueryPage queryPage) {
PanelStamp panelStamp = RequestUtils.getActiveStamp(requestContext);
Map<Long, Map<String, String>> answers = getRequestAnswerMap(requestContext);
ReportPageCommentProcessor sorter = new Scale1DReportPageCommentProcessor(panelStamp, queryPage, answers);
appendQueryPageComments(requestContext, queryPage, sorter);
} | java | private void appendQueryPageComments(RequestContext requestContext, final QueryPage queryPage) {
PanelStamp panelStamp = RequestUtils.getActiveStamp(requestContext);
Map<Long, Map<String, String>> answers = getRequestAnswerMap(requestContext);
ReportPageCommentProcessor sorter = new Scale1DReportPageCommentProcessor(panelStamp, queryPage, answers);
appendQueryPageComments(requestContext, queryPage, sorter);
} | [
"private",
"void",
"appendQueryPageComments",
"(",
"RequestContext",
"requestContext",
",",
"final",
"QueryPage",
"queryPage",
")",
"{",
"PanelStamp",
"panelStamp",
"=",
"RequestUtils",
".",
"getActiveStamp",
"(",
"requestContext",
")",
";",
"Map",
"<",
"Long",
",",... | Appends query page comment to request.
@param requestContext request contract
@param queryPage query page | [
"Appends",
"query",
"page",
"comment",
"to",
"request",
"."
] | train | https://github.com/Metatavu/edelphi/blob/d91a0b54f954b33b4ee674a1bdf03612d76c3305/edelphi/src/main/java/fi/metatavu/edelphi/pages/panel/admin/report/thesis/ThesisScale1DQueryReportPage.java#L113-L118 |
audit4j/audit4j-core | src/main/java/org/audit4j/core/util/EncryptionUtil.java | EncryptionUtil.generateKeyIfNotAvailable | private static void generateKeyIfNotAvailable(String key, String salt) throws NoSuchAlgorithmException,
UnsupportedEncodingException, InvalidKeySpecException {
if (null == cryptKey) {
LOG.debug("Generating Key...");
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
char[] password = key.toCharArray();
byte[] saltBytes = salt.getBytes(CoreConstants.ENCODE_UTF8);
KeySpec spec = new PBEKeySpec(password, saltBytes, 65536, 128);
SecretKey tmp = factory.generateSecret(spec);
byte[] encoded = tmp.getEncoded();
cryptKey = new SecretKeySpec(encoded, "AES");
}
} | java | private static void generateKeyIfNotAvailable(String key, String salt) throws NoSuchAlgorithmException,
UnsupportedEncodingException, InvalidKeySpecException {
if (null == cryptKey) {
LOG.debug("Generating Key...");
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
char[] password = key.toCharArray();
byte[] saltBytes = salt.getBytes(CoreConstants.ENCODE_UTF8);
KeySpec spec = new PBEKeySpec(password, saltBytes, 65536, 128);
SecretKey tmp = factory.generateSecret(spec);
byte[] encoded = tmp.getEncoded();
cryptKey = new SecretKeySpec(encoded, "AES");
}
} | [
"private",
"static",
"void",
"generateKeyIfNotAvailable",
"(",
"String",
"key",
",",
"String",
"salt",
")",
"throws",
"NoSuchAlgorithmException",
",",
"UnsupportedEncodingException",
",",
"InvalidKeySpecException",
"{",
"if",
"(",
"null",
"==",
"cryptKey",
")",
"{",
... | Generate key.
@param key
the key
@param salt
the salt
@return the key
@throws NoSuchAlgorithmException
the no such algorithm exception
@throws UnsupportedEncodingException
the unsupported encoding exception
@throws InvalidKeySpecException
the invalid key spec exception | [
"Generate",
"key",
"."
] | train | https://github.com/audit4j/audit4j-core/blob/dc8569108851e64cb0ecc7a39048db0ad070fba2/src/main/java/org/audit4j/core/util/EncryptionUtil.java#L148-L161 |
reapzor/FiloFirmata | src/main/java/com/bortbort/arduino/FiloFirmata/Firmata.java | Firmata.dispatchMessage | @SuppressWarnings("unchecked")
private void dispatchMessage(ArrayListMultimap<Integer, MessageListener> listenerMap, Message message) {
List<MessageListener> messageListeners;
// If the message is a Channel Message, hit the channel based listeners first.
if (message instanceof ChannelMessage) {
messageListeners = listenerMap.get(((ChannelMessage) message).getChannelInt());
if (messageListeners != null) {
for (MessageListener listener : messageListeners) {
listener.messageReceived(message);
}
}
}
// Then send the message to any listeners registered to all channels
// or to listeners for messages that do not support channels.
messageListeners = listenerMap.get(null);
if (messageListeners != null) {
for (MessageListener listener : messageListeners) {
listener.messageReceived(message);
}
}
} | java | @SuppressWarnings("unchecked")
private void dispatchMessage(ArrayListMultimap<Integer, MessageListener> listenerMap, Message message) {
List<MessageListener> messageListeners;
// If the message is a Channel Message, hit the channel based listeners first.
if (message instanceof ChannelMessage) {
messageListeners = listenerMap.get(((ChannelMessage) message).getChannelInt());
if (messageListeners != null) {
for (MessageListener listener : messageListeners) {
listener.messageReceived(message);
}
}
}
// Then send the message to any listeners registered to all channels
// or to listeners for messages that do not support channels.
messageListeners = listenerMap.get(null);
if (messageListeners != null) {
for (MessageListener listener : messageListeners) {
listener.messageReceived(message);
}
}
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"private",
"void",
"dispatchMessage",
"(",
"ArrayListMultimap",
"<",
"Integer",
",",
"MessageListener",
">",
"listenerMap",
",",
"Message",
"message",
")",
"{",
"List",
"<",
"MessageListener",
">",
"messageListener... | Dispatch a message to the corresponding listener arrays in the listener map
@param listenerMap ArrayListMultimap of listener arrays to dispatch the message to
@param message Message to be dispatched to the listeners | [
"Dispatch",
"a",
"message",
"to",
"the",
"corresponding",
"listener",
"arrays",
"in",
"the",
"listener",
"map"
] | train | https://github.com/reapzor/FiloFirmata/blob/39c26c1a577b8fff8690245e105cb62e02284f16/src/main/java/com/bortbort/arduino/FiloFirmata/Firmata.java#L615-L637 |
dihedron/dihedron-commons | src/main/java/org/dihedron/patterns/activities/TypedVector.java | TypedVector.addAll | @Override
public boolean addAll(int index, Collection<? extends E> collection) {
int idx = getRealIndex(index);
return super.addAll(idx, collection);
} | java | @Override
public boolean addAll(int index, Collection<? extends E> collection) {
int idx = getRealIndex(index);
return super.addAll(idx, collection);
} | [
"@",
"Override",
"public",
"boolean",
"addAll",
"(",
"int",
"index",
",",
"Collection",
"<",
"?",
"extends",
"E",
">",
"collection",
")",
"{",
"int",
"idx",
"=",
"getRealIndex",
"(",
"index",
")",
";",
"return",
"super",
".",
"addAll",
"(",
"idx",
",",... | Inserts all of the elements in the specified Collection into this Vector
at the specified position.
@param index
the index can be a positive number, or a negative number that is smaller
than the size of the vector; see {@link #getRealIndex(int)}.
@return
{@code true} if this vector changed as a result of the call.
@see
java.util.Vector#addAll(int, java.util.Collection) | [
"Inserts",
"all",
"of",
"the",
"elements",
"in",
"the",
"specified",
"Collection",
"into",
"this",
"Vector",
"at",
"the",
"specified",
"position",
"."
] | train | https://github.com/dihedron/dihedron-commons/blob/a5194cdaa0d6417ef4aade6ea407a1cad6e8458e/src/main/java/org/dihedron/patterns/activities/TypedVector.java#L99-L103 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.