repository_name stringlengths 7 58 | func_path_in_repository stringlengths 18 201 | func_name stringlengths 4 126 | whole_func_string stringlengths 75 3.57k | language stringclasses 1
value | func_code_string stringlengths 75 3.57k | func_code_tokens listlengths 21 599 | func_documentation_string stringlengths 61 1.95k | func_documentation_tokens listlengths 1 478 | split_name stringclasses 1
value | func_code_url stringlengths 111 308 |
|---|---|---|---|---|---|---|---|---|---|---|
exoplatform/jcr | exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/core/query/lucene/SearchIndex.java | SearchIndex.createNewIndex | public MultiIndex createNewIndex(String suffix) throws IOException {
IndexInfos indexInfos = new IndexInfos();
IndexUpdateMonitor indexUpdateMonitor = new DefaultIndexUpdateMonitor();
IndexerIoModeHandler modeHandler = new IndexerIoModeHandler(IndexerIoMode.READ_WRITE);
MultiIndex newIndex = new MultiIndex(this, getContext().getIndexingTree(), modeHandler,
indexInfos, indexUpdateMonitor, cloneDirectoryManager(this.getDirectoryManager(), suffix));
return newIndex;
} | java | public MultiIndex createNewIndex(String suffix) throws IOException {
IndexInfos indexInfos = new IndexInfos();
IndexUpdateMonitor indexUpdateMonitor = new DefaultIndexUpdateMonitor();
IndexerIoModeHandler modeHandler = new IndexerIoModeHandler(IndexerIoMode.READ_WRITE);
MultiIndex newIndex = new MultiIndex(this, getContext().getIndexingTree(), modeHandler,
indexInfos, indexUpdateMonitor, cloneDirectoryManager(this.getDirectoryManager(), suffix));
return newIndex;
} | [
"public",
"MultiIndex",
"createNewIndex",
"(",
"String",
"suffix",
")",
"throws",
"IOException",
"{",
"IndexInfos",
"indexInfos",
"=",
"new",
"IndexInfos",
"(",
")",
";",
"IndexUpdateMonitor",
"indexUpdateMonitor",
"=",
"new",
"DefaultIndexUpdateMonitor",
"(",
")",
... | Create a new index with the same actual context.
@return MultiIndex the actual index. | [
"Create",
"a",
"new",
"index",
"with",
"the",
"same",
"actual",
"context",
"."
] | train | https://github.com/exoplatform/jcr/blob/3e7f9ee1b5683640d73a4316fb4b0ad5eac5b8a2/exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/core/query/lucene/SearchIndex.java#L1881-L1891 |
voldemort/voldemort | src/java/voldemort/utils/RebalanceUtils.java | RebalanceUtils.getInterimCluster | public static Cluster getInterimCluster(Cluster currentCluster, Cluster finalCluster) {
List<Node> newNodeList = new ArrayList<Node>(currentCluster.getNodes());
for(Node node: finalCluster.getNodes()) {
if(!currentCluster.hasNodeWithId(node.getId())) {
newNodeList.add(UpdateClusterUtils.updateNode(node, new ArrayList<Integer>()));
}
}
Collections.sort(newNodeList);
return new Cluster(currentCluster.getName(),
newNodeList,
Lists.newArrayList(finalCluster.getZones()));
} | java | public static Cluster getInterimCluster(Cluster currentCluster, Cluster finalCluster) {
List<Node> newNodeList = new ArrayList<Node>(currentCluster.getNodes());
for(Node node: finalCluster.getNodes()) {
if(!currentCluster.hasNodeWithId(node.getId())) {
newNodeList.add(UpdateClusterUtils.updateNode(node, new ArrayList<Integer>()));
}
}
Collections.sort(newNodeList);
return new Cluster(currentCluster.getName(),
newNodeList,
Lists.newArrayList(finalCluster.getZones()));
} | [
"public",
"static",
"Cluster",
"getInterimCluster",
"(",
"Cluster",
"currentCluster",
",",
"Cluster",
"finalCluster",
")",
"{",
"List",
"<",
"Node",
">",
"newNodeList",
"=",
"new",
"ArrayList",
"<",
"Node",
">",
"(",
"currentCluster",
".",
"getNodes",
"(",
")"... | Given the current cluster and final cluster, generates an interim cluster
with empty new nodes (and zones).
@param currentCluster Current cluster metadata
@param finalCluster Final cluster metadata
@return Returns a new interim cluster which contains nodes and zones of
final cluster, but with empty partition lists if they were not
present in current cluster. | [
"Given",
"the",
"current",
"cluster",
"and",
"final",
"cluster",
"generates",
"an",
"interim",
"cluster",
"with",
"empty",
"new",
"nodes",
"(",
"and",
"zones",
")",
"."
] | train | https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/utils/RebalanceUtils.java#L268-L279 |
Azure/azure-sdk-for-java | cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/implementation/TrainingsImpl.java | TrainingsImpl.getTagsWithServiceResponseAsync | public Observable<ServiceResponse<List<Tag>>> getTagsWithServiceResponseAsync(UUID projectId, GetTagsOptionalParameter getTagsOptionalParameter) {
if (projectId == null) {
throw new IllegalArgumentException("Parameter projectId is required and cannot be null.");
}
if (this.client.apiKey() == null) {
throw new IllegalArgumentException("Parameter this.client.apiKey() is required and cannot be null.");
}
final UUID iterationId = getTagsOptionalParameter != null ? getTagsOptionalParameter.iterationId() : null;
return getTagsWithServiceResponseAsync(projectId, iterationId);
} | java | public Observable<ServiceResponse<List<Tag>>> getTagsWithServiceResponseAsync(UUID projectId, GetTagsOptionalParameter getTagsOptionalParameter) {
if (projectId == null) {
throw new IllegalArgumentException("Parameter projectId is required and cannot be null.");
}
if (this.client.apiKey() == null) {
throw new IllegalArgumentException("Parameter this.client.apiKey() is required and cannot be null.");
}
final UUID iterationId = getTagsOptionalParameter != null ? getTagsOptionalParameter.iterationId() : null;
return getTagsWithServiceResponseAsync(projectId, iterationId);
} | [
"public",
"Observable",
"<",
"ServiceResponse",
"<",
"List",
"<",
"Tag",
">",
">",
">",
"getTagsWithServiceResponseAsync",
"(",
"UUID",
"projectId",
",",
"GetTagsOptionalParameter",
"getTagsOptionalParameter",
")",
"{",
"if",
"(",
"projectId",
"==",
"null",
")",
"... | Get the tags for a given project and iteration.
@param projectId The project id
@param getTagsOptionalParameter the object representing the optional parameters to be set before calling this API
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the List<Tag> object | [
"Get",
"the",
"tags",
"for",
"a",
"given",
"project",
"and",
"iteration",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/implementation/TrainingsImpl.java#L495-L505 |
jparsec/jparsec | jparsec/src/main/java/org/jparsec/ParseContext.java | ParseContext.renderError | final ParseErrorDetails renderError() {
final int errorIndex = toIndex(currentErrorAt);
final String encounteredName = getEncountered();
final ArrayList<String> errorStrings = Lists.arrayList(errors.size());
for (Object error : errors) {
errorStrings.add(String.valueOf(error));
}
switch (currentErrorType) {
case UNEXPECTED :
return new EmptyParseError(errorIndex, encounteredName) {
@Override public String getUnexpected() {
return errorStrings.get(0);
}
};
case FAILURE :
return new EmptyParseError(errorIndex, encounteredName) {
@Override public String getFailureMessage() {
return errorStrings.get(0);
}
};
case EXPECTING:
case MISSING:
case DELIMITING:
return new EmptyParseError(errorIndex, encounteredName) {
@Override public List<String> getExpected() {
return errorStrings;
}
};
default:
return new EmptyParseError(errorIndex, encounteredName);
}
} | java | final ParseErrorDetails renderError() {
final int errorIndex = toIndex(currentErrorAt);
final String encounteredName = getEncountered();
final ArrayList<String> errorStrings = Lists.arrayList(errors.size());
for (Object error : errors) {
errorStrings.add(String.valueOf(error));
}
switch (currentErrorType) {
case UNEXPECTED :
return new EmptyParseError(errorIndex, encounteredName) {
@Override public String getUnexpected() {
return errorStrings.get(0);
}
};
case FAILURE :
return new EmptyParseError(errorIndex, encounteredName) {
@Override public String getFailureMessage() {
return errorStrings.get(0);
}
};
case EXPECTING:
case MISSING:
case DELIMITING:
return new EmptyParseError(errorIndex, encounteredName) {
@Override public List<String> getExpected() {
return errorStrings;
}
};
default:
return new EmptyParseError(errorIndex, encounteredName);
}
} | [
"final",
"ParseErrorDetails",
"renderError",
"(",
")",
"{",
"final",
"int",
"errorIndex",
"=",
"toIndex",
"(",
"currentErrorAt",
")",
";",
"final",
"String",
"encounteredName",
"=",
"getEncountered",
"(",
")",
";",
"final",
"ArrayList",
"<",
"String",
">",
"er... | Only called when rendering the error in {@link ParserException}. | [
"Only",
"called",
"when",
"rendering",
"the",
"error",
"in",
"{"
] | train | https://github.com/jparsec/jparsec/blob/df1280259f5da9eb5ffc537437569dddba66cb94/jparsec/src/main/java/org/jparsec/ParseContext.java#L216-L247 |
xcesco/kripton | kripton-processor/src/main/java/com/abubusoft/kripton/processor/sqlite/SqlSelectBuilder.java | SqlSelectBuilder.convertJQL2SQL | public static String convertJQL2SQL(final SQLiteModelMethod method, final boolean replaceWithQuestion) {
JQLChecker jqlChecker = JQLChecker.getInstance();
// convert jql to sql
String sql = jqlChecker.replace(method, method.jql, new JQLReplacerListenerImpl(method) {
@Override
public String onBindParameter(String bindParameterName, boolean inStatement) {
if (replaceWithQuestion) {
return "?";
}
return SqlAnalyzer.PARAM_PREFIX + bindParameterName + SqlAnalyzer.PARAM_SUFFIX;
}
@Override
public String onColumnName(String columnName) {
SQLProperty tempProperty = currentEntity.get(columnName);
AssertKripton.assertTrueOrUnknownPropertyInJQLException(tempProperty != null, method, columnName);
return tempProperty.columnName;
}
@Override
public String onColumnAlias(String alias) {
SQLProperty tempProperty = currentEntity.get(alias);
AssertKripton.assertTrueOrUnknownPropertyInJQLException(tempProperty != null, method, alias);
return tempProperty.columnName;
}
});
return sql;
} | java | public static String convertJQL2SQL(final SQLiteModelMethod method, final boolean replaceWithQuestion) {
JQLChecker jqlChecker = JQLChecker.getInstance();
// convert jql to sql
String sql = jqlChecker.replace(method, method.jql, new JQLReplacerListenerImpl(method) {
@Override
public String onBindParameter(String bindParameterName, boolean inStatement) {
if (replaceWithQuestion) {
return "?";
}
return SqlAnalyzer.PARAM_PREFIX + bindParameterName + SqlAnalyzer.PARAM_SUFFIX;
}
@Override
public String onColumnName(String columnName) {
SQLProperty tempProperty = currentEntity.get(columnName);
AssertKripton.assertTrueOrUnknownPropertyInJQLException(tempProperty != null, method, columnName);
return tempProperty.columnName;
}
@Override
public String onColumnAlias(String alias) {
SQLProperty tempProperty = currentEntity.get(alias);
AssertKripton.assertTrueOrUnknownPropertyInJQLException(tempProperty != null, method, alias);
return tempProperty.columnName;
}
});
return sql;
} | [
"public",
"static",
"String",
"convertJQL2SQL",
"(",
"final",
"SQLiteModelMethod",
"method",
",",
"final",
"boolean",
"replaceWithQuestion",
")",
"{",
"JQLChecker",
"jqlChecker",
"=",
"JQLChecker",
".",
"getInstance",
"(",
")",
";",
"// convert jql to sql",
"String",
... | Convert JQL 2 SQL.
@param method
the method
@param replaceWithQuestion
the replace with question
@return the string | [
"Convert",
"JQL",
"2",
"SQL",
"."
] | train | https://github.com/xcesco/kripton/blob/90de2c0523d39b99e81b8d38aa996898762f594a/kripton-processor/src/main/java/com/abubusoft/kripton/processor/sqlite/SqlSelectBuilder.java#L438-L469 |
line/armeria | grpc/src/main/java/com/linecorp/armeria/server/grpc/GrpcDocStringExtractor.java | GrpcDocStringExtractor.getFullName | private static Optional<String> getFullName(FileDescriptorProto descriptor, List<Integer> path) {
String fullNameSoFar = descriptor.getPackage();
switch (path.get(0)) {
case FileDescriptorProto.MESSAGE_TYPE_FIELD_NUMBER:
final DescriptorProto message = descriptor.getMessageType(path.get(1));
return appendMessageToFullName(message, path, fullNameSoFar);
case FileDescriptorProto.ENUM_TYPE_FIELD_NUMBER:
final EnumDescriptorProto enumDescriptor = descriptor.getEnumType(path.get(1));
return Optional.of(appendEnumToFullName(enumDescriptor, path, fullNameSoFar));
case FileDescriptorProto.SERVICE_FIELD_NUMBER:
final ServiceDescriptorProto serviceDescriptor = descriptor.getService(path.get(1));
fullNameSoFar = appendNameComponent(fullNameSoFar, serviceDescriptor.getName());
if (path.size() > 2) {
fullNameSoFar = appendFieldComponent(
fullNameSoFar, serviceDescriptor.getMethod(path.get(3)).getName());
}
return Optional.of(fullNameSoFar);
default:
return Optional.empty();
}
} | java | private static Optional<String> getFullName(FileDescriptorProto descriptor, List<Integer> path) {
String fullNameSoFar = descriptor.getPackage();
switch (path.get(0)) {
case FileDescriptorProto.MESSAGE_TYPE_FIELD_NUMBER:
final DescriptorProto message = descriptor.getMessageType(path.get(1));
return appendMessageToFullName(message, path, fullNameSoFar);
case FileDescriptorProto.ENUM_TYPE_FIELD_NUMBER:
final EnumDescriptorProto enumDescriptor = descriptor.getEnumType(path.get(1));
return Optional.of(appendEnumToFullName(enumDescriptor, path, fullNameSoFar));
case FileDescriptorProto.SERVICE_FIELD_NUMBER:
final ServiceDescriptorProto serviceDescriptor = descriptor.getService(path.get(1));
fullNameSoFar = appendNameComponent(fullNameSoFar, serviceDescriptor.getName());
if (path.size() > 2) {
fullNameSoFar = appendFieldComponent(
fullNameSoFar, serviceDescriptor.getMethod(path.get(3)).getName());
}
return Optional.of(fullNameSoFar);
default:
return Optional.empty();
}
} | [
"private",
"static",
"Optional",
"<",
"String",
">",
"getFullName",
"(",
"FileDescriptorProto",
"descriptor",
",",
"List",
"<",
"Integer",
">",
"path",
")",
"{",
"String",
"fullNameSoFar",
"=",
"descriptor",
".",
"getPackage",
"(",
")",
";",
"switch",
"(",
"... | would have path [MESSAGE_TYPE_FIELD_NUMBER, 0, NESTED_TYPE_FIELD_NUMBER, 2, FIELD_FIELD_NUMBER, 1] | [
"would",
"have",
"path",
"[",
"MESSAGE_TYPE_FIELD_NUMBER",
"0",
"NESTED_TYPE_FIELD_NUMBER",
"2",
"FIELD_FIELD_NUMBER",
"1",
"]"
] | train | https://github.com/line/armeria/blob/67d29e019fd35a35f89c45cc8f9119ff9b12b44d/grpc/src/main/java/com/linecorp/armeria/server/grpc/GrpcDocStringExtractor.java#L109-L129 |
lessthanoptimal/BoofCV | main/boofcv-geo/src/main/java/boofcv/alg/distort/NarrowToWidePtoP_F64.java | NarrowToWidePtoP_F64.compute | @Override
public void compute(double x, double y, Point2D_F64 out) {
narrowToNorm.compute(x,y, norm);
// Convert from 2D homogenous to 3D
unit.set( norm.x , norm.y , 1.0);
// Rotate then make it a unit vector
GeometryMath_F64.mult(rotateWideToNarrow,unit,unit);
double n = unit.norm();
unit.x /= n;
unit.y /= n;
unit.z /= n;
unitToWide.compute(unit.x,unit.y,unit.z,out);
} | java | @Override
public void compute(double x, double y, Point2D_F64 out) {
narrowToNorm.compute(x,y, norm);
// Convert from 2D homogenous to 3D
unit.set( norm.x , norm.y , 1.0);
// Rotate then make it a unit vector
GeometryMath_F64.mult(rotateWideToNarrow,unit,unit);
double n = unit.norm();
unit.x /= n;
unit.y /= n;
unit.z /= n;
unitToWide.compute(unit.x,unit.y,unit.z,out);
} | [
"@",
"Override",
"public",
"void",
"compute",
"(",
"double",
"x",
",",
"double",
"y",
",",
"Point2D_F64",
"out",
")",
"{",
"narrowToNorm",
".",
"compute",
"(",
"x",
",",
"y",
",",
"norm",
")",
";",
"// Convert from 2D homogenous to 3D",
"unit",
".",
"set",... | Apply the transformation
@param x x-coordinate of point in pixels. Synthetic narrow FOV camera
@param y y-coordinate of point in pixels. Synthetic narrow FOV camera
@param out Pixel location of point in wide FOV camera. | [
"Apply",
"the",
"transformation"
] | train | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-geo/src/main/java/boofcv/alg/distort/NarrowToWidePtoP_F64.java#L74-L89 |
seedstack/i18n-addon | rest/src/main/java/org/seedstack/i18n/rest/internal/translation/TranslationsResource.java | TranslationsResource.getTranslations | @GET
@Produces(MediaType.APPLICATION_JSON)
@RequiresPermissions(I18nPermissions.TRANSLATION_READ)
public Response getTranslations(@QueryParam(PAGE_INDEX) Long pageIndex, @QueryParam(PAGE_SIZE) Integer pageSize,
@QueryParam(IS_MISSING) Boolean isMissing, @QueryParam(IS_APPROX) Boolean isApprox,
@QueryParam(IS_OUTDATED) Boolean isOutdated, @QueryParam(SEARCH_NAME) String searchName) {
Response response = Response.noContent().build();
if (pageIndex != null && pageSize != null) {
KeySearchCriteria criteria = new KeySearchCriteria(isMissing, isApprox, isOutdated, searchName, locale);
response = Response.ok(translationFinder.findAllTranslations(new Page(pageIndex, pageSize), criteria))
.build();
} else {
List<TranslationRepresentation> translations = translationFinder.findTranslations(locale);
if (!translations.isEmpty()) {
response = Response.ok(translations).build();
}
}
return response;
} | java | @GET
@Produces(MediaType.APPLICATION_JSON)
@RequiresPermissions(I18nPermissions.TRANSLATION_READ)
public Response getTranslations(@QueryParam(PAGE_INDEX) Long pageIndex, @QueryParam(PAGE_SIZE) Integer pageSize,
@QueryParam(IS_MISSING) Boolean isMissing, @QueryParam(IS_APPROX) Boolean isApprox,
@QueryParam(IS_OUTDATED) Boolean isOutdated, @QueryParam(SEARCH_NAME) String searchName) {
Response response = Response.noContent().build();
if (pageIndex != null && pageSize != null) {
KeySearchCriteria criteria = new KeySearchCriteria(isMissing, isApprox, isOutdated, searchName, locale);
response = Response.ok(translationFinder.findAllTranslations(new Page(pageIndex, pageSize), criteria))
.build();
} else {
List<TranslationRepresentation> translations = translationFinder.findTranslations(locale);
if (!translations.isEmpty()) {
response = Response.ok(translations).build();
}
}
return response;
} | [
"@",
"GET",
"@",
"Produces",
"(",
"MediaType",
".",
"APPLICATION_JSON",
")",
"@",
"RequiresPermissions",
"(",
"I18nPermissions",
".",
"TRANSLATION_READ",
")",
"public",
"Response",
"getTranslations",
"(",
"@",
"QueryParam",
"(",
"PAGE_INDEX",
")",
"Long",
"pageInd... | Returns filtered translation with pagination.
@param pageIndex page index
@param pageSize page size
@param isMissing filter indicator on missing translation
@param isApprox filter indicator on approximate translation
@param isOutdated filter indicator on outdated translation
@param searchName filter on key name
@return status code 200 with filtered translations or 204 if no translation | [
"Returns",
"filtered",
"translation",
"with",
"pagination",
"."
] | train | https://github.com/seedstack/i18n-addon/blob/1e65101d8554623f09bda2497b0151fd10a16615/rest/src/main/java/org/seedstack/i18n/rest/internal/translation/TranslationsResource.java#L72-L92 |
Ordinastie/MalisisCore | src/main/java/net/malisis/core/inventory/message/CloseInventoryMessage.java | CloseInventoryMessage.process | @Override
public void process(Packet message, MessageContext ctx)
{
if (MalisisGui.current() != null)
MalisisGui.current().close();
} | java | @Override
public void process(Packet message, MessageContext ctx)
{
if (MalisisGui.current() != null)
MalisisGui.current().close();
} | [
"@",
"Override",
"public",
"void",
"process",
"(",
"Packet",
"message",
",",
"MessageContext",
"ctx",
")",
"{",
"if",
"(",
"MalisisGui",
".",
"current",
"(",
")",
"!=",
"null",
")",
"MalisisGui",
".",
"current",
"(",
")",
".",
"close",
"(",
")",
";",
... | Handles the received {@link Packet} on the client. Closes the GUI.
@param message the message
@param ctx the ctx | [
"Handles",
"the",
"received",
"{",
"@link",
"Packet",
"}",
"on",
"the",
"client",
".",
"Closes",
"the",
"GUI",
"."
] | train | https://github.com/Ordinastie/MalisisCore/blob/4f8e1fa462d5c372fc23414482ba9f429881cc54/src/main/java/net/malisis/core/inventory/message/CloseInventoryMessage.java#L58-L63 |
jbundle/jbundle | base/base/src/main/java/org/jbundle/base/db/event/DateChangedHandler.java | DateChangedHandler.init | public void init(Record record, DateTimeField field, String mainFilesFieldName)
{
super.init(record);
m_field = field;
if (field != null)
if (field.getRecord() != record)
field.addListener(new FieldRemoveBOnCloseHandler(this));
this.mainFilesFieldName = mainFilesFieldName;
} | java | public void init(Record record, DateTimeField field, String mainFilesFieldName)
{
super.init(record);
m_field = field;
if (field != null)
if (field.getRecord() != record)
field.addListener(new FieldRemoveBOnCloseHandler(this));
this.mainFilesFieldName = mainFilesFieldName;
} | [
"public",
"void",
"init",
"(",
"Record",
"record",
",",
"DateTimeField",
"field",
",",
"String",
"mainFilesFieldName",
")",
"{",
"super",
".",
"init",
"(",
"record",
")",
";",
"m_field",
"=",
"field",
";",
"if",
"(",
"field",
"!=",
"null",
")",
"if",
"... | Constructor.
@param record My owner (usually passed as null, and set on addListener in setOwner()).
@param iMainFilesField The sequence of the date changed field in this record.
@param field The date changed field in this record. | [
"Constructor",
"."
] | train | https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/base/base/src/main/java/org/jbundle/base/db/event/DateChangedHandler.java#L71-L79 |
google/error-prone | core/src/main/java/com/google/errorprone/bugpatterns/threadsafety/ImmutableAnalysis.java | ImmutableAnalysis.getImmutableAnnotation | AnnotationInfo getImmutableAnnotation(Tree tree, VisitorState state) {
Symbol sym = ASTHelpers.getSymbol(tree);
return sym == null ? null : threadSafety.getMarkerOrAcceptedAnnotation(sym, state);
} | java | AnnotationInfo getImmutableAnnotation(Tree tree, VisitorState state) {
Symbol sym = ASTHelpers.getSymbol(tree);
return sym == null ? null : threadSafety.getMarkerOrAcceptedAnnotation(sym, state);
} | [
"AnnotationInfo",
"getImmutableAnnotation",
"(",
"Tree",
"tree",
",",
"VisitorState",
"state",
")",
"{",
"Symbol",
"sym",
"=",
"ASTHelpers",
".",
"getSymbol",
"(",
"tree",
")",
";",
"return",
"sym",
"==",
"null",
"?",
"null",
":",
"threadSafety",
".",
"getMa... | Gets the {@link Tree}'s {@code @Immutable} annotation info, either from an annotation on the
symbol or from the list of well-known immutable types. | [
"Gets",
"the",
"{"
] | train | https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/core/src/main/java/com/google/errorprone/bugpatterns/threadsafety/ImmutableAnalysis.java#L330-L333 |
Azure/azure-sdk-for-java | containerregistry/resource-manager/v2018_02_01_preview/src/main/java/com/microsoft/azure/management/containerregistry/v2018_02_01_preview/implementation/RegistriesInner.java | RegistriesInner.queueBuild | public BuildInner queueBuild(String resourceGroupName, String registryName, QueueBuildRequest buildRequest) {
return queueBuildWithServiceResponseAsync(resourceGroupName, registryName, buildRequest).toBlocking().last().body();
} | java | public BuildInner queueBuild(String resourceGroupName, String registryName, QueueBuildRequest buildRequest) {
return queueBuildWithServiceResponseAsync(resourceGroupName, registryName, buildRequest).toBlocking().last().body();
} | [
"public",
"BuildInner",
"queueBuild",
"(",
"String",
"resourceGroupName",
",",
"String",
"registryName",
",",
"QueueBuildRequest",
"buildRequest",
")",
"{",
"return",
"queueBuildWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"registryName",
",",
"buildRequest",
... | Creates a new build based on the request parameters and add it to the build queue.
@param resourceGroupName The name of the resource group to which the container registry belongs.
@param registryName The name of the container registry.
@param buildRequest The parameters of a build that needs to queued.
@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 BuildInner object if successful. | [
"Creates",
"a",
"new",
"build",
"based",
"on",
"the",
"request",
"parameters",
"and",
"add",
"it",
"to",
"the",
"build",
"queue",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/containerregistry/resource-manager/v2018_02_01_preview/src/main/java/com/microsoft/azure/management/containerregistry/v2018_02_01_preview/implementation/RegistriesInner.java#L1727-L1729 |
wildfly/wildfly-core | controller/src/main/java/org/jboss/as/controller/AttributeMarshaller.java | AttributeMarshaller.isMarshallable | public boolean isMarshallable(final AttributeDefinition attribute, final ModelNode resourceModel, final boolean marshallDefault) {
return resourceModel.hasDefined(attribute.getName()) && (marshallDefault || !resourceModel.get(attribute.getName()).equals(attribute.getDefaultValue()));
} | java | public boolean isMarshallable(final AttributeDefinition attribute, final ModelNode resourceModel, final boolean marshallDefault) {
return resourceModel.hasDefined(attribute.getName()) && (marshallDefault || !resourceModel.get(attribute.getName()).equals(attribute.getDefaultValue()));
} | [
"public",
"boolean",
"isMarshallable",
"(",
"final",
"AttributeDefinition",
"attribute",
",",
"final",
"ModelNode",
"resourceModel",
",",
"final",
"boolean",
"marshallDefault",
")",
"{",
"return",
"resourceModel",
".",
"hasDefined",
"(",
"attribute",
".",
"getName",
... | Gets whether the given {@code resourceModel} has a value for this attribute that should be marshalled to XML.
@param attribute - attribute for which marshaling is being done
@param resourceModel the model, a non-null node of {@link org.jboss.dmr.ModelType#OBJECT}.
@param marshallDefault {@code true} if the value should be marshalled even if it matches the default value
@return {@code true} if the given {@code resourceModel} has a defined value under this attribute's {@link AttributeDefinition#getName()} () name}
and {@code marshallDefault} is {@code true} or that value differs from this attribute's {@link AttributeDefinition#getDefaultValue() default value}. | [
"Gets",
"whether",
"the",
"given",
"{",
"@code",
"resourceModel",
"}",
"has",
"a",
"value",
"for",
"this",
"attribute",
"that",
"should",
"be",
"marshalled",
"to",
"XML",
"."
] | train | https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/controller/src/main/java/org/jboss/as/controller/AttributeMarshaller.java#L63-L65 |
FXMisc/RichTextFX | richtextfx/src/main/java/org/fxmisc/richtext/MultiChangeBuilder.java | MultiChangeBuilder.replaceAbsolutely | public MultiChangeBuilder<PS, SEG, S> replaceAbsolutely(int start, int end, StyledDocument<PS, SEG, S> replacement) {
return absoluteReplace(start, end, ReadOnlyStyledDocument.from(replacement));
} | java | public MultiChangeBuilder<PS, SEG, S> replaceAbsolutely(int start, int end, StyledDocument<PS, SEG, S> replacement) {
return absoluteReplace(start, end, ReadOnlyStyledDocument.from(replacement));
} | [
"public",
"MultiChangeBuilder",
"<",
"PS",
",",
"SEG",
",",
"S",
">",
"replaceAbsolutely",
"(",
"int",
"start",
",",
"int",
"end",
",",
"StyledDocument",
"<",
"PS",
",",
"SEG",
",",
"S",
">",
"replacement",
")",
"{",
"return",
"absoluteReplace",
"(",
"st... | Replaces a range of characters with the given rich-text document. | [
"Replaces",
"a",
"range",
"of",
"characters",
"with",
"the",
"given",
"rich",
"-",
"text",
"document",
"."
] | train | https://github.com/FXMisc/RichTextFX/blob/bc7cab6a637855e0f37d9b9c12a9172c31545f0b/richtextfx/src/main/java/org/fxmisc/richtext/MultiChangeBuilder.java#L352-L354 |
apache/flink | flink-streaming-java/src/main/java/org/apache/flink/streaming/api/environment/StreamExecutionEnvironment.java | StreamExecutionEnvironment.addSource | public <OUT> DataStreamSource<OUT> addSource(SourceFunction<OUT> function, TypeInformation<OUT> typeInfo) {
return addSource(function, "Custom Source", typeInfo);
} | java | public <OUT> DataStreamSource<OUT> addSource(SourceFunction<OUT> function, TypeInformation<OUT> typeInfo) {
return addSource(function, "Custom Source", typeInfo);
} | [
"public",
"<",
"OUT",
">",
"DataStreamSource",
"<",
"OUT",
">",
"addSource",
"(",
"SourceFunction",
"<",
"OUT",
">",
"function",
",",
"TypeInformation",
"<",
"OUT",
">",
"typeInfo",
")",
"{",
"return",
"addSource",
"(",
"function",
",",
"\"Custom Source\"",
... | Ads a data source with a custom type information thus opening a
{@link DataStream}. Only in very special cases does the user need to
support type information. Otherwise use
{@link #addSource(org.apache.flink.streaming.api.functions.source.SourceFunction)}
@param function
the user defined function
@param <OUT>
type of the returned stream
@param typeInfo
the user defined type information for the stream
@return the data stream constructed | [
"Ads",
"a",
"data",
"source",
"with",
"a",
"custom",
"type",
"information",
"thus",
"opening",
"a",
"{",
"@link",
"DataStream",
"}",
".",
"Only",
"in",
"very",
"special",
"cases",
"does",
"the",
"user",
"need",
"to",
"support",
"type",
"information",
".",
... | train | https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-streaming-java/src/main/java/org/apache/flink/streaming/api/environment/StreamExecutionEnvironment.java#L1429-L1431 |
comapi/comapi-sdk-android | COMAPI/foundation/src/main/java/com/comapi/internal/network/InternalService.java | InternalService.queryEvents | public void queryEvents(@NonNull final String conversationId, @NonNull final Long from, @NonNull final Integer limit, @Nullable Callback<ComapiResult<EventsQueryResponse>> callback) {
adapter.adapt(queryEvents(conversationId, from, limit), callback);
} | java | public void queryEvents(@NonNull final String conversationId, @NonNull final Long from, @NonNull final Integer limit, @Nullable Callback<ComapiResult<EventsQueryResponse>> callback) {
adapter.adapt(queryEvents(conversationId, from, limit), callback);
} | [
"public",
"void",
"queryEvents",
"(",
"@",
"NonNull",
"final",
"String",
"conversationId",
",",
"@",
"NonNull",
"final",
"Long",
"from",
",",
"@",
"NonNull",
"final",
"Integer",
"limit",
",",
"@",
"Nullable",
"Callback",
"<",
"ComapiResult",
"<",
"EventsQueryR... | Query chanel events.
@param conversationId ID of a conversation to query events in it.
@param from ID of the event to start from.
@param limit Limit of events to obtain in this call.
@param callback Callback to deliver new session instance. | [
"Query",
"chanel",
"events",
"."
] | train | https://github.com/comapi/comapi-sdk-android/blob/53140a58d5a62afe196047ccc5120bfe090ef211/COMAPI/foundation/src/main/java/com/comapi/internal/network/InternalService.java#L857-L859 |
xiaolongzuo/niubi-job | niubi-job-framework/niubi-job-scheduler/src/main/java/com/zuoxiaolong/niubi/job/scheduler/JobEnvironmentCache.java | JobEnvironmentCache.loadJobEnvironment | public void loadJobEnvironment(String jarFilePath, String packagesToScan, boolean isSpring) throws Exception {
JobBeanFactory jobBeanFactory = jobBeanFactoryMap.get(jarFilePath);
if (jobBeanFactory != null) {
return;
}
synchronized (jobBeanFactoryMap) {
jobBeanFactory = jobBeanFactoryMap.get(jarFilePath);
if (jobBeanFactory != null) {
return;
}
jobBeanFactory = createJobBeanFactory(jarFilePath, isSpring);
jobBeanFactoryMap.put(jarFilePath, jobBeanFactory);
ClassLoader classLoader = ApplicationClassLoaderFactory.getJarApplicationClassLoader(jarFilePath);
JobScanner jobScanner = JobScannerFactory.createJarFileJobScanner(classLoader, packagesToScan, jarFilePath);
jobDescriptorListMap.put(jarFilePath, jobScanner.getJobDescriptorList());
}
} | java | public void loadJobEnvironment(String jarFilePath, String packagesToScan, boolean isSpring) throws Exception {
JobBeanFactory jobBeanFactory = jobBeanFactoryMap.get(jarFilePath);
if (jobBeanFactory != null) {
return;
}
synchronized (jobBeanFactoryMap) {
jobBeanFactory = jobBeanFactoryMap.get(jarFilePath);
if (jobBeanFactory != null) {
return;
}
jobBeanFactory = createJobBeanFactory(jarFilePath, isSpring);
jobBeanFactoryMap.put(jarFilePath, jobBeanFactory);
ClassLoader classLoader = ApplicationClassLoaderFactory.getJarApplicationClassLoader(jarFilePath);
JobScanner jobScanner = JobScannerFactory.createJarFileJobScanner(classLoader, packagesToScan, jarFilePath);
jobDescriptorListMap.put(jarFilePath, jobScanner.getJobDescriptorList());
}
} | [
"public",
"void",
"loadJobEnvironment",
"(",
"String",
"jarFilePath",
",",
"String",
"packagesToScan",
",",
"boolean",
"isSpring",
")",
"throws",
"Exception",
"{",
"JobBeanFactory",
"jobBeanFactory",
"=",
"jobBeanFactoryMap",
".",
"get",
"(",
"jarFilePath",
")",
";"... | 创建Job的运行时环境,加载相应的Jar包资源.
@param jarFilePath jar包本地路径
@param packagesToScan 需要扫描的包
@param isSpring 是否spring环境
@throws Exception 当出现未检查的异常时抛出 | [
"创建Job的运行时环境",
"加载相应的Jar包资源",
"."
] | train | https://github.com/xiaolongzuo/niubi-job/blob/ed21d5b80f8b16c8b3a0b2fbc688442b878edbe4/niubi-job-framework/niubi-job-scheduler/src/main/java/com/zuoxiaolong/niubi/job/scheduler/JobEnvironmentCache.java#L106-L122 |
m-m-m/util | reflect/src/main/java/net/sf/mmm/util/reflect/base/ReflectionUtilImpl.java | ReflectionUtilImpl.findClassNames | protected void findClassNames(String packageName, boolean includeSubPackages, Set<String> classSet, Filter<? super String> filter, ClassLoader classLoader) {
ResourceVisitor visitor = new ClassNameCollector(classSet, filter);
visitResourceNames(packageName, includeSubPackages, classLoader, visitor);
} | java | protected void findClassNames(String packageName, boolean includeSubPackages, Set<String> classSet, Filter<? super String> filter, ClassLoader classLoader) {
ResourceVisitor visitor = new ClassNameCollector(classSet, filter);
visitResourceNames(packageName, includeSubPackages, classLoader, visitor);
} | [
"protected",
"void",
"findClassNames",
"(",
"String",
"packageName",
",",
"boolean",
"includeSubPackages",
",",
"Set",
"<",
"String",
">",
"classSet",
",",
"Filter",
"<",
"?",
"super",
"String",
">",
"filter",
",",
"ClassLoader",
"classLoader",
")",
"{",
"Reso... | @see #findClassNames(String, boolean, Filter, ClassLoader)
@param packageName is the name of the {@link Package} to scan.
@param includeSubPackages - if {@code true} all sub-packages of the specified {@link Package} will be included in
the search.
@param classSet is where to add the classes.
@param filter is used to {@link Filter#accept(Object) filter} the {@link Class}-names to be added to the resulting
{@link Set}. The {@link Filter} will receive {@link Class#getName() fully qualified class-names} as argument
(e.g. "net.sf.mmm.reflect.api.ReflectionUtil").
@param classLoader is the explicit {@link ClassLoader} to use.
@if the operation failed with an I/O error. | [
"@see",
"#findClassNames",
"(",
"String",
"boolean",
"Filter",
"ClassLoader",
")"
] | train | https://github.com/m-m-m/util/blob/f0e4e084448f8dfc83ca682a9e1618034a094ce6/reflect/src/main/java/net/sf/mmm/util/reflect/base/ReflectionUtilImpl.java#L699-L703 |
alkacon/opencms-core | src/org/opencms/gwt/shared/property/CmsClientProperty.java | CmsClientProperty.getPathValue | public CmsPathValue getPathValue(Mode mode) {
switch (mode) {
case resource:
return new CmsPathValue(m_resourceValue, PATH_RESOURCE_VALUE);
case structure:
return new CmsPathValue(m_structureValue, PATH_STRUCTURE_VALUE);
case effective:
default:
return getPathValue();
}
} | java | public CmsPathValue getPathValue(Mode mode) {
switch (mode) {
case resource:
return new CmsPathValue(m_resourceValue, PATH_RESOURCE_VALUE);
case structure:
return new CmsPathValue(m_structureValue, PATH_STRUCTURE_VALUE);
case effective:
default:
return getPathValue();
}
} | [
"public",
"CmsPathValue",
"getPathValue",
"(",
"Mode",
"mode",
")",
"{",
"switch",
"(",
"mode",
")",
"{",
"case",
"resource",
":",
"return",
"new",
"CmsPathValue",
"(",
"m_resourceValue",
",",
"PATH_RESOURCE_VALUE",
")",
";",
"case",
"structure",
":",
"return"... | Gets the path value for a specific access mode.<p>
@param mode the access mode
@return the path value for the access mode | [
"Gets",
"the",
"path",
"value",
"for",
"a",
"specific",
"access",
"mode",
".",
"<p",
">",
"@param",
"mode",
"the",
"access",
"mode"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/gwt/shared/property/CmsClientProperty.java#L304-L315 |
Azure/azure-sdk-for-java | sql/resource-manager/v2014_04_01/src/main/java/com/microsoft/azure/management/sql/v2014_04_01/implementation/DataMaskingPoliciesInner.java | DataMaskingPoliciesInner.createOrUpdate | public DataMaskingPolicyInner createOrUpdate(String resourceGroupName, String serverName, String databaseName, DataMaskingPolicyInner parameters) {
return createOrUpdateWithServiceResponseAsync(resourceGroupName, serverName, databaseName, parameters).toBlocking().single().body();
} | java | public DataMaskingPolicyInner createOrUpdate(String resourceGroupName, String serverName, String databaseName, DataMaskingPolicyInner parameters) {
return createOrUpdateWithServiceResponseAsync(resourceGroupName, serverName, databaseName, parameters).toBlocking().single().body();
} | [
"public",
"DataMaskingPolicyInner",
"createOrUpdate",
"(",
"String",
"resourceGroupName",
",",
"String",
"serverName",
",",
"String",
"databaseName",
",",
"DataMaskingPolicyInner",
"parameters",
")",
"{",
"return",
"createOrUpdateWithServiceResponseAsync",
"(",
"resourceGroup... | Creates or updates a database data masking policy.
@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.
@param parameters Parameters for creating or updating a data masking policy.
@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 DataMaskingPolicyInner object if successful. | [
"Creates",
"or",
"updates",
"a",
"database",
"data",
"masking",
"policy",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/sql/resource-manager/v2014_04_01/src/main/java/com/microsoft/azure/management/sql/v2014_04_01/implementation/DataMaskingPoliciesInner.java#L79-L81 |
VoltDB/voltdb | third_party/java/src/org/HdrHistogram_voltpatches/DoubleHistogram.java | DoubleHistogram.decodeFromCompressedByteBuffer | public static DoubleHistogram decodeFromCompressedByteBuffer(
final ByteBuffer buffer,
final long minBarForHighestToLowestValueRatio) throws DataFormatException {
return decodeFromCompressedByteBuffer(buffer, Histogram.class, minBarForHighestToLowestValueRatio);
} | java | public static DoubleHistogram decodeFromCompressedByteBuffer(
final ByteBuffer buffer,
final long minBarForHighestToLowestValueRatio) throws DataFormatException {
return decodeFromCompressedByteBuffer(buffer, Histogram.class, minBarForHighestToLowestValueRatio);
} | [
"public",
"static",
"DoubleHistogram",
"decodeFromCompressedByteBuffer",
"(",
"final",
"ByteBuffer",
"buffer",
",",
"final",
"long",
"minBarForHighestToLowestValueRatio",
")",
"throws",
"DataFormatException",
"{",
"return",
"decodeFromCompressedByteBuffer",
"(",
"buffer",
","... | Construct a new DoubleHistogram by decoding it from a compressed form in a ByteBuffer.
@param buffer The buffer to decode from
@param minBarForHighestToLowestValueRatio Force highestTrackableValue to be set at least this high
@return The newly constructed DoubleHistogram
@throws DataFormatException on error parsing/decompressing the buffer | [
"Construct",
"a",
"new",
"DoubleHistogram",
"by",
"decoding",
"it",
"from",
"a",
"compressed",
"form",
"in",
"a",
"ByteBuffer",
"."
] | train | https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/third_party/java/src/org/HdrHistogram_voltpatches/DoubleHistogram.java#L1529-L1533 |
alkacon/opencms-core | src/org/opencms/main/CmsSingleThreadDumperThread.java | CmsSingleThreadDumperThread.saveSummaryXml | private void saveSummaryXml(SampleNode root) {
root.sortTree();
Document doc = DocumentHelper.createDocument();
Element rootElem = doc.addElement("root");
root.appendToXml(rootElem);
OutputFormat outformat = OutputFormat.createPrettyPrint();
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
outformat.setEncoding("UTF-8");
try {
XMLWriter writer = new XMLWriter(buffer, outformat);
writer.write(doc);
writer.flush();
try (FileOutputStream fos = new FileOutputStream(m_summaryFilename)) {
fos.write(buffer.toByteArray());
}
} catch (Exception e) {
e.printStackTrace();
}
} | java | private void saveSummaryXml(SampleNode root) {
root.sortTree();
Document doc = DocumentHelper.createDocument();
Element rootElem = doc.addElement("root");
root.appendToXml(rootElem);
OutputFormat outformat = OutputFormat.createPrettyPrint();
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
outformat.setEncoding("UTF-8");
try {
XMLWriter writer = new XMLWriter(buffer, outformat);
writer.write(doc);
writer.flush();
try (FileOutputStream fos = new FileOutputStream(m_summaryFilename)) {
fos.write(buffer.toByteArray());
}
} catch (Exception e) {
e.printStackTrace();
}
} | [
"private",
"void",
"saveSummaryXml",
"(",
"SampleNode",
"root",
")",
"{",
"root",
".",
"sortTree",
"(",
")",
";",
"Document",
"doc",
"=",
"DocumentHelper",
".",
"createDocument",
"(",
")",
";",
"Element",
"rootElem",
"=",
"doc",
".",
"addElement",
"(",
"\"... | Saves the stack trace summary tree starting from the given root node to an XML file.<p>
@param root the root node | [
"Saves",
"the",
"stack",
"trace",
"summary",
"tree",
"starting",
"from",
"the",
"given",
"root",
"node",
"to",
"an",
"XML",
"file",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/main/CmsSingleThreadDumperThread.java#L356-L375 |
google/closure-compiler | src/com/google/javascript/jscomp/SymbolTable.java | SymbolTable.mergeSymbol | private void mergeSymbol(Symbol from, Symbol to) {
for (Node nodeToMove : from.references.keySet()) {
if (!nodeToMove.equals(from.getDeclarationNode())) {
to.defineReferenceAt(nodeToMove);
}
}
removeSymbol(from);
} | java | private void mergeSymbol(Symbol from, Symbol to) {
for (Node nodeToMove : from.references.keySet()) {
if (!nodeToMove.equals(from.getDeclarationNode())) {
to.defineReferenceAt(nodeToMove);
}
}
removeSymbol(from);
} | [
"private",
"void",
"mergeSymbol",
"(",
"Symbol",
"from",
",",
"Symbol",
"to",
")",
"{",
"for",
"(",
"Node",
"nodeToMove",
":",
"from",
".",
"references",
".",
"keySet",
"(",
")",
")",
"{",
"if",
"(",
"!",
"nodeToMove",
".",
"equals",
"(",
"from",
"."... | Merges 'from' symbol to 'to' symbol by moving all references to point to the 'to' symbol and
removing 'from' symbol. | [
"Merges",
"from",
"symbol",
"to",
"to",
"symbol",
"by",
"moving",
"all",
"references",
"to",
"point",
"to",
"the",
"to",
"symbol",
"and",
"removing",
"from",
"symbol",
"."
] | train | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/SymbolTable.java#L653-L660 |
google/closure-compiler | src/com/google/javascript/jscomp/ClosureCodingConvention.java | ClosureCodingConvention.extractClassNameIfProvide | @Override
public String extractClassNameIfProvide(Node node, Node parent) {
String namespace = extractClassNameIfGoog(node, parent, "goog.provide");
if (namespace == null) {
namespace = extractClassNameIfGoog(node, parent, "goog.module");
}
return namespace;
} | java | @Override
public String extractClassNameIfProvide(Node node, Node parent) {
String namespace = extractClassNameIfGoog(node, parent, "goog.provide");
if (namespace == null) {
namespace = extractClassNameIfGoog(node, parent, "goog.module");
}
return namespace;
} | [
"@",
"Override",
"public",
"String",
"extractClassNameIfProvide",
"(",
"Node",
"node",
",",
"Node",
"parent",
")",
"{",
"String",
"namespace",
"=",
"extractClassNameIfGoog",
"(",
"node",
",",
"parent",
",",
"\"goog.provide\"",
")",
";",
"if",
"(",
"namespace",
... | Extracts X from goog.provide('X'), if the applied Node is goog.
@return The extracted class name, or null. | [
"Extracts",
"X",
"from",
"goog",
".",
"provide",
"(",
"X",
")",
"if",
"the",
"applied",
"Node",
"is",
"goog",
"."
] | train | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/ClosureCodingConvention.java#L211-L218 |
TheHortonMachine/hortonmachine | gears/src/main/java/org/hortonmachine/gears/utils/optimizers/particleswarm/PSEngine.java | PSEngine.parametersInRange | public static boolean parametersInRange( double[] parameters, double[]... ranges ) {
for( int i = 0; i < ranges.length; i++ ) {
if (!NumericsUtilities.isBetween(parameters[i], ranges[i])) {
return false;
}
}
return true;
} | java | public static boolean parametersInRange( double[] parameters, double[]... ranges ) {
for( int i = 0; i < ranges.length; i++ ) {
if (!NumericsUtilities.isBetween(parameters[i], ranges[i])) {
return false;
}
}
return true;
} | [
"public",
"static",
"boolean",
"parametersInRange",
"(",
"double",
"[",
"]",
"parameters",
",",
"double",
"[",
"]",
"...",
"ranges",
")",
"{",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"ranges",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",... | Checks if the parameters are in the ranges.
@param parameters the params.
@param ranges the ranges.
@return <code>true</code>, if they are inside the given ranges. | [
"Checks",
"if",
"the",
"parameters",
"are",
"in",
"the",
"ranges",
"."
] | train | https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/org/hortonmachine/gears/utils/optimizers/particleswarm/PSEngine.java#L211-L218 |
deeplearning4j/deeplearning4j | deeplearning4j/deeplearning4j-common/src/main/java/org/deeplearning4j/common/resources/DL4JResources.java | DL4JResources.getDirectory | public static File getDirectory(ResourceType resourceType, String resourceName){
File f = new File(baseDirectory, resourceType.resourceName());
f = new File(f, resourceName);
f.mkdirs();
return f;
} | java | public static File getDirectory(ResourceType resourceType, String resourceName){
File f = new File(baseDirectory, resourceType.resourceName());
f = new File(f, resourceName);
f.mkdirs();
return f;
} | [
"public",
"static",
"File",
"getDirectory",
"(",
"ResourceType",
"resourceType",
",",
"String",
"resourceName",
")",
"{",
"File",
"f",
"=",
"new",
"File",
"(",
"baseDirectory",
",",
"resourceType",
".",
"resourceName",
"(",
")",
")",
";",
"f",
"=",
"new",
... | Get the storage location for the specified resource type and resource name
@param resourceType Type of resource
@param resourceName Name of the resource
@return The root directory. Creates the directory and any parent directories, if required | [
"Get",
"the",
"storage",
"location",
"for",
"the",
"specified",
"resource",
"type",
"and",
"resource",
"name"
] | train | https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/deeplearning4j/deeplearning4j-common/src/main/java/org/deeplearning4j/common/resources/DL4JResources.java#L148-L153 |
zaproxy/zaproxy | src/org/zaproxy/zap/extension/httpsessions/ExtensionHttpSessions.java | ExtensionHttpSessions.markRemovedDefaultSessionToken | private void markRemovedDefaultSessionToken(String site, String token) {
if (removedDefaultTokens == null)
removedDefaultTokens = new HashMap<>(1);
HashSet<String> removedSet = removedDefaultTokens.get(site);
if (removedSet == null) {
removedSet = new HashSet<>(1);
removedDefaultTokens.put(site, removedSet);
}
removedSet.add(token);
} | java | private void markRemovedDefaultSessionToken(String site, String token) {
if (removedDefaultTokens == null)
removedDefaultTokens = new HashMap<>(1);
HashSet<String> removedSet = removedDefaultTokens.get(site);
if (removedSet == null) {
removedSet = new HashSet<>(1);
removedDefaultTokens.put(site, removedSet);
}
removedSet.add(token);
} | [
"private",
"void",
"markRemovedDefaultSessionToken",
"(",
"String",
"site",
",",
"String",
"token",
")",
"{",
"if",
"(",
"removedDefaultTokens",
"==",
"null",
")",
"removedDefaultTokens",
"=",
"new",
"HashMap",
"<>",
"(",
"1",
")",
";",
"HashSet",
"<",
"String... | Marks a default session token as removed for a particular site.
@param site the site. This parameter has to be formed as defined in the
{@link ExtensionHttpSessions} class documentation.
@param token the token | [
"Marks",
"a",
"default",
"session",
"token",
"as",
"removed",
"for",
"a",
"particular",
"site",
"."
] | train | https://github.com/zaproxy/zaproxy/blob/0cbe5121f2ae1ecca222513d182759210c569bec/src/org/zaproxy/zap/extension/httpsessions/ExtensionHttpSessions.java#L325-L334 |
contentful/contentful-management.java | src/main/java/com/contentful/java/cma/ModuleEntries.java | ModuleEntries.fetchOne | public CMAEntry fetchOne(String spaceId, String environmentId, String entryId) {
assertNotNull(spaceId, "spaceId");
assertNotNull(environmentId, "environmentId");
assertNotNull(entryId, "entryId");
return service.fetchOne(spaceId, environmentId, entryId).blockingFirst();
} | java | public CMAEntry fetchOne(String spaceId, String environmentId, String entryId) {
assertNotNull(spaceId, "spaceId");
assertNotNull(environmentId, "environmentId");
assertNotNull(entryId, "entryId");
return service.fetchOne(spaceId, environmentId, entryId).blockingFirst();
} | [
"public",
"CMAEntry",
"fetchOne",
"(",
"String",
"spaceId",
",",
"String",
"environmentId",
",",
"String",
"entryId",
")",
"{",
"assertNotNull",
"(",
"spaceId",
",",
"\"spaceId\"",
")",
";",
"assertNotNull",
"(",
"environmentId",
",",
"\"environmentId\"",
")",
"... | Fetch an entry with the given entryId from the given environment and space.
@param spaceId Space ID
@param environmentId Environment ID
@param entryId Entry ID
@return {@link CMAEntry} result instance
@throws IllegalArgumentException if space id is null.
@throws IllegalArgumentException if environment id is null.
@throws IllegalArgumentException if entry id is null. | [
"Fetch",
"an",
"entry",
"with",
"the",
"given",
"entryId",
"from",
"the",
"given",
"environment",
"and",
"space",
"."
] | train | https://github.com/contentful/contentful-management.java/blob/ca310fb9ea9577fcff0ca57949ab7c2315fa2534/src/main/java/com/contentful/java/cma/ModuleEntries.java#L266-L271 |
kkopacz/agiso-tempel | templates/abstract-directoryExtenderEngine/src/main/java/org/agiso/tempel/engine/DirectoryExtenderEngine.java | DirectoryExtenderEngine.processVelocityResource | protected void processVelocityResource(ITemplateSource source, Map<String, Object> params, String target) throws Exception {
for(ITemplateSourceEntry entry : source.listEntries()) {
//System.out.println("Wykryto zasób: " + entry.getName());
if(entry.isFile()) {
// System.out.println("Element " + entry.getTemplate() + "/" + source.getResource() +
// "/"+ entry.getName() + " jest plikiem");
processVelocityFile(entry, source.getResource(), params, target);
}
}
} | java | protected void processVelocityResource(ITemplateSource source, Map<String, Object> params, String target) throws Exception {
for(ITemplateSourceEntry entry : source.listEntries()) {
//System.out.println("Wykryto zasób: " + entry.getName());
if(entry.isFile()) {
// System.out.println("Element " + entry.getTemplate() + "/" + source.getResource() +
// "/"+ entry.getName() + " jest plikiem");
processVelocityFile(entry, source.getResource(), params, target);
}
}
} | [
"protected",
"void",
"processVelocityResource",
"(",
"ITemplateSource",
"source",
",",
"Map",
"<",
"String",
",",
"Object",
">",
"params",
",",
"String",
"target",
")",
"throws",
"Exception",
"{",
"for",
"(",
"ITemplateSourceEntry",
"entry",
":",
"source",
".",
... | Szablon może być pojedynczym katalogiem. W takiej sytuacji przetwarzane
są wszsytkie jego wpisy. | [
"Szablon",
"może",
"być",
"pojedynczym",
"katalogiem",
".",
"W",
"takiej",
"sytuacji",
"przetwarzane",
"są",
"wszsytkie",
"jego",
"wpisy",
"."
] | train | https://github.com/kkopacz/agiso-tempel/blob/ff7a96153153b6bc07212d776816b87d9538f6fa/templates/abstract-directoryExtenderEngine/src/main/java/org/agiso/tempel/engine/DirectoryExtenderEngine.java#L83-L94 |
google/j2objc | jre_emul/android/platform/libcore/luni/src/main/java/libcore/io/Streams.java | Streams.writeSingleByte | public static void writeSingleByte(OutputStream out, int b) throws IOException {
byte[] buffer = new byte[1];
buffer[0] = (byte) (b & 0xff);
out.write(buffer);
} | java | public static void writeSingleByte(OutputStream out, int b) throws IOException {
byte[] buffer = new byte[1];
buffer[0] = (byte) (b & 0xff);
out.write(buffer);
} | [
"public",
"static",
"void",
"writeSingleByte",
"(",
"OutputStream",
"out",
",",
"int",
"b",
")",
"throws",
"IOException",
"{",
"byte",
"[",
"]",
"buffer",
"=",
"new",
"byte",
"[",
"1",
"]",
";",
"buffer",
"[",
"0",
"]",
"=",
"(",
"byte",
")",
"(",
... | Implements OutputStream.write(int) in terms of OutputStream.write(byte[], int, int).
OutputStream assumes that you implement OutputStream.write(int) and provides default
implementations of the others, but often the opposite is more efficient. | [
"Implements",
"OutputStream",
".",
"write",
"(",
"int",
")",
"in",
"terms",
"of",
"OutputStream",
".",
"write",
"(",
"byte",
"[]",
"int",
"int",
")",
".",
"OutputStream",
"assumes",
"that",
"you",
"implement",
"OutputStream",
".",
"write",
"(",
"int",
")",... | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/luni/src/main/java/libcore/io/Streams.java#L50-L54 |
steveohara/j2mod | src/main/java/com/ghgande/j2mod/modbus/msg/ReadWriteMultipleRequest.java | ReadWriteMultipleRequest.readData | public void readData(DataInput input) throws IOException {
readReference = input.readUnsignedShort();
readCount = input.readUnsignedShort();
writeReference = input.readUnsignedShort();
writeCount = input.readUnsignedShort();
int byteCount = input.readUnsignedByte();
if (nonWordDataHandler == null) {
byte buffer[] = new byte[byteCount];
input.readFully(buffer, 0, byteCount);
int offset = 0;
registers = new Register[writeCount];
for (int register = 0; register < writeCount; register++) {
registers[register] = new SimpleRegister(buffer[offset], buffer[offset + 1]);
offset += 2;
}
}
else {
nonWordDataHandler.readData(input, writeReference, writeCount);
}
} | java | public void readData(DataInput input) throws IOException {
readReference = input.readUnsignedShort();
readCount = input.readUnsignedShort();
writeReference = input.readUnsignedShort();
writeCount = input.readUnsignedShort();
int byteCount = input.readUnsignedByte();
if (nonWordDataHandler == null) {
byte buffer[] = new byte[byteCount];
input.readFully(buffer, 0, byteCount);
int offset = 0;
registers = new Register[writeCount];
for (int register = 0; register < writeCount; register++) {
registers[register] = new SimpleRegister(buffer[offset], buffer[offset + 1]);
offset += 2;
}
}
else {
nonWordDataHandler.readData(input, writeReference, writeCount);
}
} | [
"public",
"void",
"readData",
"(",
"DataInput",
"input",
")",
"throws",
"IOException",
"{",
"readReference",
"=",
"input",
".",
"readUnsignedShort",
"(",
")",
";",
"readCount",
"=",
"input",
".",
"readUnsignedShort",
"(",
")",
";",
"writeReference",
"=",
"inpu... | readData -- read the values of the registers to be written, along with
the reference and count for the registers to be read. | [
"readData",
"--",
"read",
"the",
"values",
"of",
"the",
"registers",
"to",
"be",
"written",
"along",
"with",
"the",
"reference",
"and",
"count",
"for",
"the",
"registers",
"to",
"be",
"read",
"."
] | train | https://github.com/steveohara/j2mod/blob/67162c55d7c02564e50211a9df06b8314953b5f2/src/main/java/com/ghgande/j2mod/modbus/msg/ReadWriteMultipleRequest.java#L321-L343 |
alkacon/opencms-core | src/org/opencms/jsp/util/CmsJspImageBean.java | CmsJspImageBean.setResource | protected void setResource(CmsObject cms, CmsResource resource) {
m_resource = CmsJspResourceWrapper.wrap(cms, resource);
} | java | protected void setResource(CmsObject cms, CmsResource resource) {
m_resource = CmsJspResourceWrapper.wrap(cms, resource);
} | [
"protected",
"void",
"setResource",
"(",
"CmsObject",
"cms",
",",
"CmsResource",
"resource",
")",
"{",
"m_resource",
"=",
"CmsJspResourceWrapper",
".",
"wrap",
"(",
"cms",
",",
"resource",
")",
";",
"}"
] | Sets the CmsResource for this image.<p>
@param cms the current OpenCms user context, required for wrapping the resource
@param resource the VFS resource for this image | [
"Sets",
"the",
"CmsResource",
"for",
"this",
"image",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/jsp/util/CmsJspImageBean.java#L1097-L1100 |
apereo/cas | core/cas-server-core-util-api/src/main/java/org/apereo/cas/util/scripting/ScriptingUtils.java | ScriptingUtils.executeScriptEngine | public static <T> T executeScriptEngine(final String scriptFile, final Object[] args, final Class<T> clazz) {
try {
val engineName = getScriptEngineName(scriptFile);
val engine = new ScriptEngineManager().getEngineByName(engineName);
if (engine == null || StringUtils.isBlank(engineName)) {
LOGGER.warn("Script engine is not available for [{}]", engineName);
return null;
}
val resourceFrom = ResourceUtils.getResourceFrom(scriptFile);
val theScriptFile = resourceFrom.getFile();
if (theScriptFile.exists()) {
LOGGER.debug("Created object instance from class [{}]", theScriptFile.getCanonicalPath());
try (val reader = Files.newBufferedReader(theScriptFile.toPath(), StandardCharsets.UTF_8)) {
engine.eval(reader);
}
val invocable = (Invocable) engine;
LOGGER.debug("Executing script's run method, with parameters [{}]", args);
val result = invocable.invokeFunction("run", args);
LOGGER.debug("Groovy script result is [{}]", result);
return getGroovyScriptExecutionResultOrThrow(clazz, result);
}
LOGGER.warn("[{}] script [{}] does not exist, or cannot be loaded", StringUtils.capitalize(engineName), scriptFile);
} catch (final Exception e) {
LOGGER.error(e.getMessage(), e);
}
return null;
} | java | public static <T> T executeScriptEngine(final String scriptFile, final Object[] args, final Class<T> clazz) {
try {
val engineName = getScriptEngineName(scriptFile);
val engine = new ScriptEngineManager().getEngineByName(engineName);
if (engine == null || StringUtils.isBlank(engineName)) {
LOGGER.warn("Script engine is not available for [{}]", engineName);
return null;
}
val resourceFrom = ResourceUtils.getResourceFrom(scriptFile);
val theScriptFile = resourceFrom.getFile();
if (theScriptFile.exists()) {
LOGGER.debug("Created object instance from class [{}]", theScriptFile.getCanonicalPath());
try (val reader = Files.newBufferedReader(theScriptFile.toPath(), StandardCharsets.UTF_8)) {
engine.eval(reader);
}
val invocable = (Invocable) engine;
LOGGER.debug("Executing script's run method, with parameters [{}]", args);
val result = invocable.invokeFunction("run", args);
LOGGER.debug("Groovy script result is [{}]", result);
return getGroovyScriptExecutionResultOrThrow(clazz, result);
}
LOGGER.warn("[{}] script [{}] does not exist, or cannot be loaded", StringUtils.capitalize(engineName), scriptFile);
} catch (final Exception e) {
LOGGER.error(e.getMessage(), e);
}
return null;
} | [
"public",
"static",
"<",
"T",
">",
"T",
"executeScriptEngine",
"(",
"final",
"String",
"scriptFile",
",",
"final",
"Object",
"[",
"]",
"args",
",",
"final",
"Class",
"<",
"T",
">",
"clazz",
")",
"{",
"try",
"{",
"val",
"engineName",
"=",
"getScriptEngine... | Execute groovy script engine t.
@param <T> the type parameter
@param scriptFile the script file
@param args the args
@param clazz the clazz
@return the t | [
"Execute",
"groovy",
"script",
"engine",
"t",
"."
] | train | https://github.com/apereo/cas/blob/b4b306433a8782cef803a39bea5b1f96740e0e9b/core/cas-server-core-util-api/src/main/java/org/apereo/cas/util/scripting/ScriptingUtils.java#L337-L365 |
wisdom-framework/wisdom | framework/ehcache-cache-service/src/main/java/org/wisdom/cache/ehcache/CachedActionInterceptor.java | CachedActionInterceptor.call | @Override
public Result call(Cached configuration, RequestContext context) throws Exception {
// Can we use the Cached version ?
boolean nocache =
HeaderNames.NOCACHE_VALUE.equalsIgnoreCase(context.context().header(HeaderNames.CACHE_CONTROL));
String key;
if (Strings.isNullOrEmpty(configuration.key())) {
key = context.request().uri();
} else {
key = configuration.key();
}
Result result = null;
if (!nocache) {
result = (Result) cache.get(key);
}
if (result == null) {
result = context.proceed();
} else {
LOGGER.info("Returning cached result for {} (key:{})",
context.request().uri(), key);
return result;
}
Duration duration;
if (configuration.duration() == 0) {
// Eternity == 1 year.
duration = Duration.standardDays(365);
} else {
duration = Duration.standardSeconds(configuration.duration());
}
cache.set(key, result, duration);
LoggerFactory.getLogger(this.getClass()).info("Caching result of {} for {} seconds (key:{})",
context.request().uri(), configuration.duration(), key);
return result;
} | java | @Override
public Result call(Cached configuration, RequestContext context) throws Exception {
// Can we use the Cached version ?
boolean nocache =
HeaderNames.NOCACHE_VALUE.equalsIgnoreCase(context.context().header(HeaderNames.CACHE_CONTROL));
String key;
if (Strings.isNullOrEmpty(configuration.key())) {
key = context.request().uri();
} else {
key = configuration.key();
}
Result result = null;
if (!nocache) {
result = (Result) cache.get(key);
}
if (result == null) {
result = context.proceed();
} else {
LOGGER.info("Returning cached result for {} (key:{})",
context.request().uri(), key);
return result;
}
Duration duration;
if (configuration.duration() == 0) {
// Eternity == 1 year.
duration = Duration.standardDays(365);
} else {
duration = Duration.standardSeconds(configuration.duration());
}
cache.set(key, result, duration);
LoggerFactory.getLogger(this.getClass()).info("Caching result of {} for {} seconds (key:{})",
context.request().uri(), configuration.duration(), key);
return result;
} | [
"@",
"Override",
"public",
"Result",
"call",
"(",
"Cached",
"configuration",
",",
"RequestContext",
"context",
")",
"throws",
"Exception",
"{",
"// Can we use the Cached version ?",
"boolean",
"nocache",
"=",
"HeaderNames",
".",
"NOCACHE_VALUE",
".",
"equalsIgnoreCase",... | Intercepts a @Cached action method.
If the result of the action is cached, returned it immediately without having actually invoked the action method.
In this case, the interception chain is cut.
<p>
If the result is not yet cached, the interception chain continues, and the result is cached to be used during
the next invocation.
@param configuration the interception configuration
@param context the interception context
@return the result.
@throws Exception something bad happened | [
"Intercepts",
"a",
"@Cached",
"action",
"method",
".",
"If",
"the",
"result",
"of",
"the",
"action",
"is",
"cached",
"returned",
"it",
"immediately",
"without",
"having",
"actually",
"invoked",
"the",
"action",
"method",
".",
"In",
"this",
"case",
"the",
"in... | train | https://github.com/wisdom-framework/wisdom/blob/a35b6431200fec56b178c0ff60837ed73fd7874d/framework/ehcache-cache-service/src/main/java/org/wisdom/cache/ehcache/CachedActionInterceptor.java#L64-L104 |
iig-uni-freiburg/SEWOL | src/de/uni/freiburg/iig/telematik/sewol/context/constraint/ConstraintContextProperties.java | ConstraintContextProperties.getConstraintNameIndexes | private Set<Integer> getConstraintNameIndexes() throws PropertyException{
Set<Integer> result = new HashSet<>();
Set<String> constraintNames = getConstraintNameList();
if(constraintNames.isEmpty())
return result;
for(String constraintName: constraintNames){
int separatorIndex = constraintName.lastIndexOf("_");
if(separatorIndex == -1 || (constraintName.length() == separatorIndex + 1))
throw new PropertyException(ConstraintContextProperty.CONSTRAINT, constraintName, "Corrupted property file (invalid constraint name)");
Integer index = null;
try {
index = Integer.parseInt(constraintName.substring(separatorIndex+1));
} catch(Exception e){
throw new PropertyException(ConstraintContextProperty.CONSTRAINT, constraintName, "Corrupted property file (invalid constraint name)");
}
result.add(index);
}
return result;
} | java | private Set<Integer> getConstraintNameIndexes() throws PropertyException{
Set<Integer> result = new HashSet<>();
Set<String> constraintNames = getConstraintNameList();
if(constraintNames.isEmpty())
return result;
for(String constraintName: constraintNames){
int separatorIndex = constraintName.lastIndexOf("_");
if(separatorIndex == -1 || (constraintName.length() == separatorIndex + 1))
throw new PropertyException(ConstraintContextProperty.CONSTRAINT, constraintName, "Corrupted property file (invalid constraint name)");
Integer index = null;
try {
index = Integer.parseInt(constraintName.substring(separatorIndex+1));
} catch(Exception e){
throw new PropertyException(ConstraintContextProperty.CONSTRAINT, constraintName, "Corrupted property file (invalid constraint name)");
}
result.add(index);
}
return result;
} | [
"private",
"Set",
"<",
"Integer",
">",
"getConstraintNameIndexes",
"(",
")",
"throws",
"PropertyException",
"{",
"Set",
"<",
"Integer",
">",
"result",
"=",
"new",
"HashSet",
"<>",
"(",
")",
";",
"Set",
"<",
"String",
">",
"constraintNames",
"=",
"getConstrai... | Returns all used indexes for constraint property names.<br>
Constraint names are enumerated (CONSTRAINT_1, CONSTRAINT_2, ...).<br>
When new constraints are added, the lowest unused index is used within the new property name.
@return The set of indexes in use.
@throws PropertyException if existing constraint names are invalid (e.g. due to external file manipulation). | [
"Returns",
"all",
"used",
"indexes",
"for",
"constraint",
"property",
"names",
".",
"<br",
">",
"Constraint",
"names",
"are",
"enumerated",
"(",
"CONSTRAINT_1",
"CONSTRAINT_2",
"...",
")",
".",
"<br",
">",
"When",
"new",
"constraints",
"are",
"added",
"the",
... | train | https://github.com/iig-uni-freiburg/SEWOL/blob/e791cb07a6e62ecf837d760d58a25f32fbf6bbca/src/de/uni/freiburg/iig/telematik/sewol/context/constraint/ConstraintContextProperties.java#L153-L171 |
svenkubiak/mangooio | mangooio-core/src/main/java/io/mangoo/routing/bindings/Validator.java | Validator.validateFalse | public void validateFalse(boolean value, String name) {
validateFalse(value, name, messages.get(Validation.FALSE_KEY.name(), name));
} | java | public void validateFalse(boolean value, String name) {
validateFalse(value, name, messages.get(Validation.FALSE_KEY.name(), name));
} | [
"public",
"void",
"validateFalse",
"(",
"boolean",
"value",
",",
"String",
"name",
")",
"{",
"validateFalse",
"(",
"value",
",",
"name",
",",
"messages",
".",
"get",
"(",
"Validation",
".",
"FALSE_KEY",
".",
"name",
"(",
")",
",",
"name",
")",
")",
";"... | Validates a given value to be false
@param value The value to check
@param name The name of the field to display the error message | [
"Validates",
"a",
"given",
"value",
"to",
"be",
"false"
] | train | https://github.com/svenkubiak/mangooio/blob/b3beb6d09510dbbab0ed947d5069c463e1fda6e7/mangooio-core/src/main/java/io/mangoo/routing/bindings/Validator.java#L465-L467 |
Waikato/moa | moa/src/main/java/moa/clusterers/kmeanspm/ClusteringFeature.java | ClusteringFeature.calcKMeansCosts | public double calcKMeansCosts(double[] center, ClusteringFeature points) {
assert (this.sumPoints.length == center.length &&
this.sumPoints.length == points.sumPoints.length);
return (this.sumSquaredLength + points.sumSquaredLength)
- 2 * Metric.dotProductWithAddition(this.sumPoints,
points.sumPoints, center)
+ (this.numPoints + points.numPoints)
* Metric.dotProduct(center);
} | java | public double calcKMeansCosts(double[] center, ClusteringFeature points) {
assert (this.sumPoints.length == center.length &&
this.sumPoints.length == points.sumPoints.length);
return (this.sumSquaredLength + points.sumSquaredLength)
- 2 * Metric.dotProductWithAddition(this.sumPoints,
points.sumPoints, center)
+ (this.numPoints + points.numPoints)
* Metric.dotProduct(center);
} | [
"public",
"double",
"calcKMeansCosts",
"(",
"double",
"[",
"]",
"center",
",",
"ClusteringFeature",
"points",
")",
"{",
"assert",
"(",
"this",
".",
"sumPoints",
".",
"length",
"==",
"center",
".",
"length",
"&&",
"this",
".",
"sumPoints",
".",
"length",
"=... | Calculates the k-means costs of the ClusteringFeature and another
ClusteringFeature too a center.
@param center
the center too calculate the costs
@param points
the points too calculate the costs
@return the costs | [
"Calculates",
"the",
"k",
"-",
"means",
"costs",
"of",
"the",
"ClusteringFeature",
"and",
"another",
"ClusteringFeature",
"too",
"a",
"center",
"."
] | train | https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/clusterers/kmeanspm/ClusteringFeature.java#L297-L305 |
nakamura5akihito/six-util | src/main/java/jp/go/aist/six/util/core/web/spring/Http.java | Http.postFrom | public static String postFrom(
final URL to_url,
final InputStream from_stream,
final MediaType media_type
)
{
InputStreamRequestCallback callback =
new InputStreamRequestCallback( from_stream, media_type );
String location = _execute( to_url, HttpMethod.POST, callback,
new LocationHeaderResponseExtractor() );
return location;
} | java | public static String postFrom(
final URL to_url,
final InputStream from_stream,
final MediaType media_type
)
{
InputStreamRequestCallback callback =
new InputStreamRequestCallback( from_stream, media_type );
String location = _execute( to_url, HttpMethod.POST, callback,
new LocationHeaderResponseExtractor() );
return location;
} | [
"public",
"static",
"String",
"postFrom",
"(",
"final",
"URL",
"to_url",
",",
"final",
"InputStream",
"from_stream",
",",
"final",
"MediaType",
"media_type",
")",
"{",
"InputStreamRequestCallback",
"callback",
"=",
"new",
"InputStreamRequestCallback",
"(",
"from_strea... | HTTP POST: Reads the contents from the specified stream and sends them to the URL.
@return
the location, as an URI, where the resource is created.
@throws HttpException
when an exceptional condition occurred during the HTTP method execution. | [
"HTTP",
"POST",
":",
"Reads",
"the",
"contents",
"from",
"the",
"specified",
"stream",
"and",
"sends",
"them",
"to",
"the",
"URL",
"."
] | train | https://github.com/nakamura5akihito/six-util/blob/a6db388a345e220cea2b1fa6324d15c80c6278b6/src/main/java/jp/go/aist/six/util/core/web/spring/Http.java#L243-L255 |
haraldk/TwelveMonkeys | servlet/src/main/java/com/twelvemonkeys/servlet/image/ContentNegotiationFilter.java | ContentNegotiationFilter.findBestFormat | private static String findBestFormat(Map<String, Float> pFormatQuality) {
String acceptable = null;
float acceptQuality = 0.0f;
for (Map.Entry<String, Float> entry : pFormatQuality.entrySet()) {
float qValue = entry.getValue();
if (qValue > acceptQuality) {
acceptQuality = qValue;
acceptable = entry.getKey();
}
}
//System.out.println("Accepted format: " + acceptable);
//System.out.println("Accepted quality: " + acceptQuality);
return acceptable;
} | java | private static String findBestFormat(Map<String, Float> pFormatQuality) {
String acceptable = null;
float acceptQuality = 0.0f;
for (Map.Entry<String, Float> entry : pFormatQuality.entrySet()) {
float qValue = entry.getValue();
if (qValue > acceptQuality) {
acceptQuality = qValue;
acceptable = entry.getKey();
}
}
//System.out.println("Accepted format: " + acceptable);
//System.out.println("Accepted quality: " + acceptQuality);
return acceptable;
} | [
"private",
"static",
"String",
"findBestFormat",
"(",
"Map",
"<",
"String",
",",
"Float",
">",
"pFormatQuality",
")",
"{",
"String",
"acceptable",
"=",
"null",
";",
"float",
"acceptQuality",
"=",
"0.0f",
";",
"for",
"(",
"Map",
".",
"Entry",
"<",
"String",... | Finds the best available format.
@param pFormatQuality the format to quality mapping
@return the mime type of the best available format | [
"Finds",
"the",
"best",
"available",
"format",
"."
] | train | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/servlet/src/main/java/com/twelvemonkeys/servlet/image/ContentNegotiationFilter.java#L275-L289 |
jmxtrans/embedded-jmxtrans | src/main/java/org/jmxtrans/embedded/ResultNameStrategy.java | ResultNameStrategy.resolveExpression | public String resolveExpression(String expression) {
StringBuilder result = new StringBuilder(expression.length());
int position = 0;
while (position < expression.length()) {
char c = expression.charAt(position);
if (c == '#') {
int beginningSeparatorPosition = position;
int endingSeparatorPosition = expression.indexOf('#', beginningSeparatorPosition + 1);
if (endingSeparatorPosition == -1) {
throw new IllegalStateException("Invalid expression '" + expression + "', no ending '#' after beginning '#' at position " + beginningSeparatorPosition);
}
String key = expression.substring(beginningSeparatorPosition + 1, endingSeparatorPosition);
Callable<String> expressionProcessor = expressionEvaluators.get(key);
String value;
if (expressionProcessor == null) {
value = "#unsupported_expression#";
logger.info("Unsupported expression '" + key + "'");
} else {
try {
value = expressionProcessor.call();
} catch (Exception e) {
value = "#expression_error#";
logger.warn("Error evaluating expression '" + key + "'", e);
}
}
appendEscapedNonAlphaNumericChars(value, false, result);
position = endingSeparatorPosition + 1;
} else {
result.append(c);
position++;
}
}
logger.trace("resolveExpression({}): {}", expression, result);
return result.toString();
} | java | public String resolveExpression(String expression) {
StringBuilder result = new StringBuilder(expression.length());
int position = 0;
while (position < expression.length()) {
char c = expression.charAt(position);
if (c == '#') {
int beginningSeparatorPosition = position;
int endingSeparatorPosition = expression.indexOf('#', beginningSeparatorPosition + 1);
if (endingSeparatorPosition == -1) {
throw new IllegalStateException("Invalid expression '" + expression + "', no ending '#' after beginning '#' at position " + beginningSeparatorPosition);
}
String key = expression.substring(beginningSeparatorPosition + 1, endingSeparatorPosition);
Callable<String> expressionProcessor = expressionEvaluators.get(key);
String value;
if (expressionProcessor == null) {
value = "#unsupported_expression#";
logger.info("Unsupported expression '" + key + "'");
} else {
try {
value = expressionProcessor.call();
} catch (Exception e) {
value = "#expression_error#";
logger.warn("Error evaluating expression '" + key + "'", e);
}
}
appendEscapedNonAlphaNumericChars(value, false, result);
position = endingSeparatorPosition + 1;
} else {
result.append(c);
position++;
}
}
logger.trace("resolveExpression({}): {}", expression, result);
return result.toString();
} | [
"public",
"String",
"resolveExpression",
"(",
"String",
"expression",
")",
"{",
"StringBuilder",
"result",
"=",
"new",
"StringBuilder",
"(",
"expression",
".",
"length",
"(",
")",
")",
";",
"int",
"position",
"=",
"0",
";",
"while",
"(",
"position",
"<",
"... | Replace all the '#' based keywords (e.g. <code>#hostname#</code>) by their value.
@param expression the expression to resolve (e.g. <code>"servers.#hostname#."</code>)
@return the resolved expression (e.g. <code>"servers.tomcat5"</code>) | [
"Replace",
"all",
"the",
"#",
"based",
"keywords",
"(",
"e",
".",
"g",
".",
"<code",
">",
"#hostname#<",
"/",
"code",
">",
")",
"by",
"their",
"value",
"."
] | train | https://github.com/jmxtrans/embedded-jmxtrans/blob/17224389e7d8323284cabc2a5167fc03bed6d223/src/main/java/org/jmxtrans/embedded/ResultNameStrategy.java#L158-L195 |
groovy/groovy-core | src/main/org/codehaus/groovy/runtime/DefaultGroovyMethods.java | DefaultGroovyMethods.eachWithIndex | public static <T> T eachWithIndex(T self, Closure closure) {
final Object[] args = new Object[2];
int counter = 0;
for (Iterator iter = InvokerHelper.asIterator(self); iter.hasNext();) {
args[0] = iter.next();
args[1] = counter++;
closure.call(args);
}
return self;
} | java | public static <T> T eachWithIndex(T self, Closure closure) {
final Object[] args = new Object[2];
int counter = 0;
for (Iterator iter = InvokerHelper.asIterator(self); iter.hasNext();) {
args[0] = iter.next();
args[1] = counter++;
closure.call(args);
}
return self;
} | [
"public",
"static",
"<",
"T",
">",
"T",
"eachWithIndex",
"(",
"T",
"self",
",",
"Closure",
"closure",
")",
"{",
"final",
"Object",
"[",
"]",
"args",
"=",
"new",
"Object",
"[",
"2",
"]",
";",
"int",
"counter",
"=",
"0",
";",
"for",
"(",
"Iterator",
... | Iterates through an aggregate type or data structure,
passing each item and the item's index (a counter starting at
zero) to the given closure.
@param self an Object
@param closure a Closure to operate on each item
@return the self Object
@since 1.0 | [
"Iterates",
"through",
"an",
"aggregate",
"type",
"or",
"data",
"structure",
"passing",
"each",
"item",
"and",
"the",
"item",
"s",
"index",
"(",
"a",
"counter",
"starting",
"at",
"zero",
")",
"to",
"the",
"given",
"closure",
"."
] | train | https://github.com/groovy/groovy-core/blob/01309f9d4be34ddf93c4a9943b5a97843bff6181/src/main/org/codehaus/groovy/runtime/DefaultGroovyMethods.java#L1904-L1913 |
walkmod/walkmod-core | src/main/java/org/walkmod/WalkModFacade.java | WalkModFacade.addIncludesToChain | public void addIncludesToChain(String chain, List<String> includes, boolean recursive, boolean setToReader,
boolean setToWriter) {
long startTime = System.currentTimeMillis();
Exception exception = null;
if (cfg.exists()) {
userDir = new File(System.getProperty("user.dir")).getAbsolutePath();
System.setProperty("user.dir", options.getExecutionDirectory().getAbsolutePath());
try {
ConfigurationManager manager = new ConfigurationManager(cfg, false);
manager.getProjectConfigurationProvider().addIncludesToChain(chain, includes, recursive, setToReader,
setToWriter);
} catch (Exception e) {
exception = e;
} finally {
System.setProperty("user.dir", userDir);
updateMsg(startTime, exception);
}
}
} | java | public void addIncludesToChain(String chain, List<String> includes, boolean recursive, boolean setToReader,
boolean setToWriter) {
long startTime = System.currentTimeMillis();
Exception exception = null;
if (cfg.exists()) {
userDir = new File(System.getProperty("user.dir")).getAbsolutePath();
System.setProperty("user.dir", options.getExecutionDirectory().getAbsolutePath());
try {
ConfigurationManager manager = new ConfigurationManager(cfg, false);
manager.getProjectConfigurationProvider().addIncludesToChain(chain, includes, recursive, setToReader,
setToWriter);
} catch (Exception e) {
exception = e;
} finally {
System.setProperty("user.dir", userDir);
updateMsg(startTime, exception);
}
}
} | [
"public",
"void",
"addIncludesToChain",
"(",
"String",
"chain",
",",
"List",
"<",
"String",
">",
"includes",
",",
"boolean",
"recursive",
",",
"boolean",
"setToReader",
",",
"boolean",
"setToWriter",
")",
"{",
"long",
"startTime",
"=",
"System",
".",
"currentT... | Adds a list of includes rules into a chain
@param chain
Chain to apply the includes list
@param includes
List of includes
@param recursive
If it necessary to set the parameter to all the submodules.
@param setToReader
If it is added into the reader includes list
@param setToWriter
If it is added into the writer includes list | [
"Adds",
"a",
"list",
"of",
"includes",
"rules",
"into",
"a",
"chain"
] | train | https://github.com/walkmod/walkmod-core/blob/fa79b836894fa00ca4b3e2bd26326a44b778f46f/src/main/java/org/walkmod/WalkModFacade.java#L1049-L1068 |
OpenLiberty/open-liberty | dev/com.ibm.ws.channelfw/src/com/ibm/ws/channelfw/internal/ChannelFrameworkImpl.java | ChannelFrameworkImpl.stringForMap | public static String stringForMap(Map<Object, Object> map) {
StringBuilder sbOutput = new StringBuilder();
if (map == null) {
sbOutput.append("\tNULL");
} else {
for (Entry<Object, Object> entry : map.entrySet()) {
sbOutput.append('\t').append(entry).append('\n');
}
}
return sbOutput.toString();
} | java | public static String stringForMap(Map<Object, Object> map) {
StringBuilder sbOutput = new StringBuilder();
if (map == null) {
sbOutput.append("\tNULL");
} else {
for (Entry<Object, Object> entry : map.entrySet()) {
sbOutput.append('\t').append(entry).append('\n');
}
}
return sbOutput.toString();
} | [
"public",
"static",
"String",
"stringForMap",
"(",
"Map",
"<",
"Object",
",",
"Object",
">",
"map",
")",
"{",
"StringBuilder",
"sbOutput",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"if",
"(",
"map",
"==",
"null",
")",
"{",
"sbOutput",
".",
"append",
... | Utility method to extract a string representing the contents of a map.
This is currently used by various methods as part of debug tracing.
@param map
@return string representing contents of Map | [
"Utility",
"method",
"to",
"extract",
"a",
"string",
"representing",
"the",
"contents",
"of",
"a",
"map",
".",
"This",
"is",
"currently",
"used",
"by",
"various",
"methods",
"as",
"part",
"of",
"debug",
"tracing",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.channelfw/src/com/ibm/ws/channelfw/internal/ChannelFrameworkImpl.java#L700-L710 |
hsiafan/requests | src/main/java/net/dongliu/requests/Header.java | Header.of | public static Header of(String name, String value) {
return new Header(requireNonNull(name), requireNonNull(value));
} | java | public static Header of(String name, String value) {
return new Header(requireNonNull(name), requireNonNull(value));
} | [
"public",
"static",
"Header",
"of",
"(",
"String",
"name",
",",
"String",
"value",
")",
"{",
"return",
"new",
"Header",
"(",
"requireNonNull",
"(",
"name",
")",
",",
"requireNonNull",
"(",
"value",
")",
")",
";",
"}"
] | Create new header.
@param name header name
@param value header value
@return header | [
"Create",
"new",
"header",
"."
] | train | https://github.com/hsiafan/requests/blob/a6cc6f8293e808cc937d3789aec2616a8383dee0/src/main/java/net/dongliu/requests/Header.java#L35-L37 |
EdwardRaff/JSAT | JSAT/src/jsat/utils/ListUtils.java | ListUtils.splitList | public static <T> List<List<T>> splitList(List<T> source, int count)
{
if(count <= 0)
throw new RuntimeException("Chunks must be greater then 0, not " + count);
List<List<T>> chunks = new ArrayList<List<T>>(count);
int baseSize = source.size() / count;
int remainder = source.size() % count;
int start = 0;
for(int i = 0; i < count; i++)
{
int end = start+baseSize;
if(remainder-- > 0)
end++;
chunks.add(source.subList(start, end));
start = end;
}
return chunks;
} | java | public static <T> List<List<T>> splitList(List<T> source, int count)
{
if(count <= 0)
throw new RuntimeException("Chunks must be greater then 0, not " + count);
List<List<T>> chunks = new ArrayList<List<T>>(count);
int baseSize = source.size() / count;
int remainder = source.size() % count;
int start = 0;
for(int i = 0; i < count; i++)
{
int end = start+baseSize;
if(remainder-- > 0)
end++;
chunks.add(source.subList(start, end));
start = end;
}
return chunks;
} | [
"public",
"static",
"<",
"T",
">",
"List",
"<",
"List",
"<",
"T",
">",
">",
"splitList",
"(",
"List",
"<",
"T",
">",
"source",
",",
"int",
"count",
")",
"{",
"if",
"(",
"count",
"<=",
"0",
")",
"throw",
"new",
"RuntimeException",
"(",
"\"Chunks mus... | This method takes a list and breaks it into <tt>count</tt> lists backed by the original
list, with elements being equally spaced among the lists. The lists will be returned in
order of the consecutive values they represent in the source list.
<br><br><b>NOTE</b>: Because the implementation uses {@link List#subList(int, int) },
changes to the returned lists will be reflected in the source list.
@param <T> the type contained in the list
@param source the source list that will be used to back the <tt>count</tt> lists
@param count the number of lists to partition the source into.
@return a lists of lists, each of with the same size with at most a difference of 1. | [
"This",
"method",
"takes",
"a",
"list",
"and",
"breaks",
"it",
"into",
"<tt",
">",
"count<",
"/",
"tt",
">",
"lists",
"backed",
"by",
"the",
"original",
"list",
"with",
"elements",
"being",
"equally",
"spaced",
"among",
"the",
"lists",
".",
"The",
"lists... | train | https://github.com/EdwardRaff/JSAT/blob/0ff53b7b39684b2379cc1da522f5b3a954b15cfb/JSAT/src/jsat/utils/ListUtils.java#L37-L57 |
Samsung/GearVRf | GVRf/Extensions/widgetLib/src/org/gearvrf/widgetlib/widget/properties/JSONHelpers.java | JSONHelpers.optInt | public static <P extends Enum<P>> int optInt(final JSONObject json, P e) {
return json.optInt(e.name());
} | java | public static <P extends Enum<P>> int optInt(final JSONObject json, P e) {
return json.optInt(e.name());
} | [
"public",
"static",
"<",
"P",
"extends",
"Enum",
"<",
"P",
">",
">",
"int",
"optInt",
"(",
"final",
"JSONObject",
"json",
",",
"P",
"e",
")",
"{",
"return",
"json",
".",
"optInt",
"(",
"e",
".",
"name",
"(",
")",
")",
";",
"}"
] | Returns the value mapped to {@code e} if it exists and is an {@code int} or can be coerced to
an {@code int}. Returns 0 otherwise.
@param json {@link JSONObject} to get data from
@param e {@link Enum} labeling the data to get | [
"Returns",
"the",
"value",
"mapped",
"to",
"{",
"@code",
"e",
"}",
"if",
"it",
"exists",
"and",
"is",
"an",
"{",
"@code",
"int",
"}",
"or",
"can",
"be",
"coerced",
"to",
"an",
"{",
"@code",
"int",
"}",
".",
"Returns",
"0",
"otherwise",
"."
] | train | https://github.com/Samsung/GearVRf/blob/05034d465a7b0a494fabb9e9f2971ac19392f32d/GVRf/Extensions/widgetLib/src/org/gearvrf/widgetlib/widget/properties/JSONHelpers.java#L197-L199 |
QSFT/Doradus | doradus-server/src/main/java/com/dell/doradus/service/schema/SchemaService.java | SchemaService.initializeApplication | private void initializeApplication(ApplicationDefinition currAppDef, ApplicationDefinition appDef) {
getStorageService(appDef).initializeApplication(currAppDef, appDef);
storeApplicationSchema(appDef);
} | java | private void initializeApplication(ApplicationDefinition currAppDef, ApplicationDefinition appDef) {
getStorageService(appDef).initializeApplication(currAppDef, appDef);
storeApplicationSchema(appDef);
} | [
"private",
"void",
"initializeApplication",
"(",
"ApplicationDefinition",
"currAppDef",
",",
"ApplicationDefinition",
"appDef",
")",
"{",
"getStorageService",
"(",
"appDef",
")",
".",
"initializeApplication",
"(",
"currAppDef",
",",
"appDef",
")",
";",
"storeApplication... | Initialize storage and store the given schema for the given new or updated application. | [
"Initialize",
"storage",
"and",
"store",
"the",
"given",
"schema",
"for",
"the",
"given",
"new",
"or",
"updated",
"application",
"."
] | train | https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-server/src/main/java/com/dell/doradus/service/schema/SchemaService.java#L336-L339 |
rundeck/rundeck | core/src/main/java/com/dtolabs/rundeck/core/plugins/configuration/Validator.java | Validator.mapProperties | public static Map<String, String> mapProperties(final Map<String, String> input, final Description desc) {
final Map<String, String> mapping = desc.getPropertiesMapping();
if (null == mapping) {
return input;
}
return performMapping(input, mapping, false);
} | java | public static Map<String, String> mapProperties(final Map<String, String> input, final Description desc) {
final Map<String, String> mapping = desc.getPropertiesMapping();
if (null == mapping) {
return input;
}
return performMapping(input, mapping, false);
} | [
"public",
"static",
"Map",
"<",
"String",
",",
"String",
">",
"mapProperties",
"(",
"final",
"Map",
"<",
"String",
",",
"String",
">",
"input",
",",
"final",
"Description",
"desc",
")",
"{",
"final",
"Map",
"<",
"String",
",",
"String",
">",
"mapping",
... | Converts a set of input configuration keys using the description's configuration to property mapping, or the same
input if the description has no mapping
@param input input map
@param desc plugin description
@return mapped values | [
"Converts",
"a",
"set",
"of",
"input",
"configuration",
"keys",
"using",
"the",
"description",
"s",
"configuration",
"to",
"property",
"mapping",
"or",
"the",
"same",
"input",
"if",
"the",
"description",
"has",
"no",
"mapping"
] | train | https://github.com/rundeck/rundeck/blob/8070f774f55bffaa1118ff0c03aea319d40a9668/core/src/main/java/com/dtolabs/rundeck/core/plugins/configuration/Validator.java#L240-L246 |
RobotiumTech/robotium | robotium-solo/src/main/java/com/robotium/solo/Solo.java | Solo.clickLongOnView | public void clickLongOnView(View view, int time) {
if(config.commandLogging){
Log.d(config.commandLoggingTag, "clickLongOnView("+view+", "+time+")");
}
clicker.clickOnScreen(view, true, time);
} | java | public void clickLongOnView(View view, int time) {
if(config.commandLogging){
Log.d(config.commandLoggingTag, "clickLongOnView("+view+", "+time+")");
}
clicker.clickOnScreen(view, true, time);
} | [
"public",
"void",
"clickLongOnView",
"(",
"View",
"view",
",",
"int",
"time",
")",
"{",
"if",
"(",
"config",
".",
"commandLogging",
")",
"{",
"Log",
".",
"d",
"(",
"config",
".",
"commandLoggingTag",
",",
"\"clickLongOnView(\"",
"+",
"view",
"+",
"\", \"",... | Long clicks the specified View for a specified amount of time.
@param view the {@link View} to long click
@param time the amount of time to long click | [
"Long",
"clicks",
"the",
"specified",
"View",
"for",
"a",
"specified",
"amount",
"of",
"time",
"."
] | train | https://github.com/RobotiumTech/robotium/blob/75e567c38f26a6a87dc8bef90b3886a20e28d291/robotium-solo/src/main/java/com/robotium/solo/Solo.java#L1491-L1498 |
OpenFeign/feign | core/src/main/java/feign/Util.java | Util.resolveLastTypeParameter | public static Type resolveLastTypeParameter(Type genericContext, Class<?> supertype)
throws IllegalStateException {
Type resolvedSuperType =
Types.getSupertype(genericContext, Types.getRawType(genericContext), supertype);
checkState(resolvedSuperType instanceof ParameterizedType,
"could not resolve %s into a parameterized type %s",
genericContext, supertype);
Type[] types = ParameterizedType.class.cast(resolvedSuperType).getActualTypeArguments();
for (int i = 0; i < types.length; i++) {
Type type = types[i];
if (type instanceof WildcardType) {
types[i] = ((WildcardType) type).getUpperBounds()[0];
}
}
return types[types.length - 1];
} | java | public static Type resolveLastTypeParameter(Type genericContext, Class<?> supertype)
throws IllegalStateException {
Type resolvedSuperType =
Types.getSupertype(genericContext, Types.getRawType(genericContext), supertype);
checkState(resolvedSuperType instanceof ParameterizedType,
"could not resolve %s into a parameterized type %s",
genericContext, supertype);
Type[] types = ParameterizedType.class.cast(resolvedSuperType).getActualTypeArguments();
for (int i = 0; i < types.length; i++) {
Type type = types[i];
if (type instanceof WildcardType) {
types[i] = ((WildcardType) type).getUpperBounds()[0];
}
}
return types[types.length - 1];
} | [
"public",
"static",
"Type",
"resolveLastTypeParameter",
"(",
"Type",
"genericContext",
",",
"Class",
"<",
"?",
">",
"supertype",
")",
"throws",
"IllegalStateException",
"{",
"Type",
"resolvedSuperType",
"=",
"Types",
".",
"getSupertype",
"(",
"genericContext",
",",
... | Resolves the last type parameter of the parameterized {@code supertype}, based on the {@code
genericContext}, into its upper bounds.
<p/>
Implementation copied from {@code
retrofit.RestMethodInfo}.
@param genericContext Ex. {@link java.lang.reflect.Field#getGenericType()}
@param supertype Ex. {@code Decoder.class}
@return in the example above, the type parameter of {@code Decoder}.
@throws IllegalStateException if {@code supertype} cannot be resolved into a parameterized type
using {@code context}. | [
"Resolves",
"the",
"last",
"type",
"parameter",
"of",
"the",
"parameterized",
"{",
"@code",
"supertype",
"}",
"based",
"on",
"the",
"{",
"@code",
"genericContext",
"}",
"into",
"its",
"upper",
"bounds",
".",
"<p",
"/",
">",
"Implementation",
"copied",
"from"... | train | https://github.com/OpenFeign/feign/blob/318fb0e955b8cfcf64f70d6aeea0ba5795f8a7eb/core/src/main/java/feign/Util.java#L219-L234 |
alkacon/opencms-core | src/org/opencms/ade/sitemap/CmsVfsSitemapService.java | CmsVfsSitemapService.createNewContainerElements | private void createNewContainerElements(CmsObject cms, CmsXmlContainerPage page, String sitePath)
throws CmsException {
CmsADEConfigData configData = OpenCms.getADEManager().lookupConfiguration(cms, cms.addSiteRoot(sitePath));
Locale contentLocale = OpenCms.getLocaleManager().getDefaultLocale(cms, CmsResource.getFolderPath(sitePath));
CmsObject cloneCms = OpenCms.initCmsObject(cms);
cloneCms.getRequestContext().setLocale(contentLocale);
CmsContainerPageBean pageBean = page.getContainerPage(cms);
boolean needsChanges = false;
List<CmsContainerBean> updatedContainers = new ArrayList<CmsContainerBean>();
for (CmsContainerBean container : pageBean.getContainers().values()) {
List<CmsContainerElementBean> updatedElements = new ArrayList<CmsContainerElementBean>();
for (CmsContainerElementBean element : container.getElements()) {
if (element.isCreateNew() && !element.isGroupContainer(cms) && !element.isInheritedContainer(cms)) {
needsChanges = true;
String typeName = OpenCms.getResourceManager().getResourceType(element.getResource()).getTypeName();
CmsResourceTypeConfig typeConfig = configData.getResourceType(typeName);
if (typeConfig == null) {
throw new IllegalArgumentException(
"Can not copy template model element '"
+ element.getResource().getRootPath()
+ "' because the resource type '"
+ typeName
+ "' is not available in this sitemap.");
}
CmsResource newResource = typeConfig.createNewElement(
cloneCms,
element.getResource(),
CmsResource.getParentFolder(cms.getRequestContext().addSiteRoot(sitePath)));
CmsContainerElementBean newBean = new CmsContainerElementBean(
newResource.getStructureId(),
element.getFormatterId(),
element.getIndividualSettings(),
false);
updatedElements.add(newBean);
} else {
updatedElements.add(element);
}
}
CmsContainerBean updatedContainer = new CmsContainerBean(
container.getName(),
container.getType(),
container.getParentInstanceId(),
container.isRootContainer(),
container.getMaxElements(),
updatedElements);
updatedContainers.add(updatedContainer);
}
if (needsChanges) {
CmsContainerPageBean updatedPage = new CmsContainerPageBean(updatedContainers);
page.writeContainerPage(cms, updatedPage);
}
} | java | private void createNewContainerElements(CmsObject cms, CmsXmlContainerPage page, String sitePath)
throws CmsException {
CmsADEConfigData configData = OpenCms.getADEManager().lookupConfiguration(cms, cms.addSiteRoot(sitePath));
Locale contentLocale = OpenCms.getLocaleManager().getDefaultLocale(cms, CmsResource.getFolderPath(sitePath));
CmsObject cloneCms = OpenCms.initCmsObject(cms);
cloneCms.getRequestContext().setLocale(contentLocale);
CmsContainerPageBean pageBean = page.getContainerPage(cms);
boolean needsChanges = false;
List<CmsContainerBean> updatedContainers = new ArrayList<CmsContainerBean>();
for (CmsContainerBean container : pageBean.getContainers().values()) {
List<CmsContainerElementBean> updatedElements = new ArrayList<CmsContainerElementBean>();
for (CmsContainerElementBean element : container.getElements()) {
if (element.isCreateNew() && !element.isGroupContainer(cms) && !element.isInheritedContainer(cms)) {
needsChanges = true;
String typeName = OpenCms.getResourceManager().getResourceType(element.getResource()).getTypeName();
CmsResourceTypeConfig typeConfig = configData.getResourceType(typeName);
if (typeConfig == null) {
throw new IllegalArgumentException(
"Can not copy template model element '"
+ element.getResource().getRootPath()
+ "' because the resource type '"
+ typeName
+ "' is not available in this sitemap.");
}
CmsResource newResource = typeConfig.createNewElement(
cloneCms,
element.getResource(),
CmsResource.getParentFolder(cms.getRequestContext().addSiteRoot(sitePath)));
CmsContainerElementBean newBean = new CmsContainerElementBean(
newResource.getStructureId(),
element.getFormatterId(),
element.getIndividualSettings(),
false);
updatedElements.add(newBean);
} else {
updatedElements.add(element);
}
}
CmsContainerBean updatedContainer = new CmsContainerBean(
container.getName(),
container.getType(),
container.getParentInstanceId(),
container.isRootContainer(),
container.getMaxElements(),
updatedElements);
updatedContainers.add(updatedContainer);
}
if (needsChanges) {
CmsContainerPageBean updatedPage = new CmsContainerPageBean(updatedContainers);
page.writeContainerPage(cms, updatedPage);
}
} | [
"private",
"void",
"createNewContainerElements",
"(",
"CmsObject",
"cms",
",",
"CmsXmlContainerPage",
"page",
",",
"String",
"sitePath",
")",
"throws",
"CmsException",
"{",
"CmsADEConfigData",
"configData",
"=",
"OpenCms",
".",
"getADEManager",
"(",
")",
".",
"looku... | Creates new content elements if required by the model page.<p>
@param cms the cms context
@param page the page
@param sitePath the resource site path
@throws CmsException when unable to create the content elements | [
"Creates",
"new",
"content",
"elements",
"if",
"required",
"by",
"the",
"model",
"page",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ade/sitemap/CmsVfsSitemapService.java#L1654-L1708 |
Azure/azure-sdk-for-java | appservice/resource-manager/v2018_02_01/src/main/java/com/microsoft/azure/management/appservice/v2018_02_01/implementation/WebSiteManagementClientImpl.java | WebSiteManagementClientImpl.validateMoveAsync | public Observable<Void> validateMoveAsync(String resourceGroupName, CsmMoveResourceEnvelope moveResourceEnvelope) {
return validateMoveWithServiceResponseAsync(resourceGroupName, moveResourceEnvelope).map(new Func1<ServiceResponse<Void>, Void>() {
@Override
public Void call(ServiceResponse<Void> response) {
return response.body();
}
});
} | java | public Observable<Void> validateMoveAsync(String resourceGroupName, CsmMoveResourceEnvelope moveResourceEnvelope) {
return validateMoveWithServiceResponseAsync(resourceGroupName, moveResourceEnvelope).map(new Func1<ServiceResponse<Void>, Void>() {
@Override
public Void call(ServiceResponse<Void> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"Void",
">",
"validateMoveAsync",
"(",
"String",
"resourceGroupName",
",",
"CsmMoveResourceEnvelope",
"moveResourceEnvelope",
")",
"{",
"return",
"validateMoveWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"moveResourceEnvelope",
")",
... | Validate whether a resource can be moved.
Validate whether a resource can be moved.
@param resourceGroupName Name of the resource group to which the resource belongs.
@param moveResourceEnvelope Object that represents the resource to move.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the {@link ServiceResponse} object if successful. | [
"Validate",
"whether",
"a",
"resource",
"can",
"be",
"moved",
".",
"Validate",
"whether",
"a",
"resource",
"can",
"be",
"moved",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/appservice/resource-manager/v2018_02_01/src/main/java/com/microsoft/azure/management/appservice/v2018_02_01/implementation/WebSiteManagementClientImpl.java#L2357-L2364 |
javagl/CommonUI | src/main/java/de/javagl/common/ui/text/StringUtils.java | StringUtils.indexOf | static int indexOf(String source, String target,
int startIndex, boolean ignoreCase)
{
if (ignoreCase)
{
return indexOf(source, target, startIndex, IGNORING_CASE);
}
return indexOf(source, target, startIndex,
(c0, c1) -> Integer.compare(c0, c1));
} | java | static int indexOf(String source, String target,
int startIndex, boolean ignoreCase)
{
if (ignoreCase)
{
return indexOf(source, target, startIndex, IGNORING_CASE);
}
return indexOf(source, target, startIndex,
(c0, c1) -> Integer.compare(c0, c1));
} | [
"static",
"int",
"indexOf",
"(",
"String",
"source",
",",
"String",
"target",
",",
"int",
"startIndex",
",",
"boolean",
"ignoreCase",
")",
"{",
"if",
"(",
"ignoreCase",
")",
"{",
"return",
"indexOf",
"(",
"source",
",",
"target",
",",
"startIndex",
",",
... | Returns the index of the first appearance of the given target in
the given source, starting at the given index. Returns -1 if the
target string is not found.
@param source The source string
@param target The target string
@param startIndex The start index
@param ignoreCase Whether the case should be ignored
@return The index | [
"Returns",
"the",
"index",
"of",
"the",
"first",
"appearance",
"of",
"the",
"given",
"target",
"in",
"the",
"given",
"source",
"starting",
"at",
"the",
"given",
"index",
".",
"Returns",
"-",
"1",
"if",
"the",
"target",
"string",
"is",
"not",
"found",
"."... | train | https://github.com/javagl/CommonUI/blob/b2c7a7637d4e288271392ba148dc17e4c9780255/src/main/java/de/javagl/common/ui/text/StringUtils.java#L66-L75 |
google/closure-compiler | src/com/google/javascript/jscomp/AstFactory.java | AstFactory.createSingleConstNameDeclaration | Node createSingleConstNameDeclaration(String variableName, Node value) {
return IR.constNode(createName(variableName, value.getJSType()), value);
} | java | Node createSingleConstNameDeclaration(String variableName, Node value) {
return IR.constNode(createName(variableName, value.getJSType()), value);
} | [
"Node",
"createSingleConstNameDeclaration",
"(",
"String",
"variableName",
",",
"Node",
"value",
")",
"{",
"return",
"IR",
".",
"constNode",
"(",
"createName",
"(",
"variableName",
",",
"value",
".",
"getJSType",
"(",
")",
")",
",",
"value",
")",
";",
"}"
] | Creates a new `const` declaration statement for a single variable name.
<p>Takes the type for the variable name from the value node.
<p>e.g. `const variableName = value;` | [
"Creates",
"a",
"new",
"const",
"declaration",
"statement",
"for",
"a",
"single",
"variable",
"name",
"."
] | train | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/AstFactory.java#L334-L336 |
Jasig/uPortal | uPortal-api/uPortal-api-internal/src/main/java/org/apereo/portal/portlets/groupadmin/GroupAdministrationHelper.java | GroupAdministrationHelper.deleteGroup | public void deleteGroup(String key, IPerson deleter) {
if (!canDeleteGroup(deleter, key)) {
throw new RuntimeAuthorizationException(
deleter, IPermission.DELETE_GROUP_ACTIVITY, key);
}
log.info("Deleting group with key " + key);
// find the current version of this group entity
IEntityGroup group = GroupService.findGroup(key);
// remove this group from the membership list of any current parent
// groups
for (IEntityGroup parent : group.getParentGroups()) {
parent.removeChild(group);
parent.updateMembers();
}
// delete the group
group.delete();
} | java | public void deleteGroup(String key, IPerson deleter) {
if (!canDeleteGroup(deleter, key)) {
throw new RuntimeAuthorizationException(
deleter, IPermission.DELETE_GROUP_ACTIVITY, key);
}
log.info("Deleting group with key " + key);
// find the current version of this group entity
IEntityGroup group = GroupService.findGroup(key);
// remove this group from the membership list of any current parent
// groups
for (IEntityGroup parent : group.getParentGroups()) {
parent.removeChild(group);
parent.updateMembers();
}
// delete the group
group.delete();
} | [
"public",
"void",
"deleteGroup",
"(",
"String",
"key",
",",
"IPerson",
"deleter",
")",
"{",
"if",
"(",
"!",
"canDeleteGroup",
"(",
"deleter",
",",
"key",
")",
")",
"{",
"throw",
"new",
"RuntimeAuthorizationException",
"(",
"deleter",
",",
"IPermission",
".",... | Delete a group from the group store
@param key key of the group to be deleted
@param user performing the delete operation | [
"Delete",
"a",
"group",
"from",
"the",
"group",
"store"
] | train | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-api/uPortal-api-internal/src/main/java/org/apereo/portal/portlets/groupadmin/GroupAdministrationHelper.java#L88-L109 |
iipc/openwayback | wayback-core/src/main/java/org/archive/wayback/util/url/UrlOperations.java | UrlOperations.resolveUrl | public static String resolveUrl(String baseUrl, String url) {
String resolvedUrl = resolveUrl(baseUrl, url, null);
if (resolvedUrl == null) {
resolvedUrl = url.replace(" ", "%20");
resolvedUrl = resolvedUrl.replace("\r", "%0D");
}
return resolvedUrl;
} | java | public static String resolveUrl(String baseUrl, String url) {
String resolvedUrl = resolveUrl(baseUrl, url, null);
if (resolvedUrl == null) {
resolvedUrl = url.replace(" ", "%20");
resolvedUrl = resolvedUrl.replace("\r", "%0D");
}
return resolvedUrl;
} | [
"public",
"static",
"String",
"resolveUrl",
"(",
"String",
"baseUrl",
",",
"String",
"url",
")",
"{",
"String",
"resolvedUrl",
"=",
"resolveUrl",
"(",
"baseUrl",
",",
"url",
",",
"null",
")",
";",
"if",
"(",
"resolvedUrl",
"==",
"null",
")",
"{",
"resolv... | Resolve URL, but return a minimally escaped version in case of
error
@param baseUrl the base URL against which the url should be resolved
@param url the URL, possibly relative, to make absolute.
@return url resolved against baseUrl, unless it is absolute already, and
further transformed by whatever escaping normally takes place with a
UsableURI.
In case of error, return URL. | [
"Resolve",
"URL",
"but",
"return",
"a",
"minimally",
"escaped",
"version",
"in",
"case",
"of",
"error"
] | train | https://github.com/iipc/openwayback/blob/da74c3a59a5b5a5c365bd4702dcb45d263535794/wayback-core/src/main/java/org/archive/wayback/util/url/UrlOperations.java#L163-L170 |
HubSpot/jinjava | src/main/java/com/hubspot/jinjava/interpret/JinjavaInterpreter.java | JinjavaInterpreter.retraceVariable | public Object retraceVariable(String variable, int lineNumber, int startPosition) {
if (StringUtils.isBlank(variable)) {
return "";
}
Variable var = new Variable(this, variable);
String varName = var.getName();
Object obj = context.get(varName);
if (obj != null) {
if (obj instanceof DeferredValue) {
throw new DeferredValueException(variable, lineNumber, startPosition);
}
obj = var.resolve(obj);
} else if (getConfig().isFailOnUnknownTokens()) {
throw new UnknownTokenException(variable, lineNumber, startPosition);
}
return obj;
} | java | public Object retraceVariable(String variable, int lineNumber, int startPosition) {
if (StringUtils.isBlank(variable)) {
return "";
}
Variable var = new Variable(this, variable);
String varName = var.getName();
Object obj = context.get(varName);
if (obj != null) {
if (obj instanceof DeferredValue) {
throw new DeferredValueException(variable, lineNumber, startPosition);
}
obj = var.resolve(obj);
} else if (getConfig().isFailOnUnknownTokens()) {
throw new UnknownTokenException(variable, lineNumber, startPosition);
}
return obj;
} | [
"public",
"Object",
"retraceVariable",
"(",
"String",
"variable",
",",
"int",
"lineNumber",
",",
"int",
"startPosition",
")",
"{",
"if",
"(",
"StringUtils",
".",
"isBlank",
"(",
"variable",
")",
")",
"{",
"return",
"\"\"",
";",
"}",
"Variable",
"var",
"=",... | Resolve a variable from the interpreter context, returning null if not found. This method updates the template error accumulators when a variable is not found.
@param variable
name of variable in context
@param lineNumber
current line number, for error reporting
@param startPosition
current line position, for error reporting
@return resolved value for variable | [
"Resolve",
"a",
"variable",
"from",
"the",
"interpreter",
"context",
"returning",
"null",
"if",
"not",
"found",
".",
"This",
"method",
"updates",
"the",
"template",
"error",
"accumulators",
"when",
"a",
"variable",
"is",
"not",
"found",
"."
] | train | https://github.com/HubSpot/jinjava/blob/ce570935630f49c666170d2330b0b9ba4eddb955/src/main/java/com/hubspot/jinjava/interpret/JinjavaInterpreter.java#L325-L341 |
lessthanoptimal/ejml | main/ejml-ddense/src/org/ejml/dense/fixed/CommonOps_DDF2.java | CommonOps_DDF2.extractRow | public static DMatrix2 extractRow( DMatrix2x2 a , int row , DMatrix2 out ) {
if( out == null) out = new DMatrix2();
switch( row ) {
case 0:
out.a1 = a.a11;
out.a2 = a.a12;
break;
case 1:
out.a1 = a.a21;
out.a2 = a.a22;
break;
default:
throw new IllegalArgumentException("Out of bounds row. row = "+row);
}
return out;
} | java | public static DMatrix2 extractRow( DMatrix2x2 a , int row , DMatrix2 out ) {
if( out == null) out = new DMatrix2();
switch( row ) {
case 0:
out.a1 = a.a11;
out.a2 = a.a12;
break;
case 1:
out.a1 = a.a21;
out.a2 = a.a22;
break;
default:
throw new IllegalArgumentException("Out of bounds row. row = "+row);
}
return out;
} | [
"public",
"static",
"DMatrix2",
"extractRow",
"(",
"DMatrix2x2",
"a",
",",
"int",
"row",
",",
"DMatrix2",
"out",
")",
"{",
"if",
"(",
"out",
"==",
"null",
")",
"out",
"=",
"new",
"DMatrix2",
"(",
")",
";",
"switch",
"(",
"row",
")",
"{",
"case",
"0... | Extracts the row from the matrix a.
@param a Input matrix
@param row Which row is to be extracted
@param out output. Storage for the extracted row. If null then a new vector will be returned.
@return The extracted row. | [
"Extracts",
"the",
"row",
"from",
"the",
"matrix",
"a",
"."
] | train | https://github.com/lessthanoptimal/ejml/blob/1444680cc487af5e866730e62f48f5f9636850d9/main/ejml-ddense/src/org/ejml/dense/fixed/CommonOps_DDF2.java#L1157-L1172 |
timols/java-gitlab-api | src/main/java/org/gitlab/api/GitlabAPI.java | GitlabAPI.getGroupBadge | public GitlabBadge getGroupBadge(Integer groupId, Integer badgeId) throws IOException {
String tailUrl = GitlabGroup.URL + "/" + groupId + GitlabBadge.URL
+ "/" + badgeId;
return retrieve().to(tailUrl, GitlabBadge.class);
} | java | public GitlabBadge getGroupBadge(Integer groupId, Integer badgeId) throws IOException {
String tailUrl = GitlabGroup.URL + "/" + groupId + GitlabBadge.URL
+ "/" + badgeId;
return retrieve().to(tailUrl, GitlabBadge.class);
} | [
"public",
"GitlabBadge",
"getGroupBadge",
"(",
"Integer",
"groupId",
",",
"Integer",
"badgeId",
")",
"throws",
"IOException",
"{",
"String",
"tailUrl",
"=",
"GitlabGroup",
".",
"URL",
"+",
"\"/\"",
"+",
"groupId",
"+",
"GitlabBadge",
".",
"URL",
"+",
"\"/\"",
... | Get group badge
@param groupId The id of the group for which the badge should be retrieved
@param badgeId The id of the badge that should be retrieved
@return The badge with a given id
@throws IOException on GitLab API call error | [
"Get",
"group",
"badge"
] | train | https://github.com/timols/java-gitlab-api/blob/f03eedf952cfbb40306be3bf9234dcf78fab029e/src/main/java/org/gitlab/api/GitlabAPI.java#L2695-L2699 |
deeplearning4j/deeplearning4j | deeplearning4j/deeplearning4j-nlp-parent/deeplearning4j-nlp/src/main/java/org/deeplearning4j/models/glove/GloveWeightLookupTable.java | GloveWeightLookupTable.iterateSample | public double iterateSample(T w1, T w2, double score) {
INDArray w1Vector = syn0.slice(w1.getIndex());
INDArray w2Vector = syn0.slice(w2.getIndex());
//prediction: input + bias
if (w1.getIndex() < 0 || w1.getIndex() >= syn0.rows())
throw new IllegalArgumentException("Illegal index for word " + w1.getLabel());
if (w2.getIndex() < 0 || w2.getIndex() >= syn0.rows())
throw new IllegalArgumentException("Illegal index for word " + w2.getLabel());
//w1 * w2 + bias
double prediction = Nd4j.getBlasWrapper().dot(w1Vector, w2Vector);
prediction += bias.getDouble(w1.getIndex()) + bias.getDouble(w2.getIndex());
double weight = Math.pow(Math.min(1.0, (score / maxCount)), xMax);
double fDiff = score > xMax ? prediction : weight * (prediction - Math.log(score));
if (Double.isNaN(fDiff))
fDiff = Nd4j.EPS_THRESHOLD;
//amount of change
double gradient = fDiff;
//note the update step here: the gradient is
//the gradient of the OPPOSITE word
//for adagrad we will use the index of the word passed in
//for the gradient calculation we will use the context vector
update(w1, w1Vector, w2Vector, gradient);
update(w2, w2Vector, w1Vector, gradient);
return fDiff;
} | java | public double iterateSample(T w1, T w2, double score) {
INDArray w1Vector = syn0.slice(w1.getIndex());
INDArray w2Vector = syn0.slice(w2.getIndex());
//prediction: input + bias
if (w1.getIndex() < 0 || w1.getIndex() >= syn0.rows())
throw new IllegalArgumentException("Illegal index for word " + w1.getLabel());
if (w2.getIndex() < 0 || w2.getIndex() >= syn0.rows())
throw new IllegalArgumentException("Illegal index for word " + w2.getLabel());
//w1 * w2 + bias
double prediction = Nd4j.getBlasWrapper().dot(w1Vector, w2Vector);
prediction += bias.getDouble(w1.getIndex()) + bias.getDouble(w2.getIndex());
double weight = Math.pow(Math.min(1.0, (score / maxCount)), xMax);
double fDiff = score > xMax ? prediction : weight * (prediction - Math.log(score));
if (Double.isNaN(fDiff))
fDiff = Nd4j.EPS_THRESHOLD;
//amount of change
double gradient = fDiff;
//note the update step here: the gradient is
//the gradient of the OPPOSITE word
//for adagrad we will use the index of the word passed in
//for the gradient calculation we will use the context vector
update(w1, w1Vector, w2Vector, gradient);
update(w2, w2Vector, w1Vector, gradient);
return fDiff;
} | [
"public",
"double",
"iterateSample",
"(",
"T",
"w1",
",",
"T",
"w2",
",",
"double",
"score",
")",
"{",
"INDArray",
"w1Vector",
"=",
"syn0",
".",
"slice",
"(",
"w1",
".",
"getIndex",
"(",
")",
")",
";",
"INDArray",
"w2Vector",
"=",
"syn0",
".",
"slice... | glove iteration
@param w1 the first word
@param w2 the second word
@param score the weight learned for the particular co occurrences | [
"glove",
"iteration"
] | train | https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/deeplearning4j/deeplearning4j-nlp-parent/deeplearning4j-nlp/src/main/java/org/deeplearning4j/models/glove/GloveWeightLookupTable.java#L105-L137 |
mongodb/stitch-android-sdk | core/services/mongodb-remote/src/main/java/com/mongodb/stitch/core/services/mongodb/remote/sync/internal/DataSynchronizer.java | DataSynchronizer.deleteOneFromRemote | @CheckReturnValue
@Nullable
private LocalSyncWriteModelContainer deleteOneFromRemote(
final NamespaceSynchronizationConfig nsConfig,
final BsonValue documentId
) {
final MongoNamespace namespace = nsConfig.getNamespace();
final Lock lock = this.syncConfig.getNamespaceConfig(namespace).getLock().writeLock();
lock.lock();
final CoreDocumentSynchronizationConfig config;
try {
config = syncConfig.getSynchronizedDocument(namespace, documentId);
if (config == null) {
return null;
}
} finally {
lock.unlock();
}
eventDispatcher.emitEvent(nsConfig,
ChangeEvents.changeEventForLocalDelete(namespace, documentId, false));
return desyncDocumentsFromRemote(nsConfig, documentId);
} | java | @CheckReturnValue
@Nullable
private LocalSyncWriteModelContainer deleteOneFromRemote(
final NamespaceSynchronizationConfig nsConfig,
final BsonValue documentId
) {
final MongoNamespace namespace = nsConfig.getNamespace();
final Lock lock = this.syncConfig.getNamespaceConfig(namespace).getLock().writeLock();
lock.lock();
final CoreDocumentSynchronizationConfig config;
try {
config = syncConfig.getSynchronizedDocument(namespace, documentId);
if (config == null) {
return null;
}
} finally {
lock.unlock();
}
eventDispatcher.emitEvent(nsConfig,
ChangeEvents.changeEventForLocalDelete(namespace, documentId, false));
return desyncDocumentsFromRemote(nsConfig, documentId);
} | [
"@",
"CheckReturnValue",
"@",
"Nullable",
"private",
"LocalSyncWriteModelContainer",
"deleteOneFromRemote",
"(",
"final",
"NamespaceSynchronizationConfig",
"nsConfig",
",",
"final",
"BsonValue",
"documentId",
")",
"{",
"final",
"MongoNamespace",
"namespace",
"=",
"nsConfig"... | Deletes a single synchronized document by its given id. No deletion will occur if the _id is
not being synchronized.
@param nsConfig the namespace synchronization config of the namespace where the document
lives.
@param documentId the _id of the document. | [
"Deletes",
"a",
"single",
"synchronized",
"document",
"by",
"its",
"given",
"id",
".",
"No",
"deletion",
"will",
"occur",
"if",
"the",
"_id",
"is",
"not",
"being",
"synchronized",
"."
] | train | https://github.com/mongodb/stitch-android-sdk/blob/159b9334b1f1a827285544be5ee20cdf7b04e4cc/core/services/mongodb-remote/src/main/java/com/mongodb/stitch/core/services/mongodb/remote/sync/internal/DataSynchronizer.java#L2915-L2936 |
Alluxio/alluxio | core/common/src/main/java/alluxio/util/io/BufferUtils.java | BufferUtils.writeBufferToFile | public static void writeBufferToFile(String path, byte[] buffer) throws IOException {
try (FileOutputStream os = new FileOutputStream(path)) {
os.write(buffer);
}
} | java | public static void writeBufferToFile(String path, byte[] buffer) throws IOException {
try (FileOutputStream os = new FileOutputStream(path)) {
os.write(buffer);
}
} | [
"public",
"static",
"void",
"writeBufferToFile",
"(",
"String",
"path",
",",
"byte",
"[",
"]",
"buffer",
")",
"throws",
"IOException",
"{",
"try",
"(",
"FileOutputStream",
"os",
"=",
"new",
"FileOutputStream",
"(",
"path",
")",
")",
"{",
"os",
".",
"write"... | Writes buffer to the given file path.
@param path file path to write the data
@param buffer raw data | [
"Writes",
"buffer",
"to",
"the",
"given",
"file",
"path",
"."
] | train | https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/common/src/main/java/alluxio/util/io/BufferUtils.java#L273-L277 |
hazelcast/hazelcast | hazelcast/src/main/java/com/hazelcast/cache/impl/AbstractCacheService.java | AbstractCacheService.addInvalidationListener | @Override
public String addInvalidationListener(String cacheNameWithPrefix, CacheEventListener listener, boolean localOnly) {
EventService eventService = nodeEngine.getEventService();
EventRegistration registration;
if (localOnly) {
registration = eventService.registerLocalListener(SERVICE_NAME, cacheNameWithPrefix, listener);
} else {
registration = eventService.registerListener(SERVICE_NAME, cacheNameWithPrefix, listener);
}
return registration.getId();
} | java | @Override
public String addInvalidationListener(String cacheNameWithPrefix, CacheEventListener listener, boolean localOnly) {
EventService eventService = nodeEngine.getEventService();
EventRegistration registration;
if (localOnly) {
registration = eventService.registerLocalListener(SERVICE_NAME, cacheNameWithPrefix, listener);
} else {
registration = eventService.registerListener(SERVICE_NAME, cacheNameWithPrefix, listener);
}
return registration.getId();
} | [
"@",
"Override",
"public",
"String",
"addInvalidationListener",
"(",
"String",
"cacheNameWithPrefix",
",",
"CacheEventListener",
"listener",
",",
"boolean",
"localOnly",
")",
"{",
"EventService",
"eventService",
"=",
"nodeEngine",
".",
"getEventService",
"(",
")",
";"... | Registers and {@link com.hazelcast.cache.impl.CacheEventListener} for specified {@code cacheNameWithPrefix}
@param cacheNameWithPrefix the full name of the cache (including manager scope prefix)
that {@link com.hazelcast.cache.impl.CacheEventListener} will be registered for
@param listener the {@link com.hazelcast.cache.impl.CacheEventListener} to be registered
for specified {@code cacheNameWithPrefix}
@param localOnly true if only events originated from this member wants be listened, false if all
invalidation events in the cluster wants to be listened
@return the ID which is unique for current registration | [
"Registers",
"and",
"{",
"@link",
"com",
".",
"hazelcast",
".",
"cache",
".",
"impl",
".",
"CacheEventListener",
"}",
"for",
"specified",
"{",
"@code",
"cacheNameWithPrefix",
"}"
] | train | https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/cache/impl/AbstractCacheService.java#L798-L808 |
groovy/groovy-core | subprojects/groovy-nio/src/main/java/org/codehaus/groovy/runtime/NioGroovyMethods.java | NioGroovyMethods.newWriter | public static BufferedWriter newWriter(Path self, String charset, boolean append) throws IOException {
if (append) {
return Files.newBufferedWriter(self, Charset.forName(charset), CREATE, APPEND);
}
return Files.newBufferedWriter(self, Charset.forName(charset));
} | java | public static BufferedWriter newWriter(Path self, String charset, boolean append) throws IOException {
if (append) {
return Files.newBufferedWriter(self, Charset.forName(charset), CREATE, APPEND);
}
return Files.newBufferedWriter(self, Charset.forName(charset));
} | [
"public",
"static",
"BufferedWriter",
"newWriter",
"(",
"Path",
"self",
",",
"String",
"charset",
",",
"boolean",
"append",
")",
"throws",
"IOException",
"{",
"if",
"(",
"append",
")",
"{",
"return",
"Files",
".",
"newBufferedWriter",
"(",
"self",
",",
"Char... | Helper method to create a buffered writer for a file. If the given
charset is "UTF-16BE" or "UTF-16LE", the requisite byte order mark is
written to the stream before the writer is returned.
@param self a Path
@param charset the name of the encoding used to write in this file
@param append true if in append mode
@return a BufferedWriter
@throws java.io.IOException if an IOException occurs.
@since 2.3.0 | [
"Helper",
"method",
"to",
"create",
"a",
"buffered",
"writer",
"for",
"a",
"file",
".",
"If",
"the",
"given",
"charset",
"is",
"UTF",
"-",
"16BE",
"or",
"UTF",
"-",
"16LE",
"the",
"requisite",
"byte",
"order",
"mark",
"is",
"written",
"to",
"the",
"str... | train | https://github.com/groovy/groovy-core/blob/01309f9d4be34ddf93c4a9943b5a97843bff6181/subprojects/groovy-nio/src/main/java/org/codehaus/groovy/runtime/NioGroovyMethods.java#L1480-L1485 |
kite-sdk/kite | kite-tools-parent/kite-tools/src/main/java/org/kitesdk/tools/JobClasspathHelper.java | JobClasspathHelper.createMd5SumFile | private void createMd5SumFile(FileSystem fs, String md5sum, Path remoteMd5Path) throws IOException {
FSDataOutputStream os = null;
try {
os = fs.create(remoteMd5Path, true);
os.writeBytes(md5sum);
os.flush();
} catch (Exception e) {
LOG.error("{}", e);
} finally {
if (os != null) {
os.close();
}
}
} | java | private void createMd5SumFile(FileSystem fs, String md5sum, Path remoteMd5Path) throws IOException {
FSDataOutputStream os = null;
try {
os = fs.create(remoteMd5Path, true);
os.writeBytes(md5sum);
os.flush();
} catch (Exception e) {
LOG.error("{}", e);
} finally {
if (os != null) {
os.close();
}
}
} | [
"private",
"void",
"createMd5SumFile",
"(",
"FileSystem",
"fs",
",",
"String",
"md5sum",
",",
"Path",
"remoteMd5Path",
")",
"throws",
"IOException",
"{",
"FSDataOutputStream",
"os",
"=",
"null",
";",
"try",
"{",
"os",
"=",
"fs",
".",
"create",
"(",
"remoteMd... | This method creates an file that contains a line with a MD5 sum
@param fs
FileSystem where to create the file.
@param md5sum
The string containing the MD5 sum.
@param remoteMd5Path
The path where to save the file.
@throws IOException | [
"This",
"method",
"creates",
"an",
"file",
"that",
"contains",
"a",
"line",
"with",
"a",
"MD5",
"sum"
] | train | https://github.com/kite-sdk/kite/blob/72bfb4b1a881af85808cd7f14bc3e15160a1e811/kite-tools-parent/kite-tools/src/main/java/org/kitesdk/tools/JobClasspathHelper.java#L231-L244 |
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/ExtendedServerBlobAuditingPoliciesInner.java | ExtendedServerBlobAuditingPoliciesInner.createOrUpdateAsync | public Observable<ExtendedServerBlobAuditingPolicyInner> createOrUpdateAsync(String resourceGroupName, String serverName, ExtendedServerBlobAuditingPolicyInner parameters) {
return createOrUpdateWithServiceResponseAsync(resourceGroupName, serverName, parameters).map(new Func1<ServiceResponse<ExtendedServerBlobAuditingPolicyInner>, ExtendedServerBlobAuditingPolicyInner>() {
@Override
public ExtendedServerBlobAuditingPolicyInner call(ServiceResponse<ExtendedServerBlobAuditingPolicyInner> response) {
return response.body();
}
});
} | java | public Observable<ExtendedServerBlobAuditingPolicyInner> createOrUpdateAsync(String resourceGroupName, String serverName, ExtendedServerBlobAuditingPolicyInner parameters) {
return createOrUpdateWithServiceResponseAsync(resourceGroupName, serverName, parameters).map(new Func1<ServiceResponse<ExtendedServerBlobAuditingPolicyInner>, ExtendedServerBlobAuditingPolicyInner>() {
@Override
public ExtendedServerBlobAuditingPolicyInner call(ServiceResponse<ExtendedServerBlobAuditingPolicyInner> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"ExtendedServerBlobAuditingPolicyInner",
">",
"createOrUpdateAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"serverName",
",",
"ExtendedServerBlobAuditingPolicyInner",
"parameters",
")",
"{",
"return",
"createOrUpdateWithServiceResponseAsy... | Creates or updates an extended server's blob auditing policy.
@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 parameters Properties of extended blob auditing policy
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable for the request | [
"Creates",
"or",
"updates",
"an",
"extended",
"server",
"s",
"blob",
"auditing",
"policy",
"."
] | 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/ExtendedServerBlobAuditingPoliciesInner.java#L196-L203 |
aws/aws-sdk-java | jmespath-java/src/main/java/com/amazonaws/jmespath/JmesPathEvaluationVisitor.java | JmesPathEvaluationVisitor.visit | @Override
public JsonNode visit(JmesPathField fieldNode, JsonNode input) {
if (input.isObject()) {
//TODO : CamelCase will need to change at some point
return input.get(CamelCaseUtils.toCamelCase(fieldNode.getValue()));
}
return NullNode.getInstance();
} | java | @Override
public JsonNode visit(JmesPathField fieldNode, JsonNode input) {
if (input.isObject()) {
//TODO : CamelCase will need to change at some point
return input.get(CamelCaseUtils.toCamelCase(fieldNode.getValue()));
}
return NullNode.getInstance();
} | [
"@",
"Override",
"public",
"JsonNode",
"visit",
"(",
"JmesPathField",
"fieldNode",
",",
"JsonNode",
"input",
")",
"{",
"if",
"(",
"input",
".",
"isObject",
"(",
")",
")",
"{",
"//TODO : CamelCase will need to change at some point",
"return",
"input",
".",
"get",
... | Retrieves the value of the field node
@param fieldNode JmesPath field type
@param input Input json node whose value is
retrieved
@return Value of the input json node | [
"Retrieves",
"the",
"value",
"of",
"the",
"field",
"node"
] | train | https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/jmespath-java/src/main/java/com/amazonaws/jmespath/JmesPathEvaluationVisitor.java#L56-L63 |
craterdog/java-security-framework | java-certificate-management-api/src/main/java/craterdog/security/CertificateManager.java | CertificateManager.retrievePrivateKey | public final PrivateKey retrievePrivateKey(KeyStore keyStore, String keyName, char[] password) {
try {
logger.entry();
PrivateKey privateKey = (PrivateKey) keyStore.getKey(keyName, password);
logger.exit();
return privateKey;
} catch (KeyStoreException | NoSuchAlgorithmException | UnrecoverableKeyException e) {
RuntimeException exception = new RuntimeException("An unexpected exception occurred while attempting to retrieve a private key.", e);
logger.error(exception.toString());
throw exception;
}
} | java | public final PrivateKey retrievePrivateKey(KeyStore keyStore, String keyName, char[] password) {
try {
logger.entry();
PrivateKey privateKey = (PrivateKey) keyStore.getKey(keyName, password);
logger.exit();
return privateKey;
} catch (KeyStoreException | NoSuchAlgorithmException | UnrecoverableKeyException e) {
RuntimeException exception = new RuntimeException("An unexpected exception occurred while attempting to retrieve a private key.", e);
logger.error(exception.toString());
throw exception;
}
} | [
"public",
"final",
"PrivateKey",
"retrievePrivateKey",
"(",
"KeyStore",
"keyStore",
",",
"String",
"keyName",
",",
"char",
"[",
"]",
"password",
")",
"{",
"try",
"{",
"logger",
".",
"entry",
"(",
")",
";",
"PrivateKey",
"privateKey",
"=",
"(",
"PrivateKey",
... | This method retrieves a private key from a key store.
@param keyStore The key store containing the private key.
@param keyName The name (alias) of the private key.
@param password The password used to encrypt the private key.
@return The decrypted private key. | [
"This",
"method",
"retrieves",
"a",
"private",
"key",
"from",
"a",
"key",
"store",
"."
] | train | https://github.com/craterdog/java-security-framework/blob/a5634c19812d473b608bc11060f5cbb4b4b0b5da/java-certificate-management-api/src/main/java/craterdog/security/CertificateManager.java#L109-L120 |
YahooArchive/samoa | samoa-api/src/main/java/com/yahoo/labs/samoa/learners/classifiers/trees/SplitNode.java | SplitNode.setChild | void setChild(int index, Node child){
if ((this.splitTest.maxBranches() >= 0)
&& (index >= this.splitTest.maxBranches())) {
throw new IndexOutOfBoundsException();
}
this.children.set(index, child);
} | java | void setChild(int index, Node child){
if ((this.splitTest.maxBranches() >= 0)
&& (index >= this.splitTest.maxBranches())) {
throw new IndexOutOfBoundsException();
}
this.children.set(index, child);
} | [
"void",
"setChild",
"(",
"int",
"index",
",",
"Node",
"child",
")",
"{",
"if",
"(",
"(",
"this",
".",
"splitTest",
".",
"maxBranches",
"(",
")",
">=",
"0",
")",
"&&",
"(",
"index",
">=",
"this",
".",
"splitTest",
".",
"maxBranches",
"(",
")",
")",
... | Method to set the children in a specific index of the SplitNode with the appropriate child
@param index Index of the child in the SplitNode
@param child The child node | [
"Method",
"to",
"set",
"the",
"children",
"in",
"a",
"specific",
"index",
"of",
"the",
"SplitNode",
"with",
"the",
"appropriate",
"child"
] | train | https://github.com/YahooArchive/samoa/blob/540a2c30167ac85c432b593baabd5ca97e7e8a0f/samoa-api/src/main/java/com/yahoo/labs/samoa/learners/classifiers/trees/SplitNode.java#L83-L89 |
apereo/cas | support/cas-server-support-hazelcast-core/src/main/java/org/apereo/cas/hz/HazelcastConfigurationFactory.java | HazelcastConfigurationFactory.buildMapConfig | public MapConfig buildMapConfig(final BaseHazelcastProperties hz, final String mapName, final long timeoutSeconds) {
val cluster = hz.getCluster();
val evictionPolicy = EvictionPolicy.valueOf(cluster.getEvictionPolicy());
LOGGER.trace("Creating Hazelcast map configuration for [{}] with idle timeoutSeconds [{}] second(s)", mapName, timeoutSeconds);
val maxSizeConfig = new MaxSizeConfig()
.setMaxSizePolicy(MaxSizeConfig.MaxSizePolicy.valueOf(cluster.getMaxSizePolicy()))
.setSize(cluster.getMaxHeapSizePercentage());
val mergePolicyConfig = new MergePolicyConfig();
if (StringUtils.hasText(cluster.getMapMergePolicy())) {
mergePolicyConfig.setPolicy(cluster.getMapMergePolicy());
}
return new MapConfig()
.setName(mapName)
.setMergePolicyConfig(mergePolicyConfig)
.setMaxIdleSeconds((int) timeoutSeconds)
.setBackupCount(cluster.getBackupCount())
.setAsyncBackupCount(cluster.getAsyncBackupCount())
.setEvictionPolicy(evictionPolicy)
.setMaxSizeConfig(maxSizeConfig);
} | java | public MapConfig buildMapConfig(final BaseHazelcastProperties hz, final String mapName, final long timeoutSeconds) {
val cluster = hz.getCluster();
val evictionPolicy = EvictionPolicy.valueOf(cluster.getEvictionPolicy());
LOGGER.trace("Creating Hazelcast map configuration for [{}] with idle timeoutSeconds [{}] second(s)", mapName, timeoutSeconds);
val maxSizeConfig = new MaxSizeConfig()
.setMaxSizePolicy(MaxSizeConfig.MaxSizePolicy.valueOf(cluster.getMaxSizePolicy()))
.setSize(cluster.getMaxHeapSizePercentage());
val mergePolicyConfig = new MergePolicyConfig();
if (StringUtils.hasText(cluster.getMapMergePolicy())) {
mergePolicyConfig.setPolicy(cluster.getMapMergePolicy());
}
return new MapConfig()
.setName(mapName)
.setMergePolicyConfig(mergePolicyConfig)
.setMaxIdleSeconds((int) timeoutSeconds)
.setBackupCount(cluster.getBackupCount())
.setAsyncBackupCount(cluster.getAsyncBackupCount())
.setEvictionPolicy(evictionPolicy)
.setMaxSizeConfig(maxSizeConfig);
} | [
"public",
"MapConfig",
"buildMapConfig",
"(",
"final",
"BaseHazelcastProperties",
"hz",
",",
"final",
"String",
"mapName",
",",
"final",
"long",
"timeoutSeconds",
")",
"{",
"val",
"cluster",
"=",
"hz",
".",
"getCluster",
"(",
")",
";",
"val",
"evictionPolicy",
... | Build map config map config.
@param hz the hz
@param mapName the storage name
@param timeoutSeconds the timeoutSeconds
@return the map config | [
"Build",
"map",
"config",
"map",
"config",
"."
] | train | https://github.com/apereo/cas/blob/b4b306433a8782cef803a39bea5b1f96740e0e9b/support/cas-server-support-hazelcast-core/src/main/java/org/apereo/cas/hz/HazelcastConfigurationFactory.java#L49-L71 |
acromusashi/acromusashi-stream | src/main/java/acromusashi/stream/util/TimeIntervalFormatUtil.java | TimeIntervalFormatUtil.generateDatumTime | public static long generateDatumTime(long initializeTime, TimeUnit unit) throws ParseException
{
// 初期に生成するファイル名称を基準となる値にするため、ファイル切替インターバル(単位)より1つ大きな単位を取得し
// 1つ大きな単位をベースに時刻を算出する。
// 例:10分間隔であれば「0.10.20....」というのが基準となる値。
SimpleDateFormat parentDateFormat = new SimpleDateFormat(
TimeUnitUtil.getDatePattern(TimeUnitUtil.getParentUnit(unit)));
// 1つ大きな単位をベースに基準時刻を取得し、初期生成ファイル名称用の日時を算出する。
// 例:10分間隔をインターバルとし、8:35を起動時刻とした場合、8:00を基準時刻とする。
String datumTimeString = parentDateFormat.format(new Date(initializeTime));
long datumTime = parentDateFormat.parse(datumTimeString).getTime();
return datumTime;
} | java | public static long generateDatumTime(long initializeTime, TimeUnit unit) throws ParseException
{
// 初期に生成するファイル名称を基準となる値にするため、ファイル切替インターバル(単位)より1つ大きな単位を取得し
// 1つ大きな単位をベースに時刻を算出する。
// 例:10分間隔であれば「0.10.20....」というのが基準となる値。
SimpleDateFormat parentDateFormat = new SimpleDateFormat(
TimeUnitUtil.getDatePattern(TimeUnitUtil.getParentUnit(unit)));
// 1つ大きな単位をベースに基準時刻を取得し、初期生成ファイル名称用の日時を算出する。
// 例:10分間隔をインターバルとし、8:35を起動時刻とした場合、8:00を基準時刻とする。
String datumTimeString = parentDateFormat.format(new Date(initializeTime));
long datumTime = parentDateFormat.parse(datumTimeString).getTime();
return datumTime;
} | [
"public",
"static",
"long",
"generateDatumTime",
"(",
"long",
"initializeTime",
",",
"TimeUnit",
"unit",
")",
"throws",
"ParseException",
"{",
"// 初期に生成するファイル名称を基準となる値にするため、ファイル切替インターバル(単位)より1つ大きな単位を取得し\r",
"// 1つ大きな単位をベースに時刻を算出する。\r",
"// 例:10分間隔であれば「0.10.20....」というのが基準となる値。\r",
"... | 指定した初期化時刻と切替単位を基に、整時用の基準時刻(long値)を取得する。
@param initializeTime 初期化時刻
@param unit 切替単位
@return 整時用の基準時刻(long値)
@throws ParseException パース失敗時 | [
"指定した初期化時刻と切替単位を基に、整時用の基準時刻",
"(",
"long値",
")",
"を取得する。"
] | train | https://github.com/acromusashi/acromusashi-stream/blob/65b1f335d771d657c5640a2056ab5c8546eddec9/src/main/java/acromusashi/stream/util/TimeIntervalFormatUtil.java#L104-L118 |
moleculer-java/moleculer-java | src/main/java/services/moleculer/cacher/Cacher.java | Cacher.getCacheKey | public String getCacheKey(String name, Tree params, String... keys) {
if (params == null) {
return name;
}
StringBuilder key = new StringBuilder(128);
key.append(name);
key.append(':');
serializeKey(key, params, keys);
return key.toString();
} | java | public String getCacheKey(String name, Tree params, String... keys) {
if (params == null) {
return name;
}
StringBuilder key = new StringBuilder(128);
key.append(name);
key.append(':');
serializeKey(key, params, keys);
return key.toString();
} | [
"public",
"String",
"getCacheKey",
"(",
"String",
"name",
",",
"Tree",
"params",
",",
"String",
"...",
"keys",
")",
"{",
"if",
"(",
"params",
"==",
"null",
")",
"{",
"return",
"name",
";",
"}",
"StringBuilder",
"key",
"=",
"new",
"StringBuilder",
"(",
... | Creates a cacher-specific key by name and params. Concatenates the name
and params.
@param name
qualified name of the action
@param params
input (key) structure (~JSON)
@param keys
optional array of keys (eg. "id")
@return generated cache key | [
"Creates",
"a",
"cacher",
"-",
"specific",
"key",
"by",
"name",
"and",
"params",
".",
"Concatenates",
"the",
"name",
"and",
"params",
"."
] | train | https://github.com/moleculer-java/moleculer-java/blob/27575c44b9ecacc17c4456ceacf5d1851abf1cc4/src/main/java/services/moleculer/cacher/Cacher.java#L123-L132 |
b3dgs/lionengine | lionengine-core/src/main/java/com/b3dgs/lionengine/graphic/drawable/Drawable.java | Drawable.loadSpriteFont | public static SpriteFont loadSpriteFont(Media media, Media data, int letterWidth, int letterHeight)
{
return new SpriteFontImpl(getMediaDpi(media), data, letterWidth, letterHeight);
} | java | public static SpriteFont loadSpriteFont(Media media, Media data, int letterWidth, int letterHeight)
{
return new SpriteFontImpl(getMediaDpi(media), data, letterWidth, letterHeight);
} | [
"public",
"static",
"SpriteFont",
"loadSpriteFont",
"(",
"Media",
"media",
",",
"Media",
"data",
",",
"int",
"letterWidth",
",",
"int",
"letterHeight",
")",
"{",
"return",
"new",
"SpriteFontImpl",
"(",
"getMediaDpi",
"(",
"media",
")",
",",
"data",
",",
"let... | Load a font based on an image.
<p>
Once created, sprite must call {@link SpriteFont#load()} before any other operations.
</p>
@param media The font sprite media (must not be <code>null</code>).
@param data The font data media (must not be <code>null</code>).
@param letterWidth The font image letter width (must be strictly positive).
@param letterHeight The font image letter height (must be strictly positive).
@return The created font sprite.
@throws LionEngineException If an error occurred when creating the font. | [
"Load",
"a",
"font",
"based",
"on",
"an",
"image",
".",
"<p",
">",
"Once",
"created",
"sprite",
"must",
"call",
"{",
"@link",
"SpriteFont#load",
"()",
"}",
"before",
"any",
"other",
"operations",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/b3dgs/lionengine/blob/cac3d5578532cf11724a737b9f09e71bf9995ab2/lionengine-core/src/main/java/com/b3dgs/lionengine/graphic/drawable/Drawable.java#L268-L271 |
facebookarchive/swift | swift-service/src/main/java/com/facebook/swift/service/ThriftClientManager.java | ThriftClientManager.getNiftyChannel | public NiftyClientChannel getNiftyChannel(Object client)
{
try {
return NiftyClientChannel.class.cast(getRequestChannel(client));
}
catch (ClassCastException e) {
throw new IllegalArgumentException("The swift client uses a channel that is not a NiftyClientChannel", e);
}
} | java | public NiftyClientChannel getNiftyChannel(Object client)
{
try {
return NiftyClientChannel.class.cast(getRequestChannel(client));
}
catch (ClassCastException e) {
throw new IllegalArgumentException("The swift client uses a channel that is not a NiftyClientChannel", e);
}
} | [
"public",
"NiftyClientChannel",
"getNiftyChannel",
"(",
"Object",
"client",
")",
"{",
"try",
"{",
"return",
"NiftyClientChannel",
".",
"class",
".",
"cast",
"(",
"getRequestChannel",
"(",
"client",
")",
")",
";",
"}",
"catch",
"(",
"ClassCastException",
"e",
"... | Returns the {@link NiftyClientChannel} backing a Swift client
@throws IllegalArgumentException if the client is not using a {@link com.facebook.nifty.client.NiftyClientChannel}
@deprecated Use {@link #getRequestChannel} instead, and cast the result to a {@link NiftyClientChannel} if necessary | [
"Returns",
"the",
"{",
"@link",
"NiftyClientChannel",
"}",
"backing",
"a",
"Swift",
"client"
] | train | https://github.com/facebookarchive/swift/blob/3f1f098a50d6106f50cd6fe1c361dd373ede0197/swift-service/src/main/java/com/facebook/swift/service/ThriftClientManager.java#L319-L327 |
teatrove/teatrove | teaapps/src/main/java/org/teatrove/teaapps/contexts/ArrayContext.java | ArrayContext.setArrayElement | public void setArrayElement(Object array, int index, Object value) {
Array.set(array, index, value);
} | java | public void setArrayElement(Object array, int index, Object value) {
Array.set(array, index, value);
} | [
"public",
"void",
"setArrayElement",
"(",
"Object",
"array",
",",
"int",
"index",
",",
"Object",
"value",
")",
"{",
"Array",
".",
"set",
"(",
"array",
",",
"index",
",",
"value",
")",
";",
"}"
] | Set the element at the given index in the given array. This is a helper
method for {@link Array#set(Object, int, Object)}. If the given array is
not an array, then {@link IllegalArgumentException} is thrown. If the
given index is out of bounds, then {@link ArrayIndexOutOfBoundsException}
is thrown. Note that if the component type of the array is a primitive,
then the value will be unwrapped. This may result in a
{@link NullPointerException} being thrown.
@param array The array to set the element to
@param index The index of the array to set
@param value The value of the array to set | [
"Set",
"the",
"element",
"at",
"the",
"given",
"index",
"in",
"the",
"given",
"array",
".",
"This",
"is",
"a",
"helper",
"method",
"for",
"{",
"@link",
"Array#set",
"(",
"Object",
"int",
"Object",
")",
"}",
".",
"If",
"the",
"given",
"array",
"is",
"... | train | https://github.com/teatrove/teatrove/blob/7039bdd4da6817ff8c737f7e4e07bac7e3ad8bea/teaapps/src/main/java/org/teatrove/teaapps/contexts/ArrayContext.java#L204-L206 |
netty/netty | codec-http/src/main/java/io/netty/handler/codec/http/HttpHeaders.java | HttpHeaders.getDate | @Deprecated
public static Date getDate(HttpMessage message) throws ParseException {
return getDateHeader(message, HttpHeaderNames.DATE);
} | java | @Deprecated
public static Date getDate(HttpMessage message) throws ParseException {
return getDateHeader(message, HttpHeaderNames.DATE);
} | [
"@",
"Deprecated",
"public",
"static",
"Date",
"getDate",
"(",
"HttpMessage",
"message",
")",
"throws",
"ParseException",
"{",
"return",
"getDateHeader",
"(",
"message",
",",
"HttpHeaderNames",
".",
"DATE",
")",
";",
"}"
] | @deprecated Use {@link #getTimeMillis(CharSequence)} instead.
Returns the value of the {@code "Date"} header.
@throws ParseException
if there is no such header or the header value is not a formatted date | [
"@deprecated",
"Use",
"{",
"@link",
"#getTimeMillis",
"(",
"CharSequence",
")",
"}",
"instead",
"."
] | train | https://github.com/netty/netty/blob/ba06eafa1c1824bd154f1a380019e7ea2edf3c4c/codec-http/src/main/java/io/netty/handler/codec/http/HttpHeaders.java#L1047-L1050 |
tango-controls/JTango | server/src/main/java/org/tango/server/events/EventManager.java | EventManager.checkEventCriteria | public static void checkEventCriteria(final AttributeImpl attribute, final EventType eventType) throws DevFailed {
switch (eventType) {
case CHANGE_EVENT:
ChangeEventTrigger.checkEventCriteria(attribute);
break;
case ARCHIVE_EVENT:
ArchiveEventTrigger.checkEventCriteria(attribute);
break;
default:
break;
}
} | java | public static void checkEventCriteria(final AttributeImpl attribute, final EventType eventType) throws DevFailed {
switch (eventType) {
case CHANGE_EVENT:
ChangeEventTrigger.checkEventCriteria(attribute);
break;
case ARCHIVE_EVENT:
ArchiveEventTrigger.checkEventCriteria(attribute);
break;
default:
break;
}
} | [
"public",
"static",
"void",
"checkEventCriteria",
"(",
"final",
"AttributeImpl",
"attribute",
",",
"final",
"EventType",
"eventType",
")",
"throws",
"DevFailed",
"{",
"switch",
"(",
"eventType",
")",
"{",
"case",
"CHANGE_EVENT",
":",
"ChangeEventTrigger",
".",
"ch... | Check if event criteria are set for change and archive events
@param attribute the specified attribute
@param eventType the specified event type
@throws DevFailed if event type is change or archive and no event criteria is set. | [
"Check",
"if",
"event",
"criteria",
"are",
"set",
"for",
"change",
"and",
"archive",
"events"
] | train | https://github.com/tango-controls/JTango/blob/1ccc9dcb83e6de2359a9f1906d170571cacf1345/server/src/main/java/org/tango/server/events/EventManager.java#L137-L148 |
opengeospatial/teamengine | teamengine-core/src/main/java/com/occamlab/te/parsers/ImageParser.java | ImageParser.parseBase64 | public static Document parseBase64(String base64Data, Element instruction)
throws Exception {
byte[] imageData = Base64.decodeBase64(base64Data);
ByteArrayInputStream bais = new ByteArrayInputStream(imageData);
StringWriter swLogger = new StringWriter();
PrintWriter pwLogger = new PrintWriter(swLogger);
return parse(bais, instruction, pwLogger);
} | java | public static Document parseBase64(String base64Data, Element instruction)
throws Exception {
byte[] imageData = Base64.decodeBase64(base64Data);
ByteArrayInputStream bais = new ByteArrayInputStream(imageData);
StringWriter swLogger = new StringWriter();
PrintWriter pwLogger = new PrintWriter(swLogger);
return parse(bais, instruction, pwLogger);
} | [
"public",
"static",
"Document",
"parseBase64",
"(",
"String",
"base64Data",
",",
"Element",
"instruction",
")",
"throws",
"Exception",
"{",
"byte",
"[",
"]",
"imageData",
"=",
"Base64",
".",
"decodeBase64",
"(",
"base64Data",
")",
";",
"ByteArrayInputStream",
"b... | /*
Parse a string of base64 encoded image data. 2011-09-08 PwD | [
"/",
"*",
"Parse",
"a",
"string",
"of",
"base64",
"encoded",
"image",
"data",
".",
"2011",
"-",
"09",
"-",
"08",
"PwD"
] | train | https://github.com/opengeospatial/teamengine/blob/b6b890214b6784bbe19460bf753bdf28a9514bee/teamengine-core/src/main/java/com/occamlab/te/parsers/ImageParser.java#L707-L714 |
netty/netty | codec-http/src/main/java/io/netty/handler/codec/http/HttpHeaders.java | HttpHeaders.getDateHeader | @Deprecated
public static Date getDateHeader(HttpMessage message, String name) throws ParseException {
return getDateHeader(message, (CharSequence) name);
} | java | @Deprecated
public static Date getDateHeader(HttpMessage message, String name) throws ParseException {
return getDateHeader(message, (CharSequence) name);
} | [
"@",
"Deprecated",
"public",
"static",
"Date",
"getDateHeader",
"(",
"HttpMessage",
"message",
",",
"String",
"name",
")",
"throws",
"ParseException",
"{",
"return",
"getDateHeader",
"(",
"message",
",",
"(",
"CharSequence",
")",
"name",
")",
";",
"}"
] | @deprecated Use {@link #getTimeMillis(CharSequence)} instead.
@see #getDateHeader(HttpMessage, CharSequence) | [
"@deprecated",
"Use",
"{",
"@link",
"#getTimeMillis",
"(",
"CharSequence",
")",
"}",
"instead",
"."
] | train | https://github.com/netty/netty/blob/ba06eafa1c1824bd154f1a380019e7ea2edf3c4c/codec-http/src/main/java/io/netty/handler/codec/http/HttpHeaders.java#L826-L829 |
jboss/jboss-jstl-api_spec | src/main/java/org/apache/taglibs/standard/tag/common/fmt/SetLocaleSupport.java | SetLocaleSupport.findFormattingMatch | private static Locale findFormattingMatch(Locale pref, Locale[] avail) {
Locale match = null;
boolean langAndCountryMatch = false;
for (Locale locale : avail) {
if (pref.equals(locale)) {
// Exact match
match = locale;
break;
} else if (
!"".equals(pref.getVariant()) &&
"".equals(locale.getVariant()) &&
pref.getLanguage().equals(locale.getLanguage()) &&
pref.getCountry().equals(locale.getCountry())) {
// Language and country match; different variant
match = locale;
langAndCountryMatch = true;
} else if (
!langAndCountryMatch &&
pref.getLanguage().equals(locale.getLanguage()) &&
("".equals(locale.getCountry()))) {
// Language match
if (match == null) {
match = locale;
}
}
}
return match;
} | java | private static Locale findFormattingMatch(Locale pref, Locale[] avail) {
Locale match = null;
boolean langAndCountryMatch = false;
for (Locale locale : avail) {
if (pref.equals(locale)) {
// Exact match
match = locale;
break;
} else if (
!"".equals(pref.getVariant()) &&
"".equals(locale.getVariant()) &&
pref.getLanguage().equals(locale.getLanguage()) &&
pref.getCountry().equals(locale.getCountry())) {
// Language and country match; different variant
match = locale;
langAndCountryMatch = true;
} else if (
!langAndCountryMatch &&
pref.getLanguage().equals(locale.getLanguage()) &&
("".equals(locale.getCountry()))) {
// Language match
if (match == null) {
match = locale;
}
}
}
return match;
} | [
"private",
"static",
"Locale",
"findFormattingMatch",
"(",
"Locale",
"pref",
",",
"Locale",
"[",
"]",
"avail",
")",
"{",
"Locale",
"match",
"=",
"null",
";",
"boolean",
"langAndCountryMatch",
"=",
"false",
";",
"for",
"(",
"Locale",
"locale",
":",
"avail",
... | /*
Returns the best match between the given preferred locale and the
given available locales.
The best match is given as the first available locale that exactly
matches the given preferred locale ("exact match"). If no exact match
exists, the best match is given to an available locale that meets
the following criteria (in order of priority):
- available locale's variant is empty and exact match for both
language and country
- available locale's variant and country are empty, and exact match
for language.
@param pref the preferred locale
@param avail the available formatting locales
@return Available locale that best matches the given preferred locale,
or <tt>null</tt> if no match exists | [
"/",
"*",
"Returns",
"the",
"best",
"match",
"between",
"the",
"given",
"preferred",
"locale",
"and",
"the",
"given",
"available",
"locales",
"."
] | train | https://github.com/jboss/jboss-jstl-api_spec/blob/4ad412ae5be1ae606b8d33c188cb3d98bfcbe84c/src/main/java/org/apache/taglibs/standard/tag/common/fmt/SetLocaleSupport.java#L373-L400 |
Deep-Symmetry/beat-link | src/main/java/org/deepsymmetry/beatlink/Util.java | Util.numberToBytes | public static void numberToBytes(int number, byte[] buffer, int start, int length) {
for (int index = start + length - 1; index >= start; index--) {
buffer[index] = (byte)(number & 0xff);
number = number >> 8;
}
} | java | public static void numberToBytes(int number, byte[] buffer, int start, int length) {
for (int index = start + length - 1; index >= start; index--) {
buffer[index] = (byte)(number & 0xff);
number = number >> 8;
}
} | [
"public",
"static",
"void",
"numberToBytes",
"(",
"int",
"number",
",",
"byte",
"[",
"]",
"buffer",
",",
"int",
"start",
",",
"int",
"length",
")",
"{",
"for",
"(",
"int",
"index",
"=",
"start",
"+",
"length",
"-",
"1",
";",
"index",
">=",
"start",
... | Writes a number to the specified byte array field, breaking it into its component bytes in big-endian order.
If the number is too large to fit in the specified number of bytes, only the low-order bytes are written.
@param number the number to be written to the array
@param buffer the buffer to which the number should be written
@param start where the high-order byte should be written
@param length how many bytes of the number should be written | [
"Writes",
"a",
"number",
"to",
"the",
"specified",
"byte",
"array",
"field",
"breaking",
"it",
"into",
"its",
"component",
"bytes",
"in",
"big",
"-",
"endian",
"order",
".",
"If",
"the",
"number",
"is",
"too",
"large",
"to",
"fit",
"in",
"the",
"specifie... | train | https://github.com/Deep-Symmetry/beat-link/blob/f958a2a70e8a87a31a75326d7b4db77c2f0b4212/src/main/java/org/deepsymmetry/beatlink/Util.java#L277-L282 |
google/closure-compiler | src/com/google/javascript/jscomp/SourceMapResolver.java | SourceMapResolver.getRelativePath | @Nullable
static SourceFile getRelativePath(String baseFilePath, String relativePath) {
return SourceFile.fromPath(
FileSystems.getDefault().getPath(baseFilePath).resolveSibling(relativePath).normalize(),
UTF_8);
} | java | @Nullable
static SourceFile getRelativePath(String baseFilePath, String relativePath) {
return SourceFile.fromPath(
FileSystems.getDefault().getPath(baseFilePath).resolveSibling(relativePath).normalize(),
UTF_8);
} | [
"@",
"Nullable",
"static",
"SourceFile",
"getRelativePath",
"(",
"String",
"baseFilePath",
",",
"String",
"relativePath",
")",
"{",
"return",
"SourceFile",
".",
"fromPath",
"(",
"FileSystems",
".",
"getDefault",
"(",
")",
".",
"getPath",
"(",
"baseFilePath",
")"... | Returns the relative path, resolved relative to the base path, where the base path is
interpreted as a filename rather than a directory. E.g.: getRelativeTo("../foo/bar.js",
"baz/bam/qux.js") --> "baz/foo/bar.js" | [
"Returns",
"the",
"relative",
"path",
"resolved",
"relative",
"to",
"the",
"base",
"path",
"where",
"the",
"base",
"path",
"is",
"interpreted",
"as",
"a",
"filename",
"rather",
"than",
"a",
"directory",
".",
"E",
".",
"g",
".",
":",
"getRelativeTo",
"(",
... | train | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/SourceMapResolver.java#L99-L104 |
wildfly/wildfly-core | logging/src/main/java/org/jboss/as/logging/deployments/resources/LoggingConfigurationReadStepHandler.java | LoggingConfigurationReadStepHandler.addProperties | static void addProperties(final PropertyConfigurable configuration, final ModelNode model) {
for (String name : configuration.getPropertyNames()) {
setModelValue(model.get(name), configuration.getPropertyValueString(name));
}
} | java | static void addProperties(final PropertyConfigurable configuration, final ModelNode model) {
for (String name : configuration.getPropertyNames()) {
setModelValue(model.get(name), configuration.getPropertyValueString(name));
}
} | [
"static",
"void",
"addProperties",
"(",
"final",
"PropertyConfigurable",
"configuration",
",",
"final",
"ModelNode",
"model",
")",
"{",
"for",
"(",
"String",
"name",
":",
"configuration",
".",
"getPropertyNames",
"(",
")",
")",
"{",
"setModelValue",
"(",
"model"... | Adds properties to the model in key/value pairs.
@param configuration the configuration to get the properties from
@param model the model to update | [
"Adds",
"properties",
"to",
"the",
"model",
"in",
"key",
"/",
"value",
"pairs",
"."
] | train | https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/logging/src/main/java/org/jboss/as/logging/deployments/resources/LoggingConfigurationReadStepHandler.java#L77-L81 |
aws/aws-sdk-java | aws-java-sdk-mediatailor/src/main/java/com/amazonaws/services/mediatailor/model/PlaybackConfiguration.java | PlaybackConfiguration.withTags | public PlaybackConfiguration withTags(java.util.Map<String, String> tags) {
setTags(tags);
return this;
} | java | public PlaybackConfiguration withTags(java.util.Map<String, String> tags) {
setTags(tags);
return this;
} | [
"public",
"PlaybackConfiguration",
"withTags",
"(",
"java",
".",
"util",
".",
"Map",
"<",
"String",
",",
"String",
">",
"tags",
")",
"{",
"setTags",
"(",
"tags",
")",
";",
"return",
"this",
";",
"}"
] | <p>
The tags assigned to the playback configuration.
</p>
@param tags
The tags assigned to the playback configuration.
@return Returns a reference to this object so that method calls can be chained together. | [
"<p",
">",
"The",
"tags",
"assigned",
"to",
"the",
"playback",
"configuration",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-mediatailor/src/main/java/com/amazonaws/services/mediatailor/model/PlaybackConfiguration.java#L560-L563 |
khuxtable/seaglass | src/main/java/com/seaglasslookandfeel/painter/util/ShapeGenerator.java | ShapeGenerator.createSliderThumbContinuous | public Shape createSliderThumbContinuous(final int x, final int y, final int diameter) {
return createEllipseInternal(x, y, diameter, diameter);
} | java | public Shape createSliderThumbContinuous(final int x, final int y, final int diameter) {
return createEllipseInternal(x, y, diameter, diameter);
} | [
"public",
"Shape",
"createSliderThumbContinuous",
"(",
"final",
"int",
"x",
",",
"final",
"int",
"y",
",",
"final",
"int",
"diameter",
")",
"{",
"return",
"createEllipseInternal",
"(",
"x",
",",
"y",
",",
"diameter",
",",
"diameter",
")",
";",
"}"
] | Return a path for a continuous slider thumb's concentric sections.
@param x the X coordinate of the upper-left corner of the section
@param y the Y coordinate of the upper-left corner of the section
@param diameter the diameter of the section
@return a path representing the shape. | [
"Return",
"a",
"path",
"for",
"a",
"continuous",
"slider",
"thumb",
"s",
"concentric",
"sections",
"."
] | train | https://github.com/khuxtable/seaglass/blob/f25ecba622923d7b29b64cb7d6068dd8005989b3/src/main/java/com/seaglasslookandfeel/painter/util/ShapeGenerator.java#L512-L514 |
Netflix/servo | servo-core/src/main/java/com/netflix/servo/util/ThreadCpuStats.java | ThreadCpuStats.printThreadCpuUsages | public void printThreadCpuUsages(OutputStream out, CpuUsageComparator cmp) {
final PrintWriter writer = getPrintWriter(out);
final Map<String, Object> threadCpuUsages = getThreadCpuUsages(cmp);
writer.printf("Time: %s%n%n", new Date((Long) threadCpuUsages.get(CURRENT_TIME)));
final long uptimeMillis = (Long) threadCpuUsages.get(UPTIME_MS);
final long uptimeNanos = TimeUnit.NANOSECONDS.convert(uptimeMillis, TimeUnit.MILLISECONDS);
writer.printf("Uptime: %s%n%n", toDuration(uptimeNanos));
@SuppressWarnings("unchecked")
final Map<String, Long> jvmUsageTime = (Map<String, Long>)
threadCpuUsages.get(JVM_USAGE_TIME);
writer.println("JVM Usage Time: ");
writer.printf("%11s %11s %11s %11s %7s %s%n",
"1-min", "5-min", "15-min", "overall", "id", "name");
writer.printf("%11s %11s %11s %11s %7s %s%n",
toDuration(jvmUsageTime.get(ONE_MIN)),
toDuration(jvmUsageTime.get(FIVE_MIN)),
toDuration(jvmUsageTime.get(FIFTEEN_MIN)),
toDuration(jvmUsageTime.get(OVERALL)),
"-",
"jvm");
writer.println();
@SuppressWarnings("unchecked")
final Map<String, Double> jvmUsagePerc =
(Map<String, Double>) threadCpuUsages.get(JVM_USAGE_PERCENT);
writer.println("JVM Usage Percent: ");
writer.printf("%11s %11s %11s %11s %7s %s%n",
"1-min", "5-min", "15-min", "overall", "id", "name");
writer.printf("%10.2f%% %10.2f%% %10.2f%% %10.2f%% %7s %s%n",
jvmUsagePerc.get(ONE_MIN),
jvmUsagePerc.get(FIVE_MIN),
jvmUsagePerc.get(FIFTEEN_MIN),
jvmUsagePerc.get(OVERALL),
"-",
"jvm");
writer.println();
writer.println("Breakdown by thread (100% = total cpu usage for jvm):");
writer.printf("%11s %11s %11s %11s %7s %s%n",
"1-min", "5-min", "15-min", "overall", "id", "name");
@SuppressWarnings("unchecked")
List<Map<String, Object>> threads =
(List<Map<String, Object>>) threadCpuUsages.get(THREADS);
for (Map<String, Object> thread : threads) {
writer.printf("%10.2f%% %10.2f%% %10.2f%% %10.2f%% %7d %s%n",
thread.get(ONE_MIN),
thread.get(FIVE_MIN),
thread.get(FIFTEEN_MIN),
thread.get(OVERALL),
thread.get(ID),
thread.get(NAME));
}
writer.println();
writer.flush();
} | java | public void printThreadCpuUsages(OutputStream out, CpuUsageComparator cmp) {
final PrintWriter writer = getPrintWriter(out);
final Map<String, Object> threadCpuUsages = getThreadCpuUsages(cmp);
writer.printf("Time: %s%n%n", new Date((Long) threadCpuUsages.get(CURRENT_TIME)));
final long uptimeMillis = (Long) threadCpuUsages.get(UPTIME_MS);
final long uptimeNanos = TimeUnit.NANOSECONDS.convert(uptimeMillis, TimeUnit.MILLISECONDS);
writer.printf("Uptime: %s%n%n", toDuration(uptimeNanos));
@SuppressWarnings("unchecked")
final Map<String, Long> jvmUsageTime = (Map<String, Long>)
threadCpuUsages.get(JVM_USAGE_TIME);
writer.println("JVM Usage Time: ");
writer.printf("%11s %11s %11s %11s %7s %s%n",
"1-min", "5-min", "15-min", "overall", "id", "name");
writer.printf("%11s %11s %11s %11s %7s %s%n",
toDuration(jvmUsageTime.get(ONE_MIN)),
toDuration(jvmUsageTime.get(FIVE_MIN)),
toDuration(jvmUsageTime.get(FIFTEEN_MIN)),
toDuration(jvmUsageTime.get(OVERALL)),
"-",
"jvm");
writer.println();
@SuppressWarnings("unchecked")
final Map<String, Double> jvmUsagePerc =
(Map<String, Double>) threadCpuUsages.get(JVM_USAGE_PERCENT);
writer.println("JVM Usage Percent: ");
writer.printf("%11s %11s %11s %11s %7s %s%n",
"1-min", "5-min", "15-min", "overall", "id", "name");
writer.printf("%10.2f%% %10.2f%% %10.2f%% %10.2f%% %7s %s%n",
jvmUsagePerc.get(ONE_MIN),
jvmUsagePerc.get(FIVE_MIN),
jvmUsagePerc.get(FIFTEEN_MIN),
jvmUsagePerc.get(OVERALL),
"-",
"jvm");
writer.println();
writer.println("Breakdown by thread (100% = total cpu usage for jvm):");
writer.printf("%11s %11s %11s %11s %7s %s%n",
"1-min", "5-min", "15-min", "overall", "id", "name");
@SuppressWarnings("unchecked")
List<Map<String, Object>> threads =
(List<Map<String, Object>>) threadCpuUsages.get(THREADS);
for (Map<String, Object> thread : threads) {
writer.printf("%10.2f%% %10.2f%% %10.2f%% %10.2f%% %7d %s%n",
thread.get(ONE_MIN),
thread.get(FIVE_MIN),
thread.get(FIFTEEN_MIN),
thread.get(OVERALL),
thread.get(ID),
thread.get(NAME));
}
writer.println();
writer.flush();
} | [
"public",
"void",
"printThreadCpuUsages",
"(",
"OutputStream",
"out",
",",
"CpuUsageComparator",
"cmp",
")",
"{",
"final",
"PrintWriter",
"writer",
"=",
"getPrintWriter",
"(",
"out",
")",
";",
"final",
"Map",
"<",
"String",
",",
"Object",
">",
"threadCpuUsages",... | Utility function that dumps the cpu usages for the threads to stdout. Output will be sorted
based on the 1-minute usage from highest to lowest.
@param out stream where output will be written
@param cmp order to use for the results | [
"Utility",
"function",
"that",
"dumps",
"the",
"cpu",
"usages",
"for",
"the",
"threads",
"to",
"stdout",
".",
"Output",
"will",
"be",
"sorted",
"based",
"on",
"the",
"1",
"-",
"minute",
"usage",
"from",
"highest",
"to",
"lowest",
"."
] | train | https://github.com/Netflix/servo/blob/d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815/servo-core/src/main/java/com/netflix/servo/util/ThreadCpuStats.java#L282-L338 |
Alluxio/alluxio | shell/src/main/java/alluxio/cli/fs/command/HelpCommand.java | HelpCommand.printCommandInfo | public static void printCommandInfo(Command command, PrintWriter pw) {
String description =
String.format("%s: %s", command.getCommandName(), command.getDescription());
int width = 80;
try {
width = TerminalFactory.get().getWidth();
} catch (Exception e) {
// In case the terminal factory failed to decide terminal type, use default width
}
HELP_FORMATTER.printWrapped(pw, width, description);
HELP_FORMATTER.printUsage(pw, width, command.getUsage());
if (command.getOptions().getOptions().size() > 0) {
HELP_FORMATTER.printOptions(pw, width, command.getOptions(), HELP_FORMATTER.getLeftPadding(),
HELP_FORMATTER.getDescPadding());
}
} | java | public static void printCommandInfo(Command command, PrintWriter pw) {
String description =
String.format("%s: %s", command.getCommandName(), command.getDescription());
int width = 80;
try {
width = TerminalFactory.get().getWidth();
} catch (Exception e) {
// In case the terminal factory failed to decide terminal type, use default width
}
HELP_FORMATTER.printWrapped(pw, width, description);
HELP_FORMATTER.printUsage(pw, width, command.getUsage());
if (command.getOptions().getOptions().size() > 0) {
HELP_FORMATTER.printOptions(pw, width, command.getOptions(), HELP_FORMATTER.getLeftPadding(),
HELP_FORMATTER.getDescPadding());
}
} | [
"public",
"static",
"void",
"printCommandInfo",
"(",
"Command",
"command",
",",
"PrintWriter",
"pw",
")",
"{",
"String",
"description",
"=",
"String",
".",
"format",
"(",
"\"%s: %s\"",
",",
"command",
".",
"getCommandName",
"(",
")",
",",
"command",
".",
"ge... | Prints the info about a command to the given print writer.
@param command command to print info
@param pw where to print the info | [
"Prints",
"the",
"info",
"about",
"a",
"command",
"to",
"the",
"given",
"print",
"writer",
"."
] | train | https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/shell/src/main/java/alluxio/cli/fs/command/HelpCommand.java#L46-L62 |
spring-projects/spring-boot | spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/json-shade/java/org/springframework/boot/configurationprocessor/json/JSONObject.java | JSONObject.optDouble | public double optDouble(String name, double fallback) {
Object object = opt(name);
Double result = JSON.toDouble(object);
return result != null ? result : fallback;
} | java | public double optDouble(String name, double fallback) {
Object object = opt(name);
Double result = JSON.toDouble(object);
return result != null ? result : fallback;
} | [
"public",
"double",
"optDouble",
"(",
"String",
"name",
",",
"double",
"fallback",
")",
"{",
"Object",
"object",
"=",
"opt",
"(",
"name",
")",
";",
"Double",
"result",
"=",
"JSON",
".",
"toDouble",
"(",
"object",
")",
";",
"return",
"result",
"!=",
"nu... | Returns the value mapped by {@code name} if it exists and is a double or can be
coerced to a double. Returns {@code fallback} otherwise.
@param name the name of the property
@param fallback a fallback value
@return the value or {@code fallback} | [
"Returns",
"the",
"value",
"mapped",
"by",
"{"
] | train | https://github.com/spring-projects/spring-boot/blob/0b27f7c70e164b2b1a96477f1d9c1acba56790c1/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/json-shade/java/org/springframework/boot/configurationprocessor/json/JSONObject.java#L465-L469 |
jmxtrans/jmxtrans | jmxtrans-core/src/main/java/com/googlecode/jmxtrans/model/naming/StringUtils.java | StringUtils.cleanupStr | public static String cleanupStr(String name, boolean allowDottedKeys) {
if (name == null) {
return null;
}
Pattern pattern;
if (!allowDottedKeys) {
pattern = DOT_SLASH_UNDERSCORE_PAT;
} else {
pattern = SLASH_UNDERSCORE_PAT;
}
String clean = pattern.matcher(name).replaceAll("_");
clean = SPACE_PAT.matcher(clean).replaceAll("");
clean = org.apache.commons.lang.StringUtils.chomp(clean, ".");
clean = org.apache.commons.lang.StringUtils.chomp(clean, "_");
return clean;
} | java | public static String cleanupStr(String name, boolean allowDottedKeys) {
if (name == null) {
return null;
}
Pattern pattern;
if (!allowDottedKeys) {
pattern = DOT_SLASH_UNDERSCORE_PAT;
} else {
pattern = SLASH_UNDERSCORE_PAT;
}
String clean = pattern.matcher(name).replaceAll("_");
clean = SPACE_PAT.matcher(clean).replaceAll("");
clean = org.apache.commons.lang.StringUtils.chomp(clean, ".");
clean = org.apache.commons.lang.StringUtils.chomp(clean, "_");
return clean;
} | [
"public",
"static",
"String",
"cleanupStr",
"(",
"String",
"name",
",",
"boolean",
"allowDottedKeys",
")",
"{",
"if",
"(",
"name",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"Pattern",
"pattern",
";",
"if",
"(",
"!",
"allowDottedKeys",
")",
"{",... | Replaces all . and / with _ and removes all spaces and double/single quotes.
Chomps any trailing . or _ character.
@param allowDottedKeys whether we remove the dots or not. | [
"Replaces",
"all",
".",
"and",
"/",
"with",
"_",
"and",
"removes",
"all",
"spaces",
"and",
"double",
"/",
"single",
"quotes",
".",
"Chomps",
"any",
"trailing",
".",
"or",
"_",
"character",
"."
] | train | https://github.com/jmxtrans/jmxtrans/blob/496f342de3bcf2c2226626374b7a16edf8f4ba2a/jmxtrans-core/src/main/java/com/googlecode/jmxtrans/model/naming/StringUtils.java#L47-L62 |
google/closure-compiler | src/com/google/javascript/jscomp/JsMessageVisitor.java | JsMessageVisitor.parseMessageTextNode | private static void parseMessageTextNode(Builder builder, Node node)
throws MalformedException {
String value = extractStringFromStringExprNode(node);
while (true) {
int phBegin = value.indexOf(PH_JS_PREFIX);
if (phBegin < 0) {
// Just a string literal
builder.appendStringPart(value);
return;
} else {
if (phBegin > 0) {
// A string literal followed by a placeholder
builder.appendStringPart(value.substring(0, phBegin));
}
// A placeholder. Find where it ends
int phEnd = value.indexOf(PH_JS_SUFFIX, phBegin);
if (phEnd < 0) {
throw new MalformedException(
"Placeholder incorrectly formatted in: " + builder.getKey(),
node);
}
String phName = value.substring(phBegin + PH_JS_PREFIX.length(),
phEnd);
builder.appendPlaceholderReference(phName);
int nextPos = phEnd + PH_JS_SUFFIX.length();
if (nextPos < value.length()) {
// Iterate on the rest of the message value
value = value.substring(nextPos);
} else {
// The message is parsed
return;
}
}
}
} | java | private static void parseMessageTextNode(Builder builder, Node node)
throws MalformedException {
String value = extractStringFromStringExprNode(node);
while (true) {
int phBegin = value.indexOf(PH_JS_PREFIX);
if (phBegin < 0) {
// Just a string literal
builder.appendStringPart(value);
return;
} else {
if (phBegin > 0) {
// A string literal followed by a placeholder
builder.appendStringPart(value.substring(0, phBegin));
}
// A placeholder. Find where it ends
int phEnd = value.indexOf(PH_JS_SUFFIX, phBegin);
if (phEnd < 0) {
throw new MalformedException(
"Placeholder incorrectly formatted in: " + builder.getKey(),
node);
}
String phName = value.substring(phBegin + PH_JS_PREFIX.length(),
phEnd);
builder.appendPlaceholderReference(phName);
int nextPos = phEnd + PH_JS_SUFFIX.length();
if (nextPos < value.length()) {
// Iterate on the rest of the message value
value = value.substring(nextPos);
} else {
// The message is parsed
return;
}
}
}
} | [
"private",
"static",
"void",
"parseMessageTextNode",
"(",
"Builder",
"builder",
",",
"Node",
"node",
")",
"throws",
"MalformedException",
"{",
"String",
"value",
"=",
"extractStringFromStringExprNode",
"(",
"node",
")",
";",
"while",
"(",
"true",
")",
"{",
"int"... | Appends the message parts in a JS message value extracted from the given
text node.
@param builder the JS message builder to append parts to
@param node the node with string literal that contains the message text
@throws MalformedException if {@code value} contains a reference to
an unregistered placeholder | [
"Appends",
"the",
"message",
"parts",
"in",
"a",
"JS",
"message",
"value",
"extracted",
"from",
"the",
"given",
"text",
"node",
"."
] | train | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/JsMessageVisitor.java#L817-L854 |
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.getPrebuiltEntityRole | public EntityRole getPrebuiltEntityRole(UUID appId, String versionId, UUID entityId, UUID roleId) {
return getPrebuiltEntityRoleWithServiceResponseAsync(appId, versionId, entityId, roleId).toBlocking().single().body();
} | java | public EntityRole getPrebuiltEntityRole(UUID appId, String versionId, UUID entityId, UUID roleId) {
return getPrebuiltEntityRoleWithServiceResponseAsync(appId, versionId, entityId, roleId).toBlocking().single().body();
} | [
"public",
"EntityRole",
"getPrebuiltEntityRole",
"(",
"UUID",
"appId",
",",
"String",
"versionId",
",",
"UUID",
"entityId",
",",
"UUID",
"roleId",
")",
"{",
"return",
"getPrebuiltEntityRoleWithServiceResponseAsync",
"(",
"appId",
",",
"versionId",
",",
"entityId",
"... | Get one entity role for a given entity.
@param appId The application ID.
@param versionId The version ID.
@param entityId entity ID.
@param roleId entity role 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 EntityRole object if successful. | [
"Get",
"one",
"entity",
"role",
"for",
"a",
"given",
"entity",
"."
] | 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#L11145-L11147 |
SonarSource/sonarqube | sonar-plugin-api/src/main/java/org/sonar/api/notifications/Notification.java | Notification.setFieldValue | public Notification setFieldValue(String field, @Nullable String value) {
fields.put(field, value);
return this;
} | java | public Notification setFieldValue(String field, @Nullable String value) {
fields.put(field, value);
return this;
} | [
"public",
"Notification",
"setFieldValue",
"(",
"String",
"field",
",",
"@",
"Nullable",
"String",
"value",
")",
"{",
"fields",
".",
"put",
"(",
"field",
",",
"value",
")",
";",
"return",
"this",
";",
"}"
] | Adds a field (kind of property) to the notification
@param field the name of the field (= the key)
@param value the value of the field
@return the notification itself | [
"Adds",
"a",
"field",
"(",
"kind",
"of",
"property",
")",
"to",
"the",
"notification"
] | train | https://github.com/SonarSource/sonarqube/blob/2fffa4c2f79ae3714844d7742796e82822b6a98a/sonar-plugin-api/src/main/java/org/sonar/api/notifications/Notification.java#L104-L107 |
apache/flink | flink-core/src/main/java/org/apache/flink/util/StringValueUtils.java | StringValueUtils.replaceNonWordChars | public static void replaceNonWordChars(StringValue string, char replacement) {
final char[] chars = string.getCharArray();
final int len = string.length();
for (int i = 0; i < len; i++) {
final char c = chars[i];
if (!(Character.isLetter(c) || Character.isDigit(c) || c == '_')) {
chars[i] = replacement;
}
}
} | java | public static void replaceNonWordChars(StringValue string, char replacement) {
final char[] chars = string.getCharArray();
final int len = string.length();
for (int i = 0; i < len; i++) {
final char c = chars[i];
if (!(Character.isLetter(c) || Character.isDigit(c) || c == '_')) {
chars[i] = replacement;
}
}
} | [
"public",
"static",
"void",
"replaceNonWordChars",
"(",
"StringValue",
"string",
",",
"char",
"replacement",
")",
"{",
"final",
"char",
"[",
"]",
"chars",
"=",
"string",
".",
"getCharArray",
"(",
")",
";",
"final",
"int",
"len",
"=",
"string",
".",
"length... | Replaces all non-word characters in a string by a given character. The only
characters not replaced are the characters that qualify as word characters
or digit characters with respect to {@link Character#isLetter(char)} or
{@link Character#isDigit(char)}, as well as the underscore character.
<p>This operation is intended to simplify strings for counting distinct words.
@param string The string value to have the non-word characters replaced.
@param replacement The character to use as the replacement. | [
"Replaces",
"all",
"non",
"-",
"word",
"characters",
"in",
"a",
"string",
"by",
"a",
"given",
"character",
".",
"The",
"only",
"characters",
"not",
"replaced",
"are",
"the",
"characters",
"that",
"qualify",
"as",
"word",
"characters",
"or",
"digit",
"charact... | train | https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-core/src/main/java/org/apache/flink/util/StringValueUtils.java#L62-L72 |
Javacord/Javacord | javacord-core/src/main/java/org/javacord/core/entity/message/MessageSetImpl.java | MessageSetImpl.getMessagesAfter | public static CompletableFuture<MessageSet> getMessagesAfter(TextChannel channel, int limit, long after) {
return getMessages(channel, limit, -1, after);
} | java | public static CompletableFuture<MessageSet> getMessagesAfter(TextChannel channel, int limit, long after) {
return getMessages(channel, limit, -1, after);
} | [
"public",
"static",
"CompletableFuture",
"<",
"MessageSet",
">",
"getMessagesAfter",
"(",
"TextChannel",
"channel",
",",
"int",
"limit",
",",
"long",
"after",
")",
"{",
"return",
"getMessages",
"(",
"channel",
",",
"limit",
",",
"-",
"1",
",",
"after",
")",
... | Gets up to a given amount of messages in the given channel after a given message in any channel.
@param channel The channel of the messages.
@param limit The limit of messages to get.
@param after Get messages after the message with this id.
@return The messages.
@see #getMessagesAfterAsStream(TextChannel, long) | [
"Gets",
"up",
"to",
"a",
"given",
"amount",
"of",
"messages",
"in",
"the",
"given",
"channel",
"after",
"a",
"given",
"message",
"in",
"any",
"channel",
"."
] | train | https://github.com/Javacord/Javacord/blob/915aad084dc5e863284267529d0dccd625fc6886/javacord-core/src/main/java/org/javacord/core/entity/message/MessageSetImpl.java#L376-L378 |
groovy/groovy-core | src/main/org/codehaus/groovy/runtime/StringGroovyMethods.java | StringGroovyMethods.getAt | public static List getAt(Matcher self, Collection indices) {
List result = new ArrayList();
for (Object value : indices) {
if (value instanceof Range) {
result.addAll(getAt(self, (Range) value));
} else {
int idx = DefaultTypeTransformation.intUnbox(value);
result.add(getAt(self, idx));
}
}
return result;
} | java | public static List getAt(Matcher self, Collection indices) {
List result = new ArrayList();
for (Object value : indices) {
if (value instanceof Range) {
result.addAll(getAt(self, (Range) value));
} else {
int idx = DefaultTypeTransformation.intUnbox(value);
result.add(getAt(self, idx));
}
}
return result;
} | [
"public",
"static",
"List",
"getAt",
"(",
"Matcher",
"self",
",",
"Collection",
"indices",
")",
"{",
"List",
"result",
"=",
"new",
"ArrayList",
"(",
")",
";",
"for",
"(",
"Object",
"value",
":",
"indices",
")",
"{",
"if",
"(",
"value",
"instanceof",
"R... | Select a List of values from a Matcher using a Collection
to identify the indices to be selected.
@param self a Matcher
@param indices a Collection of indices
@return a String of the values at the given indices
@since 1.6.0 | [
"Select",
"a",
"List",
"of",
"values",
"from",
"a",
"Matcher",
"using",
"a",
"Collection",
"to",
"identify",
"the",
"indices",
"to",
"be",
"selected",
"."
] | train | https://github.com/groovy/groovy-core/blob/01309f9d4be34ddf93c4a9943b5a97843bff6181/src/main/org/codehaus/groovy/runtime/StringGroovyMethods.java#L1316-L1327 |
google/j2objc | jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/UnicodeSet.java | UnicodeSet.indexOf | public int indexOf(int c) {
if (c < MIN_VALUE || c > MAX_VALUE) {
throw new IllegalArgumentException("Invalid code point U+" + Utility.hex(c, 6));
}
int i = 0;
int n = 0;
for (;;) {
int start = list[i++];
if (c < start) {
return -1;
}
int limit = list[i++];
if (c < limit) {
return n + c - start;
}
n += limit - start;
}
} | java | public int indexOf(int c) {
if (c < MIN_VALUE || c > MAX_VALUE) {
throw new IllegalArgumentException("Invalid code point U+" + Utility.hex(c, 6));
}
int i = 0;
int n = 0;
for (;;) {
int start = list[i++];
if (c < start) {
return -1;
}
int limit = list[i++];
if (c < limit) {
return n + c - start;
}
n += limit - start;
}
} | [
"public",
"int",
"indexOf",
"(",
"int",
"c",
")",
"{",
"if",
"(",
"c",
"<",
"MIN_VALUE",
"||",
"c",
">",
"MAX_VALUE",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Invalid code point U+\"",
"+",
"Utility",
".",
"hex",
"(",
"c",
",",
"6",
... | Returns the index of the given character within this set, where
the set is ordered by ascending code point. If the character
is not in this set, return -1. The inverse of this method is
<code>charAt()</code>.
@return an index from 0..size()-1, or -1 | [
"Returns",
"the",
"index",
"of",
"the",
"given",
"character",
"within",
"this",
"set",
"where",
"the",
"set",
"is",
"ordered",
"by",
"ascending",
"code",
"point",
".",
"If",
"the",
"character",
"is",
"not",
"in",
"this",
"set",
"return",
"-",
"1",
".",
... | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/UnicodeSet.java#L1091-L1108 |
Carbonado/Carbonado | src/main/java/com/amazon/carbonado/raw/KeyEncoder.java | KeyEncoder.encodeDesc | public static int encodeDesc(BigDecimal value, byte[] dst, int dstOffset) {
if (value == null) {
dst[dstOffset] = NULL_BYTE_LOW;
return 1;
}
if (value.signum() == 0) {
dst[dstOffset] = (byte) 0x7f;
return 1;
}
return encode(value).copyDescTo(dst, dstOffset);
} | java | public static int encodeDesc(BigDecimal value, byte[] dst, int dstOffset) {
if (value == null) {
dst[dstOffset] = NULL_BYTE_LOW;
return 1;
}
if (value.signum() == 0) {
dst[dstOffset] = (byte) 0x7f;
return 1;
}
return encode(value).copyDescTo(dst, dstOffset);
} | [
"public",
"static",
"int",
"encodeDesc",
"(",
"BigDecimal",
"value",
",",
"byte",
"[",
"]",
"dst",
",",
"int",
"dstOffset",
")",
"{",
"if",
"(",
"value",
"==",
"null",
")",
"{",
"dst",
"[",
"dstOffset",
"]",
"=",
"NULL_BYTE_LOW",
";",
"return",
"1",
... | Encodes the given optional BigDecimal into a variable amount of bytes
for descending order. If the BigDecimal is null, exactly 1 byte is
written. Otherwise, the amount written can be determined by calling
calculateEncodedLength.
<p><i>Note:</i> It is recommended that value be normalized by stripping
trailing zeros. This makes searching by value much simpler.
@param value BigDecimal value to encode, may be null
@param dst destination for encoded bytes
@param dstOffset offset into destination array
@return amount of bytes written
@since 1.2 | [
"Encodes",
"the",
"given",
"optional",
"BigDecimal",
"into",
"a",
"variable",
"amount",
"of",
"bytes",
"for",
"descending",
"order",
".",
"If",
"the",
"BigDecimal",
"is",
"null",
"exactly",
"1",
"byte",
"is",
"written",
".",
"Otherwise",
"the",
"amount",
"wr... | train | https://github.com/Carbonado/Carbonado/blob/eee29b365a61c8f03e1a1dc6bed0692e6b04b1db/src/main/java/com/amazon/carbonado/raw/KeyEncoder.java#L467-L479 |
groupon/odo | proxylib/src/main/java/com/groupon/odo/proxylib/PathOverrideService.java | PathOverrideService.createOverride | public void createOverride(int groupId, String methodName, String className) throws Exception {
// first make sure this doesn't already exist
for (Method method : EditService.getInstance().getMethodsFromGroupId(groupId, null)) {
if (method.getMethodName().equals(methodName) && method.getClassName().equals(className)) {
// don't add if it already exists in the group
return;
}
}
try (Connection sqlConnection = sqlService.getConnection()) {
PreparedStatement statement = sqlConnection.prepareStatement(
"INSERT INTO " + Constants.DB_TABLE_OVERRIDE
+ "(" + Constants.OVERRIDE_METHOD_NAME
+ "," + Constants.OVERRIDE_CLASS_NAME
+ "," + Constants.OVERRIDE_GROUP_ID
+ ")"
+ " VALUES (?, ?, ?)"
);
statement.setString(1, methodName);
statement.setString(2, className);
statement.setInt(3, groupId);
statement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
} | java | public void createOverride(int groupId, String methodName, String className) throws Exception {
// first make sure this doesn't already exist
for (Method method : EditService.getInstance().getMethodsFromGroupId(groupId, null)) {
if (method.getMethodName().equals(methodName) && method.getClassName().equals(className)) {
// don't add if it already exists in the group
return;
}
}
try (Connection sqlConnection = sqlService.getConnection()) {
PreparedStatement statement = sqlConnection.prepareStatement(
"INSERT INTO " + Constants.DB_TABLE_OVERRIDE
+ "(" + Constants.OVERRIDE_METHOD_NAME
+ "," + Constants.OVERRIDE_CLASS_NAME
+ "," + Constants.OVERRIDE_GROUP_ID
+ ")"
+ " VALUES (?, ?, ?)"
);
statement.setString(1, methodName);
statement.setString(2, className);
statement.setInt(3, groupId);
statement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
} | [
"public",
"void",
"createOverride",
"(",
"int",
"groupId",
",",
"String",
"methodName",
",",
"String",
"className",
")",
"throws",
"Exception",
"{",
"// first make sure this doesn't already exist",
"for",
"(",
"Method",
"method",
":",
"EditService",
".",
"getInstance"... | given the groupId, and 2 string arrays, adds the name-responses pair to the table_override
@param groupId ID of group
@param methodName name of method
@param className name of class
@throws Exception exception | [
"given",
"the",
"groupId",
"and",
"2",
"string",
"arrays",
"adds",
"the",
"name",
"-",
"responses",
"pair",
"to",
"the",
"table_override"
] | train | https://github.com/groupon/odo/blob/3bae43d5eca8ace036775e5b2d3ed9af1a9ff9b1/proxylib/src/main/java/com/groupon/odo/proxylib/PathOverrideService.java#L400-L425 |
javagl/ND | nd-tuples/src/main/java/de/javagl/nd/tuples/d/DoubleTuples.java | DoubleTuples.createRandom | public static MutableDoubleTuple createRandom(int size, Random random)
{
MutableDoubleTuple t = create(size);
randomize(t, random);
return t;
} | java | public static MutableDoubleTuple createRandom(int size, Random random)
{
MutableDoubleTuple t = create(size);
randomize(t, random);
return t;
} | [
"public",
"static",
"MutableDoubleTuple",
"createRandom",
"(",
"int",
"size",
",",
"Random",
"random",
")",
"{",
"MutableDoubleTuple",
"t",
"=",
"create",
"(",
"size",
")",
";",
"randomize",
"(",
"t",
",",
"random",
")",
";",
"return",
"t",
";",
"}"
] | Creates a tuple with the given size that
is filled with random values in [0,1)
@param size The size
@param random The random number generator
@return The new tuple | [
"Creates",
"a",
"tuple",
"with",
"the",
"given",
"size",
"that",
"is",
"filled",
"with",
"random",
"values",
"in",
"[",
"0",
"1",
")"
] | train | https://github.com/javagl/ND/blob/bcb655aaf5fc88af6194f73a27cca079186ff559/nd-tuples/src/main/java/de/javagl/nd/tuples/d/DoubleTuples.java#L1485-L1490 |
bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/core/PeerGroup.java | PeerGroup.addDataEventListenerToPeer | private static void addDataEventListenerToPeer(Executor executor, Peer peer, PeerDataEventListener downloadListener) {
peer.addBlocksDownloadedEventListener(executor, downloadListener);
peer.addChainDownloadStartedEventListener(executor, downloadListener);
peer.addGetDataEventListener(executor, downloadListener);
peer.addPreMessageReceivedEventListener(executor, downloadListener);
} | java | private static void addDataEventListenerToPeer(Executor executor, Peer peer, PeerDataEventListener downloadListener) {
peer.addBlocksDownloadedEventListener(executor, downloadListener);
peer.addChainDownloadStartedEventListener(executor, downloadListener);
peer.addGetDataEventListener(executor, downloadListener);
peer.addPreMessageReceivedEventListener(executor, downloadListener);
} | [
"private",
"static",
"void",
"addDataEventListenerToPeer",
"(",
"Executor",
"executor",
",",
"Peer",
"peer",
",",
"PeerDataEventListener",
"downloadListener",
")",
"{",
"peer",
".",
"addBlocksDownloadedEventListener",
"(",
"executor",
",",
"downloadListener",
")",
";",
... | Register a data event listener against a single peer (i.e. for blockchain
download). Handling registration/deregistration on peer death/add is
outside the scope of these methods. | [
"Register",
"a",
"data",
"event",
"listener",
"against",
"a",
"single",
"peer",
"(",
"i",
".",
"e",
".",
"for",
"blockchain",
"download",
")",
".",
"Handling",
"registration",
"/",
"deregistration",
"on",
"peer",
"death",
"/",
"add",
"is",
"outside",
"the"... | train | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/PeerGroup.java#L1430-L1435 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.