repository_name
stringlengths 7
58
| func_path_in_repository
stringlengths 11
218
| func_name
stringlengths 4
140
| whole_func_string
stringlengths 153
5.32k
| language
stringclasses 1
value | func_code_string
stringlengths 72
4k
| func_code_tokens
listlengths 20
832
| func_documentation_string
stringlengths 61
2k
| func_documentation_tokens
listlengths 1
647
| split_name
stringclasses 1
value | func_code_url
stringlengths 102
339
|
---|---|---|---|---|---|---|---|---|---|---|
sagiegurari/fax4j | src/main/java/org/fax4j/spi/process/ProcessFaxClientSpi.java | ProcessFaxClientSpi.updateFaxJob | protected void updateFaxJob(FaxJob faxJob,ProcessOutput processOutput,FaxActionType faxActionType) {
"""
Updates the fax job based on the data from the process output.
@param faxJob
The fax job object
@param processOutput
The process output
@param faxActionType
The fax action type
"""
if(this.processOutputHandler!=null)
{
//update fax job
this.processOutputHandler.updateFaxJob(this,faxJob,processOutput,faxActionType);
}
} | java | protected void updateFaxJob(FaxJob faxJob,ProcessOutput processOutput,FaxActionType faxActionType)
{
if(this.processOutputHandler!=null)
{
//update fax job
this.processOutputHandler.updateFaxJob(this,faxJob,processOutput,faxActionType);
}
} | [
"protected",
"void",
"updateFaxJob",
"(",
"FaxJob",
"faxJob",
",",
"ProcessOutput",
"processOutput",
",",
"FaxActionType",
"faxActionType",
")",
"{",
"if",
"(",
"this",
".",
"processOutputHandler",
"!=",
"null",
")",
"{",
"//update fax job",
"this",
".",
"processOutputHandler",
".",
"updateFaxJob",
"(",
"this",
",",
"faxJob",
",",
"processOutput",
",",
"faxActionType",
")",
";",
"}",
"}"
]
| Updates the fax job based on the data from the process output.
@param faxJob
The fax job object
@param processOutput
The process output
@param faxActionType
The fax action type | [
"Updates",
"the",
"fax",
"job",
"based",
"on",
"the",
"data",
"from",
"the",
"process",
"output",
"."
]
| train | https://github.com/sagiegurari/fax4j/blob/42fa51acabe7bf279e27ab3dd1cf76146b27955f/src/main/java/org/fax4j/spi/process/ProcessFaxClientSpi.java#L579-L586 |
wisdom-framework/wisdom-jcr | wisdom-modeshape-web-jcr-rest/src/main/java/org/modeshape/web/jcr/rest/handler/RestNodeHandlerImpl.java | RestNodeHandlerImpl.nodeWithId | @Override
public RestItem nodeWithId(Request request,
String repositoryName,
String workspaceName,
String id,
int depth) throws RepositoryException {
"""
Retrieves the JCR {@link javax.jcr.Item} at the given path, returning its rest representation.
@param request the servlet request; may not be null or unauthenticated
@param repositoryName the URL-encoded repository name
@param workspaceName the URL-encoded workspace name
@param id the node identifier
@param depth the depth of the node graph that should be returned if {@code path} refers to a node. @{code 0} means return
the requested node only. A negative value indicates that the full subgraph under the node should be returned. This
parameter defaults to {@code 0} and is ignored if {@code path} refers to a property.
@return a the rest representation of the item, as a {@link RestItem} instance.
@throws javax.jcr.RepositoryException if any JCR operations fail.
"""
Session session = getSession(request, repositoryName, workspaceName);
Node node = nodeWithId(id, session);
return createRestItem(request, depth, session, node);
} | java | @Override
public RestItem nodeWithId(Request request,
String repositoryName,
String workspaceName,
String id,
int depth) throws RepositoryException {
Session session = getSession(request, repositoryName, workspaceName);
Node node = nodeWithId(id, session);
return createRestItem(request, depth, session, node);
} | [
"@",
"Override",
"public",
"RestItem",
"nodeWithId",
"(",
"Request",
"request",
",",
"String",
"repositoryName",
",",
"String",
"workspaceName",
",",
"String",
"id",
",",
"int",
"depth",
")",
"throws",
"RepositoryException",
"{",
"Session",
"session",
"=",
"getSession",
"(",
"request",
",",
"repositoryName",
",",
"workspaceName",
")",
";",
"Node",
"node",
"=",
"nodeWithId",
"(",
"id",
",",
"session",
")",
";",
"return",
"createRestItem",
"(",
"request",
",",
"depth",
",",
"session",
",",
"node",
")",
";",
"}"
]
| Retrieves the JCR {@link javax.jcr.Item} at the given path, returning its rest representation.
@param request the servlet request; may not be null or unauthenticated
@param repositoryName the URL-encoded repository name
@param workspaceName the URL-encoded workspace name
@param id the node identifier
@param depth the depth of the node graph that should be returned if {@code path} refers to a node. @{code 0} means return
the requested node only. A negative value indicates that the full subgraph under the node should be returned. This
parameter defaults to {@code 0} and is ignored if {@code path} refers to a property.
@return a the rest representation of the item, as a {@link RestItem} instance.
@throws javax.jcr.RepositoryException if any JCR operations fail. | [
"Retrieves",
"the",
"JCR",
"{",
"@link",
"javax",
".",
"jcr",
".",
"Item",
"}",
"at",
"the",
"given",
"path",
"returning",
"its",
"rest",
"representation",
"."
]
| train | https://github.com/wisdom-framework/wisdom-jcr/blob/2711383dde2239a19b90c226b3fd2aecab5715e4/wisdom-modeshape-web-jcr-rest/src/main/java/org/modeshape/web/jcr/rest/handler/RestNodeHandlerImpl.java#L79-L88 |
weld/core | impl/src/main/java/org/jboss/weld/security/GetDeclaredMethodAction.java | GetDeclaredMethodAction.wrapException | public static PrivilegedAction<Method> wrapException(Class<?> javaClass, String methodName, Class<?>... parameterTypes) {
"""
Returns {@link PrivilegedAction} instead of {@link PrivilegedExceptionAction}. If {@link NoSuchMethodException} is thrown
it is wrapped within {@link WeldException} using {@link ReflectionLogger#noSuchMethodWrapper(NoSuchMethodException, String)}.
"""
return new WrappingAction(javaClass, methodName, parameterTypes);
} | java | public static PrivilegedAction<Method> wrapException(Class<?> javaClass, String methodName, Class<?>... parameterTypes) {
return new WrappingAction(javaClass, methodName, parameterTypes);
} | [
"public",
"static",
"PrivilegedAction",
"<",
"Method",
">",
"wrapException",
"(",
"Class",
"<",
"?",
">",
"javaClass",
",",
"String",
"methodName",
",",
"Class",
"<",
"?",
">",
"...",
"parameterTypes",
")",
"{",
"return",
"new",
"WrappingAction",
"(",
"javaClass",
",",
"methodName",
",",
"parameterTypes",
")",
";",
"}"
]
| Returns {@link PrivilegedAction} instead of {@link PrivilegedExceptionAction}. If {@link NoSuchMethodException} is thrown
it is wrapped within {@link WeldException} using {@link ReflectionLogger#noSuchMethodWrapper(NoSuchMethodException, String)}. | [
"Returns",
"{"
]
| train | https://github.com/weld/core/blob/567a2eaf95b168597d23a56be89bf05a7834b2aa/impl/src/main/java/org/jboss/weld/security/GetDeclaredMethodAction.java#L36-L38 |
alexvasilkov/GestureViews | library/src/main/java/com/alexvasilkov/gestures/views/GestureFrameLayout.java | GestureFrameLayout.invalidateChildInParent | @SuppressWarnings("deprecation")
@Override
public ViewParent invalidateChildInParent(int[] location, @NonNull Rect dirty) {
"""
It seems to be fine to use this method instead of suggested onDescendantInvalidated(...)
"""
// Invalidating correct rectangle
applyMatrix(dirty, matrix);
return super.invalidateChildInParent(location, dirty);
} | java | @SuppressWarnings("deprecation")
@Override
public ViewParent invalidateChildInParent(int[] location, @NonNull Rect dirty) {
// Invalidating correct rectangle
applyMatrix(dirty, matrix);
return super.invalidateChildInParent(location, dirty);
} | [
"@",
"SuppressWarnings",
"(",
"\"deprecation\"",
")",
"@",
"Override",
"public",
"ViewParent",
"invalidateChildInParent",
"(",
"int",
"[",
"]",
"location",
",",
"@",
"NonNull",
"Rect",
"dirty",
")",
"{",
"// Invalidating correct rectangle",
"applyMatrix",
"(",
"dirty",
",",
"matrix",
")",
";",
"return",
"super",
".",
"invalidateChildInParent",
"(",
"location",
",",
"dirty",
")",
";",
"}"
]
| It seems to be fine to use this method instead of suggested onDescendantInvalidated(...) | [
"It",
"seems",
"to",
"be",
"fine",
"to",
"use",
"this",
"method",
"instead",
"of",
"suggested",
"onDescendantInvalidated",
"(",
"...",
")"
]
| train | https://github.com/alexvasilkov/GestureViews/blob/f0a4c266e31dcad23bd0d9013531bc1c501b9c9f/library/src/main/java/com/alexvasilkov/gestures/views/GestureFrameLayout.java#L109-L115 |
kuali/ojb-1.0.4 | src/tools/org/apache/ojb/tools/mapping/reversedb2/propertyEditors/EditableTreeNodeWithProperties.java | EditableTreeNodeWithProperties.setAttribute | public void setAttribute(String strKey, Object value) {
"""
Set an attribute of this node as Object. This method is backed by
a HashMap, so all rules of HashMap apply to this method.
Fires a PropertyChangeEvent.
"""
this.propertyChangeDelegate.firePropertyChange(strKey,
hmAttributes.put(strKey, value), value);
} | java | public void setAttribute(String strKey, Object value)
{
this.propertyChangeDelegate.firePropertyChange(strKey,
hmAttributes.put(strKey, value), value);
} | [
"public",
"void",
"setAttribute",
"(",
"String",
"strKey",
",",
"Object",
"value",
")",
"{",
"this",
".",
"propertyChangeDelegate",
".",
"firePropertyChange",
"(",
"strKey",
",",
"hmAttributes",
".",
"put",
"(",
"strKey",
",",
"value",
")",
",",
"value",
")",
";",
"}"
]
| Set an attribute of this node as Object. This method is backed by
a HashMap, so all rules of HashMap apply to this method.
Fires a PropertyChangeEvent. | [
"Set",
"an",
"attribute",
"of",
"this",
"node",
"as",
"Object",
".",
"This",
"method",
"is",
"backed",
"by",
"a",
"HashMap",
"so",
"all",
"rules",
"of",
"HashMap",
"apply",
"to",
"this",
"method",
".",
"Fires",
"a",
"PropertyChangeEvent",
"."
]
| train | https://github.com/kuali/ojb-1.0.4/blob/9a544372f67ce965f662cdc71609dd03683c8f04/src/tools/org/apache/ojb/tools/mapping/reversedb2/propertyEditors/EditableTreeNodeWithProperties.java#L103-L107 |
ngageoint/geopackage-android-map | geopackage-map/src/main/java/mil/nga/geopackage/map/tiles/overlay/GeoPackageOverlayFactory.java | GeoPackageOverlayFactory.getBoundedOverlay | public static BoundedOverlay getBoundedOverlay(TileDao tileDao, float density, TileScaling scaling) {
"""
Get a Bounded Overlay Tile Provider for the Tile DAO with the display density and tile creator options
@param tileDao tile dao
@param density display density: {@link android.util.DisplayMetrics#density}
@param scaling tile scaling options
@return bounded overlay
@since 3.2.0
"""
return new GeoPackageOverlay(tileDao, density, scaling);
} | java | public static BoundedOverlay getBoundedOverlay(TileDao tileDao, float density, TileScaling scaling) {
return new GeoPackageOverlay(tileDao, density, scaling);
} | [
"public",
"static",
"BoundedOverlay",
"getBoundedOverlay",
"(",
"TileDao",
"tileDao",
",",
"float",
"density",
",",
"TileScaling",
"scaling",
")",
"{",
"return",
"new",
"GeoPackageOverlay",
"(",
"tileDao",
",",
"density",
",",
"scaling",
")",
";",
"}"
]
| Get a Bounded Overlay Tile Provider for the Tile DAO with the display density and tile creator options
@param tileDao tile dao
@param density display density: {@link android.util.DisplayMetrics#density}
@param scaling tile scaling options
@return bounded overlay
@since 3.2.0 | [
"Get",
"a",
"Bounded",
"Overlay",
"Tile",
"Provider",
"for",
"the",
"Tile",
"DAO",
"with",
"the",
"display",
"density",
"and",
"tile",
"creator",
"options"
]
| train | https://github.com/ngageoint/geopackage-android-map/blob/634d78468a5c52d2bc98791cc7ff03981ebf573b/geopackage-map/src/main/java/mil/nga/geopackage/map/tiles/overlay/GeoPackageOverlayFactory.java#L107-L109 |
Azure/azure-sdk-for-java | sql/resource-manager/v2017_10_01_preview/src/main/java/com/microsoft/azure/management/sql/v2017_10_01_preview/implementation/DatabaseVulnerabilityAssessmentScansInner.java | DatabaseVulnerabilityAssessmentScansInner.listByDatabaseWithServiceResponseAsync | public Observable<ServiceResponse<Page<VulnerabilityAssessmentScanRecordInner>>> listByDatabaseWithServiceResponseAsync(final String resourceGroupName, final String serverName, final String databaseName) {
"""
Lists the vulnerability assessment scans of a database.
@param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal.
@param serverName The name of the server.
@param databaseName The name of the database.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the PagedList<VulnerabilityAssessmentScanRecordInner> object
"""
return listByDatabaseSinglePageAsync(resourceGroupName, serverName, databaseName)
.concatMap(new Func1<ServiceResponse<Page<VulnerabilityAssessmentScanRecordInner>>, Observable<ServiceResponse<Page<VulnerabilityAssessmentScanRecordInner>>>>() {
@Override
public Observable<ServiceResponse<Page<VulnerabilityAssessmentScanRecordInner>>> call(ServiceResponse<Page<VulnerabilityAssessmentScanRecordInner>> page) {
String nextPageLink = page.body().nextPageLink();
if (nextPageLink == null) {
return Observable.just(page);
}
return Observable.just(page).concatWith(listByDatabaseNextWithServiceResponseAsync(nextPageLink));
}
});
} | java | public Observable<ServiceResponse<Page<VulnerabilityAssessmentScanRecordInner>>> listByDatabaseWithServiceResponseAsync(final String resourceGroupName, final String serverName, final String databaseName) {
return listByDatabaseSinglePageAsync(resourceGroupName, serverName, databaseName)
.concatMap(new Func1<ServiceResponse<Page<VulnerabilityAssessmentScanRecordInner>>, Observable<ServiceResponse<Page<VulnerabilityAssessmentScanRecordInner>>>>() {
@Override
public Observable<ServiceResponse<Page<VulnerabilityAssessmentScanRecordInner>>> call(ServiceResponse<Page<VulnerabilityAssessmentScanRecordInner>> page) {
String nextPageLink = page.body().nextPageLink();
if (nextPageLink == null) {
return Observable.just(page);
}
return Observable.just(page).concatWith(listByDatabaseNextWithServiceResponseAsync(nextPageLink));
}
});
} | [
"public",
"Observable",
"<",
"ServiceResponse",
"<",
"Page",
"<",
"VulnerabilityAssessmentScanRecordInner",
">",
">",
">",
"listByDatabaseWithServiceResponseAsync",
"(",
"final",
"String",
"resourceGroupName",
",",
"final",
"String",
"serverName",
",",
"final",
"String",
"databaseName",
")",
"{",
"return",
"listByDatabaseSinglePageAsync",
"(",
"resourceGroupName",
",",
"serverName",
",",
"databaseName",
")",
".",
"concatMap",
"(",
"new",
"Func1",
"<",
"ServiceResponse",
"<",
"Page",
"<",
"VulnerabilityAssessmentScanRecordInner",
">",
">",
",",
"Observable",
"<",
"ServiceResponse",
"<",
"Page",
"<",
"VulnerabilityAssessmentScanRecordInner",
">",
">",
">",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"Observable",
"<",
"ServiceResponse",
"<",
"Page",
"<",
"VulnerabilityAssessmentScanRecordInner",
">",
">",
">",
"call",
"(",
"ServiceResponse",
"<",
"Page",
"<",
"VulnerabilityAssessmentScanRecordInner",
">",
">",
"page",
")",
"{",
"String",
"nextPageLink",
"=",
"page",
".",
"body",
"(",
")",
".",
"nextPageLink",
"(",
")",
";",
"if",
"(",
"nextPageLink",
"==",
"null",
")",
"{",
"return",
"Observable",
".",
"just",
"(",
"page",
")",
";",
"}",
"return",
"Observable",
".",
"just",
"(",
"page",
")",
".",
"concatWith",
"(",
"listByDatabaseNextWithServiceResponseAsync",
"(",
"nextPageLink",
")",
")",
";",
"}",
"}",
")",
";",
"}"
]
| Lists the vulnerability assessment scans of a database.
@param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal.
@param serverName The name of the server.
@param databaseName The name of the database.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the PagedList<VulnerabilityAssessmentScanRecordInner> object | [
"Lists",
"the",
"vulnerability",
"assessment",
"scans",
"of",
"a",
"database",
"."
]
| train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/sql/resource-manager/v2017_10_01_preview/src/main/java/com/microsoft/azure/management/sql/v2017_10_01_preview/implementation/DatabaseVulnerabilityAssessmentScansInner.java#L158-L170 |
wcm-io/wcm-io-wcm | commons/src/main/java/io/wcm/wcm/commons/util/Path.java | Path.getAbsoluteParent | @SuppressWarnings("null")
public static Page getAbsoluteParent(@NotNull Page page, int parentLevel, @NotNull ResourceResolver resourceResolver) {
"""
Get absolute parent of given path.
If the path is a version history or launch path the path level is adjusted accordingly.
This is a replacement for {@link Page#getAbsoluteParent(int)}.
@param page Page
@param parentLevel Parent level
@param resourceResolver Resource resolver
@return Absolute parent page or null if path is invalid
"""
PageManager pageManager = resourceResolver.adaptTo(PageManager.class);
String absoluteParentPath = getAbsoluteParent(page.getPath(), parentLevel, resourceResolver);
if (StringUtils.isEmpty(absoluteParentPath)) {
return null;
}
return pageManager.getPage(absoluteParentPath);
} | java | @SuppressWarnings("null")
public static Page getAbsoluteParent(@NotNull Page page, int parentLevel, @NotNull ResourceResolver resourceResolver) {
PageManager pageManager = resourceResolver.adaptTo(PageManager.class);
String absoluteParentPath = getAbsoluteParent(page.getPath(), parentLevel, resourceResolver);
if (StringUtils.isEmpty(absoluteParentPath)) {
return null;
}
return pageManager.getPage(absoluteParentPath);
} | [
"@",
"SuppressWarnings",
"(",
"\"null\"",
")",
"public",
"static",
"Page",
"getAbsoluteParent",
"(",
"@",
"NotNull",
"Page",
"page",
",",
"int",
"parentLevel",
",",
"@",
"NotNull",
"ResourceResolver",
"resourceResolver",
")",
"{",
"PageManager",
"pageManager",
"=",
"resourceResolver",
".",
"adaptTo",
"(",
"PageManager",
".",
"class",
")",
";",
"String",
"absoluteParentPath",
"=",
"getAbsoluteParent",
"(",
"page",
".",
"getPath",
"(",
")",
",",
"parentLevel",
",",
"resourceResolver",
")",
";",
"if",
"(",
"StringUtils",
".",
"isEmpty",
"(",
"absoluteParentPath",
")",
")",
"{",
"return",
"null",
";",
"}",
"return",
"pageManager",
".",
"getPage",
"(",
"absoluteParentPath",
")",
";",
"}"
]
| Get absolute parent of given path.
If the path is a version history or launch path the path level is adjusted accordingly.
This is a replacement for {@link Page#getAbsoluteParent(int)}.
@param page Page
@param parentLevel Parent level
@param resourceResolver Resource resolver
@return Absolute parent page or null if path is invalid | [
"Get",
"absolute",
"parent",
"of",
"given",
"path",
".",
"If",
"the",
"path",
"is",
"a",
"version",
"history",
"or",
"launch",
"path",
"the",
"path",
"level",
"is",
"adjusted",
"accordingly",
".",
"This",
"is",
"a",
"replacement",
"for",
"{"
]
| train | https://github.com/wcm-io/wcm-io-wcm/blob/8eff9434f2f4b6462fdb718f8769ad793c55b8d7/commons/src/main/java/io/wcm/wcm/commons/util/Path.java#L95-L103 |
jenkinsci/artifactory-plugin | src/main/java/org/jfrog/hudson/pipeline/common/docker/DockerImage.java | DockerImage.generateBuildInfoModule | public Module generateBuildInfoModule(Run build, TaskListener listener, ArtifactoryConfigurator config, String buildName, String buildNumber, String timestamp) throws IOException {
"""
Generates the build-info module for this docker image.
Additionally. this method tags the deployed docker layers with properties,
such as build.name, build.number and custom properties defined in the Jenkins build.
@param build
@param listener
@param config
@param buildName
@param buildNumber
@param timestamp
@return
@throws IOException
"""
if (artifactsProps == null) {
artifactsProps = ArrayListMultimap.create();
}
artifactsProps.put("build.name", buildName);
artifactsProps.put("build.number", buildNumber);
artifactsProps.put("build.timestamp", timestamp);
String artifactsPropsStr = ExtractorUtils.buildPropertiesString(artifactsProps);
Properties buildInfoItemsProps = new Properties();
buildInfoItemsProps.setProperty("build.name", buildName);
buildInfoItemsProps.setProperty("build.number", buildNumber);
buildInfoItemsProps.setProperty("build.timestamp", timestamp);
ArtifactoryServer server = config.getArtifactoryServer();
CredentialsConfig preferredResolver = server.getDeployerCredentialsConfig();
ArtifactoryDependenciesClient dependenciesClient = null;
ArtifactoryBuildInfoClient propertyChangeClient = null;
try {
dependenciesClient = server.createArtifactoryDependenciesClient(
preferredResolver.provideUsername(build.getParent()), preferredResolver.providePassword(build.getParent()),
server.createProxyConfiguration(Jenkins.getInstance().proxy), listener);
CredentialsConfig preferredDeployer = CredentialManager.getPreferredDeployer(config, server);
propertyChangeClient = server.createArtifactoryClient(
preferredDeployer.provideUsername(build.getParent()), preferredDeployer.providePassword(build.getParent()),
server.createProxyConfiguration(Jenkins.getInstance().proxy));
Module buildInfoModule = new Module();
buildInfoModule.setId(imageTag.substring(imageTag.indexOf("/") + 1));
// If manifest and imagePath not found, return.
if ((StringUtils.isEmpty(manifest) || StringUtils.isEmpty(imagePath)) && !findAndSetManifestFromArtifactory(server, dependenciesClient, listener)) {
return buildInfoModule;
}
listener.getLogger().println("Fetching details of published docker layers from Artifactory...");
boolean includeVirtualReposSupported = propertyChangeClient.getArtifactoryVersion().isAtLeast(VIRTUAL_REPOS_SUPPORTED_VERSION);
DockerLayers layers = createLayers(dependenciesClient, includeVirtualReposSupported);
listener.getLogger().println("Tagging published docker layers with build properties in Artifactory...");
setDependenciesAndArtifacts(buildInfoModule, layers, artifactsPropsStr, buildInfoItemsProps,
dependenciesClient, propertyChangeClient, server);
setBuildInfoModuleProps(buildInfoModule);
return buildInfoModule;
} finally {
if (dependenciesClient != null) {
dependenciesClient.close();
}
if (propertyChangeClient != null) {
propertyChangeClient.close();
}
}
} | java | public Module generateBuildInfoModule(Run build, TaskListener listener, ArtifactoryConfigurator config, String buildName, String buildNumber, String timestamp) throws IOException {
if (artifactsProps == null) {
artifactsProps = ArrayListMultimap.create();
}
artifactsProps.put("build.name", buildName);
artifactsProps.put("build.number", buildNumber);
artifactsProps.put("build.timestamp", timestamp);
String artifactsPropsStr = ExtractorUtils.buildPropertiesString(artifactsProps);
Properties buildInfoItemsProps = new Properties();
buildInfoItemsProps.setProperty("build.name", buildName);
buildInfoItemsProps.setProperty("build.number", buildNumber);
buildInfoItemsProps.setProperty("build.timestamp", timestamp);
ArtifactoryServer server = config.getArtifactoryServer();
CredentialsConfig preferredResolver = server.getDeployerCredentialsConfig();
ArtifactoryDependenciesClient dependenciesClient = null;
ArtifactoryBuildInfoClient propertyChangeClient = null;
try {
dependenciesClient = server.createArtifactoryDependenciesClient(
preferredResolver.provideUsername(build.getParent()), preferredResolver.providePassword(build.getParent()),
server.createProxyConfiguration(Jenkins.getInstance().proxy), listener);
CredentialsConfig preferredDeployer = CredentialManager.getPreferredDeployer(config, server);
propertyChangeClient = server.createArtifactoryClient(
preferredDeployer.provideUsername(build.getParent()), preferredDeployer.providePassword(build.getParent()),
server.createProxyConfiguration(Jenkins.getInstance().proxy));
Module buildInfoModule = new Module();
buildInfoModule.setId(imageTag.substring(imageTag.indexOf("/") + 1));
// If manifest and imagePath not found, return.
if ((StringUtils.isEmpty(manifest) || StringUtils.isEmpty(imagePath)) && !findAndSetManifestFromArtifactory(server, dependenciesClient, listener)) {
return buildInfoModule;
}
listener.getLogger().println("Fetching details of published docker layers from Artifactory...");
boolean includeVirtualReposSupported = propertyChangeClient.getArtifactoryVersion().isAtLeast(VIRTUAL_REPOS_SUPPORTED_VERSION);
DockerLayers layers = createLayers(dependenciesClient, includeVirtualReposSupported);
listener.getLogger().println("Tagging published docker layers with build properties in Artifactory...");
setDependenciesAndArtifacts(buildInfoModule, layers, artifactsPropsStr, buildInfoItemsProps,
dependenciesClient, propertyChangeClient, server);
setBuildInfoModuleProps(buildInfoModule);
return buildInfoModule;
} finally {
if (dependenciesClient != null) {
dependenciesClient.close();
}
if (propertyChangeClient != null) {
propertyChangeClient.close();
}
}
} | [
"public",
"Module",
"generateBuildInfoModule",
"(",
"Run",
"build",
",",
"TaskListener",
"listener",
",",
"ArtifactoryConfigurator",
"config",
",",
"String",
"buildName",
",",
"String",
"buildNumber",
",",
"String",
"timestamp",
")",
"throws",
"IOException",
"{",
"if",
"(",
"artifactsProps",
"==",
"null",
")",
"{",
"artifactsProps",
"=",
"ArrayListMultimap",
".",
"create",
"(",
")",
";",
"}",
"artifactsProps",
".",
"put",
"(",
"\"build.name\"",
",",
"buildName",
")",
";",
"artifactsProps",
".",
"put",
"(",
"\"build.number\"",
",",
"buildNumber",
")",
";",
"artifactsProps",
".",
"put",
"(",
"\"build.timestamp\"",
",",
"timestamp",
")",
";",
"String",
"artifactsPropsStr",
"=",
"ExtractorUtils",
".",
"buildPropertiesString",
"(",
"artifactsProps",
")",
";",
"Properties",
"buildInfoItemsProps",
"=",
"new",
"Properties",
"(",
")",
";",
"buildInfoItemsProps",
".",
"setProperty",
"(",
"\"build.name\"",
",",
"buildName",
")",
";",
"buildInfoItemsProps",
".",
"setProperty",
"(",
"\"build.number\"",
",",
"buildNumber",
")",
";",
"buildInfoItemsProps",
".",
"setProperty",
"(",
"\"build.timestamp\"",
",",
"timestamp",
")",
";",
"ArtifactoryServer",
"server",
"=",
"config",
".",
"getArtifactoryServer",
"(",
")",
";",
"CredentialsConfig",
"preferredResolver",
"=",
"server",
".",
"getDeployerCredentialsConfig",
"(",
")",
";",
"ArtifactoryDependenciesClient",
"dependenciesClient",
"=",
"null",
";",
"ArtifactoryBuildInfoClient",
"propertyChangeClient",
"=",
"null",
";",
"try",
"{",
"dependenciesClient",
"=",
"server",
".",
"createArtifactoryDependenciesClient",
"(",
"preferredResolver",
".",
"provideUsername",
"(",
"build",
".",
"getParent",
"(",
")",
")",
",",
"preferredResolver",
".",
"providePassword",
"(",
"build",
".",
"getParent",
"(",
")",
")",
",",
"server",
".",
"createProxyConfiguration",
"(",
"Jenkins",
".",
"getInstance",
"(",
")",
".",
"proxy",
")",
",",
"listener",
")",
";",
"CredentialsConfig",
"preferredDeployer",
"=",
"CredentialManager",
".",
"getPreferredDeployer",
"(",
"config",
",",
"server",
")",
";",
"propertyChangeClient",
"=",
"server",
".",
"createArtifactoryClient",
"(",
"preferredDeployer",
".",
"provideUsername",
"(",
"build",
".",
"getParent",
"(",
")",
")",
",",
"preferredDeployer",
".",
"providePassword",
"(",
"build",
".",
"getParent",
"(",
")",
")",
",",
"server",
".",
"createProxyConfiguration",
"(",
"Jenkins",
".",
"getInstance",
"(",
")",
".",
"proxy",
")",
")",
";",
"Module",
"buildInfoModule",
"=",
"new",
"Module",
"(",
")",
";",
"buildInfoModule",
".",
"setId",
"(",
"imageTag",
".",
"substring",
"(",
"imageTag",
".",
"indexOf",
"(",
"\"/\"",
")",
"+",
"1",
")",
")",
";",
"// If manifest and imagePath not found, return.",
"if",
"(",
"(",
"StringUtils",
".",
"isEmpty",
"(",
"manifest",
")",
"||",
"StringUtils",
".",
"isEmpty",
"(",
"imagePath",
")",
")",
"&&",
"!",
"findAndSetManifestFromArtifactory",
"(",
"server",
",",
"dependenciesClient",
",",
"listener",
")",
")",
"{",
"return",
"buildInfoModule",
";",
"}",
"listener",
".",
"getLogger",
"(",
")",
".",
"println",
"(",
"\"Fetching details of published docker layers from Artifactory...\"",
")",
";",
"boolean",
"includeVirtualReposSupported",
"=",
"propertyChangeClient",
".",
"getArtifactoryVersion",
"(",
")",
".",
"isAtLeast",
"(",
"VIRTUAL_REPOS_SUPPORTED_VERSION",
")",
";",
"DockerLayers",
"layers",
"=",
"createLayers",
"(",
"dependenciesClient",
",",
"includeVirtualReposSupported",
")",
";",
"listener",
".",
"getLogger",
"(",
")",
".",
"println",
"(",
"\"Tagging published docker layers with build properties in Artifactory...\"",
")",
";",
"setDependenciesAndArtifacts",
"(",
"buildInfoModule",
",",
"layers",
",",
"artifactsPropsStr",
",",
"buildInfoItemsProps",
",",
"dependenciesClient",
",",
"propertyChangeClient",
",",
"server",
")",
";",
"setBuildInfoModuleProps",
"(",
"buildInfoModule",
")",
";",
"return",
"buildInfoModule",
";",
"}",
"finally",
"{",
"if",
"(",
"dependenciesClient",
"!=",
"null",
")",
"{",
"dependenciesClient",
".",
"close",
"(",
")",
";",
"}",
"if",
"(",
"propertyChangeClient",
"!=",
"null",
")",
"{",
"propertyChangeClient",
".",
"close",
"(",
")",
";",
"}",
"}",
"}"
]
| Generates the build-info module for this docker image.
Additionally. this method tags the deployed docker layers with properties,
such as build.name, build.number and custom properties defined in the Jenkins build.
@param build
@param listener
@param config
@param buildName
@param buildNumber
@param timestamp
@return
@throws IOException | [
"Generates",
"the",
"build",
"-",
"info",
"module",
"for",
"this",
"docker",
"image",
".",
"Additionally",
".",
"this",
"method",
"tags",
"the",
"deployed",
"docker",
"layers",
"with",
"properties",
"such",
"as",
"build",
".",
"name",
"build",
".",
"number",
"and",
"custom",
"properties",
"defined",
"in",
"the",
"Jenkins",
"build",
"."
]
| train | https://github.com/jenkinsci/artifactory-plugin/blob/f5fcfff6a5a50be5374813e49d1fe3aaf6422333/src/main/java/org/jfrog/hudson/pipeline/common/docker/DockerImage.java#L115-L169 |
baidubce/bce-sdk-java | src/main/java/com/baidubce/services/cdn/CdnClient.java | CdnClient.setRequestAuth | public void setRequestAuth(String domain, RequestAuth requestAuth) {
"""
Set the request authentication.
@param domain Name of the domain.
@param requestAuth The configuration of authentication.
"""
SetRequestAuthRequest request = new SetRequestAuthRequest()
.withDomain(domain)
.withRequestAuth(requestAuth);
setRequestAuth(request);
} | java | public void setRequestAuth(String domain, RequestAuth requestAuth) {
SetRequestAuthRequest request = new SetRequestAuthRequest()
.withDomain(domain)
.withRequestAuth(requestAuth);
setRequestAuth(request);
} | [
"public",
"void",
"setRequestAuth",
"(",
"String",
"domain",
",",
"RequestAuth",
"requestAuth",
")",
"{",
"SetRequestAuthRequest",
"request",
"=",
"new",
"SetRequestAuthRequest",
"(",
")",
".",
"withDomain",
"(",
"domain",
")",
".",
"withRequestAuth",
"(",
"requestAuth",
")",
";",
"setRequestAuth",
"(",
"request",
")",
";",
"}"
]
| Set the request authentication.
@param domain Name of the domain.
@param requestAuth The configuration of authentication. | [
"Set",
"the",
"request",
"authentication",
"."
]
| train | https://github.com/baidubce/bce-sdk-java/blob/f7140f28dd82121515c88ded7bfe769a37d0ec4a/src/main/java/com/baidubce/services/cdn/CdnClient.java#L481-L486 |
foundation-runtime/service-directory | 1.2/sd-api/src/main/java/com/cisco/oss/foundation/directory/registration/HeartbeatDirectoryRegistrationService.java | HeartbeatDirectoryRegistrationService.getCachedServiceInstance | private CachedProviderServiceInstance getCachedServiceInstance(
String serviceName, String providerAddress) {
"""
Get the Cached ProvidedServiceInstance by serviceName and providerAddress.
It is thread safe.
@param serviceName
the serviceName
@param providerAddress
the providerAddress
@return
the CachedProviderServiceInstance
"""
ServiceInstanceId id = new ServiceInstanceId(serviceName, providerAddress);
return getCacheServiceInstances().get(id);
} | java | private CachedProviderServiceInstance getCachedServiceInstance(
String serviceName, String providerAddress) {
ServiceInstanceId id = new ServiceInstanceId(serviceName, providerAddress);
return getCacheServiceInstances().get(id);
} | [
"private",
"CachedProviderServiceInstance",
"getCachedServiceInstance",
"(",
"String",
"serviceName",
",",
"String",
"providerAddress",
")",
"{",
"ServiceInstanceId",
"id",
"=",
"new",
"ServiceInstanceId",
"(",
"serviceName",
",",
"providerAddress",
")",
";",
"return",
"getCacheServiceInstances",
"(",
")",
".",
"get",
"(",
"id",
")",
";",
"}"
]
| Get the Cached ProvidedServiceInstance by serviceName and providerAddress.
It is thread safe.
@param serviceName
the serviceName
@param providerAddress
the providerAddress
@return
the CachedProviderServiceInstance | [
"Get",
"the",
"Cached",
"ProvidedServiceInstance",
"by",
"serviceName",
"and",
"providerAddress",
"."
]
| train | https://github.com/foundation-runtime/service-directory/blob/a7bdefe173dc99e75eff4a24e07e6407e62f2ed4/1.2/sd-api/src/main/java/com/cisco/oss/foundation/directory/registration/HeartbeatDirectoryRegistrationService.java#L361-L367 |
google/error-prone-javac | src/jdk.jdeps/share/classes/com/sun/tools/jdeps/Module.java | Module.isExported | public boolean isExported(String pn, String target) {
"""
Tests if the package of the given name is exported to the target
in a qualified fashion.
"""
return isExported(pn)
|| exports.containsKey(pn) && exports.get(pn).contains(target);
} | java | public boolean isExported(String pn, String target) {
return isExported(pn)
|| exports.containsKey(pn) && exports.get(pn).contains(target);
} | [
"public",
"boolean",
"isExported",
"(",
"String",
"pn",
",",
"String",
"target",
")",
"{",
"return",
"isExported",
"(",
"pn",
")",
"||",
"exports",
".",
"containsKey",
"(",
"pn",
")",
"&&",
"exports",
".",
"get",
"(",
"pn",
")",
".",
"contains",
"(",
"target",
")",
";",
"}"
]
| Tests if the package of the given name is exported to the target
in a qualified fashion. | [
"Tests",
"if",
"the",
"package",
"of",
"the",
"given",
"name",
"is",
"exported",
"to",
"the",
"target",
"in",
"a",
"qualified",
"fashion",
"."
]
| train | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.jdeps/share/classes/com/sun/tools/jdeps/Module.java#L156-L159 |
hankcs/HanLP | src/main/java/com/hankcs/hanlp/mining/word/TfIdf.java | TfIdf.idfFromTfs | public static <TERM> Map<TERM, Double> idfFromTfs(Iterable<Map<TERM, Double>> tfs) {
"""
从词频集合建立倒排频率(默认平滑词频,且加一平滑tf-idf)
@param tfs 次品集合
@param <TERM> 词语类型
@return 一个词语->倒排文档的Map
"""
return idfFromTfs(tfs, true, true);
} | java | public static <TERM> Map<TERM, Double> idfFromTfs(Iterable<Map<TERM, Double>> tfs)
{
return idfFromTfs(tfs, true, true);
} | [
"public",
"static",
"<",
"TERM",
">",
"Map",
"<",
"TERM",
",",
"Double",
">",
"idfFromTfs",
"(",
"Iterable",
"<",
"Map",
"<",
"TERM",
",",
"Double",
">",
">",
"tfs",
")",
"{",
"return",
"idfFromTfs",
"(",
"tfs",
",",
"true",
",",
"true",
")",
";",
"}"
]
| 从词频集合建立倒排频率(默认平滑词频,且加一平滑tf-idf)
@param tfs 次品集合
@param <TERM> 词语类型
@return 一个词语->倒排文档的Map | [
"从词频集合建立倒排频率(默认平滑词频,且加一平滑tf",
"-",
"idf)"
]
| train | https://github.com/hankcs/HanLP/blob/a538d0722ab2e4980a9dcd9ea40324fc3ddba7ce/src/main/java/com/hankcs/hanlp/mining/word/TfIdf.java#L243-L246 |
Erudika/para | para-server/src/main/java/com/erudika/para/rest/RestUtils.java | RestUtils.getVotingResponse | public static Response getVotingResponse(ParaObject object, Map<String, Object> entity) {
"""
Process voting request and create vote object.
@param object the object to cast vote on
@param entity request entity data
@return status codetrue if vote was successful
"""
boolean voteSuccess = false;
if (object != null && entity != null) {
String upvoterId = (String) entity.get("_voteup");
String downvoterId = (String) entity.get("_votedown");
if (!StringUtils.isBlank(upvoterId)) {
voteSuccess = object.voteUp(upvoterId);
} else if (!StringUtils.isBlank(downvoterId)) {
voteSuccess = object.voteDown(downvoterId);
}
if (voteSuccess) {
object.update();
}
}
return Response.ok(voteSuccess).build();
} | java | public static Response getVotingResponse(ParaObject object, Map<String, Object> entity) {
boolean voteSuccess = false;
if (object != null && entity != null) {
String upvoterId = (String) entity.get("_voteup");
String downvoterId = (String) entity.get("_votedown");
if (!StringUtils.isBlank(upvoterId)) {
voteSuccess = object.voteUp(upvoterId);
} else if (!StringUtils.isBlank(downvoterId)) {
voteSuccess = object.voteDown(downvoterId);
}
if (voteSuccess) {
object.update();
}
}
return Response.ok(voteSuccess).build();
} | [
"public",
"static",
"Response",
"getVotingResponse",
"(",
"ParaObject",
"object",
",",
"Map",
"<",
"String",
",",
"Object",
">",
"entity",
")",
"{",
"boolean",
"voteSuccess",
"=",
"false",
";",
"if",
"(",
"object",
"!=",
"null",
"&&",
"entity",
"!=",
"null",
")",
"{",
"String",
"upvoterId",
"=",
"(",
"String",
")",
"entity",
".",
"get",
"(",
"\"_voteup\"",
")",
";",
"String",
"downvoterId",
"=",
"(",
"String",
")",
"entity",
".",
"get",
"(",
"\"_votedown\"",
")",
";",
"if",
"(",
"!",
"StringUtils",
".",
"isBlank",
"(",
"upvoterId",
")",
")",
"{",
"voteSuccess",
"=",
"object",
".",
"voteUp",
"(",
"upvoterId",
")",
";",
"}",
"else",
"if",
"(",
"!",
"StringUtils",
".",
"isBlank",
"(",
"downvoterId",
")",
")",
"{",
"voteSuccess",
"=",
"object",
".",
"voteDown",
"(",
"downvoterId",
")",
";",
"}",
"if",
"(",
"voteSuccess",
")",
"{",
"object",
".",
"update",
"(",
")",
";",
"}",
"}",
"return",
"Response",
".",
"ok",
"(",
"voteSuccess",
")",
".",
"build",
"(",
")",
";",
"}"
]
| Process voting request and create vote object.
@param object the object to cast vote on
@param entity request entity data
@return status codetrue if vote was successful | [
"Process",
"voting",
"request",
"and",
"create",
"vote",
"object",
"."
]
| train | https://github.com/Erudika/para/blob/5ba096c477042ea7b18e9a0e8b5b1ee0f5bd6ce9/para-server/src/main/java/com/erudika/para/rest/RestUtils.java#L269-L284 |
pwheel/spring-security-oauth2-client | src/main/java/com/racquettrack/security/oauth/OAuth2AuthenticationFilter.java | OAuth2AuthenticationFilter.checkStateParameter | protected void checkStateParameter(HttpSession session, Map<String, String[]> parameters)
throws AuthenticationException {
"""
Check the state parameter to ensure it is the same as was originally sent. Subclasses can override this
behaviour if they so choose, but it is not recommended.
@param session The http session, which will contain the original scope as an attribute.
@param parameters The parameters received from the OAuth 2 Provider, which should contain the same state as
originally sent to it and stored in the http session.
@throws AuthenticationException If the state differs from the original.
"""
String originalState = (String)session.getAttribute(oAuth2ServiceProperties.getStateParamName());
String receivedStates[] = parameters.get(oAuth2ServiceProperties.getStateParamName());
// There should only be one entry in the array, if there are more they will be ignored.
if (receivedStates == null || receivedStates.length == 0 ||
!receivedStates[0].equals(originalState)) {
String errorMsg = String.format("Received states %s was not equal to original state %s",
receivedStates, originalState);
LOG.error(errorMsg);
throw new AuthenticationServiceException(errorMsg);
}
} | java | protected void checkStateParameter(HttpSession session, Map<String, String[]> parameters)
throws AuthenticationException {
String originalState = (String)session.getAttribute(oAuth2ServiceProperties.getStateParamName());
String receivedStates[] = parameters.get(oAuth2ServiceProperties.getStateParamName());
// There should only be one entry in the array, if there are more they will be ignored.
if (receivedStates == null || receivedStates.length == 0 ||
!receivedStates[0].equals(originalState)) {
String errorMsg = String.format("Received states %s was not equal to original state %s",
receivedStates, originalState);
LOG.error(errorMsg);
throw new AuthenticationServiceException(errorMsg);
}
} | [
"protected",
"void",
"checkStateParameter",
"(",
"HttpSession",
"session",
",",
"Map",
"<",
"String",
",",
"String",
"[",
"]",
">",
"parameters",
")",
"throws",
"AuthenticationException",
"{",
"String",
"originalState",
"=",
"(",
"String",
")",
"session",
".",
"getAttribute",
"(",
"oAuth2ServiceProperties",
".",
"getStateParamName",
"(",
")",
")",
";",
"String",
"receivedStates",
"[",
"]",
"=",
"parameters",
".",
"get",
"(",
"oAuth2ServiceProperties",
".",
"getStateParamName",
"(",
")",
")",
";",
"// There should only be one entry in the array, if there are more they will be ignored.",
"if",
"(",
"receivedStates",
"==",
"null",
"||",
"receivedStates",
".",
"length",
"==",
"0",
"||",
"!",
"receivedStates",
"[",
"0",
"]",
".",
"equals",
"(",
"originalState",
")",
")",
"{",
"String",
"errorMsg",
"=",
"String",
".",
"format",
"(",
"\"Received states %s was not equal to original state %s\"",
",",
"receivedStates",
",",
"originalState",
")",
";",
"LOG",
".",
"error",
"(",
"errorMsg",
")",
";",
"throw",
"new",
"AuthenticationServiceException",
"(",
"errorMsg",
")",
";",
"}",
"}"
]
| Check the state parameter to ensure it is the same as was originally sent. Subclasses can override this
behaviour if they so choose, but it is not recommended.
@param session The http session, which will contain the original scope as an attribute.
@param parameters The parameters received from the OAuth 2 Provider, which should contain the same state as
originally sent to it and stored in the http session.
@throws AuthenticationException If the state differs from the original. | [
"Check",
"the",
"state",
"parameter",
"to",
"ensure",
"it",
"is",
"the",
"same",
"as",
"was",
"originally",
"sent",
".",
"Subclasses",
"can",
"override",
"this",
"behaviour",
"if",
"they",
"so",
"choose",
"but",
"it",
"is",
"not",
"recommended",
"."
]
| train | https://github.com/pwheel/spring-security-oauth2-client/blob/c0258823493e268495c9752c5d752f74c6809c6b/src/main/java/com/racquettrack/security/oauth/OAuth2AuthenticationFilter.java#L107-L121 |
Samsung/GearVRf | GVRf/Extensions/widgetLib/src/org/gearvrf/widgetlib/widget/ListWidget.java | ListWidget.scrollByOffset | @Override
public boolean scrollByOffset(final float xOffset, final float yOffset, final float zOffset,
final LayoutScroller.OnScrollListener listener) {
"""
Scroll all items in the {@link ListWidget} by {@code rotation} degrees}.
@param xOffset
@param yOffset
@param zOffset
The amount to scroll, in degrees.
"""
if (isScrolling()) {
return false;
}
Vector3Axis offset = new Vector3Axis(xOffset, yOffset, zOffset);
if (offset.isInfinite() || offset.isNaN()) {
Log.e(TAG, new IllegalArgumentException(),
"Invalid scrolling delta: %s", offset);
return false;
}
Log.d(Log.SUBSYSTEM.LAYOUT, TAG, "scrollBy(%s): offset %s", getName(), offset);
onScrollImpl(offset, listener);
return true;
} | java | @Override
public boolean scrollByOffset(final float xOffset, final float yOffset, final float zOffset,
final LayoutScroller.OnScrollListener listener) {
if (isScrolling()) {
return false;
}
Vector3Axis offset = new Vector3Axis(xOffset, yOffset, zOffset);
if (offset.isInfinite() || offset.isNaN()) {
Log.e(TAG, new IllegalArgumentException(),
"Invalid scrolling delta: %s", offset);
return false;
}
Log.d(Log.SUBSYSTEM.LAYOUT, TAG, "scrollBy(%s): offset %s", getName(), offset);
onScrollImpl(offset, listener);
return true;
} | [
"@",
"Override",
"public",
"boolean",
"scrollByOffset",
"(",
"final",
"float",
"xOffset",
",",
"final",
"float",
"yOffset",
",",
"final",
"float",
"zOffset",
",",
"final",
"LayoutScroller",
".",
"OnScrollListener",
"listener",
")",
"{",
"if",
"(",
"isScrolling",
"(",
")",
")",
"{",
"return",
"false",
";",
"}",
"Vector3Axis",
"offset",
"=",
"new",
"Vector3Axis",
"(",
"xOffset",
",",
"yOffset",
",",
"zOffset",
")",
";",
"if",
"(",
"offset",
".",
"isInfinite",
"(",
")",
"||",
"offset",
".",
"isNaN",
"(",
")",
")",
"{",
"Log",
".",
"e",
"(",
"TAG",
",",
"new",
"IllegalArgumentException",
"(",
")",
",",
"\"Invalid scrolling delta: %s\"",
",",
"offset",
")",
";",
"return",
"false",
";",
"}",
"Log",
".",
"d",
"(",
"Log",
".",
"SUBSYSTEM",
".",
"LAYOUT",
",",
"TAG",
",",
"\"scrollBy(%s): offset %s\"",
",",
"getName",
"(",
")",
",",
"offset",
")",
";",
"onScrollImpl",
"(",
"offset",
",",
"listener",
")",
";",
"return",
"true",
";",
"}"
]
| Scroll all items in the {@link ListWidget} by {@code rotation} degrees}.
@param xOffset
@param yOffset
@param zOffset
The amount to scroll, in degrees. | [
"Scroll",
"all",
"items",
"in",
"the",
"{",
"@link",
"ListWidget",
"}",
"by",
"{",
"@code",
"rotation",
"}",
"degrees",
"}",
"."
]
| train | https://github.com/Samsung/GearVRf/blob/05034d465a7b0a494fabb9e9f2971ac19392f32d/GVRf/Extensions/widgetLib/src/org/gearvrf/widgetlib/widget/ListWidget.java#L621-L638 |
bramp/ffmpeg-cli-wrapper | src/main/java/net/bramp/ffmpeg/builder/FFmpegOutputBuilder.java | FFmpegOutputBuilder.buildOptions | @CheckReturnValue
@Override
public EncodingOptions buildOptions() {
"""
Returns a representation of this Builder that can be safely serialised.
<p>NOTE: This method is horribly out of date, and its use should be rethought.
@return A new EncodingOptions capturing this Builder's state
"""
// TODO When/if modelmapper supports @ConstructorProperties, we map this
// object, instead of doing new XXX(...)
// https://github.com/jhalterman/modelmapper/issues/44
return new EncodingOptions(
new MainEncodingOptions(format, startOffset, duration),
new AudioEncodingOptions(
audio_enabled,
audio_codec,
audio_channels,
audio_sample_rate,
audio_sample_format,
audio_bit_rate,
audio_quality),
new VideoEncodingOptions(
video_enabled,
video_codec,
video_frame_rate,
video_width,
video_height,
video_bit_rate,
video_frames,
video_filter,
video_preset));
} | java | @CheckReturnValue
@Override
public EncodingOptions buildOptions() {
// TODO When/if modelmapper supports @ConstructorProperties, we map this
// object, instead of doing new XXX(...)
// https://github.com/jhalterman/modelmapper/issues/44
return new EncodingOptions(
new MainEncodingOptions(format, startOffset, duration),
new AudioEncodingOptions(
audio_enabled,
audio_codec,
audio_channels,
audio_sample_rate,
audio_sample_format,
audio_bit_rate,
audio_quality),
new VideoEncodingOptions(
video_enabled,
video_codec,
video_frame_rate,
video_width,
video_height,
video_bit_rate,
video_frames,
video_filter,
video_preset));
} | [
"@",
"CheckReturnValue",
"@",
"Override",
"public",
"EncodingOptions",
"buildOptions",
"(",
")",
"{",
"// TODO When/if modelmapper supports @ConstructorProperties, we map this",
"// object, instead of doing new XXX(...)",
"// https://github.com/jhalterman/modelmapper/issues/44",
"return",
"new",
"EncodingOptions",
"(",
"new",
"MainEncodingOptions",
"(",
"format",
",",
"startOffset",
",",
"duration",
")",
",",
"new",
"AudioEncodingOptions",
"(",
"audio_enabled",
",",
"audio_codec",
",",
"audio_channels",
",",
"audio_sample_rate",
",",
"audio_sample_format",
",",
"audio_bit_rate",
",",
"audio_quality",
")",
",",
"new",
"VideoEncodingOptions",
"(",
"video_enabled",
",",
"video_codec",
",",
"video_frame_rate",
",",
"video_width",
",",
"video_height",
",",
"video_bit_rate",
",",
"video_frames",
",",
"video_filter",
",",
"video_preset",
")",
")",
";",
"}"
]
| Returns a representation of this Builder that can be safely serialised.
<p>NOTE: This method is horribly out of date, and its use should be rethought.
@return A new EncodingOptions capturing this Builder's state | [
"Returns",
"a",
"representation",
"of",
"this",
"Builder",
"that",
"can",
"be",
"safely",
"serialised",
"."
]
| train | https://github.com/bramp/ffmpeg-cli-wrapper/blob/3819b155edf9132acc75bb6af66dcef1b98c64b2/src/main/java/net/bramp/ffmpeg/builder/FFmpegOutputBuilder.java#L186-L212 |
Azure/azure-sdk-for-java | network/resource-manager/v2017_10_01/src/main/java/com/microsoft/azure/management/network/v2017_10_01/implementation/VirtualNetworkGatewayConnectionsInner.java | VirtualNetworkGatewayConnectionsInner.beginSetSharedKeyAsync | public Observable<ConnectionSharedKeyInner> beginSetSharedKeyAsync(String resourceGroupName, String virtualNetworkGatewayConnectionName, String value) {
"""
The Put VirtualNetworkGatewayConnectionSharedKey operation sets the virtual network gateway connection shared key for passed virtual network gateway connection in the specified resource group through Network resource provider.
@param resourceGroupName The name of the resource group.
@param virtualNetworkGatewayConnectionName The virtual network gateway connection name.
@param value The virtual network connection shared key value.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the ConnectionSharedKeyInner object
"""
return beginSetSharedKeyWithServiceResponseAsync(resourceGroupName, virtualNetworkGatewayConnectionName, value).map(new Func1<ServiceResponse<ConnectionSharedKeyInner>, ConnectionSharedKeyInner>() {
@Override
public ConnectionSharedKeyInner call(ServiceResponse<ConnectionSharedKeyInner> response) {
return response.body();
}
});
} | java | public Observable<ConnectionSharedKeyInner> beginSetSharedKeyAsync(String resourceGroupName, String virtualNetworkGatewayConnectionName, String value) {
return beginSetSharedKeyWithServiceResponseAsync(resourceGroupName, virtualNetworkGatewayConnectionName, value).map(new Func1<ServiceResponse<ConnectionSharedKeyInner>, ConnectionSharedKeyInner>() {
@Override
public ConnectionSharedKeyInner call(ServiceResponse<ConnectionSharedKeyInner> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"ConnectionSharedKeyInner",
">",
"beginSetSharedKeyAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"virtualNetworkGatewayConnectionName",
",",
"String",
"value",
")",
"{",
"return",
"beginSetSharedKeyWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"virtualNetworkGatewayConnectionName",
",",
"value",
")",
".",
"map",
"(",
"new",
"Func1",
"<",
"ServiceResponse",
"<",
"ConnectionSharedKeyInner",
">",
",",
"ConnectionSharedKeyInner",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"ConnectionSharedKeyInner",
"call",
"(",
"ServiceResponse",
"<",
"ConnectionSharedKeyInner",
">",
"response",
")",
"{",
"return",
"response",
".",
"body",
"(",
")",
";",
"}",
"}",
")",
";",
"}"
]
| The Put VirtualNetworkGatewayConnectionSharedKey operation sets the virtual network gateway connection shared key for passed virtual network gateway connection in the specified resource group through Network resource provider.
@param resourceGroupName The name of the resource group.
@param virtualNetworkGatewayConnectionName The virtual network gateway connection name.
@param value The virtual network connection shared key value.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the ConnectionSharedKeyInner object | [
"The",
"Put",
"VirtualNetworkGatewayConnectionSharedKey",
"operation",
"sets",
"the",
"virtual",
"network",
"gateway",
"connection",
"shared",
"key",
"for",
"passed",
"virtual",
"network",
"gateway",
"connection",
"in",
"the",
"specified",
"resource",
"group",
"through",
"Network",
"resource",
"provider",
"."
]
| train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2017_10_01/src/main/java/com/microsoft/azure/management/network/v2017_10_01/implementation/VirtualNetworkGatewayConnectionsInner.java#L959-L966 |
AgNO3/jcifs-ng | src/main/java/jcifs/dcerpc/DcerpcHandle.java | DcerpcHandle.getHandle | public static DcerpcHandle getHandle ( String url, CIFSContext tc, boolean unshared ) throws MalformedURLException, DcerpcException {
"""
Get a handle to a service
@param url
@param tc
@param unshared
whether an exclusive connection should be used
@return a DCERPC handle for the given url
@throws MalformedURLException
@throws DcerpcException
"""
if ( url.startsWith("ncacn_np:") ) {
return new DcerpcPipeHandle(url, tc, unshared);
}
throw new DcerpcException("DCERPC transport not supported: " + url);
} | java | public static DcerpcHandle getHandle ( String url, CIFSContext tc, boolean unshared ) throws MalformedURLException, DcerpcException {
if ( url.startsWith("ncacn_np:") ) {
return new DcerpcPipeHandle(url, tc, unshared);
}
throw new DcerpcException("DCERPC transport not supported: " + url);
} | [
"public",
"static",
"DcerpcHandle",
"getHandle",
"(",
"String",
"url",
",",
"CIFSContext",
"tc",
",",
"boolean",
"unshared",
")",
"throws",
"MalformedURLException",
",",
"DcerpcException",
"{",
"if",
"(",
"url",
".",
"startsWith",
"(",
"\"ncacn_np:\"",
")",
")",
"{",
"return",
"new",
"DcerpcPipeHandle",
"(",
"url",
",",
"tc",
",",
"unshared",
")",
";",
"}",
"throw",
"new",
"DcerpcException",
"(",
"\"DCERPC transport not supported: \"",
"+",
"url",
")",
";",
"}"
]
| Get a handle to a service
@param url
@param tc
@param unshared
whether an exclusive connection should be used
@return a DCERPC handle for the given url
@throws MalformedURLException
@throws DcerpcException | [
"Get",
"a",
"handle",
"to",
"a",
"service"
]
| train | https://github.com/AgNO3/jcifs-ng/blob/0311107a077ea372527ae74839eec8042197332f/src/main/java/jcifs/dcerpc/DcerpcHandle.java#L198-L203 |
samskivert/samskivert | src/main/java/com/samskivert/util/RandomUtil.java | RandomUtil.pickRandom | public static <T> T pickRandom (Iterator<T> iter, int count, Random r) {
"""
Picks a random object from the supplied iterator (which must iterate over exactly
<code>count</code> objects using the given Random.
@param r the random number generator to use.
@return a randomly selected item.
@exception NoSuchElementException thrown if the iterator provides fewer than
<code>count</code> elements.
"""
if (count < 1) {
throw new IllegalArgumentException(
"Must have at least one element [count=" + count + "]");
}
for (int ii = 0, ll = getInt(count, r); ii < ll; ii++) {
iter.next();
}
return iter.next();
} | java | public static <T> T pickRandom (Iterator<T> iter, int count, Random r)
{
if (count < 1) {
throw new IllegalArgumentException(
"Must have at least one element [count=" + count + "]");
}
for (int ii = 0, ll = getInt(count, r); ii < ll; ii++) {
iter.next();
}
return iter.next();
} | [
"public",
"static",
"<",
"T",
">",
"T",
"pickRandom",
"(",
"Iterator",
"<",
"T",
">",
"iter",
",",
"int",
"count",
",",
"Random",
"r",
")",
"{",
"if",
"(",
"count",
"<",
"1",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Must have at least one element [count=\"",
"+",
"count",
"+",
"\"]\"",
")",
";",
"}",
"for",
"(",
"int",
"ii",
"=",
"0",
",",
"ll",
"=",
"getInt",
"(",
"count",
",",
"r",
")",
";",
"ii",
"<",
"ll",
";",
"ii",
"++",
")",
"{",
"iter",
".",
"next",
"(",
")",
";",
"}",
"return",
"iter",
".",
"next",
"(",
")",
";",
"}"
]
| Picks a random object from the supplied iterator (which must iterate over exactly
<code>count</code> objects using the given Random.
@param r the random number generator to use.
@return a randomly selected item.
@exception NoSuchElementException thrown if the iterator provides fewer than
<code>count</code> elements. | [
"Picks",
"a",
"random",
"object",
"from",
"the",
"supplied",
"iterator",
"(",
"which",
"must",
"iterate",
"over",
"exactly",
"<code",
">",
"count<",
"/",
"code",
">",
"objects",
"using",
"the",
"given",
"Random",
"."
]
| train | https://github.com/samskivert/samskivert/blob/a64d9ef42b69819bdb2c66bddac6a64caef928b6/src/main/java/com/samskivert/util/RandomUtil.java#L406-L417 |
codeprimate-software/cp-elements | src/main/java/org/cp/elements/util/ArrayUtils.java | ArrayUtils.getFirst | @NullSafe
@SafeVarargs
public static <T> T getFirst(T... array) {
"""
Returns the first element (at index 0) in the {@code array}.
@param <T> {@link Class} type of elements in the array.
@param array array from which to extract the first element.
@return the first element in the array or {@literal null}
if the {@code array} is {@literal null} or empty.
@see #getFirst(Object[], Object)
"""
return getFirst(array, null);
} | java | @NullSafe
@SafeVarargs
public static <T> T getFirst(T... array) {
return getFirst(array, null);
} | [
"@",
"NullSafe",
"@",
"SafeVarargs",
"public",
"static",
"<",
"T",
">",
"T",
"getFirst",
"(",
"T",
"...",
"array",
")",
"{",
"return",
"getFirst",
"(",
"array",
",",
"null",
")",
";",
"}"
]
| Returns the first element (at index 0) in the {@code array}.
@param <T> {@link Class} type of elements in the array.
@param array array from which to extract the first element.
@return the first element in the array or {@literal null}
if the {@code array} is {@literal null} or empty.
@see #getFirst(Object[], Object) | [
"Returns",
"the",
"first",
"element",
"(",
"at",
"index",
"0",
")",
"in",
"the",
"{",
"@code",
"array",
"}",
"."
]
| train | https://github.com/codeprimate-software/cp-elements/blob/f2163c149fbbef05015e688132064ebcac7c49ab/src/main/java/org/cp/elements/util/ArrayUtils.java#L453-L457 |
Impetus/Kundera | src/kundera-rethinkdb/src/main/java/com/impetus/client/rethink/RethinkDBClient.java | RethinkDBClient.populateRmap | private MapObject populateRmap(EntityMetadata entityMetadata, Object entity) {
"""
Populate rmap.
@param entityMetadata
the entity metadata
@param entity
the entity
@return the map object
"""
MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata()
.getMetamodel(entityMetadata.getPersistenceUnit());
Class entityClazz = entityMetadata.getEntityClazz();
EntityType entityType = metaModel.entity(entityClazz);
Set<Attribute> attributes = entityType.getAttributes();
Iterator<Attribute> iterator = attributes.iterator();
return iterateAndPopulateRmap(entity, metaModel, iterator);
} | java | private MapObject populateRmap(EntityMetadata entityMetadata, Object entity)
{
MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata()
.getMetamodel(entityMetadata.getPersistenceUnit());
Class entityClazz = entityMetadata.getEntityClazz();
EntityType entityType = metaModel.entity(entityClazz);
Set<Attribute> attributes = entityType.getAttributes();
Iterator<Attribute> iterator = attributes.iterator();
return iterateAndPopulateRmap(entity, metaModel, iterator);
} | [
"private",
"MapObject",
"populateRmap",
"(",
"EntityMetadata",
"entityMetadata",
",",
"Object",
"entity",
")",
"{",
"MetamodelImpl",
"metaModel",
"=",
"(",
"MetamodelImpl",
")",
"kunderaMetadata",
".",
"getApplicationMetadata",
"(",
")",
".",
"getMetamodel",
"(",
"entityMetadata",
".",
"getPersistenceUnit",
"(",
")",
")",
";",
"Class",
"entityClazz",
"=",
"entityMetadata",
".",
"getEntityClazz",
"(",
")",
";",
"EntityType",
"entityType",
"=",
"metaModel",
".",
"entity",
"(",
"entityClazz",
")",
";",
"Set",
"<",
"Attribute",
">",
"attributes",
"=",
"entityType",
".",
"getAttributes",
"(",
")",
";",
"Iterator",
"<",
"Attribute",
">",
"iterator",
"=",
"attributes",
".",
"iterator",
"(",
")",
";",
"return",
"iterateAndPopulateRmap",
"(",
"entity",
",",
"metaModel",
",",
"iterator",
")",
";",
"}"
]
| Populate rmap.
@param entityMetadata
the entity metadata
@param entity
the entity
@return the map object | [
"Populate",
"rmap",
"."
]
| train | https://github.com/Impetus/Kundera/blob/268958ab1ec09d14ec4d9184f0c8ded7a9158908/src/kundera-rethinkdb/src/main/java/com/impetus/client/rethink/RethinkDBClient.java#L325-L334 |
cdk/cdk | legacy/src/main/java/org/openscience/cdk/smsd/tools/BondEnergies.java | BondEnergies.getEnergies | public int getEnergies(IAtom sourceAtom, IAtom targetAtom, Order bondOrder) {
"""
Returns bond energy for a bond type, given atoms and bond type
@param sourceAtom First bondEnergy
@param targetAtom Second bondEnergy
@param bondOrder (single, double etc)
@return bond energy
"""
int dKJPerMol = -1;
for (Map.Entry<Integer, BondEnergy> entry : bondEngergies.entrySet()) {
BondEnergy bondEnergy = entry.getValue();
String atom1 = bondEnergy.getSymbolFirstAtom();
String atom2 = bondEnergy.getSymbolSecondAtom();
if ((atom1.equalsIgnoreCase(sourceAtom.getSymbol()) && atom2.equalsIgnoreCase(targetAtom.getSymbol()))
|| (atom2.equalsIgnoreCase(sourceAtom.getSymbol()) && atom1
.equalsIgnoreCase(targetAtom.getSymbol()))) {
Order order = bondEnergy.getBondOrder();
if (order.compareTo(bondOrder) == 0) {
dKJPerMol = bondEnergy.getEnergy();
}
}
}
return dKJPerMol;
} | java | public int getEnergies(IAtom sourceAtom, IAtom targetAtom, Order bondOrder) {
int dKJPerMol = -1;
for (Map.Entry<Integer, BondEnergy> entry : bondEngergies.entrySet()) {
BondEnergy bondEnergy = entry.getValue();
String atom1 = bondEnergy.getSymbolFirstAtom();
String atom2 = bondEnergy.getSymbolSecondAtom();
if ((atom1.equalsIgnoreCase(sourceAtom.getSymbol()) && atom2.equalsIgnoreCase(targetAtom.getSymbol()))
|| (atom2.equalsIgnoreCase(sourceAtom.getSymbol()) && atom1
.equalsIgnoreCase(targetAtom.getSymbol()))) {
Order order = bondEnergy.getBondOrder();
if (order.compareTo(bondOrder) == 0) {
dKJPerMol = bondEnergy.getEnergy();
}
}
}
return dKJPerMol;
} | [
"public",
"int",
"getEnergies",
"(",
"IAtom",
"sourceAtom",
",",
"IAtom",
"targetAtom",
",",
"Order",
"bondOrder",
")",
"{",
"int",
"dKJPerMol",
"=",
"-",
"1",
";",
"for",
"(",
"Map",
".",
"Entry",
"<",
"Integer",
",",
"BondEnergy",
">",
"entry",
":",
"bondEngergies",
".",
"entrySet",
"(",
")",
")",
"{",
"BondEnergy",
"bondEnergy",
"=",
"entry",
".",
"getValue",
"(",
")",
";",
"String",
"atom1",
"=",
"bondEnergy",
".",
"getSymbolFirstAtom",
"(",
")",
";",
"String",
"atom2",
"=",
"bondEnergy",
".",
"getSymbolSecondAtom",
"(",
")",
";",
"if",
"(",
"(",
"atom1",
".",
"equalsIgnoreCase",
"(",
"sourceAtom",
".",
"getSymbol",
"(",
")",
")",
"&&",
"atom2",
".",
"equalsIgnoreCase",
"(",
"targetAtom",
".",
"getSymbol",
"(",
")",
")",
")",
"||",
"(",
"atom2",
".",
"equalsIgnoreCase",
"(",
"sourceAtom",
".",
"getSymbol",
"(",
")",
")",
"&&",
"atom1",
".",
"equalsIgnoreCase",
"(",
"targetAtom",
".",
"getSymbol",
"(",
")",
")",
")",
")",
"{",
"Order",
"order",
"=",
"bondEnergy",
".",
"getBondOrder",
"(",
")",
";",
"if",
"(",
"order",
".",
"compareTo",
"(",
"bondOrder",
")",
"==",
"0",
")",
"{",
"dKJPerMol",
"=",
"bondEnergy",
".",
"getEnergy",
"(",
")",
";",
"}",
"}",
"}",
"return",
"dKJPerMol",
";",
"}"
]
| Returns bond energy for a bond type, given atoms and bond type
@param sourceAtom First bondEnergy
@param targetAtom Second bondEnergy
@param bondOrder (single, double etc)
@return bond energy | [
"Returns",
"bond",
"energy",
"for",
"a",
"bond",
"type",
"given",
"atoms",
"and",
"bond",
"type"
]
| train | https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/legacy/src/main/java/org/openscience/cdk/smsd/tools/BondEnergies.java#L244-L262 |
google/error-prone-javac | src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Resolve.java | Resolve.findInheritedMemberType | Symbol findInheritedMemberType(Env<AttrContext> env,
Type site,
Name name,
TypeSymbol c) {
"""
Find a member type inherited from a superclass or interface.
@param env The current environment.
@param site The original type from where the selection takes
place.
@param name The type's name.
@param c The class to search for the member type. This is
always a superclass or implemented interface of
site's class.
"""
Symbol bestSoFar = typeNotFound;
Symbol sym;
Type st = types.supertype(c.type);
if (st != null && st.hasTag(CLASS)) {
sym = findMemberType(env, site, name, st.tsym);
bestSoFar = bestOf(bestSoFar, sym);
}
for (List<Type> l = types.interfaces(c.type);
bestSoFar.kind != AMBIGUOUS && l.nonEmpty();
l = l.tail) {
sym = findMemberType(env, site, name, l.head.tsym);
if (!bestSoFar.kind.isResolutionError() &&
!sym.kind.isResolutionError() &&
sym.owner != bestSoFar.owner)
bestSoFar = new AmbiguityError(bestSoFar, sym);
else
bestSoFar = bestOf(bestSoFar, sym);
}
return bestSoFar;
} | java | Symbol findInheritedMemberType(Env<AttrContext> env,
Type site,
Name name,
TypeSymbol c) {
Symbol bestSoFar = typeNotFound;
Symbol sym;
Type st = types.supertype(c.type);
if (st != null && st.hasTag(CLASS)) {
sym = findMemberType(env, site, name, st.tsym);
bestSoFar = bestOf(bestSoFar, sym);
}
for (List<Type> l = types.interfaces(c.type);
bestSoFar.kind != AMBIGUOUS && l.nonEmpty();
l = l.tail) {
sym = findMemberType(env, site, name, l.head.tsym);
if (!bestSoFar.kind.isResolutionError() &&
!sym.kind.isResolutionError() &&
sym.owner != bestSoFar.owner)
bestSoFar = new AmbiguityError(bestSoFar, sym);
else
bestSoFar = bestOf(bestSoFar, sym);
}
return bestSoFar;
} | [
"Symbol",
"findInheritedMemberType",
"(",
"Env",
"<",
"AttrContext",
">",
"env",
",",
"Type",
"site",
",",
"Name",
"name",
",",
"TypeSymbol",
"c",
")",
"{",
"Symbol",
"bestSoFar",
"=",
"typeNotFound",
";",
"Symbol",
"sym",
";",
"Type",
"st",
"=",
"types",
".",
"supertype",
"(",
"c",
".",
"type",
")",
";",
"if",
"(",
"st",
"!=",
"null",
"&&",
"st",
".",
"hasTag",
"(",
"CLASS",
")",
")",
"{",
"sym",
"=",
"findMemberType",
"(",
"env",
",",
"site",
",",
"name",
",",
"st",
".",
"tsym",
")",
";",
"bestSoFar",
"=",
"bestOf",
"(",
"bestSoFar",
",",
"sym",
")",
";",
"}",
"for",
"(",
"List",
"<",
"Type",
">",
"l",
"=",
"types",
".",
"interfaces",
"(",
"c",
".",
"type",
")",
";",
"bestSoFar",
".",
"kind",
"!=",
"AMBIGUOUS",
"&&",
"l",
".",
"nonEmpty",
"(",
")",
";",
"l",
"=",
"l",
".",
"tail",
")",
"{",
"sym",
"=",
"findMemberType",
"(",
"env",
",",
"site",
",",
"name",
",",
"l",
".",
"head",
".",
"tsym",
")",
";",
"if",
"(",
"!",
"bestSoFar",
".",
"kind",
".",
"isResolutionError",
"(",
")",
"&&",
"!",
"sym",
".",
"kind",
".",
"isResolutionError",
"(",
")",
"&&",
"sym",
".",
"owner",
"!=",
"bestSoFar",
".",
"owner",
")",
"bestSoFar",
"=",
"new",
"AmbiguityError",
"(",
"bestSoFar",
",",
"sym",
")",
";",
"else",
"bestSoFar",
"=",
"bestOf",
"(",
"bestSoFar",
",",
"sym",
")",
";",
"}",
"return",
"bestSoFar",
";",
"}"
]
| Find a member type inherited from a superclass or interface.
@param env The current environment.
@param site The original type from where the selection takes
place.
@param name The type's name.
@param c The class to search for the member type. This is
always a superclass or implemented interface of
site's class. | [
"Find",
"a",
"member",
"type",
"inherited",
"from",
"a",
"superclass",
"or",
"interface",
"."
]
| train | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Resolve.java#L2187-L2210 |
sarl/sarl | main/coreplugins/io.sarl.lang.ui/src/io/sarl/lang/ui/hover/SARLHoverSignatureProvider.java | SARLHoverSignatureProvider.getTypeName | protected String getTypeName(JvmType type) {
"""
Replies the type name for the given type.
@param type the type.
@return the string representation of the given type.
"""
if (type != null) {
if (type instanceof JvmDeclaredType) {
final ITypeReferenceOwner owner = new StandardTypeReferenceOwner(this.services, type);
return owner.toLightweightTypeReference(type).getHumanReadableName();
}
return type.getSimpleName();
}
return Messages.SARLHoverSignatureProvider_1;
} | java | protected String getTypeName(JvmType type) {
if (type != null) {
if (type instanceof JvmDeclaredType) {
final ITypeReferenceOwner owner = new StandardTypeReferenceOwner(this.services, type);
return owner.toLightweightTypeReference(type).getHumanReadableName();
}
return type.getSimpleName();
}
return Messages.SARLHoverSignatureProvider_1;
} | [
"protected",
"String",
"getTypeName",
"(",
"JvmType",
"type",
")",
"{",
"if",
"(",
"type",
"!=",
"null",
")",
"{",
"if",
"(",
"type",
"instanceof",
"JvmDeclaredType",
")",
"{",
"final",
"ITypeReferenceOwner",
"owner",
"=",
"new",
"StandardTypeReferenceOwner",
"(",
"this",
".",
"services",
",",
"type",
")",
";",
"return",
"owner",
".",
"toLightweightTypeReference",
"(",
"type",
")",
".",
"getHumanReadableName",
"(",
")",
";",
"}",
"return",
"type",
".",
"getSimpleName",
"(",
")",
";",
"}",
"return",
"Messages",
".",
"SARLHoverSignatureProvider_1",
";",
"}"
]
| Replies the type name for the given type.
@param type the type.
@return the string representation of the given type. | [
"Replies",
"the",
"type",
"name",
"for",
"the",
"given",
"type",
"."
]
| train | https://github.com/sarl/sarl/blob/ca00ff994598c730339972def4e19a60e0b8cace/main/coreplugins/io.sarl.lang.ui/src/io/sarl/lang/ui/hover/SARLHoverSignatureProvider.java#L273-L282 |
forge/javaee-descriptors | impl/src/main/java/org/jboss/shrinkwrap/descriptor/impl/facelettaglibrary20/WebFacelettaglibraryDescriptorImpl.java | WebFacelettaglibraryDescriptorImpl.addNamespace | public WebFacelettaglibraryDescriptor addNamespace(String name, String value) {
"""
Adds a new namespace
@return the current instance of <code>WebFacelettaglibraryDescriptor</code>
"""
model.attribute(name, value);
return this;
} | java | public WebFacelettaglibraryDescriptor addNamespace(String name, String value)
{
model.attribute(name, value);
return this;
} | [
"public",
"WebFacelettaglibraryDescriptor",
"addNamespace",
"(",
"String",
"name",
",",
"String",
"value",
")",
"{",
"model",
".",
"attribute",
"(",
"name",
",",
"value",
")",
";",
"return",
"this",
";",
"}"
]
| Adds a new namespace
@return the current instance of <code>WebFacelettaglibraryDescriptor</code> | [
"Adds",
"a",
"new",
"namespace"
]
| train | https://github.com/forge/javaee-descriptors/blob/cb914330a1a0b04bfc1d0f199bd9cde3bbf0b3ed/impl/src/main/java/org/jboss/shrinkwrap/descriptor/impl/facelettaglibrary20/WebFacelettaglibraryDescriptorImpl.java#L87-L91 |
facebook/fresco | fbcore/src/main/java/com/facebook/common/statfs/StatFsHelper.java | StatFsHelper.updateStatsHelper | private @Nullable StatFs updateStatsHelper(@Nullable StatFs statfs, @Nullable File dir) {
"""
Update stats for a single directory and return the StatFs object for that directory. If the
directory does not exist or the StatFs restat() or constructor fails (throws), a null StatFs
object is returned.
"""
if(dir == null || !dir.exists()) {
// The path does not exist, do not track stats for it.
return null;
}
try {
if (statfs == null) {
// Create a new StatFs object for this path.
statfs = createStatFs(dir.getAbsolutePath());
} else {
// Call restat and keep the existing StatFs object.
statfs.restat(dir.getAbsolutePath());
}
} catch (IllegalArgumentException ex) {
// Invalidate the StatFs object for this directory. The native StatFs implementation throws
// IllegalArgumentException in the case that the statfs() system call fails and it invalidates
// its internal data structures so subsequent calls against the StatFs object will fail or
// throw (so we should make no more calls on the object). The most likely reason for this call
// to fail is because the provided path no longer exists. The next call to updateStats() will
// a new statfs object if the path exists. This will handle the case that a path is unmounted
// and later remounted (but it has to have been mounted when this object was initialized).
statfs = null;
} catch (Throwable ex) {
// Any other exception types are not expected and should be propagated as runtime errors.
throw Throwables.propagate(ex);
}
return statfs;
} | java | private @Nullable StatFs updateStatsHelper(@Nullable StatFs statfs, @Nullable File dir) {
if(dir == null || !dir.exists()) {
// The path does not exist, do not track stats for it.
return null;
}
try {
if (statfs == null) {
// Create a new StatFs object for this path.
statfs = createStatFs(dir.getAbsolutePath());
} else {
// Call restat and keep the existing StatFs object.
statfs.restat(dir.getAbsolutePath());
}
} catch (IllegalArgumentException ex) {
// Invalidate the StatFs object for this directory. The native StatFs implementation throws
// IllegalArgumentException in the case that the statfs() system call fails and it invalidates
// its internal data structures so subsequent calls against the StatFs object will fail or
// throw (so we should make no more calls on the object). The most likely reason for this call
// to fail is because the provided path no longer exists. The next call to updateStats() will
// a new statfs object if the path exists. This will handle the case that a path is unmounted
// and later remounted (but it has to have been mounted when this object was initialized).
statfs = null;
} catch (Throwable ex) {
// Any other exception types are not expected and should be propagated as runtime errors.
throw Throwables.propagate(ex);
}
return statfs;
} | [
"private",
"@",
"Nullable",
"StatFs",
"updateStatsHelper",
"(",
"@",
"Nullable",
"StatFs",
"statfs",
",",
"@",
"Nullable",
"File",
"dir",
")",
"{",
"if",
"(",
"dir",
"==",
"null",
"||",
"!",
"dir",
".",
"exists",
"(",
")",
")",
"{",
"// The path does not exist, do not track stats for it.",
"return",
"null",
";",
"}",
"try",
"{",
"if",
"(",
"statfs",
"==",
"null",
")",
"{",
"// Create a new StatFs object for this path.",
"statfs",
"=",
"createStatFs",
"(",
"dir",
".",
"getAbsolutePath",
"(",
")",
")",
";",
"}",
"else",
"{",
"// Call restat and keep the existing StatFs object.",
"statfs",
".",
"restat",
"(",
"dir",
".",
"getAbsolutePath",
"(",
")",
")",
";",
"}",
"}",
"catch",
"(",
"IllegalArgumentException",
"ex",
")",
"{",
"// Invalidate the StatFs object for this directory. The native StatFs implementation throws",
"// IllegalArgumentException in the case that the statfs() system call fails and it invalidates",
"// its internal data structures so subsequent calls against the StatFs object will fail or",
"// throw (so we should make no more calls on the object). The most likely reason for this call",
"// to fail is because the provided path no longer exists. The next call to updateStats() will",
"// a new statfs object if the path exists. This will handle the case that a path is unmounted",
"// and later remounted (but it has to have been mounted when this object was initialized).",
"statfs",
"=",
"null",
";",
"}",
"catch",
"(",
"Throwable",
"ex",
")",
"{",
"// Any other exception types are not expected and should be propagated as runtime errors.",
"throw",
"Throwables",
".",
"propagate",
"(",
"ex",
")",
";",
"}",
"return",
"statfs",
";",
"}"
]
| Update stats for a single directory and return the StatFs object for that directory. If the
directory does not exist or the StatFs restat() or constructor fails (throws), a null StatFs
object is returned. | [
"Update",
"stats",
"for",
"a",
"single",
"directory",
"and",
"return",
"the",
"StatFs",
"object",
"for",
"that",
"directory",
".",
"If",
"the",
"directory",
"does",
"not",
"exist",
"or",
"the",
"StatFs",
"restat",
"()",
"or",
"constructor",
"fails",
"(",
"throws",
")",
"a",
"null",
"StatFs",
"object",
"is",
"returned",
"."
]
| train | https://github.com/facebook/fresco/blob/0b85879d51c5036d5e46e627a6651afefc0b971a/fbcore/src/main/java/com/facebook/common/statfs/StatFsHelper.java#L259-L288 |
OpenLiberty/open-liberty | dev/com.ibm.ws.messaging.runtime/src/com/ibm/ws/sib/processor/impl/DestinationManager.java | DestinationManager.checkMQLinkExists | private void checkMQLinkExists(boolean condition, String mqlinkName)
throws SINotPossibleInCurrentConfigurationException {
"""
Asserts that an MQLink exists. Throws out the
appropriate exception if the condition has failed.
@param condition This is the existence check. An expression here should
evaluate to true if the destination exists, false otherwise.
For example, a simple expression here could be (dh != null).
@param mqLinkName The name of the link we were looking for.
@throws SINotPossibleInCurrentConfigurationException
"""
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(
tc,
"checkMQLinkExists",
new Object[] { new Boolean(condition), mqlinkName });
if (!condition)
{
SIMPNotPossibleInCurrentConfigurationException e =
new SIMPNotPossibleInCurrentConfigurationException(
nls_cwsik.getFormattedMessage(
"DELIVERY_ERROR_SIRC_42",
new Object[] { mqlinkName, messageProcessor.getMessagingEngineName(),
messageProcessor.getMessagingEngineBus() },
null));
e.setExceptionInserts(new String[] { mqlinkName, messageProcessor.getMessagingEngineName(), messageProcessor.getMessagingEngineBus() });
e.setExceptionReason(SIRCConstants.SIRC0042_MQ_LINK_NOT_FOUND_ERROR);
SibTr.exception(tc, e);
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "checkMQLinkExists", e);
throw e;
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "checkMQLinkExists");
} | java | private void checkMQLinkExists(boolean condition, String mqlinkName)
throws SINotPossibleInCurrentConfigurationException
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(
tc,
"checkMQLinkExists",
new Object[] { new Boolean(condition), mqlinkName });
if (!condition)
{
SIMPNotPossibleInCurrentConfigurationException e =
new SIMPNotPossibleInCurrentConfigurationException(
nls_cwsik.getFormattedMessage(
"DELIVERY_ERROR_SIRC_42",
new Object[] { mqlinkName, messageProcessor.getMessagingEngineName(),
messageProcessor.getMessagingEngineBus() },
null));
e.setExceptionInserts(new String[] { mqlinkName, messageProcessor.getMessagingEngineName(), messageProcessor.getMessagingEngineBus() });
e.setExceptionReason(SIRCConstants.SIRC0042_MQ_LINK_NOT_FOUND_ERROR);
SibTr.exception(tc, e);
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "checkMQLinkExists", e);
throw e;
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "checkMQLinkExists");
} | [
"private",
"void",
"checkMQLinkExists",
"(",
"boolean",
"condition",
",",
"String",
"mqlinkName",
")",
"throws",
"SINotPossibleInCurrentConfigurationException",
"{",
"if",
"(",
"TraceComponent",
".",
"isAnyTracingEnabled",
"(",
")",
"&&",
"tc",
".",
"isEntryEnabled",
"(",
")",
")",
"SibTr",
".",
"entry",
"(",
"tc",
",",
"\"checkMQLinkExists\"",
",",
"new",
"Object",
"[",
"]",
"{",
"new",
"Boolean",
"(",
"condition",
")",
",",
"mqlinkName",
"}",
")",
";",
"if",
"(",
"!",
"condition",
")",
"{",
"SIMPNotPossibleInCurrentConfigurationException",
"e",
"=",
"new",
"SIMPNotPossibleInCurrentConfigurationException",
"(",
"nls_cwsik",
".",
"getFormattedMessage",
"(",
"\"DELIVERY_ERROR_SIRC_42\"",
",",
"new",
"Object",
"[",
"]",
"{",
"mqlinkName",
",",
"messageProcessor",
".",
"getMessagingEngineName",
"(",
")",
",",
"messageProcessor",
".",
"getMessagingEngineBus",
"(",
")",
"}",
",",
"null",
")",
")",
";",
"e",
".",
"setExceptionInserts",
"(",
"new",
"String",
"[",
"]",
"{",
"mqlinkName",
",",
"messageProcessor",
".",
"getMessagingEngineName",
"(",
")",
",",
"messageProcessor",
".",
"getMessagingEngineBus",
"(",
")",
"}",
")",
";",
"e",
".",
"setExceptionReason",
"(",
"SIRCConstants",
".",
"SIRC0042_MQ_LINK_NOT_FOUND_ERROR",
")",
";",
"SibTr",
".",
"exception",
"(",
"tc",
",",
"e",
")",
";",
"if",
"(",
"TraceComponent",
".",
"isAnyTracingEnabled",
"(",
")",
"&&",
"tc",
".",
"isEntryEnabled",
"(",
")",
")",
"SibTr",
".",
"exit",
"(",
"tc",
",",
"\"checkMQLinkExists\"",
",",
"e",
")",
";",
"throw",
"e",
";",
"}",
"if",
"(",
"TraceComponent",
".",
"isAnyTracingEnabled",
"(",
")",
"&&",
"tc",
".",
"isEntryEnabled",
"(",
")",
")",
"SibTr",
".",
"exit",
"(",
"tc",
",",
"\"checkMQLinkExists\"",
")",
";",
"}"
]
| Asserts that an MQLink exists. Throws out the
appropriate exception if the condition has failed.
@param condition This is the existence check. An expression here should
evaluate to true if the destination exists, false otherwise.
For example, a simple expression here could be (dh != null).
@param mqLinkName The name of the link we were looking for.
@throws SINotPossibleInCurrentConfigurationException | [
"Asserts",
"that",
"an",
"MQLink",
"exists",
".",
"Throws",
"out",
"the",
"appropriate",
"exception",
"if",
"the",
"condition",
"has",
"failed",
"."
]
| train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.messaging.runtime/src/com/ibm/ws/sib/processor/impl/DestinationManager.java#L4260-L4294 |
algolia/instantsearch-android | core/src/main/java/com/algolia/instantsearch/core/helpers/Searcher.java | Searcher.create | @SuppressWarnings( {
"""
Constructs a Searcher from an existing {@link Searchable}.
@param searchable an Index initialized and eventually configured.
@return the new instance.
""""WeakerAccess", "unused"}) // For library users
public static Searcher create(@NonNull final Searchable searchable) {
final String key = searchable.toString();
Searcher instance = instances.get(key);
if (instance == null) {
instance = new Searcher(searchable, key);
instances.put(key, instance);
} else {
throw new IllegalStateException("There is already a Searcher for index " + key + ", you must specify a variant.");
}
return instance;
} | java | @SuppressWarnings({"WeakerAccess", "unused"}) // For library users
public static Searcher create(@NonNull final Searchable searchable) {
final String key = searchable.toString();
Searcher instance = instances.get(key);
if (instance == null) {
instance = new Searcher(searchable, key);
instances.put(key, instance);
} else {
throw new IllegalStateException("There is already a Searcher for index " + key + ", you must specify a variant.");
}
return instance;
} | [
"@",
"SuppressWarnings",
"(",
"{",
"\"WeakerAccess\"",
",",
"\"unused\"",
"}",
")",
"// For library users",
"public",
"static",
"Searcher",
"create",
"(",
"@",
"NonNull",
"final",
"Searchable",
"searchable",
")",
"{",
"final",
"String",
"key",
"=",
"searchable",
".",
"toString",
"(",
")",
";",
"Searcher",
"instance",
"=",
"instances",
".",
"get",
"(",
"key",
")",
";",
"if",
"(",
"instance",
"==",
"null",
")",
"{",
"instance",
"=",
"new",
"Searcher",
"(",
"searchable",
",",
"key",
")",
";",
"instances",
".",
"put",
"(",
"key",
",",
"instance",
")",
";",
"}",
"else",
"{",
"throw",
"new",
"IllegalStateException",
"(",
"\"There is already a Searcher for index \"",
"+",
"key",
"+",
"\", you must specify a variant.\"",
")",
";",
"}",
"return",
"instance",
";",
"}"
]
| Constructs a Searcher from an existing {@link Searchable}.
@param searchable an Index initialized and eventually configured.
@return the new instance. | [
"Constructs",
"a",
"Searcher",
"from",
"an",
"existing",
"{",
"@link",
"Searchable",
"}",
"."
]
| train | https://github.com/algolia/instantsearch-android/blob/12092ec30140df9ffc2bf916339b433372034616/core/src/main/java/com/algolia/instantsearch/core/helpers/Searcher.java#L207-L218 |
apache/flink | flink-runtime/src/main/java/org/apache/flink/runtime/net/SSLUtils.java | SSLUtils.createRestServerSSLContext | @Nullable
public static SSLContext createRestServerSSLContext(Configuration config) throws Exception {
"""
Creates an SSL context for the external REST endpoint server.
"""
final RestSSLContextConfigMode configMode;
if (isRestSSLAuthenticationEnabled(config)) {
configMode = RestSSLContextConfigMode.MUTUAL;
} else {
configMode = RestSSLContextConfigMode.SERVER;
}
return createRestSSLContext(config, configMode);
} | java | @Nullable
public static SSLContext createRestServerSSLContext(Configuration config) throws Exception {
final RestSSLContextConfigMode configMode;
if (isRestSSLAuthenticationEnabled(config)) {
configMode = RestSSLContextConfigMode.MUTUAL;
} else {
configMode = RestSSLContextConfigMode.SERVER;
}
return createRestSSLContext(config, configMode);
} | [
"@",
"Nullable",
"public",
"static",
"SSLContext",
"createRestServerSSLContext",
"(",
"Configuration",
"config",
")",
"throws",
"Exception",
"{",
"final",
"RestSSLContextConfigMode",
"configMode",
";",
"if",
"(",
"isRestSSLAuthenticationEnabled",
"(",
"config",
")",
")",
"{",
"configMode",
"=",
"RestSSLContextConfigMode",
".",
"MUTUAL",
";",
"}",
"else",
"{",
"configMode",
"=",
"RestSSLContextConfigMode",
".",
"SERVER",
";",
"}",
"return",
"createRestSSLContext",
"(",
"config",
",",
"configMode",
")",
";",
"}"
]
| Creates an SSL context for the external REST endpoint server. | [
"Creates",
"an",
"SSL",
"context",
"for",
"the",
"external",
"REST",
"endpoint",
"server",
"."
]
| train | https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-runtime/src/main/java/org/apache/flink/runtime/net/SSLUtils.java#L328-L338 |
lessthanoptimal/ejml | main/ejml-ddense/src/org/ejml/dense/row/CommonOps_DDRM.java | CommonOps_DDRM.multAddTransB | public static void multAddTransB(DMatrix1Row a , DMatrix1Row b , DMatrix1Row c ) {
"""
<p>
Performs the following operation:<br>
<br>
c = c + a * b<sup>T</sup> <br>
c<sub>ij</sub> = c<sub>ij</sub> + ∑<sub>k=1:n</sub> { a<sub>ik</sub> * b<sub>jk</sub>}
</p>
@param a The left matrix in the multiplication operation. Not modified.
@param b The right matrix in the multiplication operation. Not modified.
@param c Where the results of the operation are stored. Modified.
"""
MatrixMatrixMult_DDRM.multAddTransB(a,b,c);
} | java | public static void multAddTransB(DMatrix1Row a , DMatrix1Row b , DMatrix1Row c )
{
MatrixMatrixMult_DDRM.multAddTransB(a,b,c);
} | [
"public",
"static",
"void",
"multAddTransB",
"(",
"DMatrix1Row",
"a",
",",
"DMatrix1Row",
"b",
",",
"DMatrix1Row",
"c",
")",
"{",
"MatrixMatrixMult_DDRM",
".",
"multAddTransB",
"(",
"a",
",",
"b",
",",
"c",
")",
";",
"}"
]
| <p>
Performs the following operation:<br>
<br>
c = c + a * b<sup>T</sup> <br>
c<sub>ij</sub> = c<sub>ij</sub> + ∑<sub>k=1:n</sub> { a<sub>ik</sub> * b<sub>jk</sub>}
</p>
@param a The left matrix in the multiplication operation. Not modified.
@param b The right matrix in the multiplication operation. Not modified.
@param c Where the results of the operation are stored. Modified. | [
"<p",
">",
"Performs",
"the",
"following",
"operation",
":",
"<br",
">",
"<br",
">",
"c",
"=",
"c",
"+",
"a",
"*",
"b<sup",
">",
"T<",
"/",
"sup",
">",
"<br",
">",
"c<sub",
">",
"ij<",
"/",
"sub",
">",
"=",
"c<sub",
">",
"ij<",
"/",
"sub",
">",
"+",
"&sum",
";",
"<sub",
">",
"k",
"=",
"1",
":",
"n<",
"/",
"sub",
">",
"{",
"a<sub",
">",
"ik<",
"/",
"sub",
">",
"*",
"b<sub",
">",
"jk<",
"/",
"sub",
">",
"}",
"<",
"/",
"p",
">"
]
| train | https://github.com/lessthanoptimal/ejml/blob/1444680cc487af5e866730e62f48f5f9636850d9/main/ejml-ddense/src/org/ejml/dense/row/CommonOps_DDRM.java#L435-L438 |
ben-manes/caffeine | caffeine/src/main/java/com/github/benmanes/caffeine/cache/BoundedLocalCache.java | BoundedLocalCache.expireAfterAccessOrder | @SuppressWarnings("GuardedByChecker")
Map<K, V> expireAfterAccessOrder(int limit, Function<V, V> transformer, boolean oldest) {
"""
Returns an unmodifiable snapshot map ordered in access expiration order, either ascending or
descending. Beware that obtaining the mappings is <em>NOT</em> a constant-time operation.
@param limit the maximum number of entries
@param transformer a function that unwraps the value
@param oldest the iteration order
@return an unmodifiable snapshot in a specified order
"""
if (!evicts()) {
Supplier<Iterator<Node<K, V>>> iteratorSupplier = () -> oldest
? accessOrderWindowDeque().iterator()
: accessOrderWindowDeque().descendingIterator();
return fixedSnapshot(iteratorSupplier, limit, transformer);
}
Supplier<Iterator<Node<K, V>>> iteratorSupplier = () -> {
Comparator<Node<K, V>> comparator = Comparator.comparingLong(Node::getAccessTime);
PeekingIterator<Node<K, V>> first, second, third;
if (oldest) {
first = accessOrderWindowDeque().iterator();
second = accessOrderProbationDeque().iterator();
third = accessOrderProtectedDeque().iterator();
} else {
comparator = comparator.reversed();
first = accessOrderWindowDeque().descendingIterator();
second = accessOrderProbationDeque().descendingIterator();
third = accessOrderProtectedDeque().descendingIterator();
}
return PeekingIterator.comparing(
PeekingIterator.comparing(first, second, comparator), third, comparator);
};
return fixedSnapshot(iteratorSupplier, limit, transformer);
} | java | @SuppressWarnings("GuardedByChecker")
Map<K, V> expireAfterAccessOrder(int limit, Function<V, V> transformer, boolean oldest) {
if (!evicts()) {
Supplier<Iterator<Node<K, V>>> iteratorSupplier = () -> oldest
? accessOrderWindowDeque().iterator()
: accessOrderWindowDeque().descendingIterator();
return fixedSnapshot(iteratorSupplier, limit, transformer);
}
Supplier<Iterator<Node<K, V>>> iteratorSupplier = () -> {
Comparator<Node<K, V>> comparator = Comparator.comparingLong(Node::getAccessTime);
PeekingIterator<Node<K, V>> first, second, third;
if (oldest) {
first = accessOrderWindowDeque().iterator();
second = accessOrderProbationDeque().iterator();
third = accessOrderProtectedDeque().iterator();
} else {
comparator = comparator.reversed();
first = accessOrderWindowDeque().descendingIterator();
second = accessOrderProbationDeque().descendingIterator();
third = accessOrderProtectedDeque().descendingIterator();
}
return PeekingIterator.comparing(
PeekingIterator.comparing(first, second, comparator), third, comparator);
};
return fixedSnapshot(iteratorSupplier, limit, transformer);
} | [
"@",
"SuppressWarnings",
"(",
"\"GuardedByChecker\"",
")",
"Map",
"<",
"K",
",",
"V",
">",
"expireAfterAccessOrder",
"(",
"int",
"limit",
",",
"Function",
"<",
"V",
",",
"V",
">",
"transformer",
",",
"boolean",
"oldest",
")",
"{",
"if",
"(",
"!",
"evicts",
"(",
")",
")",
"{",
"Supplier",
"<",
"Iterator",
"<",
"Node",
"<",
"K",
",",
"V",
">",
">",
">",
"iteratorSupplier",
"=",
"(",
")",
"->",
"oldest",
"?",
"accessOrderWindowDeque",
"(",
")",
".",
"iterator",
"(",
")",
":",
"accessOrderWindowDeque",
"(",
")",
".",
"descendingIterator",
"(",
")",
";",
"return",
"fixedSnapshot",
"(",
"iteratorSupplier",
",",
"limit",
",",
"transformer",
")",
";",
"}",
"Supplier",
"<",
"Iterator",
"<",
"Node",
"<",
"K",
",",
"V",
">",
">",
">",
"iteratorSupplier",
"=",
"(",
")",
"->",
"{",
"Comparator",
"<",
"Node",
"<",
"K",
",",
"V",
">",
">",
"comparator",
"=",
"Comparator",
".",
"comparingLong",
"(",
"Node",
"::",
"getAccessTime",
")",
";",
"PeekingIterator",
"<",
"Node",
"<",
"K",
",",
"V",
">",
">",
"first",
",",
"second",
",",
"third",
";",
"if",
"(",
"oldest",
")",
"{",
"first",
"=",
"accessOrderWindowDeque",
"(",
")",
".",
"iterator",
"(",
")",
";",
"second",
"=",
"accessOrderProbationDeque",
"(",
")",
".",
"iterator",
"(",
")",
";",
"third",
"=",
"accessOrderProtectedDeque",
"(",
")",
".",
"iterator",
"(",
")",
";",
"}",
"else",
"{",
"comparator",
"=",
"comparator",
".",
"reversed",
"(",
")",
";",
"first",
"=",
"accessOrderWindowDeque",
"(",
")",
".",
"descendingIterator",
"(",
")",
";",
"second",
"=",
"accessOrderProbationDeque",
"(",
")",
".",
"descendingIterator",
"(",
")",
";",
"third",
"=",
"accessOrderProtectedDeque",
"(",
")",
".",
"descendingIterator",
"(",
")",
";",
"}",
"return",
"PeekingIterator",
".",
"comparing",
"(",
"PeekingIterator",
".",
"comparing",
"(",
"first",
",",
"second",
",",
"comparator",
")",
",",
"third",
",",
"comparator",
")",
";",
"}",
";",
"return",
"fixedSnapshot",
"(",
"iteratorSupplier",
",",
"limit",
",",
"transformer",
")",
";",
"}"
]
| Returns an unmodifiable snapshot map ordered in access expiration order, either ascending or
descending. Beware that obtaining the mappings is <em>NOT</em> a constant-time operation.
@param limit the maximum number of entries
@param transformer a function that unwraps the value
@param oldest the iteration order
@return an unmodifiable snapshot in a specified order | [
"Returns",
"an",
"unmodifiable",
"snapshot",
"map",
"ordered",
"in",
"access",
"expiration",
"order",
"either",
"ascending",
"or",
"descending",
".",
"Beware",
"that",
"obtaining",
"the",
"mappings",
"is",
"<em",
">",
"NOT<",
"/",
"em",
">",
"a",
"constant",
"-",
"time",
"operation",
"."
]
| train | https://github.com/ben-manes/caffeine/blob/4cf6d6e6a18ea2e8088f166261e5949343b0f2eb/caffeine/src/main/java/com/github/benmanes/caffeine/cache/BoundedLocalCache.java#L2650-L2676 |
SimiaCryptus/utilities | java-util/src/main/java/com/simiacryptus/util/binary/BitInputStream.java | BitInputStream.readAhead | public Bits readAhead(final int bytes) throws IOException {
"""
Read ahead bits.
@param bytes the bytes
@return the bits
@throws IOException the io exception
"""
assert (0 < bytes);
if (0 < bytes) {
final byte[] buffer = new byte[bytes];
int bytesRead = this.inner.read(buffer);
if (bytesRead > 0) {
this.remainder = this.remainder.concatenate(new Bits(Arrays.copyOf(buffer, bytesRead)));
}
}
return this.remainder;
} | java | public Bits readAhead(final int bytes) throws IOException {
assert (0 < bytes);
if (0 < bytes) {
final byte[] buffer = new byte[bytes];
int bytesRead = this.inner.read(buffer);
if (bytesRead > 0) {
this.remainder = this.remainder.concatenate(new Bits(Arrays.copyOf(buffer, bytesRead)));
}
}
return this.remainder;
} | [
"public",
"Bits",
"readAhead",
"(",
"final",
"int",
"bytes",
")",
"throws",
"IOException",
"{",
"assert",
"(",
"0",
"<",
"bytes",
")",
";",
"if",
"(",
"0",
"<",
"bytes",
")",
"{",
"final",
"byte",
"[",
"]",
"buffer",
"=",
"new",
"byte",
"[",
"bytes",
"]",
";",
"int",
"bytesRead",
"=",
"this",
".",
"inner",
".",
"read",
"(",
"buffer",
")",
";",
"if",
"(",
"bytesRead",
">",
"0",
")",
"{",
"this",
".",
"remainder",
"=",
"this",
".",
"remainder",
".",
"concatenate",
"(",
"new",
"Bits",
"(",
"Arrays",
".",
"copyOf",
"(",
"buffer",
",",
"bytesRead",
")",
")",
")",
";",
"}",
"}",
"return",
"this",
".",
"remainder",
";",
"}"
]
| Read ahead bits.
@param bytes the bytes
@return the bits
@throws IOException the io exception | [
"Read",
"ahead",
"bits",
"."
]
| train | https://github.com/SimiaCryptus/utilities/blob/b5a5e73449aae57de7dbfca2ed7a074432c5b17e/java-util/src/main/java/com/simiacryptus/util/binary/BitInputStream.java#L150-L160 |
xmlunit/xmlunit | xmlunit-core/src/main/java/org/xmlunit/diff/DefaultComparisonFormatter.java | DefaultComparisonFormatter.appendDocumentElementIndication | protected void appendDocumentElementIndication(StringBuilder sb, Document doc) {
"""
Appends a short indication of the document's root element like "<ElementName...>" for {@link
#getShortString}.
@param sb the builder to append to
@param doc the XML document node
@since XMLUnit 2.4.0
"""
sb.append("<");
sb.append(doc.getDocumentElement().getNodeName());
sb.append("...>");
} | java | protected void appendDocumentElementIndication(StringBuilder sb, Document doc) {
sb.append("<");
sb.append(doc.getDocumentElement().getNodeName());
sb.append("...>");
} | [
"protected",
"void",
"appendDocumentElementIndication",
"(",
"StringBuilder",
"sb",
",",
"Document",
"doc",
")",
"{",
"sb",
".",
"append",
"(",
"\"<\"",
")",
";",
"sb",
".",
"append",
"(",
"doc",
".",
"getDocumentElement",
"(",
")",
".",
"getNodeName",
"(",
")",
")",
";",
"sb",
".",
"append",
"(",
"\"...>\"",
")",
";",
"}"
]
| Appends a short indication of the document's root element like "<ElementName...>" for {@link
#getShortString}.
@param sb the builder to append to
@param doc the XML document node
@since XMLUnit 2.4.0 | [
"Appends",
"a",
"short",
"indication",
"of",
"the",
"document",
"s",
"root",
"element",
"like",
"<",
";",
"ElementName",
"...",
">",
";",
"for",
"{",
"@link",
"#getShortString",
"}",
"."
]
| train | https://github.com/xmlunit/xmlunit/blob/fe3d701d43f57ee83dcba336e4c1555619d3084b/xmlunit-core/src/main/java/org/xmlunit/diff/DefaultComparisonFormatter.java#L205-L209 |
infinispan/infinispan | core/src/main/java/org/infinispan/atomic/AtomicMapLookup.java | AtomicMapLookup.getAtomicMap | public static <MK, K, V> AtomicMap<K, V> getAtomicMap(Cache<MK, ?> cache, MK key) {
"""
Retrieves an atomic map from a given cache, stored under a given key. If an atomic map did not exist, one is
created and registered in an atomic fashion.
@param cache underlying cache
@param key key under which the atomic map exists
@param <MK> key param of the cache
@param <K> key param of the AtomicMap
@param <V> value param of the AtomicMap
@return an AtomicMap
"""
return getAtomicMap(cache, key, true);
} | java | public static <MK, K, V> AtomicMap<K, V> getAtomicMap(Cache<MK, ?> cache, MK key) {
return getAtomicMap(cache, key, true);
} | [
"public",
"static",
"<",
"MK",
",",
"K",
",",
"V",
">",
"AtomicMap",
"<",
"K",
",",
"V",
">",
"getAtomicMap",
"(",
"Cache",
"<",
"MK",
",",
"?",
">",
"cache",
",",
"MK",
"key",
")",
"{",
"return",
"getAtomicMap",
"(",
"cache",
",",
"key",
",",
"true",
")",
";",
"}"
]
| Retrieves an atomic map from a given cache, stored under a given key. If an atomic map did not exist, one is
created and registered in an atomic fashion.
@param cache underlying cache
@param key key under which the atomic map exists
@param <MK> key param of the cache
@param <K> key param of the AtomicMap
@param <V> value param of the AtomicMap
@return an AtomicMap | [
"Retrieves",
"an",
"atomic",
"map",
"from",
"a",
"given",
"cache",
"stored",
"under",
"a",
"given",
"key",
".",
"If",
"an",
"atomic",
"map",
"did",
"not",
"exist",
"one",
"is",
"created",
"and",
"registered",
"in",
"an",
"atomic",
"fashion",
"."
]
| train | https://github.com/infinispan/infinispan/blob/7c62b94886c3febb4774ae8376acf2baa0265ab5/core/src/main/java/org/infinispan/atomic/AtomicMapLookup.java#L33-L35 |
google/closure-templates | java/src/com/google/template/soy/soytree/SoyTreeUtils.java | SoyTreeUtils.cloneWithNewIds | public static <T extends SoyNode> T cloneWithNewIds(T origNode, IdGenerator nodeIdGen) {
"""
Clones the given node and then generates and sets new ids on all the cloned nodes (by default,
SoyNode.copy(copyState) creates cloned nodes with the same ids as the original nodes).
<p>This function will use the original Soy tree's node id generator to generate the new node
ids for the cloned nodes. Thus, the original node to be cloned must be part of a full Soy tree.
However, this does not mean that the cloned node will become part of the original tree (unless
it is manually attached later). The cloned node will be an independent subtree with parent set
to null.
@param <T> The type of the node being cloned.
@param origNode The original node to be cloned. This node must be part of a full Soy tree,
because the generator for the new node ids will be retrieved from the root (SoyFileSetNode)
of the tree.
@param nodeIdGen The ID generator used for the tree.
@return The cloned node, with all new ids for its subtree.
"""
// Clone the node.
@SuppressWarnings("unchecked")
T clone = (T) origNode.copy(new CopyState());
// Generate new ids.
(new GenNewIdsVisitor(nodeIdGen)).exec(clone);
return clone;
} | java | public static <T extends SoyNode> T cloneWithNewIds(T origNode, IdGenerator nodeIdGen) {
// Clone the node.
@SuppressWarnings("unchecked")
T clone = (T) origNode.copy(new CopyState());
// Generate new ids.
(new GenNewIdsVisitor(nodeIdGen)).exec(clone);
return clone;
} | [
"public",
"static",
"<",
"T",
"extends",
"SoyNode",
">",
"T",
"cloneWithNewIds",
"(",
"T",
"origNode",
",",
"IdGenerator",
"nodeIdGen",
")",
"{",
"// Clone the node.",
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"T",
"clone",
"=",
"(",
"T",
")",
"origNode",
".",
"copy",
"(",
"new",
"CopyState",
"(",
")",
")",
";",
"// Generate new ids.",
"(",
"new",
"GenNewIdsVisitor",
"(",
"nodeIdGen",
")",
")",
".",
"exec",
"(",
"clone",
")",
";",
"return",
"clone",
";",
"}"
]
| Clones the given node and then generates and sets new ids on all the cloned nodes (by default,
SoyNode.copy(copyState) creates cloned nodes with the same ids as the original nodes).
<p>This function will use the original Soy tree's node id generator to generate the new node
ids for the cloned nodes. Thus, the original node to be cloned must be part of a full Soy tree.
However, this does not mean that the cloned node will become part of the original tree (unless
it is manually attached later). The cloned node will be an independent subtree with parent set
to null.
@param <T> The type of the node being cloned.
@param origNode The original node to be cloned. This node must be part of a full Soy tree,
because the generator for the new node ids will be retrieved from the root (SoyFileSetNode)
of the tree.
@param nodeIdGen The ID generator used for the tree.
@return The cloned node, with all new ids for its subtree. | [
"Clones",
"the",
"given",
"node",
"and",
"then",
"generates",
"and",
"sets",
"new",
"ids",
"on",
"all",
"the",
"cloned",
"nodes",
"(",
"by",
"default",
"SoyNode",
".",
"copy",
"(",
"copyState",
")",
"creates",
"cloned",
"nodes",
"with",
"the",
"same",
"ids",
"as",
"the",
"original",
"nodes",
")",
"."
]
| train | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/soytree/SoyTreeUtils.java#L281-L291 |
OpenLiberty/open-liberty | dev/com.ibm.ws.channel.ssl/src/com/ibm/ws/channel/ssl/internal/SSLUtils.java | SSLUtils.flipBuffersToMark | public static void flipBuffersToMark(WsByteBuffer buffers[], int mark, int markBufferIndex) {
"""
Sort of like Buffer.flip(). The limit is set to the postion,
but the position is set differently. If the index of the buffer
is markIndex and the mark is not zero, then the position will of
that buffer will be set to mark. All other buffers will be flipped.
@param buffers buffers on which flip to mark
@param mark the mark to be set on the indexed buffer in the array
@param markBufferIndex the index into the array where the mark should be placed
"""
WsByteBuffer buffer = null;
// Verify the input buffer array is not null.
if (buffers != null) {
// Loop through all the buffers in the array.
for (int i = 0; i < buffers.length; i++) {
// Extract each buffer.
buffer = buffers[i];
// Verify the buffer is non null.
if (buffer != null) {
if (i == markBufferIndex && mark != 0) {
// Found the "marked" buffer.
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "mark is " + mark);
}
buffer.limit(buffer.position());
buffer.position(mark);
} else {
// Not the "marked" buffer, so flip it.
buffer.flip();
}
}
}
}
} | java | public static void flipBuffersToMark(WsByteBuffer buffers[], int mark, int markBufferIndex) {
WsByteBuffer buffer = null;
// Verify the input buffer array is not null.
if (buffers != null) {
// Loop through all the buffers in the array.
for (int i = 0; i < buffers.length; i++) {
// Extract each buffer.
buffer = buffers[i];
// Verify the buffer is non null.
if (buffer != null) {
if (i == markBufferIndex && mark != 0) {
// Found the "marked" buffer.
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "mark is " + mark);
}
buffer.limit(buffer.position());
buffer.position(mark);
} else {
// Not the "marked" buffer, so flip it.
buffer.flip();
}
}
}
}
} | [
"public",
"static",
"void",
"flipBuffersToMark",
"(",
"WsByteBuffer",
"buffers",
"[",
"]",
",",
"int",
"mark",
",",
"int",
"markBufferIndex",
")",
"{",
"WsByteBuffer",
"buffer",
"=",
"null",
";",
"// Verify the input buffer array is not null.",
"if",
"(",
"buffers",
"!=",
"null",
")",
"{",
"// Loop through all the buffers in the array.",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"buffers",
".",
"length",
";",
"i",
"++",
")",
"{",
"// Extract each buffer.",
"buffer",
"=",
"buffers",
"[",
"i",
"]",
";",
"// Verify the buffer is non null.",
"if",
"(",
"buffer",
"!=",
"null",
")",
"{",
"if",
"(",
"i",
"==",
"markBufferIndex",
"&&",
"mark",
"!=",
"0",
")",
"{",
"// Found the \"marked\" buffer.",
"if",
"(",
"TraceComponent",
".",
"isAnyTracingEnabled",
"(",
")",
"&&",
"tc",
".",
"isDebugEnabled",
"(",
")",
")",
"{",
"Tr",
".",
"debug",
"(",
"tc",
",",
"\"mark is \"",
"+",
"mark",
")",
";",
"}",
"buffer",
".",
"limit",
"(",
"buffer",
".",
"position",
"(",
")",
")",
";",
"buffer",
".",
"position",
"(",
"mark",
")",
";",
"}",
"else",
"{",
"// Not the \"marked\" buffer, so flip it.",
"buffer",
".",
"flip",
"(",
")",
";",
"}",
"}",
"}",
"}",
"}"
]
| Sort of like Buffer.flip(). The limit is set to the postion,
but the position is set differently. If the index of the buffer
is markIndex and the mark is not zero, then the position will of
that buffer will be set to mark. All other buffers will be flipped.
@param buffers buffers on which flip to mark
@param mark the mark to be set on the indexed buffer in the array
@param markBufferIndex the index into the array where the mark should be placed | [
"Sort",
"of",
"like",
"Buffer",
".",
"flip",
"()",
".",
"The",
"limit",
"is",
"set",
"to",
"the",
"postion",
"but",
"the",
"position",
"is",
"set",
"differently",
".",
"If",
"the",
"index",
"of",
"the",
"buffer",
"is",
"markIndex",
"and",
"the",
"mark",
"is",
"not",
"zero",
"then",
"the",
"position",
"will",
"of",
"that",
"buffer",
"will",
"be",
"set",
"to",
"mark",
".",
"All",
"other",
"buffers",
"will",
"be",
"flipped",
"."
]
| train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.channel.ssl/src/com/ibm/ws/channel/ssl/internal/SSLUtils.java#L322-L346 |
redkale/redkale | src/org/redkale/source/ColumnValue.java | ColumnValue.mov | public static ColumnValue mov(String column, Serializable value) {
"""
返回 {column} = {value} 操作
@param column 字段名
@param value 字段值
@return ColumnValue
"""
return new ColumnValue(column, MOV, value);
} | java | public static ColumnValue mov(String column, Serializable value) {
return new ColumnValue(column, MOV, value);
} | [
"public",
"static",
"ColumnValue",
"mov",
"(",
"String",
"column",
",",
"Serializable",
"value",
")",
"{",
"return",
"new",
"ColumnValue",
"(",
"column",
",",
"MOV",
",",
"value",
")",
";",
"}"
]
| 返回 {column} = {value} 操作
@param column 字段名
@param value 字段值
@return ColumnValue | [
"返回",
"{",
"column",
"}",
"=",
"{",
"value",
"}",
"操作"
]
| train | https://github.com/redkale/redkale/blob/ea5169b5c5ea7412fd762331c0c497165832e901/src/org/redkale/source/ColumnValue.java#L61-L63 |
spotbugs/spotbugs | spotbugs/src/main/java/edu/umd/cs/findbugs/BugInstance.java | BugInstance.addSourceLine | @Nonnull
public BugInstance addSourceLine(ClassContext classContext, Method method, Location location) {
"""
Add source line annotation for given Location in a method.
@param classContext
the ClassContext
@param method
the Method
@param location
the Location in the method
@return this BugInstance
"""
return addSourceLine(classContext, method, location.getHandle());
} | java | @Nonnull
public BugInstance addSourceLine(ClassContext classContext, Method method, Location location) {
return addSourceLine(classContext, method, location.getHandle());
} | [
"@",
"Nonnull",
"public",
"BugInstance",
"addSourceLine",
"(",
"ClassContext",
"classContext",
",",
"Method",
"method",
",",
"Location",
"location",
")",
"{",
"return",
"addSourceLine",
"(",
"classContext",
",",
"method",
",",
"location",
".",
"getHandle",
"(",
")",
")",
";",
"}"
]
| Add source line annotation for given Location in a method.
@param classContext
the ClassContext
@param method
the Method
@param location
the Location in the method
@return this BugInstance | [
"Add",
"source",
"line",
"annotation",
"for",
"given",
"Location",
"in",
"a",
"method",
"."
]
| train | https://github.com/spotbugs/spotbugs/blob/f6365c6eea6515035bded38efa4a7c8b46ccf28c/spotbugs/src/main/java/edu/umd/cs/findbugs/BugInstance.java#L1709-L1712 |
apache/flink | flink-connectors/flink-connector-kafka-0.9/src/main/java/org/apache/flink/streaming/connectors/kafka/internal/KafkaConsumerThread.java | KafkaConsumerThread.setOffsetsToCommit | void setOffsetsToCommit(
Map<TopicPartition, OffsetAndMetadata> offsetsToCommit,
@Nonnull KafkaCommitCallback commitCallback) {
"""
Tells this thread to commit a set of offsets. This method does not block, the committing
operation will happen asynchronously.
<p>Only one commit operation may be pending at any time. If the committing takes longer than
the frequency with which this method is called, then some commits may be skipped due to being
superseded by newer ones.
@param offsetsToCommit The offsets to commit
@param commitCallback callback when Kafka commit completes
"""
// record the work to be committed by the main consumer thread and make sure the consumer notices that
if (nextOffsetsToCommit.getAndSet(Tuple2.of(offsetsToCommit, commitCallback)) != null) {
log.warn("Committing offsets to Kafka takes longer than the checkpoint interval. " +
"Skipping commit of previous offsets because newer complete checkpoint offsets are available. " +
"This does not compromise Flink's checkpoint integrity.");
}
// if the consumer is blocked in a poll() or handover operation, wake it up to commit soon
handover.wakeupProducer();
synchronized (consumerReassignmentLock) {
if (consumer != null) {
consumer.wakeup();
} else {
// the consumer is currently isolated for partition reassignment;
// set this flag so that the wakeup state is restored once the reassignment is complete
hasBufferedWakeup = true;
}
}
} | java | void setOffsetsToCommit(
Map<TopicPartition, OffsetAndMetadata> offsetsToCommit,
@Nonnull KafkaCommitCallback commitCallback) {
// record the work to be committed by the main consumer thread and make sure the consumer notices that
if (nextOffsetsToCommit.getAndSet(Tuple2.of(offsetsToCommit, commitCallback)) != null) {
log.warn("Committing offsets to Kafka takes longer than the checkpoint interval. " +
"Skipping commit of previous offsets because newer complete checkpoint offsets are available. " +
"This does not compromise Flink's checkpoint integrity.");
}
// if the consumer is blocked in a poll() or handover operation, wake it up to commit soon
handover.wakeupProducer();
synchronized (consumerReassignmentLock) {
if (consumer != null) {
consumer.wakeup();
} else {
// the consumer is currently isolated for partition reassignment;
// set this flag so that the wakeup state is restored once the reassignment is complete
hasBufferedWakeup = true;
}
}
} | [
"void",
"setOffsetsToCommit",
"(",
"Map",
"<",
"TopicPartition",
",",
"OffsetAndMetadata",
">",
"offsetsToCommit",
",",
"@",
"Nonnull",
"KafkaCommitCallback",
"commitCallback",
")",
"{",
"// record the work to be committed by the main consumer thread and make sure the consumer notices that",
"if",
"(",
"nextOffsetsToCommit",
".",
"getAndSet",
"(",
"Tuple2",
".",
"of",
"(",
"offsetsToCommit",
",",
"commitCallback",
")",
")",
"!=",
"null",
")",
"{",
"log",
".",
"warn",
"(",
"\"Committing offsets to Kafka takes longer than the checkpoint interval. \"",
"+",
"\"Skipping commit of previous offsets because newer complete checkpoint offsets are available. \"",
"+",
"\"This does not compromise Flink's checkpoint integrity.\"",
")",
";",
"}",
"// if the consumer is blocked in a poll() or handover operation, wake it up to commit soon",
"handover",
".",
"wakeupProducer",
"(",
")",
";",
"synchronized",
"(",
"consumerReassignmentLock",
")",
"{",
"if",
"(",
"consumer",
"!=",
"null",
")",
"{",
"consumer",
".",
"wakeup",
"(",
")",
";",
"}",
"else",
"{",
"// the consumer is currently isolated for partition reassignment;",
"// set this flag so that the wakeup state is restored once the reassignment is complete",
"hasBufferedWakeup",
"=",
"true",
";",
"}",
"}",
"}"
]
| Tells this thread to commit a set of offsets. This method does not block, the committing
operation will happen asynchronously.
<p>Only one commit operation may be pending at any time. If the committing takes longer than
the frequency with which this method is called, then some commits may be skipped due to being
superseded by newer ones.
@param offsetsToCommit The offsets to commit
@param commitCallback callback when Kafka commit completes | [
"Tells",
"this",
"thread",
"to",
"commit",
"a",
"set",
"of",
"offsets",
".",
"This",
"method",
"does",
"not",
"block",
"the",
"committing",
"operation",
"will",
"happen",
"asynchronously",
"."
]
| train | https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-connectors/flink-connector-kafka-0.9/src/main/java/org/apache/flink/streaming/connectors/kafka/internal/KafkaConsumerThread.java#L352-L375 |
alkacon/opencms-core | src/org/opencms/file/CmsObject.java | CmsObject.setPassword | public void setPassword(String username, String newPassword) throws CmsException {
"""
Sets the password for a user.<p>
@param username the name of the user
@param newPassword the new password
@throws CmsException if operation was not successful
"""
m_securityManager.setPassword(m_context, username, newPassword);
} | java | public void setPassword(String username, String newPassword) throws CmsException {
m_securityManager.setPassword(m_context, username, newPassword);
} | [
"public",
"void",
"setPassword",
"(",
"String",
"username",
",",
"String",
"newPassword",
")",
"throws",
"CmsException",
"{",
"m_securityManager",
".",
"setPassword",
"(",
"m_context",
",",
"username",
",",
"newPassword",
")",
";",
"}"
]
| Sets the password for a user.<p>
@param username the name of the user
@param newPassword the new password
@throws CmsException if operation was not successful | [
"Sets",
"the",
"password",
"for",
"a",
"user",
".",
"<p",
">"
]
| train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/file/CmsObject.java#L3840-L3843 |
sarl/sarl | main/coreplugins/io.sarl.lang/src/io/sarl/lang/typesystem/SARLOperationHelper.java | SARLOperationHelper.evaluatePureAnnotationAdapters | boolean evaluatePureAnnotationAdapters(org.eclipse.xtext.common.types.JvmOperation operation, ISideEffectContext context) {
"""
Evalute the Pure annotatino adapters.
@param operation the operation to adapt.
@param context the context.
@return {@code true} if the pure annotation could be associated to the given operation.
"""
int index = -1;
int i = 0;
for (final Adapter adapter : operation.eAdapters()) {
if (adapter.isAdapterForType(AnnotationJavaGenerationAdapter.class)) {
index = i;
break;
}
++i;
}
if (index >= 0) {
final AnnotationJavaGenerationAdapter annotationAdapter = (AnnotationJavaGenerationAdapter) operation.eAdapters().get(index);
assert annotationAdapter != null;
return annotationAdapter.applyAdaptations(this, operation, context);
}
return false;
} | java | boolean evaluatePureAnnotationAdapters(org.eclipse.xtext.common.types.JvmOperation operation, ISideEffectContext context) {
int index = -1;
int i = 0;
for (final Adapter adapter : operation.eAdapters()) {
if (adapter.isAdapterForType(AnnotationJavaGenerationAdapter.class)) {
index = i;
break;
}
++i;
}
if (index >= 0) {
final AnnotationJavaGenerationAdapter annotationAdapter = (AnnotationJavaGenerationAdapter) operation.eAdapters().get(index);
assert annotationAdapter != null;
return annotationAdapter.applyAdaptations(this, operation, context);
}
return false;
} | [
"boolean",
"evaluatePureAnnotationAdapters",
"(",
"org",
".",
"eclipse",
".",
"xtext",
".",
"common",
".",
"types",
".",
"JvmOperation",
"operation",
",",
"ISideEffectContext",
"context",
")",
"{",
"int",
"index",
"=",
"-",
"1",
";",
"int",
"i",
"=",
"0",
";",
"for",
"(",
"final",
"Adapter",
"adapter",
":",
"operation",
".",
"eAdapters",
"(",
")",
")",
"{",
"if",
"(",
"adapter",
".",
"isAdapterForType",
"(",
"AnnotationJavaGenerationAdapter",
".",
"class",
")",
")",
"{",
"index",
"=",
"i",
";",
"break",
";",
"}",
"++",
"i",
";",
"}",
"if",
"(",
"index",
">=",
"0",
")",
"{",
"final",
"AnnotationJavaGenerationAdapter",
"annotationAdapter",
"=",
"(",
"AnnotationJavaGenerationAdapter",
")",
"operation",
".",
"eAdapters",
"(",
")",
".",
"get",
"(",
"index",
")",
";",
"assert",
"annotationAdapter",
"!=",
"null",
";",
"return",
"annotationAdapter",
".",
"applyAdaptations",
"(",
"this",
",",
"operation",
",",
"context",
")",
";",
"}",
"return",
"false",
";",
"}"
]
| Evalute the Pure annotatino adapters.
@param operation the operation to adapt.
@param context the context.
@return {@code true} if the pure annotation could be associated to the given operation. | [
"Evalute",
"the",
"Pure",
"annotatino",
"adapters",
"."
]
| train | https://github.com/sarl/sarl/blob/ca00ff994598c730339972def4e19a60e0b8cace/main/coreplugins/io.sarl.lang/src/io/sarl/lang/typesystem/SARLOperationHelper.java#L793-L809 |
deeplearning4j/deeplearning4j | nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/samediff/ops/SDBaseOps.java | SDBaseOps.gt | public SDVariable gt(SDVariable x, SDVariable y) {
"""
Greater than operation: elementwise x > y<br>
If x and y arrays have equal shape, the output shape is the same as these inputs.<br>
Note: supports broadcasting if x and y have different shapes and are broadcastable.<br>
Returns an array with values 1 where condition is satisfied, or value 0 otherwise.
@param x Input 1
@param y Input 2
@return Output SDVariable with values 0 and 1 based on where the condition is satisfied
"""
return gt(null, x, y);
} | java | public SDVariable gt(SDVariable x, SDVariable y) {
return gt(null, x, y);
} | [
"public",
"SDVariable",
"gt",
"(",
"SDVariable",
"x",
",",
"SDVariable",
"y",
")",
"{",
"return",
"gt",
"(",
"null",
",",
"x",
",",
"y",
")",
";",
"}"
]
| Greater than operation: elementwise x > y<br>
If x and y arrays have equal shape, the output shape is the same as these inputs.<br>
Note: supports broadcasting if x and y have different shapes and are broadcastable.<br>
Returns an array with values 1 where condition is satisfied, or value 0 otherwise.
@param x Input 1
@param y Input 2
@return Output SDVariable with values 0 and 1 based on where the condition is satisfied | [
"Greater",
"than",
"operation",
":",
"elementwise",
"x",
">",
"y<br",
">",
"If",
"x",
"and",
"y",
"arrays",
"have",
"equal",
"shape",
"the",
"output",
"shape",
"is",
"the",
"same",
"as",
"these",
"inputs",
".",
"<br",
">",
"Note",
":",
"supports",
"broadcasting",
"if",
"x",
"and",
"y",
"have",
"different",
"shapes",
"and",
"are",
"broadcastable",
".",
"<br",
">",
"Returns",
"an",
"array",
"with",
"values",
"1",
"where",
"condition",
"is",
"satisfied",
"or",
"value",
"0",
"otherwise",
"."
]
| train | https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/samediff/ops/SDBaseOps.java#L650-L652 |
threerings/gwt-utils | src/main/java/com/threerings/gwt/ui/DefaultTextListener.java | DefaultTextListener.getText | @Deprecated
public static String getText (TextBoxBase target, String defaultText) {
"""
Returns the contents of the supplied text box, accounting for the supplied default text.
@deprecated use Widgets.getText(TextBoxBase, String)
"""
String text = target.getText().trim();
return text.equals(defaultText.trim()) ? "" : text;
} | java | @Deprecated
public static String getText (TextBoxBase target, String defaultText)
{
String text = target.getText().trim();
return text.equals(defaultText.trim()) ? "" : text;
} | [
"@",
"Deprecated",
"public",
"static",
"String",
"getText",
"(",
"TextBoxBase",
"target",
",",
"String",
"defaultText",
")",
"{",
"String",
"text",
"=",
"target",
".",
"getText",
"(",
")",
".",
"trim",
"(",
")",
";",
"return",
"text",
".",
"equals",
"(",
"defaultText",
".",
"trim",
"(",
")",
")",
"?",
"\"\"",
":",
"text",
";",
"}"
]
| Returns the contents of the supplied text box, accounting for the supplied default text.
@deprecated use Widgets.getText(TextBoxBase, String) | [
"Returns",
"the",
"contents",
"of",
"the",
"supplied",
"text",
"box",
"accounting",
"for",
"the",
"supplied",
"default",
"text",
"."
]
| train | https://github.com/threerings/gwt-utils/blob/31b31a23b667f2a9c683160d77646db259f2aae5/src/main/java/com/threerings/gwt/ui/DefaultTextListener.java#L54-L59 |
b3log/latke | latke-core/src/main/java/org/json/JSONArray.java | JSONArray.getEnum | public <E extends Enum<E>> E getEnum(Class<E> clazz, int index) throws JSONException {
"""
Get the enum value associated with an index.
@param <E>
Enum Type
@param clazz
The type of enum to retrieve.
@param index
The index must be between 0 and length() - 1.
@return The enum value at the index location
@throws JSONException
if the key is not found or if the value cannot be converted
to an enum.
"""
E val = optEnum(clazz, index);
if(val==null) {
// JSONException should really take a throwable argument.
// If it did, I would re-implement this with the Enum.valueOf
// method and place any thrown exception in the JSONException
throw new JSONException("JSONArray[" + index + "] is not an enum of type "
+ JSONObject.quote(clazz.getSimpleName()) + ".");
}
return val;
} | java | public <E extends Enum<E>> E getEnum(Class<E> clazz, int index) throws JSONException {
E val = optEnum(clazz, index);
if(val==null) {
// JSONException should really take a throwable argument.
// If it did, I would re-implement this with the Enum.valueOf
// method and place any thrown exception in the JSONException
throw new JSONException("JSONArray[" + index + "] is not an enum of type "
+ JSONObject.quote(clazz.getSimpleName()) + ".");
}
return val;
} | [
"public",
"<",
"E",
"extends",
"Enum",
"<",
"E",
">",
">",
"E",
"getEnum",
"(",
"Class",
"<",
"E",
">",
"clazz",
",",
"int",
"index",
")",
"throws",
"JSONException",
"{",
"E",
"val",
"=",
"optEnum",
"(",
"clazz",
",",
"index",
")",
";",
"if",
"(",
"val",
"==",
"null",
")",
"{",
"// JSONException should really take a throwable argument.",
"// If it did, I would re-implement this with the Enum.valueOf",
"// method and place any thrown exception in the JSONException",
"throw",
"new",
"JSONException",
"(",
"\"JSONArray[\"",
"+",
"index",
"+",
"\"] is not an enum of type \"",
"+",
"JSONObject",
".",
"quote",
"(",
"clazz",
".",
"getSimpleName",
"(",
")",
")",
"+",
"\".\"",
")",
";",
"}",
"return",
"val",
";",
"}"
]
| Get the enum value associated with an index.
@param <E>
Enum Type
@param clazz
The type of enum to retrieve.
@param index
The index must be between 0 and length() - 1.
@return The enum value at the index location
@throws JSONException
if the key is not found or if the value cannot be converted
to an enum. | [
"Get",
"the",
"enum",
"value",
"associated",
"with",
"an",
"index",
"."
]
| train | https://github.com/b3log/latke/blob/f7e08a47eeecea5f7c94006382c24f353585de33/latke-core/src/main/java/org/json/JSONArray.java#L319-L329 |
future-architect/uroborosql | src/main/java/jp/co/future/uroborosql/utils/StringFunction.java | StringFunction.leftPad | public String leftPad(final String str, final int size, final char padChar) {
"""
文字列の先頭に指定した埋め込み文字を埋めて指定された長さにする
<pre>
StringUtils.leftPad(null, *, *) = null
StringUtils.leftPad("", 3, 'z') = "zzz"
StringUtils.leftPad("bat", 3, 'z') = "bat"
StringUtils.leftPad("bat", 5, 'z') = "zzbat"
StringUtils.leftPad("bat", 1, 'z') = "bat"
StringUtils.leftPad("bat", -1, 'z') = "bat"
</pre>
@param str 文字列
@param size 文字埋め後の長さ
@param padChar 埋め込み文字
@return 指定した長さになるまで末尾に埋め込み文字を埋めた文字列
"""
return StringUtils.leftPad(str, size, padChar);
} | java | public String leftPad(final String str, final int size, final char padChar) {
return StringUtils.leftPad(str, size, padChar);
} | [
"public",
"String",
"leftPad",
"(",
"final",
"String",
"str",
",",
"final",
"int",
"size",
",",
"final",
"char",
"padChar",
")",
"{",
"return",
"StringUtils",
".",
"leftPad",
"(",
"str",
",",
"size",
",",
"padChar",
")",
";",
"}"
]
| 文字列の先頭に指定した埋め込み文字を埋めて指定された長さにする
<pre>
StringUtils.leftPad(null, *, *) = null
StringUtils.leftPad("", 3, 'z') = "zzz"
StringUtils.leftPad("bat", 3, 'z') = "bat"
StringUtils.leftPad("bat", 5, 'z') = "zzbat"
StringUtils.leftPad("bat", 1, 'z') = "bat"
StringUtils.leftPad("bat", -1, 'z') = "bat"
</pre>
@param str 文字列
@param size 文字埋め後の長さ
@param padChar 埋め込み文字
@return 指定した長さになるまで末尾に埋め込み文字を埋めた文字列 | [
"文字列の先頭に指定した埋め込み文字を埋めて指定された長さにする"
]
| train | https://github.com/future-architect/uroborosql/blob/4c26db51defdac3c6ed16866e33ab45e190e2e0c/src/main/java/jp/co/future/uroborosql/utils/StringFunction.java#L271-L273 |
apache/flink | flink-core/src/main/java/org/apache/flink/util/StringUtils.java | StringUtils.getRandomString | public static String getRandomString(Random rnd, int minLength, int maxLength) {
"""
Creates a random string with a length within the given interval. The string contains only characters that
can be represented as a single code point.
@param rnd The random used to create the strings.
@param minLength The minimum string length.
@param maxLength The maximum string length (inclusive).
@return A random String.
"""
int len = rnd.nextInt(maxLength - minLength + 1) + minLength;
char[] data = new char[len];
for (int i = 0; i < data.length; i++) {
data[i] = (char) (rnd.nextInt(0x7fff) + 1);
}
return new String(data);
} | java | public static String getRandomString(Random rnd, int minLength, int maxLength) {
int len = rnd.nextInt(maxLength - minLength + 1) + minLength;
char[] data = new char[len];
for (int i = 0; i < data.length; i++) {
data[i] = (char) (rnd.nextInt(0x7fff) + 1);
}
return new String(data);
} | [
"public",
"static",
"String",
"getRandomString",
"(",
"Random",
"rnd",
",",
"int",
"minLength",
",",
"int",
"maxLength",
")",
"{",
"int",
"len",
"=",
"rnd",
".",
"nextInt",
"(",
"maxLength",
"-",
"minLength",
"+",
"1",
")",
"+",
"minLength",
";",
"char",
"[",
"]",
"data",
"=",
"new",
"char",
"[",
"len",
"]",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"data",
".",
"length",
";",
"i",
"++",
")",
"{",
"data",
"[",
"i",
"]",
"=",
"(",
"char",
")",
"(",
"rnd",
".",
"nextInt",
"(",
"0x7fff",
")",
"+",
"1",
")",
";",
"}",
"return",
"new",
"String",
"(",
"data",
")",
";",
"}"
]
| Creates a random string with a length within the given interval. The string contains only characters that
can be represented as a single code point.
@param rnd The random used to create the strings.
@param minLength The minimum string length.
@param maxLength The maximum string length (inclusive).
@return A random String. | [
"Creates",
"a",
"random",
"string",
"with",
"a",
"length",
"within",
"the",
"given",
"interval",
".",
"The",
"string",
"contains",
"only",
"characters",
"that",
"can",
"be",
"represented",
"as",
"a",
"single",
"code",
"point",
"."
]
| train | https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-core/src/main/java/org/apache/flink/util/StringUtils.java#L219-L227 |
code4everything/util | src/main/java/com/zhazhapan/util/MailSender.java | MailSender.config | public static void config(String host, String personal, String from, String key) {
"""
配置邮箱
@param host 邮件服务器
@param personal 个人名称
@param from 发件箱
@param key 密码
"""
setHost(host);
setPersonal(personal);
setFrom(from);
setKey(key);
} | java | public static void config(String host, String personal, String from, String key) {
setHost(host);
setPersonal(personal);
setFrom(from);
setKey(key);
} | [
"public",
"static",
"void",
"config",
"(",
"String",
"host",
",",
"String",
"personal",
",",
"String",
"from",
",",
"String",
"key",
")",
"{",
"setHost",
"(",
"host",
")",
";",
"setPersonal",
"(",
"personal",
")",
";",
"setFrom",
"(",
"from",
")",
";",
"setKey",
"(",
"key",
")",
";",
"}"
]
| 配置邮箱
@param host 邮件服务器
@param personal 个人名称
@param from 发件箱
@param key 密码 | [
"配置邮箱"
]
| train | https://github.com/code4everything/util/blob/1fc9f0ead1108f4d7208ba7c000df4244f708418/src/main/java/com/zhazhapan/util/MailSender.java#L121-L126 |
liyiorg/weixin-popular | src/main/java/weixin/popular/api/ComponentAPI.java | ComponentAPI.componentloginpage | public static String componentloginpage(String component_appid, String pre_auth_code, String redirect_uri) {
"""
生成授权页 URL
@param component_appid 第三方平台ID
@param pre_auth_code 预授权码
@param redirect_uri 重定向URI
@return URL
"""
return componentloginpage(component_appid, pre_auth_code, redirect_uri, null);
} | java | public static String componentloginpage(String component_appid, String pre_auth_code, String redirect_uri) {
return componentloginpage(component_appid, pre_auth_code, redirect_uri, null);
} | [
"public",
"static",
"String",
"componentloginpage",
"(",
"String",
"component_appid",
",",
"String",
"pre_auth_code",
",",
"String",
"redirect_uri",
")",
"{",
"return",
"componentloginpage",
"(",
"component_appid",
",",
"pre_auth_code",
",",
"redirect_uri",
",",
"null",
")",
";",
"}"
]
| 生成授权页 URL
@param component_appid 第三方平台ID
@param pre_auth_code 预授权码
@param redirect_uri 重定向URI
@return URL | [
"生成授权页",
"URL"
]
| train | https://github.com/liyiorg/weixin-popular/blob/c64255292d41463bdb671938feaabf42a335d82c/src/main/java/weixin/popular/api/ComponentAPI.java#L34-L36 |
ehcache/ehcache3 | impl/src/main/java/org/ehcache/config/builders/CacheConfigurationBuilder.java | CacheConfigurationBuilder.withValueSerializer | public CacheConfigurationBuilder<K, V> withValueSerializer(Class<? extends Serializer<V>> valueSerializerClass) {
"""
Adds a {@link Serializer} class for cache values to the configured builder.
<p>
{@link Serializer}s are what enables cache storage beyond the heap tier.
@param valueSerializerClass the key serializer to use
@return a new builder with the added value serializer
"""
return withSerializer(new DefaultSerializerConfiguration<>(requireNonNull(valueSerializerClass, "Null value serializer class"), DefaultSerializerConfiguration.Type.VALUE));
} | java | public CacheConfigurationBuilder<K, V> withValueSerializer(Class<? extends Serializer<V>> valueSerializerClass) {
return withSerializer(new DefaultSerializerConfiguration<>(requireNonNull(valueSerializerClass, "Null value serializer class"), DefaultSerializerConfiguration.Type.VALUE));
} | [
"public",
"CacheConfigurationBuilder",
"<",
"K",
",",
"V",
">",
"withValueSerializer",
"(",
"Class",
"<",
"?",
"extends",
"Serializer",
"<",
"V",
">",
">",
"valueSerializerClass",
")",
"{",
"return",
"withSerializer",
"(",
"new",
"DefaultSerializerConfiguration",
"<>",
"(",
"requireNonNull",
"(",
"valueSerializerClass",
",",
"\"Null value serializer class\"",
")",
",",
"DefaultSerializerConfiguration",
".",
"Type",
".",
"VALUE",
")",
")",
";",
"}"
]
| Adds a {@link Serializer} class for cache values to the configured builder.
<p>
{@link Serializer}s are what enables cache storage beyond the heap tier.
@param valueSerializerClass the key serializer to use
@return a new builder with the added value serializer | [
"Adds",
"a",
"{",
"@link",
"Serializer",
"}",
"class",
"for",
"cache",
"values",
"to",
"the",
"configured",
"builder",
".",
"<p",
">",
"{",
"@link",
"Serializer",
"}",
"s",
"are",
"what",
"enables",
"cache",
"storage",
"beyond",
"the",
"heap",
"tier",
"."
]
| train | https://github.com/ehcache/ehcache3/blob/3cceda57185e522f8d241ddb75146d67ee2af898/impl/src/main/java/org/ehcache/config/builders/CacheConfigurationBuilder.java#L492-L494 |
PeterisP/LVTagger | src/main/java/edu/stanford/nlp/ling/Sentence.java | Sentence.listToString | public static <T> String listToString(List<T> list, final boolean justValue) {
"""
Returns the sentence as a string with a space between words.
Designed to work robustly, even if the elements stored in the
'Sentence' are not of type Label.
This one uses the default separators for any word type that uses
separators, such as TaggedWord.
@param justValue If <code>true</code> and the elements are of type
<code>Label</code>, return just the
<code>value()</code> of the <code>Label</code> of each word;
otherwise,
call the <code>toString()</code> method on each item.
@return The sentence in String form
"""
return listToString(list, justValue, null);
} | java | public static <T> String listToString(List<T> list, final boolean justValue) {
return listToString(list, justValue, null);
} | [
"public",
"static",
"<",
"T",
">",
"String",
"listToString",
"(",
"List",
"<",
"T",
">",
"list",
",",
"final",
"boolean",
"justValue",
")",
"{",
"return",
"listToString",
"(",
"list",
",",
"justValue",
",",
"null",
")",
";",
"}"
]
| Returns the sentence as a string with a space between words.
Designed to work robustly, even if the elements stored in the
'Sentence' are not of type Label.
This one uses the default separators for any word type that uses
separators, such as TaggedWord.
@param justValue If <code>true</code> and the elements are of type
<code>Label</code>, return just the
<code>value()</code> of the <code>Label</code> of each word;
otherwise,
call the <code>toString()</code> method on each item.
@return The sentence in String form | [
"Returns",
"the",
"sentence",
"as",
"a",
"string",
"with",
"a",
"space",
"between",
"words",
".",
"Designed",
"to",
"work",
"robustly",
"even",
"if",
"the",
"elements",
"stored",
"in",
"the",
"Sentence",
"are",
"not",
"of",
"type",
"Label",
"."
]
| train | https://github.com/PeterisP/LVTagger/blob/b3d44bab9ec07ace0d13612c448a6b7298c1f681/src/main/java/edu/stanford/nlp/ling/Sentence.java#L146-L148 |
rterp/GMapsFX | GMapsFX/src/main/java/com/lynden/gmapsfx/shapes/ArcBuilder.java | ArcBuilder.buildOpenArc | public static final PolylineOptions buildOpenArc(LatLong center, LatLong start, LatLong end) {
"""
Builds the path for an open arc based on a PolylineOptions.
@param center
@param start
@param end
@return PolylineOptions with the paths element populated.
"""
MVCArray res = buildArcPoints(center, start, end);
return new PolylineOptions().path(res);
} | java | public static final PolylineOptions buildOpenArc(LatLong center, LatLong start, LatLong end) {
MVCArray res = buildArcPoints(center, start, end);
return new PolylineOptions().path(res);
} | [
"public",
"static",
"final",
"PolylineOptions",
"buildOpenArc",
"(",
"LatLong",
"center",
",",
"LatLong",
"start",
",",
"LatLong",
"end",
")",
"{",
"MVCArray",
"res",
"=",
"buildArcPoints",
"(",
"center",
",",
"start",
",",
"end",
")",
";",
"return",
"new",
"PolylineOptions",
"(",
")",
".",
"path",
"(",
"res",
")",
";",
"}"
]
| Builds the path for an open arc based on a PolylineOptions.
@param center
@param start
@param end
@return PolylineOptions with the paths element populated. | [
"Builds",
"the",
"path",
"for",
"an",
"open",
"arc",
"based",
"on",
"a",
"PolylineOptions",
"."
]
| train | https://github.com/rterp/GMapsFX/blob/4623d3f768e8ad78fc50ee32dd204d236e01059f/GMapsFX/src/main/java/com/lynden/gmapsfx/shapes/ArcBuilder.java#L50-L53 |
Netflix/governator | governator-servlet/src/main/java/com/netflix/governator/guice/servlet/GovernatorServletContextListener.java | GovernatorServletContextListener.getInjector | protected final Injector getInjector() {
"""
Override this method to create (or otherwise obtain a reference to) your
injector.
NOTE: If everything is set up right, then this method should only be called once during
application startup.
"""
if (injector != null) {
throw new IllegalStateException("Injector already created.");
}
try {
injector = createInjector();
}
catch (Exception e) {
LOG.error("Failed to created injector", e);
throw new ProvisionException("Failed to create injector", e);
}
return injector;
} | java | protected final Injector getInjector() {
if (injector != null) {
throw new IllegalStateException("Injector already created.");
}
try {
injector = createInjector();
}
catch (Exception e) {
LOG.error("Failed to created injector", e);
throw new ProvisionException("Failed to create injector", e);
}
return injector;
} | [
"protected",
"final",
"Injector",
"getInjector",
"(",
")",
"{",
"if",
"(",
"injector",
"!=",
"null",
")",
"{",
"throw",
"new",
"IllegalStateException",
"(",
"\"Injector already created.\"",
")",
";",
"}",
"try",
"{",
"injector",
"=",
"createInjector",
"(",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"LOG",
".",
"error",
"(",
"\"Failed to created injector\"",
",",
"e",
")",
";",
"throw",
"new",
"ProvisionException",
"(",
"\"Failed to create injector\"",
",",
"e",
")",
";",
"}",
"return",
"injector",
";",
"}"
]
| Override this method to create (or otherwise obtain a reference to) your
injector.
NOTE: If everything is set up right, then this method should only be called once during
application startup. | [
"Override",
"this",
"method",
"to",
"create",
"(",
"or",
"otherwise",
"obtain",
"a",
"reference",
"to",
")",
"your",
"injector",
".",
"NOTE",
":",
"If",
"everything",
"is",
"set",
"up",
"right",
"then",
"this",
"method",
"should",
"only",
"be",
"called",
"once",
"during",
"application",
"startup",
"."
]
| train | https://github.com/Netflix/governator/blob/c1f4bb1518e759c61f2e9cad8a896ec6beba0294/governator-servlet/src/main/java/com/netflix/governator/guice/servlet/GovernatorServletContextListener.java#L102-L114 |
JRebirth/JRebirth | org.jrebirth.af/core/src/main/java/org/jrebirth/af/core/link/ComponentEnhancer.java | ComponentEnhancer.manageLifecycleAnnotation | private static void manageLifecycleAnnotation(final Component<?> component, final MultiMap<String, Method> lifecycleMethod, final Class<? extends Annotation> annotationClass) {
"""
Store annotated method related to a lifecycle phase.
@param component the JRebirth component to manage
@param lifecycleMethod the map that store methods
@param annotationClass the annotation related to lifecycle phase
"""
for (final Method method : ClassUtility.getAnnotatedMethods(component.getClass(), annotationClass)) {
// Add a method to the multimap entry
// TODO sort
lifecycleMethod.add(annotationClass.getName(), method);
}
} | java | private static void manageLifecycleAnnotation(final Component<?> component, final MultiMap<String, Method> lifecycleMethod, final Class<? extends Annotation> annotationClass) {
for (final Method method : ClassUtility.getAnnotatedMethods(component.getClass(), annotationClass)) {
// Add a method to the multimap entry
// TODO sort
lifecycleMethod.add(annotationClass.getName(), method);
}
} | [
"private",
"static",
"void",
"manageLifecycleAnnotation",
"(",
"final",
"Component",
"<",
"?",
">",
"component",
",",
"final",
"MultiMap",
"<",
"String",
",",
"Method",
">",
"lifecycleMethod",
",",
"final",
"Class",
"<",
"?",
"extends",
"Annotation",
">",
"annotationClass",
")",
"{",
"for",
"(",
"final",
"Method",
"method",
":",
"ClassUtility",
".",
"getAnnotatedMethods",
"(",
"component",
".",
"getClass",
"(",
")",
",",
"annotationClass",
")",
")",
"{",
"// Add a method to the multimap entry",
"// TODO sort",
"lifecycleMethod",
".",
"add",
"(",
"annotationClass",
".",
"getName",
"(",
")",
",",
"method",
")",
";",
"}",
"}"
]
| Store annotated method related to a lifecycle phase.
@param component the JRebirth component to manage
@param lifecycleMethod the map that store methods
@param annotationClass the annotation related to lifecycle phase | [
"Store",
"annotated",
"method",
"related",
"to",
"a",
"lifecycle",
"phase",
"."
]
| train | https://github.com/JRebirth/JRebirth/blob/93f4fc087b83c73db540333b9686e97b4cec694d/org.jrebirth.af/core/src/main/java/org/jrebirth/af/core/link/ComponentEnhancer.java#L212-L219 |
fabric8io/fabric8-forge | fabric8-forge-core/src/main/java/io/fabric8/forge/rest/dto/ExecutionRequest.java | ExecutionRequest.createCommitMessage | public static String createCommitMessage(String name, ExecutionRequest executionRequest) {
"""
Lets generate a commit message with the command name and all the parameters we specify
"""
StringBuilder builder = new StringBuilder(name);
List<Map<String, Object>> inputList = executionRequest.getInputList();
for (Map<String, Object> map : inputList) {
Set<Map.Entry<String, Object>> entries = map.entrySet();
for (Map.Entry<String, Object> entry : entries) {
String key = entry.getKey();
String textValue = null;
Object value = entry.getValue();
if (value != null) {
textValue = value.toString();
}
if (!Strings.isNullOrEmpty(textValue) && !textValue.equals("0") && !textValue.toLowerCase().equals("false")) {
builder.append(" --");
builder.append(key);
builder.append("=");
builder.append(textValue);
}
}
}
return builder.toString();
} | java | public static String createCommitMessage(String name, ExecutionRequest executionRequest) {
StringBuilder builder = new StringBuilder(name);
List<Map<String, Object>> inputList = executionRequest.getInputList();
for (Map<String, Object> map : inputList) {
Set<Map.Entry<String, Object>> entries = map.entrySet();
for (Map.Entry<String, Object> entry : entries) {
String key = entry.getKey();
String textValue = null;
Object value = entry.getValue();
if (value != null) {
textValue = value.toString();
}
if (!Strings.isNullOrEmpty(textValue) && !textValue.equals("0") && !textValue.toLowerCase().equals("false")) {
builder.append(" --");
builder.append(key);
builder.append("=");
builder.append(textValue);
}
}
}
return builder.toString();
} | [
"public",
"static",
"String",
"createCommitMessage",
"(",
"String",
"name",
",",
"ExecutionRequest",
"executionRequest",
")",
"{",
"StringBuilder",
"builder",
"=",
"new",
"StringBuilder",
"(",
"name",
")",
";",
"List",
"<",
"Map",
"<",
"String",
",",
"Object",
">",
">",
"inputList",
"=",
"executionRequest",
".",
"getInputList",
"(",
")",
";",
"for",
"(",
"Map",
"<",
"String",
",",
"Object",
">",
"map",
":",
"inputList",
")",
"{",
"Set",
"<",
"Map",
".",
"Entry",
"<",
"String",
",",
"Object",
">",
">",
"entries",
"=",
"map",
".",
"entrySet",
"(",
")",
";",
"for",
"(",
"Map",
".",
"Entry",
"<",
"String",
",",
"Object",
">",
"entry",
":",
"entries",
")",
"{",
"String",
"key",
"=",
"entry",
".",
"getKey",
"(",
")",
";",
"String",
"textValue",
"=",
"null",
";",
"Object",
"value",
"=",
"entry",
".",
"getValue",
"(",
")",
";",
"if",
"(",
"value",
"!=",
"null",
")",
"{",
"textValue",
"=",
"value",
".",
"toString",
"(",
")",
";",
"}",
"if",
"(",
"!",
"Strings",
".",
"isNullOrEmpty",
"(",
"textValue",
")",
"&&",
"!",
"textValue",
".",
"equals",
"(",
"\"0\"",
")",
"&&",
"!",
"textValue",
".",
"toLowerCase",
"(",
")",
".",
"equals",
"(",
"\"false\"",
")",
")",
"{",
"builder",
".",
"append",
"(",
"\" --\"",
")",
";",
"builder",
".",
"append",
"(",
"key",
")",
";",
"builder",
".",
"append",
"(",
"\"=\"",
")",
";",
"builder",
".",
"append",
"(",
"textValue",
")",
";",
"}",
"}",
"}",
"return",
"builder",
".",
"toString",
"(",
")",
";",
"}"
]
| Lets generate a commit message with the command name and all the parameters we specify | [
"Lets",
"generate",
"a",
"commit",
"message",
"with",
"the",
"command",
"name",
"and",
"all",
"the",
"parameters",
"we",
"specify"
]
| train | https://github.com/fabric8io/fabric8-forge/blob/a59871bae4d5c5d3ece10f1e8758e73663087f19/fabric8-forge-core/src/main/java/io/fabric8/forge/rest/dto/ExecutionRequest.java#L52-L73 |
landawn/AbacusUtil | src/com/landawn/abacus/util/N.java | N.checkState | public static void checkState(boolean b, String errorMessageTemplate, double p) {
"""
Ensures the truth of an expression involving the state of the calling instance, but not
involving any parameters to the calling method.
<p>See {@link #checkState(boolean, String, Object...)} for details.
"""
if (!b) {
throw new IllegalStateException(format(errorMessageTemplate, p));
}
} | java | public static void checkState(boolean b, String errorMessageTemplate, double p) {
if (!b) {
throw new IllegalStateException(format(errorMessageTemplate, p));
}
} | [
"public",
"static",
"void",
"checkState",
"(",
"boolean",
"b",
",",
"String",
"errorMessageTemplate",
",",
"double",
"p",
")",
"{",
"if",
"(",
"!",
"b",
")",
"{",
"throw",
"new",
"IllegalStateException",
"(",
"format",
"(",
"errorMessageTemplate",
",",
"p",
")",
")",
";",
"}",
"}"
]
| Ensures the truth of an expression involving the state of the calling instance, but not
involving any parameters to the calling method.
<p>See {@link #checkState(boolean, String, Object...)} for details. | [
"Ensures",
"the",
"truth",
"of",
"an",
"expression",
"involving",
"the",
"state",
"of",
"the",
"calling",
"instance",
"but",
"not",
"involving",
"any",
"parameters",
"to",
"the",
"calling",
"method",
"."
]
| train | https://github.com/landawn/AbacusUtil/blob/544b7720175d15e9329f83dd22a8cc5fa4515e12/src/com/landawn/abacus/util/N.java#L6004-L6008 |
Coveros/selenified | src/main/java/com/coveros/selenified/element/Element.java | Element.isNotPresentDisplayedEnabled | private boolean isNotPresentDisplayedEnabled(String action, String expected, String extra) {
"""
Determines if something is present, displayed, and enabled. This returns
true if all three are true, otherwise, it returns false
@param action - what action is occurring
@param expected - what is the expected result
@param extra - what actually is occurring
@return Boolean: is the element present, displayed, and enabled?
"""
// wait for element to be present
if (isNotPresent(action, expected, extra)) {
return true;
}
// wait for element to be displayed
if (isNotDisplayed(action, expected, extra)) {
return true;
}
// wait for element to be enabled
return isNotEnabled(action, expected, extra);
} | java | private boolean isNotPresentDisplayedEnabled(String action, String expected, String extra) {
// wait for element to be present
if (isNotPresent(action, expected, extra)) {
return true;
}
// wait for element to be displayed
if (isNotDisplayed(action, expected, extra)) {
return true;
}
// wait for element to be enabled
return isNotEnabled(action, expected, extra);
} | [
"private",
"boolean",
"isNotPresentDisplayedEnabled",
"(",
"String",
"action",
",",
"String",
"expected",
",",
"String",
"extra",
")",
"{",
"// wait for element to be present",
"if",
"(",
"isNotPresent",
"(",
"action",
",",
"expected",
",",
"extra",
")",
")",
"{",
"return",
"true",
";",
"}",
"// wait for element to be displayed",
"if",
"(",
"isNotDisplayed",
"(",
"action",
",",
"expected",
",",
"extra",
")",
")",
"{",
"return",
"true",
";",
"}",
"// wait for element to be enabled",
"return",
"isNotEnabled",
"(",
"action",
",",
"expected",
",",
"extra",
")",
";",
"}"
]
| Determines if something is present, displayed, and enabled. This returns
true if all three are true, otherwise, it returns false
@param action - what action is occurring
@param expected - what is the expected result
@param extra - what actually is occurring
@return Boolean: is the element present, displayed, and enabled? | [
"Determines",
"if",
"something",
"is",
"present",
"displayed",
"and",
"enabled",
".",
"This",
"returns",
"true",
"if",
"all",
"three",
"are",
"true",
"otherwise",
"it",
"returns",
"false"
]
| train | https://github.com/Coveros/selenified/blob/396cc1f010dd69eed33cc5061c41253de246a4cd/src/main/java/com/coveros/selenified/element/Element.java#L694-L705 |
ngageoint/geopackage-core-java | src/main/java/mil/nga/geopackage/style/ColorUtils.java | ColorUtils.toColorShorthandWithAlpha | public static String toColorShorthandWithAlpha(String red, String green,
String blue, String alpha) {
"""
Convert the hex color values to a hex color, shorthanded when possible
@param red
red hex color in format RR or R
@param green
green hex color in format GG or G
@param blue
blue hex color in format BB or B
@param alpha
alpha hex color in format AA or A, null to not include alpha
@return hex color in format #ARGB, #RGB, #AARRGGBB, or #RRGGBB
"""
return shorthandHex(toColorWithAlpha(red, green, blue, alpha));
} | java | public static String toColorShorthandWithAlpha(String red, String green,
String blue, String alpha) {
return shorthandHex(toColorWithAlpha(red, green, blue, alpha));
} | [
"public",
"static",
"String",
"toColorShorthandWithAlpha",
"(",
"String",
"red",
",",
"String",
"green",
",",
"String",
"blue",
",",
"String",
"alpha",
")",
"{",
"return",
"shorthandHex",
"(",
"toColorWithAlpha",
"(",
"red",
",",
"green",
",",
"blue",
",",
"alpha",
")",
")",
";",
"}"
]
| Convert the hex color values to a hex color, shorthanded when possible
@param red
red hex color in format RR or R
@param green
green hex color in format GG or G
@param blue
blue hex color in format BB or B
@param alpha
alpha hex color in format AA or A, null to not include alpha
@return hex color in format #ARGB, #RGB, #AARRGGBB, or #RRGGBB | [
"Convert",
"the",
"hex",
"color",
"values",
"to",
"a",
"hex",
"color",
"shorthanded",
"when",
"possible"
]
| train | https://github.com/ngageoint/geopackage-core-java/blob/6431c3b041a45b7f3802904ea4156b4082a72daa/src/main/java/mil/nga/geopackage/style/ColorUtils.java#L143-L146 |
jferard/fastods | fastods/src/main/java/com/github/jferard/fastods/datastyle/NumberStyleHelper.java | NumberStyleHelper.appendNumberAttribute | public void appendNumberAttribute(final XMLUtil util, final Appendable appendable) throws IOException {
"""
Append the attributes of the number
@param util an util
@param appendable the destination
@throws IOException if an I/O error occurs
"""
this.appendMinIntegerDigitsAttribute(util, appendable);
this.appendGroupingAttribute(util, appendable);
} | java | public void appendNumberAttribute(final XMLUtil util, final Appendable appendable) throws IOException {
this.appendMinIntegerDigitsAttribute(util, appendable);
this.appendGroupingAttribute(util, appendable);
} | [
"public",
"void",
"appendNumberAttribute",
"(",
"final",
"XMLUtil",
"util",
",",
"final",
"Appendable",
"appendable",
")",
"throws",
"IOException",
"{",
"this",
".",
"appendMinIntegerDigitsAttribute",
"(",
"util",
",",
"appendable",
")",
";",
"this",
".",
"appendGroupingAttribute",
"(",
"util",
",",
"appendable",
")",
";",
"}"
]
| Append the attributes of the number
@param util an util
@param appendable the destination
@throws IOException if an I/O error occurs | [
"Append",
"the",
"attributes",
"of",
"the",
"number"
]
| train | https://github.com/jferard/fastods/blob/a034d173083ffa602dc525699b97f753082eaef9/fastods/src/main/java/com/github/jferard/fastods/datastyle/NumberStyleHelper.java#L119-L122 |
mikepenz/Materialize | library/src/main/java/com/mikepenz/materialize/holder/ColorHolder.java | ColorHolder.applyTo | public void applyTo(Context ctx, GradientDrawable drawable) {
"""
set the textColor of the ColorHolder to an drawable
@param ctx
@param drawable
"""
if (mColorInt != 0) {
drawable.setColor(mColorInt);
} else if (mColorRes != -1) {
drawable.setColor(ContextCompat.getColor(ctx, mColorRes));
}
} | java | public void applyTo(Context ctx, GradientDrawable drawable) {
if (mColorInt != 0) {
drawable.setColor(mColorInt);
} else if (mColorRes != -1) {
drawable.setColor(ContextCompat.getColor(ctx, mColorRes));
}
} | [
"public",
"void",
"applyTo",
"(",
"Context",
"ctx",
",",
"GradientDrawable",
"drawable",
")",
"{",
"if",
"(",
"mColorInt",
"!=",
"0",
")",
"{",
"drawable",
".",
"setColor",
"(",
"mColorInt",
")",
";",
"}",
"else",
"if",
"(",
"mColorRes",
"!=",
"-",
"1",
")",
"{",
"drawable",
".",
"setColor",
"(",
"ContextCompat",
".",
"getColor",
"(",
"ctx",
",",
"mColorRes",
")",
")",
";",
"}",
"}"
]
| set the textColor of the ColorHolder to an drawable
@param ctx
@param drawable | [
"set",
"the",
"textColor",
"of",
"the",
"ColorHolder",
"to",
"an",
"drawable"
]
| train | https://github.com/mikepenz/Materialize/blob/2612c10c7570191a78d57f23620e945d61370e3d/library/src/main/java/com/mikepenz/materialize/holder/ColorHolder.java#L61-L67 |
indeedeng/util | urlparsing/src/main/java/com/indeed/util/urlparsing/ParseUtils.java | ParseUtils.urlDecodeInto | public static void urlDecodeInto(CharSequence input, int start, int end, StringBuilder result) {
"""
/* URL decode CharSequence @param input into result given start and end offsets
Assumes UTF-8 encoding
Avoids creating intermediate String objects unlike UrlDecoder in java.
"""
urlDecodeInto(input, start, end, result, false);
} | java | public static void urlDecodeInto(CharSequence input, int start, int end, StringBuilder result) {
urlDecodeInto(input, start, end, result, false);
} | [
"public",
"static",
"void",
"urlDecodeInto",
"(",
"CharSequence",
"input",
",",
"int",
"start",
",",
"int",
"end",
",",
"StringBuilder",
"result",
")",
"{",
"urlDecodeInto",
"(",
"input",
",",
"start",
",",
"end",
",",
"result",
",",
"false",
")",
";",
"}"
]
| /* URL decode CharSequence @param input into result given start and end offsets
Assumes UTF-8 encoding
Avoids creating intermediate String objects unlike UrlDecoder in java. | [
"/",
"*",
"URL",
"decode",
"CharSequence"
]
| train | https://github.com/indeedeng/util/blob/332008426cf14b57e7fc3e817d9423e3f84fb922/urlparsing/src/main/java/com/indeed/util/urlparsing/ParseUtils.java#L209-L211 |
michel-kraemer/citeproc-java | citeproc-java/src/main/java/de/undercouch/citeproc/CSL.java | CSL.setAbbreviations | public void setAbbreviations(String name) {
"""
Enables the abbreviation list with the given name. The processor will
call {@link AbbreviationProvider#getAbbreviations(String)} with the
given String to get the abbreviations that should be used from here on.
@param name the name of the abbreviation list to enable
"""
try {
runner.callMethod(engine, "setAbbreviations", name);
} catch (ScriptRunnerException e) {
throw new IllegalArgumentException("Could not set abbreviations", e);
}
} | java | public void setAbbreviations(String name) {
try {
runner.callMethod(engine, "setAbbreviations", name);
} catch (ScriptRunnerException e) {
throw new IllegalArgumentException("Could not set abbreviations", e);
}
} | [
"public",
"void",
"setAbbreviations",
"(",
"String",
"name",
")",
"{",
"try",
"{",
"runner",
".",
"callMethod",
"(",
"engine",
",",
"\"setAbbreviations\"",
",",
"name",
")",
";",
"}",
"catch",
"(",
"ScriptRunnerException",
"e",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Could not set abbreviations\"",
",",
"e",
")",
";",
"}",
"}"
]
| Enables the abbreviation list with the given name. The processor will
call {@link AbbreviationProvider#getAbbreviations(String)} with the
given String to get the abbreviations that should be used from here on.
@param name the name of the abbreviation list to enable | [
"Enables",
"the",
"abbreviation",
"list",
"with",
"the",
"given",
"name",
".",
"The",
"processor",
"will",
"call",
"{"
]
| train | https://github.com/michel-kraemer/citeproc-java/blob/1d5bf0e7bbb2bdc47309530babf0ecaba838bf10/citeproc-java/src/main/java/de/undercouch/citeproc/CSL.java#L593-L599 |
lamydev/Android-Notification | core/src/zemin/notification/NotificationViewCallback.java | NotificationViewCallback.onUpdateNotification | public void onUpdateNotification(NotificationView view, View contentView, NotificationEntry entry, int layoutId) {
"""
Called when a notification is being updated.
@param view
@param contentView
@param entry
@param layoutId
"""
if (DBG) Log.v(TAG, "onUpdateNotification - " + entry.ID);
final Drawable icon = entry.iconDrawable;
final CharSequence title = entry.title;
final CharSequence text = entry.text;
final CharSequence when = entry.showWhen ? entry.whenFormatted : null;
ChildViewManager mgr = view.getChildViewManager();
mgr.setImageDrawable(ICON, icon, false);
mgr.setText(TITLE, title, false);
mgr.setText(TEXT, text, false);
mgr.setText(WHEN, when, false);
} | java | public void onUpdateNotification(NotificationView view, View contentView, NotificationEntry entry, int layoutId) {
if (DBG) Log.v(TAG, "onUpdateNotification - " + entry.ID);
final Drawable icon = entry.iconDrawable;
final CharSequence title = entry.title;
final CharSequence text = entry.text;
final CharSequence when = entry.showWhen ? entry.whenFormatted : null;
ChildViewManager mgr = view.getChildViewManager();
mgr.setImageDrawable(ICON, icon, false);
mgr.setText(TITLE, title, false);
mgr.setText(TEXT, text, false);
mgr.setText(WHEN, when, false);
} | [
"public",
"void",
"onUpdateNotification",
"(",
"NotificationView",
"view",
",",
"View",
"contentView",
",",
"NotificationEntry",
"entry",
",",
"int",
"layoutId",
")",
"{",
"if",
"(",
"DBG",
")",
"Log",
".",
"v",
"(",
"TAG",
",",
"\"onUpdateNotification - \"",
"+",
"entry",
".",
"ID",
")",
";",
"final",
"Drawable",
"icon",
"=",
"entry",
".",
"iconDrawable",
";",
"final",
"CharSequence",
"title",
"=",
"entry",
".",
"title",
";",
"final",
"CharSequence",
"text",
"=",
"entry",
".",
"text",
";",
"final",
"CharSequence",
"when",
"=",
"entry",
".",
"showWhen",
"?",
"entry",
".",
"whenFormatted",
":",
"null",
";",
"ChildViewManager",
"mgr",
"=",
"view",
".",
"getChildViewManager",
"(",
")",
";",
"mgr",
".",
"setImageDrawable",
"(",
"ICON",
",",
"icon",
",",
"false",
")",
";",
"mgr",
".",
"setText",
"(",
"TITLE",
",",
"title",
",",
"false",
")",
";",
"mgr",
".",
"setText",
"(",
"TEXT",
",",
"text",
",",
"false",
")",
";",
"mgr",
".",
"setText",
"(",
"WHEN",
",",
"when",
",",
"false",
")",
";",
"}"
]
| Called when a notification is being updated.
@param view
@param contentView
@param entry
@param layoutId | [
"Called",
"when",
"a",
"notification",
"is",
"being",
"updated",
"."
]
| train | https://github.com/lamydev/Android-Notification/blob/6d6571d2862cb6edbacf9a78125418f7d621c3f8/core/src/zemin/notification/NotificationViewCallback.java#L153-L167 |
FINRAOS/DataGenerator | dg-core/src/main/java/org/finra/datagenerator/consumer/DataConsumer.java | DataConsumer.transformAndReturn | public List<Map<String, String>> transformAndReturn(Map<String, String> initialVars) {
"""
Consumes a produced result. Calls every transformer in sequence, then
returns the produced result(s) back to the caller
Children may override this class to produce more than one consumed result
@param initialVars a map containing the initial variables assignments
@return the produced output map
"""
this.dataPipe = new DataPipe(this);
// Set initial variables
for (Map.Entry<String, String> ent : initialVars.entrySet()) {
dataPipe.getDataMap().put(ent.getKey(), ent.getValue());
}
// Call transformers
for (DataTransformer dc : dataTransformers) {
dc.transform(dataPipe);
}
List<Map<String, String>> result = new LinkedList<>();
result.add(dataPipe.getDataMap());
return result;
} | java | public List<Map<String, String>> transformAndReturn(Map<String, String> initialVars) {
this.dataPipe = new DataPipe(this);
// Set initial variables
for (Map.Entry<String, String> ent : initialVars.entrySet()) {
dataPipe.getDataMap().put(ent.getKey(), ent.getValue());
}
// Call transformers
for (DataTransformer dc : dataTransformers) {
dc.transform(dataPipe);
}
List<Map<String, String>> result = new LinkedList<>();
result.add(dataPipe.getDataMap());
return result;
} | [
"public",
"List",
"<",
"Map",
"<",
"String",
",",
"String",
">",
">",
"transformAndReturn",
"(",
"Map",
"<",
"String",
",",
"String",
">",
"initialVars",
")",
"{",
"this",
".",
"dataPipe",
"=",
"new",
"DataPipe",
"(",
"this",
")",
";",
"// Set initial variables\r",
"for",
"(",
"Map",
".",
"Entry",
"<",
"String",
",",
"String",
">",
"ent",
":",
"initialVars",
".",
"entrySet",
"(",
")",
")",
"{",
"dataPipe",
".",
"getDataMap",
"(",
")",
".",
"put",
"(",
"ent",
".",
"getKey",
"(",
")",
",",
"ent",
".",
"getValue",
"(",
")",
")",
";",
"}",
"// Call transformers\r",
"for",
"(",
"DataTransformer",
"dc",
":",
"dataTransformers",
")",
"{",
"dc",
".",
"transform",
"(",
"dataPipe",
")",
";",
"}",
"List",
"<",
"Map",
"<",
"String",
",",
"String",
">",
">",
"result",
"=",
"new",
"LinkedList",
"<>",
"(",
")",
";",
"result",
".",
"add",
"(",
"dataPipe",
".",
"getDataMap",
"(",
")",
")",
";",
"return",
"result",
";",
"}"
]
| Consumes a produced result. Calls every transformer in sequence, then
returns the produced result(s) back to the caller
Children may override this class to produce more than one consumed result
@param initialVars a map containing the initial variables assignments
@return the produced output map | [
"Consumes",
"a",
"produced",
"result",
".",
"Calls",
"every",
"transformer",
"in",
"sequence",
"then",
"returns",
"the",
"produced",
"result",
"(",
"s",
")",
"back",
"to",
"the",
"caller"
]
| train | https://github.com/FINRAOS/DataGenerator/blob/1f69f949401cbed4db4f553c3eb8350832c4d45a/dg-core/src/main/java/org/finra/datagenerator/consumer/DataConsumer.java#L172-L188 |
adamfisk/littleshoot-util | src/main/java/org/littleshoot/util/ITunesUtils.java | ITunesUtils.addAudioFile | public static boolean addAudioFile(final File file) throws IOException {
"""
Adds the specified audio file to iTunes if we're on OSX.
@param file The file to add.
@return <code>true</code> if the audio file was added to iTunes,
otherwise <code>false</code>.
@throws IOException If there's an error getting the canonical file name.
"""
if (!SystemUtils.IS_OS_MAC_OSX)
{
LOG.debug("Not on OSX, not adding to iTunes");
return false;
}
if (!isSupported(file))
{
LOG.debug("iTunes does not support this file type: {}", file);
return false;
}
//final Runnable runner = new ExecOsaScript(file.getCanonicalFile());
//final Thread thread = new DaemonThread(runner, "iTunes-Adding-Thread");
//thread.start();
Runtime.getRuntime().exec(createOSAScriptCommand(file));
return true;
} | java | public static boolean addAudioFile(final File file) throws IOException
{
if (!SystemUtils.IS_OS_MAC_OSX)
{
LOG.debug("Not on OSX, not adding to iTunes");
return false;
}
if (!isSupported(file))
{
LOG.debug("iTunes does not support this file type: {}", file);
return false;
}
//final Runnable runner = new ExecOsaScript(file.getCanonicalFile());
//final Thread thread = new DaemonThread(runner, "iTunes-Adding-Thread");
//thread.start();
Runtime.getRuntime().exec(createOSAScriptCommand(file));
return true;
} | [
"public",
"static",
"boolean",
"addAudioFile",
"(",
"final",
"File",
"file",
")",
"throws",
"IOException",
"{",
"if",
"(",
"!",
"SystemUtils",
".",
"IS_OS_MAC_OSX",
")",
"{",
"LOG",
".",
"debug",
"(",
"\"Not on OSX, not adding to iTunes\"",
")",
";",
"return",
"false",
";",
"}",
"if",
"(",
"!",
"isSupported",
"(",
"file",
")",
")",
"{",
"LOG",
".",
"debug",
"(",
"\"iTunes does not support this file type: {}\"",
",",
"file",
")",
";",
"return",
"false",
";",
"}",
"//final Runnable runner = new ExecOsaScript(file.getCanonicalFile());",
"//final Thread thread = new DaemonThread(runner, \"iTunes-Adding-Thread\");",
"//thread.start();",
"Runtime",
".",
"getRuntime",
"(",
")",
".",
"exec",
"(",
"createOSAScriptCommand",
"(",
"file",
")",
")",
";",
"return",
"true",
";",
"}"
]
| Adds the specified audio file to iTunes if we're on OSX.
@param file The file to add.
@return <code>true</code> if the audio file was added to iTunes,
otherwise <code>false</code>.
@throws IOException If there's an error getting the canonical file name. | [
"Adds",
"the",
"specified",
"audio",
"file",
"to",
"iTunes",
"if",
"we",
"re",
"on",
"OSX",
"."
]
| train | https://github.com/adamfisk/littleshoot-util/blob/3c0dc4955116b3382d6b0575d2f164b7508a4f73/src/main/java/org/littleshoot/util/ITunesUtils.java#L32-L52 |
jronrun/benayn | benayn-ustyle/src/main/java/com/benayn/ustyle/string/Levenshtein.java | Levenshtein.of | @SuppressWarnings("unchecked")
public static <T extends Levenshtein> T of(String baseTarget, String compareTarget) {
"""
Returns a new Levenshtein edit distance instance with compare target string
@see LevenshteinEditDistance
@param baseTarget
@param compareTarget
@return
"""
return (T) new LevenshteinEditDistance(baseTarget).update(compareTarget);
} | java | @SuppressWarnings("unchecked")
public static <T extends Levenshtein> T of(String baseTarget, String compareTarget) {
return (T) new LevenshteinEditDistance(baseTarget).update(compareTarget);
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"public",
"static",
"<",
"T",
"extends",
"Levenshtein",
">",
"T",
"of",
"(",
"String",
"baseTarget",
",",
"String",
"compareTarget",
")",
"{",
"return",
"(",
"T",
")",
"new",
"LevenshteinEditDistance",
"(",
"baseTarget",
")",
".",
"update",
"(",
"compareTarget",
")",
";",
"}"
]
| Returns a new Levenshtein edit distance instance with compare target string
@see LevenshteinEditDistance
@param baseTarget
@param compareTarget
@return | [
"Returns",
"a",
"new",
"Levenshtein",
"edit",
"distance",
"instance",
"with",
"compare",
"target",
"string"
]
| train | https://github.com/jronrun/benayn/blob/7585152e10e4cac07b4274c65f1c72ad7061ae69/benayn-ustyle/src/main/java/com/benayn/ustyle/string/Levenshtein.java#L61-L64 |
hazelcast/hazelcast | hazelcast/src/main/java/com/hazelcast/cache/impl/AbstractCacheRecordStore.java | AbstractCacheRecordStore.createCacheEvictionChecker | protected EvictionChecker createCacheEvictionChecker(int size, MaxSizePolicy maxSizePolicy) {
"""
Creates an instance for checking if the maximum cache size has been reached. Supports only the
{@link MaxSizePolicy#ENTRY_COUNT} policy. Returns null if other {@code maxSizePolicy} is used.
@param size the maximum number of entries
@param maxSizePolicy the way in which the size is interpreted, only the {@link MaxSizePolicy#ENTRY_COUNT} policy is
supported.
@return the instance which will check if the maximum number of entries has been reached or null if the
{@code maxSizePolicy} is not {@link MaxSizePolicy#ENTRY_COUNT}
@throws IllegalArgumentException if the {@code maxSizePolicy} is null
"""
if (maxSizePolicy == null) {
throw new IllegalArgumentException("Max-Size policy cannot be null");
}
if (maxSizePolicy == MaxSizePolicy.ENTRY_COUNT) {
return new EntryCountCacheEvictionChecker(size, records, partitionCount);
}
return null;
} | java | protected EvictionChecker createCacheEvictionChecker(int size, MaxSizePolicy maxSizePolicy) {
if (maxSizePolicy == null) {
throw new IllegalArgumentException("Max-Size policy cannot be null");
}
if (maxSizePolicy == MaxSizePolicy.ENTRY_COUNT) {
return new EntryCountCacheEvictionChecker(size, records, partitionCount);
}
return null;
} | [
"protected",
"EvictionChecker",
"createCacheEvictionChecker",
"(",
"int",
"size",
",",
"MaxSizePolicy",
"maxSizePolicy",
")",
"{",
"if",
"(",
"maxSizePolicy",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Max-Size policy cannot be null\"",
")",
";",
"}",
"if",
"(",
"maxSizePolicy",
"==",
"MaxSizePolicy",
".",
"ENTRY_COUNT",
")",
"{",
"return",
"new",
"EntryCountCacheEvictionChecker",
"(",
"size",
",",
"records",
",",
"partitionCount",
")",
";",
"}",
"return",
"null",
";",
"}"
]
| Creates an instance for checking if the maximum cache size has been reached. Supports only the
{@link MaxSizePolicy#ENTRY_COUNT} policy. Returns null if other {@code maxSizePolicy} is used.
@param size the maximum number of entries
@param maxSizePolicy the way in which the size is interpreted, only the {@link MaxSizePolicy#ENTRY_COUNT} policy is
supported.
@return the instance which will check if the maximum number of entries has been reached or null if the
{@code maxSizePolicy} is not {@link MaxSizePolicy#ENTRY_COUNT}
@throws IllegalArgumentException if the {@code maxSizePolicy} is null | [
"Creates",
"an",
"instance",
"for",
"checking",
"if",
"the",
"maximum",
"cache",
"size",
"has",
"been",
"reached",
".",
"Supports",
"only",
"the",
"{",
"@link",
"MaxSizePolicy#ENTRY_COUNT",
"}",
"policy",
".",
"Returns",
"null",
"if",
"other",
"{",
"@code",
"maxSizePolicy",
"}",
"is",
"used",
"."
]
| train | https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/cache/impl/AbstractCacheRecordStore.java#L326-L334 |
fhoeben/hsac-fitnesse-fixtures | src/main/java/nl/hsac/fitnesse/fixture/Environment.java | Environment.doGet | public void doGet(String url, HttpResponse response) {
"""
GETs content from URL.
@param url url to get from.
@param response response to store url and response value in.
"""
doGet(url, response, null, true);
} | java | public void doGet(String url, HttpResponse response) {
doGet(url, response, null, true);
} | [
"public",
"void",
"doGet",
"(",
"String",
"url",
",",
"HttpResponse",
"response",
")",
"{",
"doGet",
"(",
"url",
",",
"response",
",",
"null",
",",
"true",
")",
";",
"}"
]
| GETs content from URL.
@param url url to get from.
@param response response to store url and response value in. | [
"GETs",
"content",
"from",
"URL",
"."
]
| train | https://github.com/fhoeben/hsac-fitnesse-fixtures/blob/4e9018d7386a9aa65bfcbf07eb28ae064edd1732/src/main/java/nl/hsac/fitnesse/fixture/Environment.java#L397-L399 |
mygreen/super-csv-annotation | src/main/java/com/github/mygreen/supercsv/builder/BeanMappingFactory.java | BeanMappingFactory.buildValidators | @SuppressWarnings( {
"""
入力値検証の設定を組み立てます。
@param <T> Beanのタイプ
@param beanMapping Beanのマッピング情報
@param beanAnno アノテーション{@literal @CsvBean}のインタンス
@param groups グループ情報
""""unchecked"})
protected <T> void buildValidators(final BeanMapping<T> beanMapping, final CsvBean beanAnno, final Class<?>[] groups) {
// CsvValidatorの取得
final List<CsvValidator<T>> validators = Arrays.stream(beanAnno.validators())
.map(v -> (CsvValidator<T>)configuration.getBeanFactory().create(v))
.collect(Collectors.toList());
beanMapping.addAllValidators(validators);
beanMapping.setSkipValidationOnWrite(configuration.isSkipValidationOnWrite());
beanMapping.setGroups(groups);
} | java | @SuppressWarnings({"unchecked"})
protected <T> void buildValidators(final BeanMapping<T> beanMapping, final CsvBean beanAnno, final Class<?>[] groups) {
// CsvValidatorの取得
final List<CsvValidator<T>> validators = Arrays.stream(beanAnno.validators())
.map(v -> (CsvValidator<T>)configuration.getBeanFactory().create(v))
.collect(Collectors.toList());
beanMapping.addAllValidators(validators);
beanMapping.setSkipValidationOnWrite(configuration.isSkipValidationOnWrite());
beanMapping.setGroups(groups);
} | [
"@",
"SuppressWarnings",
"(",
"{",
"\"unchecked\"",
"}",
")",
"protected",
"<",
"T",
">",
"void",
"buildValidators",
"(",
"final",
"BeanMapping",
"<",
"T",
">",
"beanMapping",
",",
"final",
"CsvBean",
"beanAnno",
",",
"final",
"Class",
"<",
"?",
">",
"[",
"]",
"groups",
")",
"{",
"// CsvValidatorの取得\r",
"final",
"List",
"<",
"CsvValidator",
"<",
"T",
">",
">",
"validators",
"=",
"Arrays",
".",
"stream",
"(",
"beanAnno",
".",
"validators",
"(",
")",
")",
".",
"map",
"(",
"v",
"->",
"(",
"CsvValidator",
"<",
"T",
">",
")",
"configuration",
".",
"getBeanFactory",
"(",
")",
".",
"create",
"(",
"v",
")",
")",
".",
"collect",
"(",
"Collectors",
".",
"toList",
"(",
")",
")",
";",
"beanMapping",
".",
"addAllValidators",
"(",
"validators",
")",
";",
"beanMapping",
".",
"setSkipValidationOnWrite",
"(",
"configuration",
".",
"isSkipValidationOnWrite",
"(",
")",
")",
";",
"beanMapping",
".",
"setGroups",
"(",
"groups",
")",
";",
"}"
]
| 入力値検証の設定を組み立てます。
@param <T> Beanのタイプ
@param beanMapping Beanのマッピング情報
@param beanAnno アノテーション{@literal @CsvBean}のインタンス
@param groups グループ情報 | [
"入力値検証の設定を組み立てます。"
]
| train | https://github.com/mygreen/super-csv-annotation/blob/9910320cb6dc143be972c7d10d9ab5ffb09c3b84/src/main/java/com/github/mygreen/supercsv/builder/BeanMappingFactory.java#L113-L125 |
camunda/camunda-bpm-platform | engine/src/main/java/org/camunda/bpm/engine/impl/scripting/engine/ScriptEngineResolver.java | ScriptEngineResolver.getScriptEngine | public ScriptEngine getScriptEngine(String language, boolean resolveFromCache) {
"""
Returns a cached script engine or creates a new script engine if no such engine is currently cached.
@param language the language (such as 'groovy' for the script engine)
@return the cached engine or null if no script engine can be created for the given language
"""
ScriptEngine scriptEngine = null;
if (resolveFromCache) {
scriptEngine = cachedEngines.get(language);
if(scriptEngine == null) {
scriptEngine = scriptEngineManager.getEngineByName(language);
if(scriptEngine != null) {
if(ScriptingEngines.GROOVY_SCRIPTING_LANGUAGE.equals(language)) {
configureGroovyScriptEngine(scriptEngine);
}
if(isCachable(scriptEngine)) {
cachedEngines.put(language, scriptEngine);
}
}
}
} else {
scriptEngine = scriptEngineManager.getEngineByName(language);
}
return scriptEngine;
} | java | public ScriptEngine getScriptEngine(String language, boolean resolveFromCache) {
ScriptEngine scriptEngine = null;
if (resolveFromCache) {
scriptEngine = cachedEngines.get(language);
if(scriptEngine == null) {
scriptEngine = scriptEngineManager.getEngineByName(language);
if(scriptEngine != null) {
if(ScriptingEngines.GROOVY_SCRIPTING_LANGUAGE.equals(language)) {
configureGroovyScriptEngine(scriptEngine);
}
if(isCachable(scriptEngine)) {
cachedEngines.put(language, scriptEngine);
}
}
}
} else {
scriptEngine = scriptEngineManager.getEngineByName(language);
}
return scriptEngine;
} | [
"public",
"ScriptEngine",
"getScriptEngine",
"(",
"String",
"language",
",",
"boolean",
"resolveFromCache",
")",
"{",
"ScriptEngine",
"scriptEngine",
"=",
"null",
";",
"if",
"(",
"resolveFromCache",
")",
"{",
"scriptEngine",
"=",
"cachedEngines",
".",
"get",
"(",
"language",
")",
";",
"if",
"(",
"scriptEngine",
"==",
"null",
")",
"{",
"scriptEngine",
"=",
"scriptEngineManager",
".",
"getEngineByName",
"(",
"language",
")",
";",
"if",
"(",
"scriptEngine",
"!=",
"null",
")",
"{",
"if",
"(",
"ScriptingEngines",
".",
"GROOVY_SCRIPTING_LANGUAGE",
".",
"equals",
"(",
"language",
")",
")",
"{",
"configureGroovyScriptEngine",
"(",
"scriptEngine",
")",
";",
"}",
"if",
"(",
"isCachable",
"(",
"scriptEngine",
")",
")",
"{",
"cachedEngines",
".",
"put",
"(",
"language",
",",
"scriptEngine",
")",
";",
"}",
"}",
"}",
"}",
"else",
"{",
"scriptEngine",
"=",
"scriptEngineManager",
".",
"getEngineByName",
"(",
"language",
")",
";",
"}",
"return",
"scriptEngine",
";",
"}"
]
| Returns a cached script engine or creates a new script engine if no such engine is currently cached.
@param language the language (such as 'groovy' for the script engine)
@return the cached engine or null if no script engine can be created for the given language | [
"Returns",
"a",
"cached",
"script",
"engine",
"or",
"creates",
"a",
"new",
"script",
"engine",
"if",
"no",
"such",
"engine",
"is",
"currently",
"cached",
"."
]
| train | https://github.com/camunda/camunda-bpm-platform/blob/1a464fc887ef3760e53d6f91b9e5b871a0d77cc0/engine/src/main/java/org/camunda/bpm/engine/impl/scripting/engine/ScriptEngineResolver.java#L56-L85 |
QSFT/Doradus | doradus-common/src/main/java/com/dell/doradus/common/Utils.java | Utils.truncateTo | public static String truncateTo(String string, int maxLength) {
"""
Ensure that the given string is no longer than the given max length, truncating it
if necessary. If string.length() is <= maxLength, the same string is returned.
Otherwise, a substring of the first maxLength characters is returned.
@param string String to test.
@param maxLength Maximum length.
@return Same or truncated string as described above.
"""
if (string.length() <= maxLength) {
return string;
}
return string.substring(0, maxLength);
} | java | public static String truncateTo(String string, int maxLength) {
if (string.length() <= maxLength) {
return string;
}
return string.substring(0, maxLength);
} | [
"public",
"static",
"String",
"truncateTo",
"(",
"String",
"string",
",",
"int",
"maxLength",
")",
"{",
"if",
"(",
"string",
".",
"length",
"(",
")",
"<=",
"maxLength",
")",
"{",
"return",
"string",
";",
"}",
"return",
"string",
".",
"substring",
"(",
"0",
",",
"maxLength",
")",
";",
"}"
]
| Ensure that the given string is no longer than the given max length, truncating it
if necessary. If string.length() is <= maxLength, the same string is returned.
Otherwise, a substring of the first maxLength characters is returned.
@param string String to test.
@param maxLength Maximum length.
@return Same or truncated string as described above. | [
"Ensure",
"that",
"the",
"given",
"string",
"is",
"no",
"longer",
"than",
"the",
"given",
"max",
"length",
"truncating",
"it",
"if",
"necessary",
".",
"If",
"string",
".",
"length",
"()",
"is",
"<",
";",
"=",
"maxLength",
"the",
"same",
"string",
"is",
"returned",
".",
"Otherwise",
"a",
"substring",
"of",
"the",
"first",
"maxLength",
"characters",
"is",
"returned",
"."
]
| train | https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-common/src/main/java/com/dell/doradus/common/Utils.java#L2005-L2010 |
wildfly/wildfly-core | controller/src/main/java/org/jboss/as/controller/extension/ExtensionRegistry.java | ExtensionRegistry.getExtensionContext | @Deprecated
public ExtensionContext getExtensionContext(final String moduleName, ManagementResourceRegistration rootRegistration, boolean isMasterDomainController) {
"""
Gets an {@link ExtensionContext} for use when handling an {@code add} operation for
a resource representing an {@link org.jboss.as.controller.Extension}.
@param moduleName the name of the extension's module. Cannot be {@code null}
@param rootRegistration the root management resource registration
@param isMasterDomainController set to {@code true} if we are the master domain controller, in which case transformers get registered
@return the {@link ExtensionContext}. Will not return {@code null}
@deprecated use {@link #getExtensionContext(String, ManagementResourceRegistration, ExtensionRegistryType)}. Main code should be using this, but this is left behind in case any tests need to use this code.
"""
ExtensionRegistryType type = isMasterDomainController ? ExtensionRegistryType.MASTER : ExtensionRegistryType.SLAVE;
return getExtensionContext(moduleName, rootRegistration, type);
} | java | @Deprecated
public ExtensionContext getExtensionContext(final String moduleName, ManagementResourceRegistration rootRegistration, boolean isMasterDomainController) {
ExtensionRegistryType type = isMasterDomainController ? ExtensionRegistryType.MASTER : ExtensionRegistryType.SLAVE;
return getExtensionContext(moduleName, rootRegistration, type);
} | [
"@",
"Deprecated",
"public",
"ExtensionContext",
"getExtensionContext",
"(",
"final",
"String",
"moduleName",
",",
"ManagementResourceRegistration",
"rootRegistration",
",",
"boolean",
"isMasterDomainController",
")",
"{",
"ExtensionRegistryType",
"type",
"=",
"isMasterDomainController",
"?",
"ExtensionRegistryType",
".",
"MASTER",
":",
"ExtensionRegistryType",
".",
"SLAVE",
";",
"return",
"getExtensionContext",
"(",
"moduleName",
",",
"rootRegistration",
",",
"type",
")",
";",
"}"
]
| Gets an {@link ExtensionContext} for use when handling an {@code add} operation for
a resource representing an {@link org.jboss.as.controller.Extension}.
@param moduleName the name of the extension's module. Cannot be {@code null}
@param rootRegistration the root management resource registration
@param isMasterDomainController set to {@code true} if we are the master domain controller, in which case transformers get registered
@return the {@link ExtensionContext}. Will not return {@code null}
@deprecated use {@link #getExtensionContext(String, ManagementResourceRegistration, ExtensionRegistryType)}. Main code should be using this, but this is left behind in case any tests need to use this code. | [
"Gets",
"an",
"{",
"@link",
"ExtensionContext",
"}",
"for",
"use",
"when",
"handling",
"an",
"{",
"@code",
"add",
"}",
"operation",
"for",
"a",
"resource",
"representing",
"an",
"{",
"@link",
"org",
".",
"jboss",
".",
"as",
".",
"controller",
".",
"Extension",
"}",
"."
]
| train | https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/controller/src/main/java/org/jboss/as/controller/extension/ExtensionRegistry.java#L264-L268 |
shrinkwrap/shrinkwrap | api/src/main/java/org/jboss/shrinkwrap/api/ShrinkWrap.java | ShrinkWrap.createFromZipFile | public static <T extends Assignable> T createFromZipFile(final Class<T> type, final File archiveFile)
throws IllegalArgumentException, ArchiveImportException {
"""
Creates a new archive of the specified type as imported from the specified {@link File}. The file is expected to
be encoded as ZIP (ie. JAR/WAR/EAR). The name of the archive will be set to {@link File#getName()}. The archive
will be be backed by the {@link Configuration} within the {@link ShrinkWrap#getDefaultDomain()}
@param type
The type of the archive e.g. {@link org.jboss.shrinkwrap.api.spec.WebArchive}
@param archiveFile
the archiveName to use
@return An {@link Assignable} view
@throws IllegalArgumentException
If either argument is not supplied, if the specified {@link File} does not exist, or is not a valid
ZIP file
@throws org.jboss.shrinkwrap.api.importer.ArchiveImportException
If an error occurred during the import process
"""
// Delegate
return getDefaultDomain().getArchiveFactory().createFromZipFile(type, archiveFile);
} | java | public static <T extends Assignable> T createFromZipFile(final Class<T> type, final File archiveFile)
throws IllegalArgumentException, ArchiveImportException {
// Delegate
return getDefaultDomain().getArchiveFactory().createFromZipFile(type, archiveFile);
} | [
"public",
"static",
"<",
"T",
"extends",
"Assignable",
">",
"T",
"createFromZipFile",
"(",
"final",
"Class",
"<",
"T",
">",
"type",
",",
"final",
"File",
"archiveFile",
")",
"throws",
"IllegalArgumentException",
",",
"ArchiveImportException",
"{",
"// Delegate",
"return",
"getDefaultDomain",
"(",
")",
".",
"getArchiveFactory",
"(",
")",
".",
"createFromZipFile",
"(",
"type",
",",
"archiveFile",
")",
";",
"}"
]
| Creates a new archive of the specified type as imported from the specified {@link File}. The file is expected to
be encoded as ZIP (ie. JAR/WAR/EAR). The name of the archive will be set to {@link File#getName()}. The archive
will be be backed by the {@link Configuration} within the {@link ShrinkWrap#getDefaultDomain()}
@param type
The type of the archive e.g. {@link org.jboss.shrinkwrap.api.spec.WebArchive}
@param archiveFile
the archiveName to use
@return An {@link Assignable} view
@throws IllegalArgumentException
If either argument is not supplied, if the specified {@link File} does not exist, or is not a valid
ZIP file
@throws org.jboss.shrinkwrap.api.importer.ArchiveImportException
If an error occurred during the import process | [
"Creates",
"a",
"new",
"archive",
"of",
"the",
"specified",
"type",
"as",
"imported",
"from",
"the",
"specified",
"{",
"@link",
"File",
"}",
".",
"The",
"file",
"is",
"expected",
"to",
"be",
"encoded",
"as",
"ZIP",
"(",
"ie",
".",
"JAR",
"/",
"WAR",
"/",
"EAR",
")",
".",
"The",
"name",
"of",
"the",
"archive",
"will",
"be",
"set",
"to",
"{",
"@link",
"File#getName",
"()",
"}",
".",
"The",
"archive",
"will",
"be",
"be",
"backed",
"by",
"the",
"{",
"@link",
"Configuration",
"}",
"within",
"the",
"{",
"@link",
"ShrinkWrap#getDefaultDomain",
"()",
"}"
]
| train | https://github.com/shrinkwrap/shrinkwrap/blob/3f8a1a6d344651428c709a63ebb52d35343c5387/api/src/main/java/org/jboss/shrinkwrap/api/ShrinkWrap.java#L182-L186 |
nmdp-bioinformatics/ngs | feature/src/main/java/org/nmdp/ngs/feature/Allele.java | Allele.leftHardClip | public Allele leftHardClip(final String pattern) throws IllegalAlphabetException, AlleleException, IllegalSymbolException {
"""
A method to simulate hard clipping (removal) of leftmost sequence, for example synthesized sequence representing molecular barcodes or target capture probes (primers)
@param pattern sequence (will be strictly matched, no regular expressions)
@return new Allele with clipped sequence
@throws IllegalAlphabetException
@throws AlleleException
@throws IllegalSymbolException
"""
int start = this.getStart();
SymbolList copy = DNATools.createDNA(sequence.seqString());
while (copy.seqString().startsWith(pattern)) {
copy.edit(new Edit(1, pattern.length(), SymbolList.EMPTY_LIST));
start += pattern.length();
}
return builder()
.withContig(this.getContig())
.withStart(start)
.withEnd(this.getEnd())
.withSequence(copy)
.withLesion(this.lesion)
.build();
} | java | public Allele leftHardClip(final String pattern) throws IllegalAlphabetException, AlleleException, IllegalSymbolException {
int start = this.getStart();
SymbolList copy = DNATools.createDNA(sequence.seqString());
while (copy.seqString().startsWith(pattern)) {
copy.edit(new Edit(1, pattern.length(), SymbolList.EMPTY_LIST));
start += pattern.length();
}
return builder()
.withContig(this.getContig())
.withStart(start)
.withEnd(this.getEnd())
.withSequence(copy)
.withLesion(this.lesion)
.build();
} | [
"public",
"Allele",
"leftHardClip",
"(",
"final",
"String",
"pattern",
")",
"throws",
"IllegalAlphabetException",
",",
"AlleleException",
",",
"IllegalSymbolException",
"{",
"int",
"start",
"=",
"this",
".",
"getStart",
"(",
")",
";",
"SymbolList",
"copy",
"=",
"DNATools",
".",
"createDNA",
"(",
"sequence",
".",
"seqString",
"(",
")",
")",
";",
"while",
"(",
"copy",
".",
"seqString",
"(",
")",
".",
"startsWith",
"(",
"pattern",
")",
")",
"{",
"copy",
".",
"edit",
"(",
"new",
"Edit",
"(",
"1",
",",
"pattern",
".",
"length",
"(",
")",
",",
"SymbolList",
".",
"EMPTY_LIST",
")",
")",
";",
"start",
"+=",
"pattern",
".",
"length",
"(",
")",
";",
"}",
"return",
"builder",
"(",
")",
".",
"withContig",
"(",
"this",
".",
"getContig",
"(",
")",
")",
".",
"withStart",
"(",
"start",
")",
".",
"withEnd",
"(",
"this",
".",
"getEnd",
"(",
")",
")",
".",
"withSequence",
"(",
"copy",
")",
".",
"withLesion",
"(",
"this",
".",
"lesion",
")",
".",
"build",
"(",
")",
";",
"}"
]
| A method to simulate hard clipping (removal) of leftmost sequence, for example synthesized sequence representing molecular barcodes or target capture probes (primers)
@param pattern sequence (will be strictly matched, no regular expressions)
@return new Allele with clipped sequence
@throws IllegalAlphabetException
@throws AlleleException
@throws IllegalSymbolException | [
"A",
"method",
"to",
"simulate",
"hard",
"clipping",
"(",
"removal",
")",
"of",
"leftmost",
"sequence",
"for",
"example",
"synthesized",
"sequence",
"representing",
"molecular",
"barcodes",
"or",
"target",
"capture",
"probes",
"(",
"primers",
")"
]
| train | https://github.com/nmdp-bioinformatics/ngs/blob/277627e4311313a80f5dc110b3185b0d7af32bd0/feature/src/main/java/org/nmdp/ngs/feature/Allele.java#L376-L392 |
negusoft/holoaccent | HoloAccent/src/com/negusoft/holoaccent/AccentHelper.java | AccentHelper.prepareDialog | public void prepareDialog(Context c, Window window) {
"""
Paint the dialog's divider if required to correctly customize it.
"""
if (mDividerPainter == null)
mDividerPainter = initPainter(c, mOverrideColor);
mDividerPainter.paint(window);
} | java | public void prepareDialog(Context c, Window window) {
if (mDividerPainter == null)
mDividerPainter = initPainter(c, mOverrideColor);
mDividerPainter.paint(window);
} | [
"public",
"void",
"prepareDialog",
"(",
"Context",
"c",
",",
"Window",
"window",
")",
"{",
"if",
"(",
"mDividerPainter",
"==",
"null",
")",
"mDividerPainter",
"=",
"initPainter",
"(",
"c",
",",
"mOverrideColor",
")",
";",
"mDividerPainter",
".",
"paint",
"(",
"window",
")",
";",
"}"
]
| Paint the dialog's divider if required to correctly customize it. | [
"Paint",
"the",
"dialog",
"s",
"divider",
"if",
"required",
"to",
"correctly",
"customize",
"it",
"."
]
| train | https://github.com/negusoft/holoaccent/blob/7121a02dde94834e770cb81174d0bdc596323324/HoloAccent/src/com/negusoft/holoaccent/AccentHelper.java#L142-L146 |
mapsforge/mapsforge | mapsforge-core/src/main/java/org/mapsforge/core/model/LatLong.java | LatLong.fromMicroDegrees | public static LatLong fromMicroDegrees(int latitudeE6, int longitudeE6) {
"""
Constructs a new LatLong with the given latitude and longitude values, measured in
microdegrees.
@param latitudeE6 the latitude value in microdegrees.
@param longitudeE6 the longitude value in microdegrees.
@return the LatLong
@throws IllegalArgumentException if the latitudeE6 or longitudeE6 value is invalid.
"""
return new LatLong(LatLongUtils.microdegreesToDegrees(latitudeE6),
LatLongUtils.microdegreesToDegrees(longitudeE6));
} | java | public static LatLong fromMicroDegrees(int latitudeE6, int longitudeE6) {
return new LatLong(LatLongUtils.microdegreesToDegrees(latitudeE6),
LatLongUtils.microdegreesToDegrees(longitudeE6));
} | [
"public",
"static",
"LatLong",
"fromMicroDegrees",
"(",
"int",
"latitudeE6",
",",
"int",
"longitudeE6",
")",
"{",
"return",
"new",
"LatLong",
"(",
"LatLongUtils",
".",
"microdegreesToDegrees",
"(",
"latitudeE6",
")",
",",
"LatLongUtils",
".",
"microdegreesToDegrees",
"(",
"longitudeE6",
")",
")",
";",
"}"
]
| Constructs a new LatLong with the given latitude and longitude values, measured in
microdegrees.
@param latitudeE6 the latitude value in microdegrees.
@param longitudeE6 the longitude value in microdegrees.
@return the LatLong
@throws IllegalArgumentException if the latitudeE6 or longitudeE6 value is invalid. | [
"Constructs",
"a",
"new",
"LatLong",
"with",
"the",
"given",
"latitude",
"and",
"longitude",
"values",
"measured",
"in",
"microdegrees",
"."
]
| train | https://github.com/mapsforge/mapsforge/blob/c49c83f7f727552f793dff15cefa532ade030842/mapsforge-core/src/main/java/org/mapsforge/core/model/LatLong.java#L136-L139 |
infinispan/infinispan | core/src/main/java/org/infinispan/interceptors/BaseAsyncInterceptor.java | BaseAsyncInterceptor.delayedValue | public static Object delayedValue(CompletionStage<Void> stage, Object syncValue) {
"""
Returns an InvocationStage if the provided CompletionStage is null, not completed or completed via exception.
If these are not true the sync value is returned directly.
@param stage wait for completion of this if not null
@param syncValue sync value to return if stage is complete or as stage value
@return invocation stage or sync value
"""
if (stage != null) {
CompletableFuture<?> future = stage.toCompletableFuture();
if (!future.isDone()) {
return asyncValue(stage.thenApply(v -> syncValue));
}
if (future.isCompletedExceptionally()) {
return asyncValue(stage);
}
}
return syncValue;
} | java | public static Object delayedValue(CompletionStage<Void> stage, Object syncValue) {
if (stage != null) {
CompletableFuture<?> future = stage.toCompletableFuture();
if (!future.isDone()) {
return asyncValue(stage.thenApply(v -> syncValue));
}
if (future.isCompletedExceptionally()) {
return asyncValue(stage);
}
}
return syncValue;
} | [
"public",
"static",
"Object",
"delayedValue",
"(",
"CompletionStage",
"<",
"Void",
">",
"stage",
",",
"Object",
"syncValue",
")",
"{",
"if",
"(",
"stage",
"!=",
"null",
")",
"{",
"CompletableFuture",
"<",
"?",
">",
"future",
"=",
"stage",
".",
"toCompletableFuture",
"(",
")",
";",
"if",
"(",
"!",
"future",
".",
"isDone",
"(",
")",
")",
"{",
"return",
"asyncValue",
"(",
"stage",
".",
"thenApply",
"(",
"v",
"->",
"syncValue",
")",
")",
";",
"}",
"if",
"(",
"future",
".",
"isCompletedExceptionally",
"(",
")",
")",
"{",
"return",
"asyncValue",
"(",
"stage",
")",
";",
"}",
"}",
"return",
"syncValue",
";",
"}"
]
| Returns an InvocationStage if the provided CompletionStage is null, not completed or completed via exception.
If these are not true the sync value is returned directly.
@param stage wait for completion of this if not null
@param syncValue sync value to return if stage is complete or as stage value
@return invocation stage or sync value | [
"Returns",
"an",
"InvocationStage",
"if",
"the",
"provided",
"CompletionStage",
"is",
"null",
"not",
"completed",
"or",
"completed",
"via",
"exception",
".",
"If",
"these",
"are",
"not",
"true",
"the",
"sync",
"value",
"is",
"returned",
"directly",
"."
]
| train | https://github.com/infinispan/infinispan/blob/7c62b94886c3febb4774ae8376acf2baa0265ab5/core/src/main/java/org/infinispan/interceptors/BaseAsyncInterceptor.java#L299-L310 |
TheCoder4eu/BootsFaces-OSP | src/main/java/net/bootsfaces/component/navLink/NavLinkRenderer.java | NavLinkRenderer.encodeBegin | @Override
public void encodeBegin(FacesContext context, UIComponent component) throws IOException {
"""
This methods generates the HTML code of the current b:navLink.
@param context the FacesContext.
@param component the current b:navLink.
@throws IOException thrown if something goes wrong when writing the HTML
code.
"""
AbstractNavLink navlink = (AbstractNavLink) component;
if (!navlink.isRendered()) {
return;
}
// If there is the header attribute, we only render a Header
String head = navlink.getHeader();
if (head != null) {
encodeHeader(context, head, (UIComponent) navlink);
} else {
// if there is no href, no outcome, no child and no value we render
// a divider
if ((navlink.getValue() == null) && (((UIComponent) navlink).getChildCount() == 0)
&& navlink.getIcon() == null && navlink.getIconAwesome() == null) {
encodeDivider(context, navlink);
} else {
encodeHTML(context, (UIComponent) navlink);
}
} // if header
Tooltip.activateTooltips(context, component);
} | java | @Override
public void encodeBegin(FacesContext context, UIComponent component) throws IOException {
AbstractNavLink navlink = (AbstractNavLink) component;
if (!navlink.isRendered()) {
return;
}
// If there is the header attribute, we only render a Header
String head = navlink.getHeader();
if (head != null) {
encodeHeader(context, head, (UIComponent) navlink);
} else {
// if there is no href, no outcome, no child and no value we render
// a divider
if ((navlink.getValue() == null) && (((UIComponent) navlink).getChildCount() == 0)
&& navlink.getIcon() == null && navlink.getIconAwesome() == null) {
encodeDivider(context, navlink);
} else {
encodeHTML(context, (UIComponent) navlink);
}
} // if header
Tooltip.activateTooltips(context, component);
} | [
"@",
"Override",
"public",
"void",
"encodeBegin",
"(",
"FacesContext",
"context",
",",
"UIComponent",
"component",
")",
"throws",
"IOException",
"{",
"AbstractNavLink",
"navlink",
"=",
"(",
"AbstractNavLink",
")",
"component",
";",
"if",
"(",
"!",
"navlink",
".",
"isRendered",
"(",
")",
")",
"{",
"return",
";",
"}",
"// If there is the header attribute, we only render a Header",
"String",
"head",
"=",
"navlink",
".",
"getHeader",
"(",
")",
";",
"if",
"(",
"head",
"!=",
"null",
")",
"{",
"encodeHeader",
"(",
"context",
",",
"head",
",",
"(",
"UIComponent",
")",
"navlink",
")",
";",
"}",
"else",
"{",
"// if there is no href, no outcome, no child and no value we render",
"// a divider",
"if",
"(",
"(",
"navlink",
".",
"getValue",
"(",
")",
"==",
"null",
")",
"&&",
"(",
"(",
"(",
"UIComponent",
")",
"navlink",
")",
".",
"getChildCount",
"(",
")",
"==",
"0",
")",
"&&",
"navlink",
".",
"getIcon",
"(",
")",
"==",
"null",
"&&",
"navlink",
".",
"getIconAwesome",
"(",
")",
"==",
"null",
")",
"{",
"encodeDivider",
"(",
"context",
",",
"navlink",
")",
";",
"}",
"else",
"{",
"encodeHTML",
"(",
"context",
",",
"(",
"UIComponent",
")",
"navlink",
")",
";",
"}",
"}",
"// if header",
"Tooltip",
".",
"activateTooltips",
"(",
"context",
",",
"component",
")",
";",
"}"
]
| This methods generates the HTML code of the current b:navLink.
@param context the FacesContext.
@param component the current b:navLink.
@throws IOException thrown if something goes wrong when writing the HTML
code. | [
"This",
"methods",
"generates",
"the",
"HTML",
"code",
"of",
"the",
"current",
"b",
":",
"navLink",
"."
]
| train | https://github.com/TheCoder4eu/BootsFaces-OSP/blob/d1a70952bc240979b5272fa4fe1c7f100873add0/src/main/java/net/bootsfaces/component/navLink/NavLinkRenderer.java#L82-L104 |
algermissen/hawkj | src/main/java/net/jalg/hawkj/Util.java | Util.fixedTimeEqual | public static boolean fixedTimeEqual(String lhs, String rhs) {
"""
Fixed time comparison of two strings.
Fixed time comparison is necessary in order to prevent attacks analyzing differences in
verification time for corrupted tokens.
@param lhs Left hand side operand
@param rhs Right hadn side operand
@return true if the strings are equal, false otherwise.
"""
boolean equal = (lhs.length() == rhs.length() ? true : false);
// If not equal, work on a single operand to have same length.
if(!equal) {
rhs = lhs;
}
int len = lhs.length();
for(int i=0;i<len;i++) {
if(lhs.charAt(i) == rhs.charAt(i)) {
equal = equal && true;
} else {
equal = equal && false;
}
}
return equal;
} | java | public static boolean fixedTimeEqual(String lhs, String rhs) {
boolean equal = (lhs.length() == rhs.length() ? true : false);
// If not equal, work on a single operand to have same length.
if(!equal) {
rhs = lhs;
}
int len = lhs.length();
for(int i=0;i<len;i++) {
if(lhs.charAt(i) == rhs.charAt(i)) {
equal = equal && true;
} else {
equal = equal && false;
}
}
return equal;
} | [
"public",
"static",
"boolean",
"fixedTimeEqual",
"(",
"String",
"lhs",
",",
"String",
"rhs",
")",
"{",
"boolean",
"equal",
"=",
"(",
"lhs",
".",
"length",
"(",
")",
"==",
"rhs",
".",
"length",
"(",
")",
"?",
"true",
":",
"false",
")",
";",
"// If not equal, work on a single operand to have same length.",
"if",
"(",
"!",
"equal",
")",
"{",
"rhs",
"=",
"lhs",
";",
"}",
"int",
"len",
"=",
"lhs",
".",
"length",
"(",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"if",
"(",
"lhs",
".",
"charAt",
"(",
"i",
")",
"==",
"rhs",
".",
"charAt",
"(",
"i",
")",
")",
"{",
"equal",
"=",
"equal",
"&&",
"true",
";",
"}",
"else",
"{",
"equal",
"=",
"equal",
"&&",
"false",
";",
"}",
"}",
"return",
"equal",
";",
"}"
]
| Fixed time comparison of two strings.
Fixed time comparison is necessary in order to prevent attacks analyzing differences in
verification time for corrupted tokens.
@param lhs Left hand side operand
@param rhs Right hadn side operand
@return true if the strings are equal, false otherwise. | [
"Fixed",
"time",
"comparison",
"of",
"two",
"strings",
"."
]
| train | https://github.com/algermissen/hawkj/blob/f798a20f058474bcfe761f7c5c02afee17326c71/src/main/java/net/jalg/hawkj/Util.java#L71-L89 |
matthewhorridge/owlapi-gwt | owlapi-gwt-serialization/src/main/java/uk/ac/manchester/cs/owl/owlapi/OWLDataPropertyImpl_CustomFieldSerializer.java | OWLDataPropertyImpl_CustomFieldSerializer.deserializeInstance | @Override
public void deserializeInstance(SerializationStreamReader streamReader, OWLDataPropertyImpl instance) throws SerializationException {
"""
Deserializes the content of the object from the
{@link com.google.gwt.user.client.rpc.SerializationStreamReader}.
@param streamReader the {@link com.google.gwt.user.client.rpc.SerializationStreamReader} to read the
object's content from
@param instance the object instance to deserialize
@throws com.google.gwt.user.client.rpc.SerializationException
if the deserialization operation is not
successful
"""
deserialize(streamReader, instance);
} | java | @Override
public void deserializeInstance(SerializationStreamReader streamReader, OWLDataPropertyImpl instance) throws SerializationException {
deserialize(streamReader, instance);
} | [
"@",
"Override",
"public",
"void",
"deserializeInstance",
"(",
"SerializationStreamReader",
"streamReader",
",",
"OWLDataPropertyImpl",
"instance",
")",
"throws",
"SerializationException",
"{",
"deserialize",
"(",
"streamReader",
",",
"instance",
")",
";",
"}"
]
| Deserializes the content of the object from the
{@link com.google.gwt.user.client.rpc.SerializationStreamReader}.
@param streamReader the {@link com.google.gwt.user.client.rpc.SerializationStreamReader} to read the
object's content from
@param instance the object instance to deserialize
@throws com.google.gwt.user.client.rpc.SerializationException
if the deserialization operation is not
successful | [
"Deserializes",
"the",
"content",
"of",
"the",
"object",
"from",
"the",
"{"
]
| train | https://github.com/matthewhorridge/owlapi-gwt/blob/7ab975fb6cef3c8947099983551672a3b5d4e2fd/owlapi-gwt-serialization/src/main/java/uk/ac/manchester/cs/owl/owlapi/OWLDataPropertyImpl_CustomFieldSerializer.java#L83-L86 |
mozilla/rhino | src/org/mozilla/javascript/Parser.java | Parser.arrayComprehension | private AstNode arrayComprehension(AstNode result, int pos)
throws IOException {
"""
Parse a JavaScript 1.7 Array comprehension.
@param result the first expression after the opening left-bracket
@param pos start of LB token that begins the array comprehension
@return the array comprehension or an error node
"""
List<ArrayComprehensionLoop> loops =
new ArrayList<ArrayComprehensionLoop>();
while (peekToken() == Token.FOR) {
loops.add(arrayComprehensionLoop());
}
int ifPos = -1;
ConditionData data = null;
if (peekToken() == Token.IF) {
consumeToken();
ifPos = ts.tokenBeg - pos;
data = condition();
}
mustMatchToken(Token.RB, "msg.no.bracket.arg", true);
ArrayComprehension pn = new ArrayComprehension(pos, ts.tokenEnd - pos);
pn.setResult(result);
pn.setLoops(loops);
if (data != null) {
pn.setIfPosition(ifPos);
pn.setFilter(data.condition);
pn.setFilterLp(data.lp - pos);
pn.setFilterRp(data.rp - pos);
}
return pn;
} | java | private AstNode arrayComprehension(AstNode result, int pos)
throws IOException
{
List<ArrayComprehensionLoop> loops =
new ArrayList<ArrayComprehensionLoop>();
while (peekToken() == Token.FOR) {
loops.add(arrayComprehensionLoop());
}
int ifPos = -1;
ConditionData data = null;
if (peekToken() == Token.IF) {
consumeToken();
ifPos = ts.tokenBeg - pos;
data = condition();
}
mustMatchToken(Token.RB, "msg.no.bracket.arg", true);
ArrayComprehension pn = new ArrayComprehension(pos, ts.tokenEnd - pos);
pn.setResult(result);
pn.setLoops(loops);
if (data != null) {
pn.setIfPosition(ifPos);
pn.setFilter(data.condition);
pn.setFilterLp(data.lp - pos);
pn.setFilterRp(data.rp - pos);
}
return pn;
} | [
"private",
"AstNode",
"arrayComprehension",
"(",
"AstNode",
"result",
",",
"int",
"pos",
")",
"throws",
"IOException",
"{",
"List",
"<",
"ArrayComprehensionLoop",
">",
"loops",
"=",
"new",
"ArrayList",
"<",
"ArrayComprehensionLoop",
">",
"(",
")",
";",
"while",
"(",
"peekToken",
"(",
")",
"==",
"Token",
".",
"FOR",
")",
"{",
"loops",
".",
"add",
"(",
"arrayComprehensionLoop",
"(",
")",
")",
";",
"}",
"int",
"ifPos",
"=",
"-",
"1",
";",
"ConditionData",
"data",
"=",
"null",
";",
"if",
"(",
"peekToken",
"(",
")",
"==",
"Token",
".",
"IF",
")",
"{",
"consumeToken",
"(",
")",
";",
"ifPos",
"=",
"ts",
".",
"tokenBeg",
"-",
"pos",
";",
"data",
"=",
"condition",
"(",
")",
";",
"}",
"mustMatchToken",
"(",
"Token",
".",
"RB",
",",
"\"msg.no.bracket.arg\"",
",",
"true",
")",
";",
"ArrayComprehension",
"pn",
"=",
"new",
"ArrayComprehension",
"(",
"pos",
",",
"ts",
".",
"tokenEnd",
"-",
"pos",
")",
";",
"pn",
".",
"setResult",
"(",
"result",
")",
";",
"pn",
".",
"setLoops",
"(",
"loops",
")",
";",
"if",
"(",
"data",
"!=",
"null",
")",
"{",
"pn",
".",
"setIfPosition",
"(",
"ifPos",
")",
";",
"pn",
".",
"setFilter",
"(",
"data",
".",
"condition",
")",
";",
"pn",
".",
"setFilterLp",
"(",
"data",
".",
"lp",
"-",
"pos",
")",
";",
"pn",
".",
"setFilterRp",
"(",
"data",
".",
"rp",
"-",
"pos",
")",
";",
"}",
"return",
"pn",
";",
"}"
]
| Parse a JavaScript 1.7 Array comprehension.
@param result the first expression after the opening left-bracket
@param pos start of LB token that begins the array comprehension
@return the array comprehension or an error node | [
"Parse",
"a",
"JavaScript",
"1",
".",
"7",
"Array",
"comprehension",
"."
]
| train | https://github.com/mozilla/rhino/blob/fa8a86df11d37623f5faa8d445a5876612bc47b0/src/org/mozilla/javascript/Parser.java#L3323-L3349 |
OpenLiberty/open-liberty | dev/com.ibm.ws.messaging.runtime/src/com/ibm/ws/sib/processor/impl/PtoPOutputHandler.java | PtoPOutputHandler.sendFlushedMessage | public void sendFlushedMessage(SIBUuid8 ignoreUuid, SIBUuid12 streamID) throws SIResourceException {
"""
/* (non-Javadoc)
@see com.ibm.ws.sib.processor.impl.interfaces.DownstreamControl#sendFlushedMessage(com.ibm.ws.sib.utils.SIBUuid12)
Sends an 'I am flushed' message in response to a query from a target
"""
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(tc, "sendFlushedMessage", new Object[]{ignoreUuid, streamID});
ControlFlushed flushMsg = createControlFlushed(streamID);
// If the destination in a Link add Link specific properties to message
if( isLink )
{
flushMsg = (ControlFlushed)addLinkProps(flushMsg);
}
// If the destination is system or temporary then the
// routingDestination into th message
if( this.isSystemOrTemp )
{
flushMsg.setRoutingDestination(routingDestination);
}
mpio.sendToMe(routingMEUuid, SIMPConstants.MSG_HIGH_PRIORITY, flushMsg);
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "sendFlushedMessage");
} | java | public void sendFlushedMessage(SIBUuid8 ignoreUuid, SIBUuid12 streamID) throws SIResourceException
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(tc, "sendFlushedMessage", new Object[]{ignoreUuid, streamID});
ControlFlushed flushMsg = createControlFlushed(streamID);
// If the destination in a Link add Link specific properties to message
if( isLink )
{
flushMsg = (ControlFlushed)addLinkProps(flushMsg);
}
// If the destination is system or temporary then the
// routingDestination into th message
if( this.isSystemOrTemp )
{
flushMsg.setRoutingDestination(routingDestination);
}
mpio.sendToMe(routingMEUuid, SIMPConstants.MSG_HIGH_PRIORITY, flushMsg);
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "sendFlushedMessage");
} | [
"public",
"void",
"sendFlushedMessage",
"(",
"SIBUuid8",
"ignoreUuid",
",",
"SIBUuid12",
"streamID",
")",
"throws",
"SIResourceException",
"{",
"if",
"(",
"TraceComponent",
".",
"isAnyTracingEnabled",
"(",
")",
"&&",
"tc",
".",
"isEntryEnabled",
"(",
")",
")",
"SibTr",
".",
"entry",
"(",
"tc",
",",
"\"sendFlushedMessage\"",
",",
"new",
"Object",
"[",
"]",
"{",
"ignoreUuid",
",",
"streamID",
"}",
")",
";",
"ControlFlushed",
"flushMsg",
"=",
"createControlFlushed",
"(",
"streamID",
")",
";",
"// If the destination in a Link add Link specific properties to message",
"if",
"(",
"isLink",
")",
"{",
"flushMsg",
"=",
"(",
"ControlFlushed",
")",
"addLinkProps",
"(",
"flushMsg",
")",
";",
"}",
"// If the destination is system or temporary then the ",
"// routingDestination into th message",
"if",
"(",
"this",
".",
"isSystemOrTemp",
")",
"{",
"flushMsg",
".",
"setRoutingDestination",
"(",
"routingDestination",
")",
";",
"}",
"mpio",
".",
"sendToMe",
"(",
"routingMEUuid",
",",
"SIMPConstants",
".",
"MSG_HIGH_PRIORITY",
",",
"flushMsg",
")",
";",
"if",
"(",
"TraceComponent",
".",
"isAnyTracingEnabled",
"(",
")",
"&&",
"tc",
".",
"isEntryEnabled",
"(",
")",
")",
"SibTr",
".",
"exit",
"(",
"tc",
",",
"\"sendFlushedMessage\"",
")",
";",
"}"
]
| /* (non-Javadoc)
@see com.ibm.ws.sib.processor.impl.interfaces.DownstreamControl#sendFlushedMessage(com.ibm.ws.sib.utils.SIBUuid12)
Sends an 'I am flushed' message in response to a query from a target | [
"/",
"*",
"(",
"non",
"-",
"Javadoc",
")",
"@see",
"com",
".",
"ibm",
".",
"ws",
".",
"sib",
".",
"processor",
".",
"impl",
".",
"interfaces",
".",
"DownstreamControl#sendFlushedMessage",
"(",
"com",
".",
"ibm",
".",
"ws",
".",
"sib",
".",
"utils",
".",
"SIBUuid12",
")"
]
| train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.messaging.runtime/src/com/ibm/ws/sib/processor/impl/PtoPOutputHandler.java#L1910-L1931 |
CenturyLinkCloud/mdw | mdw-hub/src/com/centurylink/mdw/hub/servlet/SoapServlet.java | SoapServlet.createSoapFaultResponse | protected String createSoapFaultResponse(String soapVersion, String code, String message)
throws SOAPException, TransformerException {
"""
Allow version specific factory passed in to support SOAP 1.1 and 1.2
<b>Important</b> Faults are treated differently for 1.1 and 1.2 For 1.2
you can't use the elementName otherwise it throws an exception
@see http://docs.oracle.com/cd/E19159-01/819-3669/bnbip/index.html
@param factory
@param code
@param message
@return Xml fault string
@throws SOAPException
@throws TransformerException
"""
SOAPMessage soapMessage = getSoapMessageFactory(soapVersion).createMessage();
SOAPBody soapBody = soapMessage.getSOAPBody();
/**
* Faults are treated differently for 1.1 and 1.2 For 1.2 you can't use
* the elementName otherwise it throws an exception
*
* @see http://docs.oracle.com/cd/E19159-01/819-3669/bnbip/index.html
*/
SOAPFault fault = null;
if (soapVersion.equals(SOAPConstants.SOAP_1_1_PROTOCOL)) {
// existing 1.1 functionality
fault = soapBody.addFault(soapMessage.getSOAPHeader().getElementName(), message);
if (code != null)
fault.setFaultCode(code);
}
else if (soapVersion.equals(SOAPConstants.SOAP_1_2_PROTOCOL)) {
/**
* For 1.2 there are only a set number of allowed codes, so we can't
* just use any one like what we did in 1.1. The recommended one to
* use is SOAPConstants.SOAP_RECEIVER_FAULT
*/
fault = soapBody.addFault(SOAPConstants.SOAP_RECEIVER_FAULT,
code == null ? message : code + " : " + message);
}
return DomHelper.toXml(soapMessage.getSOAPPart().getDocumentElement());
} | java | protected String createSoapFaultResponse(String soapVersion, String code, String message)
throws SOAPException, TransformerException {
SOAPMessage soapMessage = getSoapMessageFactory(soapVersion).createMessage();
SOAPBody soapBody = soapMessage.getSOAPBody();
/**
* Faults are treated differently for 1.1 and 1.2 For 1.2 you can't use
* the elementName otherwise it throws an exception
*
* @see http://docs.oracle.com/cd/E19159-01/819-3669/bnbip/index.html
*/
SOAPFault fault = null;
if (soapVersion.equals(SOAPConstants.SOAP_1_1_PROTOCOL)) {
// existing 1.1 functionality
fault = soapBody.addFault(soapMessage.getSOAPHeader().getElementName(), message);
if (code != null)
fault.setFaultCode(code);
}
else if (soapVersion.equals(SOAPConstants.SOAP_1_2_PROTOCOL)) {
/**
* For 1.2 there are only a set number of allowed codes, so we can't
* just use any one like what we did in 1.1. The recommended one to
* use is SOAPConstants.SOAP_RECEIVER_FAULT
*/
fault = soapBody.addFault(SOAPConstants.SOAP_RECEIVER_FAULT,
code == null ? message : code + " : " + message);
}
return DomHelper.toXml(soapMessage.getSOAPPart().getDocumentElement());
} | [
"protected",
"String",
"createSoapFaultResponse",
"(",
"String",
"soapVersion",
",",
"String",
"code",
",",
"String",
"message",
")",
"throws",
"SOAPException",
",",
"TransformerException",
"{",
"SOAPMessage",
"soapMessage",
"=",
"getSoapMessageFactory",
"(",
"soapVersion",
")",
".",
"createMessage",
"(",
")",
";",
"SOAPBody",
"soapBody",
"=",
"soapMessage",
".",
"getSOAPBody",
"(",
")",
";",
"/**\n * Faults are treated differently for 1.1 and 1.2 For 1.2 you can't use\n * the elementName otherwise it throws an exception\n *\n * @see http://docs.oracle.com/cd/E19159-01/819-3669/bnbip/index.html\n */",
"SOAPFault",
"fault",
"=",
"null",
";",
"if",
"(",
"soapVersion",
".",
"equals",
"(",
"SOAPConstants",
".",
"SOAP_1_1_PROTOCOL",
")",
")",
"{",
"// existing 1.1 functionality",
"fault",
"=",
"soapBody",
".",
"addFault",
"(",
"soapMessage",
".",
"getSOAPHeader",
"(",
")",
".",
"getElementName",
"(",
")",
",",
"message",
")",
";",
"if",
"(",
"code",
"!=",
"null",
")",
"fault",
".",
"setFaultCode",
"(",
"code",
")",
";",
"}",
"else",
"if",
"(",
"soapVersion",
".",
"equals",
"(",
"SOAPConstants",
".",
"SOAP_1_2_PROTOCOL",
")",
")",
"{",
"/**\n * For 1.2 there are only a set number of allowed codes, so we can't\n * just use any one like what we did in 1.1. The recommended one to\n * use is SOAPConstants.SOAP_RECEIVER_FAULT\n */",
"fault",
"=",
"soapBody",
".",
"addFault",
"(",
"SOAPConstants",
".",
"SOAP_RECEIVER_FAULT",
",",
"code",
"==",
"null",
"?",
"message",
":",
"code",
"+",
"\" : \"",
"+",
"message",
")",
";",
"}",
"return",
"DomHelper",
".",
"toXml",
"(",
"soapMessage",
".",
"getSOAPPart",
"(",
")",
".",
"getDocumentElement",
"(",
")",
")",
";",
"}"
]
| Allow version specific factory passed in to support SOAP 1.1 and 1.2
<b>Important</b> Faults are treated differently for 1.1 and 1.2 For 1.2
you can't use the elementName otherwise it throws an exception
@see http://docs.oracle.com/cd/E19159-01/819-3669/bnbip/index.html
@param factory
@param code
@param message
@return Xml fault string
@throws SOAPException
@throws TransformerException | [
"Allow",
"version",
"specific",
"factory",
"passed",
"in",
"to",
"support",
"SOAP",
"1",
".",
"1",
"and",
"1",
".",
"2",
"<b",
">",
"Important<",
"/",
"b",
">",
"Faults",
"are",
"treated",
"differently",
"for",
"1",
".",
"1",
"and",
"1",
".",
"2",
"For",
"1",
".",
"2",
"you",
"can",
"t",
"use",
"the",
"elementName",
"otherwise",
"it",
"throws",
"an",
"exception"
]
| train | https://github.com/CenturyLinkCloud/mdw/blob/91167fe65a25a5d7022cdcf8b0fae8506f5b87ce/mdw-hub/src/com/centurylink/mdw/hub/servlet/SoapServlet.java#L410-L440 |
gallandarakhneorg/afc | advanced/gis/giscore/src/main/java/org/arakhne/afc/gis/mapelement/MapComposedElement.java | MapComposedElement.setPointAt | public final boolean setPointAt(int groupIndex, int indexInGroup, double x, double y) {
"""
Set the specified point at the given index in the specified group.
@param groupIndex is the index of the group
@param indexInGroup is the index of the ponit in the group (0 for the
first point of the group...).
@param x is the new value.
@param y is the new value.
@return <code>true</code> if the point was set, <code>false</code> if
the specified coordinates correspond to the already existing point.
@throws IndexOutOfBoundsException in case of error
"""
return setPointAt(groupIndex, indexInGroup, x, y, false);
} | java | public final boolean setPointAt(int groupIndex, int indexInGroup, double x, double y) {
return setPointAt(groupIndex, indexInGroup, x, y, false);
} | [
"public",
"final",
"boolean",
"setPointAt",
"(",
"int",
"groupIndex",
",",
"int",
"indexInGroup",
",",
"double",
"x",
",",
"double",
"y",
")",
"{",
"return",
"setPointAt",
"(",
"groupIndex",
",",
"indexInGroup",
",",
"x",
",",
"y",
",",
"false",
")",
";",
"}"
]
| Set the specified point at the given index in the specified group.
@param groupIndex is the index of the group
@param indexInGroup is the index of the ponit in the group (0 for the
first point of the group...).
@param x is the new value.
@param y is the new value.
@return <code>true</code> if the point was set, <code>false</code> if
the specified coordinates correspond to the already existing point.
@throws IndexOutOfBoundsException in case of error | [
"Set",
"the",
"specified",
"point",
"at",
"the",
"given",
"index",
"in",
"the",
"specified",
"group",
"."
]
| train | https://github.com/gallandarakhneorg/afc/blob/0c7d2e1ddefd4167ef788416d970a6c1ef6f8bbb/advanced/gis/giscore/src/main/java/org/arakhne/afc/gis/mapelement/MapComposedElement.java#L1009-L1011 |
mongodb/stitch-android-sdk | core/services/mongodb-remote/src/main/java/com/mongodb/stitch/core/services/mongodb/remote/sync/internal/DataSynchronizer.java | DataSynchronizer.resolveConflict | @CheckReturnValue
private LocalSyncWriteModelContainer resolveConflict(
final NamespaceSynchronizationConfig nsConfig,
final CoreDocumentSynchronizationConfig docConfig,
final ChangeEvent<BsonDocument> remoteEvent
) {
"""
Resolves a conflict between a synchronized document's local and remote state. The resolution
will result in either the document being desynchronized or being replaced with some resolved
state based on the conflict resolver specified for the document. Uses the last uncommitted
local event as the local state.
@param nsConfig the namespace synchronization config of the namespace where the document
lives.
@param docConfig the configuration of the document that describes the resolver and current
state.
@param remoteEvent the remote change event that is conflicting.
"""
return resolveConflict(nsConfig, docConfig, docConfig.getLastUncommittedChangeEvent(),
remoteEvent);
} | java | @CheckReturnValue
private LocalSyncWriteModelContainer resolveConflict(
final NamespaceSynchronizationConfig nsConfig,
final CoreDocumentSynchronizationConfig docConfig,
final ChangeEvent<BsonDocument> remoteEvent
) {
return resolveConflict(nsConfig, docConfig, docConfig.getLastUncommittedChangeEvent(),
remoteEvent);
} | [
"@",
"CheckReturnValue",
"private",
"LocalSyncWriteModelContainer",
"resolveConflict",
"(",
"final",
"NamespaceSynchronizationConfig",
"nsConfig",
",",
"final",
"CoreDocumentSynchronizationConfig",
"docConfig",
",",
"final",
"ChangeEvent",
"<",
"BsonDocument",
">",
"remoteEvent",
")",
"{",
"return",
"resolveConflict",
"(",
"nsConfig",
",",
"docConfig",
",",
"docConfig",
".",
"getLastUncommittedChangeEvent",
"(",
")",
",",
"remoteEvent",
")",
";",
"}"
]
| Resolves a conflict between a synchronized document's local and remote state. The resolution
will result in either the document being desynchronized or being replaced with some resolved
state based on the conflict resolver specified for the document. Uses the last uncommitted
local event as the local state.
@param nsConfig the namespace synchronization config of the namespace where the document
lives.
@param docConfig the configuration of the document that describes the resolver and current
state.
@param remoteEvent the remote change event that is conflicting. | [
"Resolves",
"a",
"conflict",
"between",
"a",
"synchronized",
"document",
"s",
"local",
"and",
"remote",
"state",
".",
"The",
"resolution",
"will",
"result",
"in",
"either",
"the",
"document",
"being",
"desynchronized",
"or",
"being",
"replaced",
"with",
"some",
"resolved",
"state",
"based",
"on",
"the",
"conflict",
"resolver",
"specified",
"for",
"the",
"document",
".",
"Uses",
"the",
"last",
"uncommitted",
"local",
"event",
"as",
"the",
"local",
"state",
"."
]
| 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#L1681-L1689 |
contentful/contentful-management.java | src/main/java/com/contentful/java/cma/AbsModule.java | AbsModule.assertNotNull | void assertNotNull(Object object, String param) {
"""
Asserts that the given {@code object} with name {@code param} is not null, throws
{@link IllegalArgumentException} otherwise.
"""
if (object == null) {
throw new IllegalArgumentException(String.format(
"%s may not be null.", param));
}
} | java | void assertNotNull(Object object, String param) {
if (object == null) {
throw new IllegalArgumentException(String.format(
"%s may not be null.", param));
}
} | [
"void",
"assertNotNull",
"(",
"Object",
"object",
",",
"String",
"param",
")",
"{",
"if",
"(",
"object",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"String",
".",
"format",
"(",
"\"%s may not be null.\"",
",",
"param",
")",
")",
";",
"}",
"}"
]
| Asserts that the given {@code object} with name {@code param} is not null, throws
{@link IllegalArgumentException} otherwise. | [
"Asserts",
"that",
"the",
"given",
"{"
]
| train | https://github.com/contentful/contentful-management.java/blob/ca310fb9ea9577fcff0ca57949ab7c2315fa2534/src/main/java/com/contentful/java/cma/AbsModule.java#L60-L65 |
apache/incubator-gobblin | gobblin-modules/gobblin-compliance/src/main/java/org/apache/gobblin/compliance/purger/HivePurgerQueryTemplate.java | HivePurgerQueryTemplate.getWhereClauseForPartition | public static String getWhereClauseForPartition(Map<String, String> spec, String prefix) {
"""
This method builds the where clause for the insertion query.
If prefix is a, then it builds a.datepartition='2016-01-01-00' AND a.size='12345' from [datepartition : '2016-01-01-00', size : '12345']
"""
StringBuilder sb = new StringBuilder();
for (Map.Entry<String, String> entry : spec.entrySet()) {
if (!sb.toString().isEmpty()) {
sb.append(" AND ");
}
sb.append(prefix + entry.getKey());
sb.append("=");
sb.append(PartitionUtils.getQuotedString(entry.getValue()));
}
return sb.toString();
} | java | public static String getWhereClauseForPartition(Map<String, String> spec, String prefix) {
StringBuilder sb = new StringBuilder();
for (Map.Entry<String, String> entry : spec.entrySet()) {
if (!sb.toString().isEmpty()) {
sb.append(" AND ");
}
sb.append(prefix + entry.getKey());
sb.append("=");
sb.append(PartitionUtils.getQuotedString(entry.getValue()));
}
return sb.toString();
} | [
"public",
"static",
"String",
"getWhereClauseForPartition",
"(",
"Map",
"<",
"String",
",",
"String",
">",
"spec",
",",
"String",
"prefix",
")",
"{",
"StringBuilder",
"sb",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"for",
"(",
"Map",
".",
"Entry",
"<",
"String",
",",
"String",
">",
"entry",
":",
"spec",
".",
"entrySet",
"(",
")",
")",
"{",
"if",
"(",
"!",
"sb",
".",
"toString",
"(",
")",
".",
"isEmpty",
"(",
")",
")",
"{",
"sb",
".",
"append",
"(",
"\" AND \"",
")",
";",
"}",
"sb",
".",
"append",
"(",
"prefix",
"+",
"entry",
".",
"getKey",
"(",
")",
")",
";",
"sb",
".",
"append",
"(",
"\"=\"",
")",
";",
"sb",
".",
"append",
"(",
"PartitionUtils",
".",
"getQuotedString",
"(",
"entry",
".",
"getValue",
"(",
")",
")",
")",
";",
"}",
"return",
"sb",
".",
"toString",
"(",
")",
";",
"}"
]
| This method builds the where clause for the insertion query.
If prefix is a, then it builds a.datepartition='2016-01-01-00' AND a.size='12345' from [datepartition : '2016-01-01-00', size : '12345'] | [
"This",
"method",
"builds",
"the",
"where",
"clause",
"for",
"the",
"insertion",
"query",
".",
"If",
"prefix",
"is",
"a",
"then",
"it",
"builds",
"a",
".",
"datepartition",
"=",
"2016",
"-",
"01",
"-",
"01",
"-",
"00",
"AND",
"a",
".",
"size",
"=",
"12345",
"from",
"[",
"datepartition",
":",
"2016",
"-",
"01",
"-",
"01",
"-",
"00",
"size",
":",
"12345",
"]"
]
| train | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-modules/gobblin-compliance/src/main/java/org/apache/gobblin/compliance/purger/HivePurgerQueryTemplate.java#L191-L202 |
samskivert/pythagoras | src/main/java/pythagoras/f/Matrix4.java | Matrix4.setToRotation | public Matrix4 setToRotation (float angle, float x, float y, float z) {
"""
Sets this to a rotation matrix. The formula comes from the OpenGL documentation for the
glRotatef function.
@return a reference to this matrix, for chaining.
"""
float c = FloatMath.cos(angle), s = FloatMath.sin(angle), omc = 1f - c;
float xs = x*s, ys = y*s, zs = z*s, xy = x*y, xz = x*z, yz = y*z;
return set(x*x*omc + c, xy*omc - zs, xz*omc + ys, 0f,
xy*omc + zs, y*y*omc + c, yz*omc - xs, 0f,
xz*omc - ys, yz*omc + xs, z*z*omc + c, 0f,
0f, 0f, 0f, 1f);
} | java | public Matrix4 setToRotation (float angle, float x, float y, float z) {
float c = FloatMath.cos(angle), s = FloatMath.sin(angle), omc = 1f - c;
float xs = x*s, ys = y*s, zs = z*s, xy = x*y, xz = x*z, yz = y*z;
return set(x*x*omc + c, xy*omc - zs, xz*omc + ys, 0f,
xy*omc + zs, y*y*omc + c, yz*omc - xs, 0f,
xz*omc - ys, yz*omc + xs, z*z*omc + c, 0f,
0f, 0f, 0f, 1f);
} | [
"public",
"Matrix4",
"setToRotation",
"(",
"float",
"angle",
",",
"float",
"x",
",",
"float",
"y",
",",
"float",
"z",
")",
"{",
"float",
"c",
"=",
"FloatMath",
".",
"cos",
"(",
"angle",
")",
",",
"s",
"=",
"FloatMath",
".",
"sin",
"(",
"angle",
")",
",",
"omc",
"=",
"1f",
"-",
"c",
";",
"float",
"xs",
"=",
"x",
"*",
"s",
",",
"ys",
"=",
"y",
"*",
"s",
",",
"zs",
"=",
"z",
"*",
"s",
",",
"xy",
"=",
"x",
"*",
"y",
",",
"xz",
"=",
"x",
"*",
"z",
",",
"yz",
"=",
"y",
"*",
"z",
";",
"return",
"set",
"(",
"x",
"*",
"x",
"*",
"omc",
"+",
"c",
",",
"xy",
"*",
"omc",
"-",
"zs",
",",
"xz",
"*",
"omc",
"+",
"ys",
",",
"0f",
",",
"xy",
"*",
"omc",
"+",
"zs",
",",
"y",
"*",
"y",
"*",
"omc",
"+",
"c",
",",
"yz",
"*",
"omc",
"-",
"xs",
",",
"0f",
",",
"xz",
"*",
"omc",
"-",
"ys",
",",
"yz",
"*",
"omc",
"+",
"xs",
",",
"z",
"*",
"z",
"*",
"omc",
"+",
"c",
",",
"0f",
",",
"0f",
",",
"0f",
",",
"0f",
",",
"1f",
")",
";",
"}"
]
| Sets this to a rotation matrix. The formula comes from the OpenGL documentation for the
glRotatef function.
@return a reference to this matrix, for chaining. | [
"Sets",
"this",
"to",
"a",
"rotation",
"matrix",
".",
"The",
"formula",
"comes",
"from",
"the",
"OpenGL",
"documentation",
"for",
"the",
"glRotatef",
"function",
"."
]
| train | https://github.com/samskivert/pythagoras/blob/b8fea743ee8a7d742ad9c06ee4f11f50571fbd32/src/main/java/pythagoras/f/Matrix4.java#L212-L219 |
graphql-java/graphql-java | src/main/java/graphql/schema/FieldCoordinates.java | FieldCoordinates.systemCoordinates | public static FieldCoordinates systemCoordinates(String fieldName) {
"""
The exception to the general rule is the system __xxxx Introspection fields which have no parent type and
are able to be specified on any type
@param fieldName the name of the system field which MUST start with __
@return the coordinates
"""
assertTrue(fieldName.startsWith("__"), "Only __ system fields can be addressed without a parent type");
assertValidName(fieldName);
return new FieldCoordinates(null, fieldName);
} | java | public static FieldCoordinates systemCoordinates(String fieldName) {
assertTrue(fieldName.startsWith("__"), "Only __ system fields can be addressed without a parent type");
assertValidName(fieldName);
return new FieldCoordinates(null, fieldName);
} | [
"public",
"static",
"FieldCoordinates",
"systemCoordinates",
"(",
"String",
"fieldName",
")",
"{",
"assertTrue",
"(",
"fieldName",
".",
"startsWith",
"(",
"\"__\"",
")",
",",
"\"Only __ system fields can be addressed without a parent type\"",
")",
";",
"assertValidName",
"(",
"fieldName",
")",
";",
"return",
"new",
"FieldCoordinates",
"(",
"null",
",",
"fieldName",
")",
";",
"}"
]
| The exception to the general rule is the system __xxxx Introspection fields which have no parent type and
are able to be specified on any type
@param fieldName the name of the system field which MUST start with __
@return the coordinates | [
"The",
"exception",
"to",
"the",
"general",
"rule",
"is",
"the",
"system",
"__xxxx",
"Introspection",
"fields",
"which",
"have",
"no",
"parent",
"type",
"and",
"are",
"able",
"to",
"be",
"specified",
"on",
"any",
"type"
]
| train | https://github.com/graphql-java/graphql-java/blob/9214b6044317849388bd88a14b54fc1c18c9f29f/src/main/java/graphql/schema/FieldCoordinates.java#L90-L94 |
needle4j/needle4j | src/main/java/org/needle4j/common/Preconditions.java | Preconditions.checkState | public static void checkState(final boolean condition, final String message, final Object... parameters) {
"""
Throws an {@link IllegalStateException} with formatted message if
condition is not met.
@param condition
a boolean condition that must be <code>true</code> to pass
@param message
text to use as exception message
@param parameters
optional parameters used in
{@link String#format(String, Object...)}
"""
if (!condition) {
throw new IllegalStateException(format(message, parameters));
}
} | java | public static void checkState(final boolean condition, final String message, final Object... parameters) {
if (!condition) {
throw new IllegalStateException(format(message, parameters));
}
} | [
"public",
"static",
"void",
"checkState",
"(",
"final",
"boolean",
"condition",
",",
"final",
"String",
"message",
",",
"final",
"Object",
"...",
"parameters",
")",
"{",
"if",
"(",
"!",
"condition",
")",
"{",
"throw",
"new",
"IllegalStateException",
"(",
"format",
"(",
"message",
",",
"parameters",
")",
")",
";",
"}",
"}"
]
| Throws an {@link IllegalStateException} with formatted message if
condition is not met.
@param condition
a boolean condition that must be <code>true</code> to pass
@param message
text to use as exception message
@param parameters
optional parameters used in
{@link String#format(String, Object...)} | [
"Throws",
"an",
"{",
"@link",
"IllegalStateException",
"}",
"with",
"formatted",
"message",
"if",
"condition",
"is",
"not",
"met",
"."
]
| train | https://github.com/needle4j/needle4j/blob/55fbcdeed72be5cf26e4404b0fe40282792b51f2/src/main/java/org/needle4j/common/Preconditions.java#L29-L33 |
apereo/cas | core/cas-server-core-services-api/src/main/java/org/apereo/cas/services/RegisteredServiceAccessStrategyUtils.java | RegisteredServiceAccessStrategyUtils.ensureServiceAccessIsAllowed | public static void ensureServiceAccessIsAllowed(final String service, final RegisteredService registeredService) {
"""
Ensure service access is allowed.
@param service the service
@param registeredService the registered service
"""
if (registeredService == null) {
val msg = String.format("Unauthorized Service Access. Service [%s] is not found in service registry.", service);
LOGGER.warn(msg);
throw new UnauthorizedServiceException(UnauthorizedServiceException.CODE_UNAUTHZ_SERVICE, msg);
}
if (!registeredService.getAccessStrategy().isServiceAccessAllowed()) {
val msg = String.format("Unauthorized Service Access. Service [%s] is not enabled in service registry.", service);
LOGGER.warn(msg);
throw new UnauthorizedServiceException(UnauthorizedServiceException.CODE_UNAUTHZ_SERVICE, msg);
}
if (!ensureServiceIsNotExpired(registeredService)) {
val msg = String.format("Expired Service Access. Service [%s] has been expired", service);
LOGGER.warn(msg);
throw new UnauthorizedServiceException(UnauthorizedServiceException.CODE_EXPIRED_SERVICE, msg);
}
} | java | public static void ensureServiceAccessIsAllowed(final String service, final RegisteredService registeredService) {
if (registeredService == null) {
val msg = String.format("Unauthorized Service Access. Service [%s] is not found in service registry.", service);
LOGGER.warn(msg);
throw new UnauthorizedServiceException(UnauthorizedServiceException.CODE_UNAUTHZ_SERVICE, msg);
}
if (!registeredService.getAccessStrategy().isServiceAccessAllowed()) {
val msg = String.format("Unauthorized Service Access. Service [%s] is not enabled in service registry.", service);
LOGGER.warn(msg);
throw new UnauthorizedServiceException(UnauthorizedServiceException.CODE_UNAUTHZ_SERVICE, msg);
}
if (!ensureServiceIsNotExpired(registeredService)) {
val msg = String.format("Expired Service Access. Service [%s] has been expired", service);
LOGGER.warn(msg);
throw new UnauthorizedServiceException(UnauthorizedServiceException.CODE_EXPIRED_SERVICE, msg);
}
} | [
"public",
"static",
"void",
"ensureServiceAccessIsAllowed",
"(",
"final",
"String",
"service",
",",
"final",
"RegisteredService",
"registeredService",
")",
"{",
"if",
"(",
"registeredService",
"==",
"null",
")",
"{",
"val",
"msg",
"=",
"String",
".",
"format",
"(",
"\"Unauthorized Service Access. Service [%s] is not found in service registry.\"",
",",
"service",
")",
";",
"LOGGER",
".",
"warn",
"(",
"msg",
")",
";",
"throw",
"new",
"UnauthorizedServiceException",
"(",
"UnauthorizedServiceException",
".",
"CODE_UNAUTHZ_SERVICE",
",",
"msg",
")",
";",
"}",
"if",
"(",
"!",
"registeredService",
".",
"getAccessStrategy",
"(",
")",
".",
"isServiceAccessAllowed",
"(",
")",
")",
"{",
"val",
"msg",
"=",
"String",
".",
"format",
"(",
"\"Unauthorized Service Access. Service [%s] is not enabled in service registry.\"",
",",
"service",
")",
";",
"LOGGER",
".",
"warn",
"(",
"msg",
")",
";",
"throw",
"new",
"UnauthorizedServiceException",
"(",
"UnauthorizedServiceException",
".",
"CODE_UNAUTHZ_SERVICE",
",",
"msg",
")",
";",
"}",
"if",
"(",
"!",
"ensureServiceIsNotExpired",
"(",
"registeredService",
")",
")",
"{",
"val",
"msg",
"=",
"String",
".",
"format",
"(",
"\"Expired Service Access. Service [%s] has been expired\"",
",",
"service",
")",
";",
"LOGGER",
".",
"warn",
"(",
"msg",
")",
";",
"throw",
"new",
"UnauthorizedServiceException",
"(",
"UnauthorizedServiceException",
".",
"CODE_EXPIRED_SERVICE",
",",
"msg",
")",
";",
"}",
"}"
]
| Ensure service access is allowed.
@param service the service
@param registeredService the registered service | [
"Ensure",
"service",
"access",
"is",
"allowed",
"."
]
| train | https://github.com/apereo/cas/blob/b4b306433a8782cef803a39bea5b1f96740e0e9b/core/cas-server-core-services-api/src/main/java/org/apereo/cas/services/RegisteredServiceAccessStrategyUtils.java#L50-L66 |
alkacon/opencms-core | src/org/opencms/module/CmsModule.java | CmsModule.adjustSiteRootIfNecessary | private static CmsObject adjustSiteRootIfNecessary(final CmsObject cms, final CmsModule module)
throws CmsException {
"""
Adjusts the site root and returns a cloned CmsObject, iff the module has set an import site that differs
from the site root of the CmsObject provided as argument. Otherwise returns the provided CmsObject unchanged.
@param cms The original CmsObject.
@param module The module where the import site is read from.
@return The original CmsObject, or, if necessary, a clone with adjusted site root
@throws CmsException see {@link OpenCms#initCmsObject(CmsObject)}
"""
CmsObject cmsClone;
if ((null == module.getSite()) || cms.getRequestContext().getSiteRoot().equals(module.getSite())) {
cmsClone = cms;
} else {
cmsClone = OpenCms.initCmsObject(cms);
cmsClone.getRequestContext().setSiteRoot(module.getSite());
}
return cmsClone;
} | java | private static CmsObject adjustSiteRootIfNecessary(final CmsObject cms, final CmsModule module)
throws CmsException {
CmsObject cmsClone;
if ((null == module.getSite()) || cms.getRequestContext().getSiteRoot().equals(module.getSite())) {
cmsClone = cms;
} else {
cmsClone = OpenCms.initCmsObject(cms);
cmsClone.getRequestContext().setSiteRoot(module.getSite());
}
return cmsClone;
} | [
"private",
"static",
"CmsObject",
"adjustSiteRootIfNecessary",
"(",
"final",
"CmsObject",
"cms",
",",
"final",
"CmsModule",
"module",
")",
"throws",
"CmsException",
"{",
"CmsObject",
"cmsClone",
";",
"if",
"(",
"(",
"null",
"==",
"module",
".",
"getSite",
"(",
")",
")",
"||",
"cms",
".",
"getRequestContext",
"(",
")",
".",
"getSiteRoot",
"(",
")",
".",
"equals",
"(",
"module",
".",
"getSite",
"(",
")",
")",
")",
"{",
"cmsClone",
"=",
"cms",
";",
"}",
"else",
"{",
"cmsClone",
"=",
"OpenCms",
".",
"initCmsObject",
"(",
"cms",
")",
";",
"cmsClone",
".",
"getRequestContext",
"(",
")",
".",
"setSiteRoot",
"(",
"module",
".",
"getSite",
"(",
")",
")",
";",
"}",
"return",
"cmsClone",
";",
"}"
]
| Adjusts the site root and returns a cloned CmsObject, iff the module has set an import site that differs
from the site root of the CmsObject provided as argument. Otherwise returns the provided CmsObject unchanged.
@param cms The original CmsObject.
@param module The module where the import site is read from.
@return The original CmsObject, or, if necessary, a clone with adjusted site root
@throws CmsException see {@link OpenCms#initCmsObject(CmsObject)} | [
"Adjusts",
"the",
"site",
"root",
"and",
"returns",
"a",
"cloned",
"CmsObject",
"iff",
"the",
"module",
"has",
"set",
"an",
"import",
"site",
"that",
"differs",
"from",
"the",
"site",
"root",
"of",
"the",
"CmsObject",
"provided",
"as",
"argument",
".",
"Otherwise",
"returns",
"the",
"provided",
"CmsObject",
"unchanged",
"."
]
| train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/module/CmsModule.java#L475-L487 |
apache/incubator-heron | heron/spi/src/java/org/apache/heron/spi/utils/NetworkUtils.java | NetworkUtils.establishSSHTunnelIfNeeded | private static Pair<InetSocketAddress, Process> establishSSHTunnelIfNeeded(
InetSocketAddress endpoint,
String tunnelHost,
TunnelType tunnelType,
Duration timeout,
int retryCount,
Duration retryInterval,
int verifyCount) {
"""
Tests if a network location is reachable. This is best effort and may give false
not reachable.
@param endpoint the endpoint to connect to
@param tunnelHost the host used to tunnel
@param tunnelType what type of tunnel should be established
@param timeout Open connection will wait for this timeout in ms.
@param retryCount In case of connection timeout try retryCount times.
@param retryInterval the interval in ms to retryCount
@param verifyCount In case of longer tunnel setup, try verify times to wait
@return a <new_reachable_endpoint, tunnelProcess> pair.
If the endpoint already reachable, then new_reachable_endpoint equals to original endpoint, and
tunnelProcess is null.
If no way to reach even through ssh tunneling,
then both new_reachable_endpoint and tunnelProcess are null.
"""
if (NetworkUtils.isLocationReachable(endpoint, timeout, retryCount, retryInterval)) {
// Already reachable, return original endpoint directly
return new Pair<InetSocketAddress, Process>(endpoint, null);
} else {
// Can not reach directly, trying to do ssh tunnel
int localFreePort = SysUtils.getFreePort();
InetSocketAddress newEndpoint = new InetSocketAddress(LOCAL_HOST, localFreePort);
LOG.log(Level.FINE, "Trying to opening up tunnel to {0} from {1}",
new Object[]{endpoint.toString(), newEndpoint.toString()});
// Set up the tunnel process
final Process tunnelProcess;
switch (tunnelType) {
case PORT_FORWARD:
tunnelProcess = ShellUtils.establishSSHTunnelProcess(
tunnelHost, localFreePort, endpoint.getHostString(), endpoint.getPort());
break;
case SOCKS_PROXY:
tunnelProcess = ShellUtils.establishSocksProxyProcess(tunnelHost, localFreePort);
break;
default:
throw new IllegalArgumentException("Unrecognized TunnelType passed: " + tunnelType);
}
// Tunnel can take time to setup.
// Verify whether the tunnel process is working fine.
if (tunnelProcess != null && tunnelProcess.isAlive() && NetworkUtils.isLocationReachable(
newEndpoint, timeout, verifyCount, retryInterval)) {
java.lang.Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
tunnelProcess.destroy();
}
});
// Can reach the destination via ssh tunnel
return new Pair<InetSocketAddress, Process>(newEndpoint, tunnelProcess);
}
LOG.log(Level.FINE, "Failed to opening up tunnel to {0} from {1}. Releasing process..",
new Object[]{endpoint, newEndpoint});
tunnelProcess.destroy();
}
// No way to reach the destination. Return null.
return new Pair<InetSocketAddress, Process>(null, null);
} | java | private static Pair<InetSocketAddress, Process> establishSSHTunnelIfNeeded(
InetSocketAddress endpoint,
String tunnelHost,
TunnelType tunnelType,
Duration timeout,
int retryCount,
Duration retryInterval,
int verifyCount) {
if (NetworkUtils.isLocationReachable(endpoint, timeout, retryCount, retryInterval)) {
// Already reachable, return original endpoint directly
return new Pair<InetSocketAddress, Process>(endpoint, null);
} else {
// Can not reach directly, trying to do ssh tunnel
int localFreePort = SysUtils.getFreePort();
InetSocketAddress newEndpoint = new InetSocketAddress(LOCAL_HOST, localFreePort);
LOG.log(Level.FINE, "Trying to opening up tunnel to {0} from {1}",
new Object[]{endpoint.toString(), newEndpoint.toString()});
// Set up the tunnel process
final Process tunnelProcess;
switch (tunnelType) {
case PORT_FORWARD:
tunnelProcess = ShellUtils.establishSSHTunnelProcess(
tunnelHost, localFreePort, endpoint.getHostString(), endpoint.getPort());
break;
case SOCKS_PROXY:
tunnelProcess = ShellUtils.establishSocksProxyProcess(tunnelHost, localFreePort);
break;
default:
throw new IllegalArgumentException("Unrecognized TunnelType passed: " + tunnelType);
}
// Tunnel can take time to setup.
// Verify whether the tunnel process is working fine.
if (tunnelProcess != null && tunnelProcess.isAlive() && NetworkUtils.isLocationReachable(
newEndpoint, timeout, verifyCount, retryInterval)) {
java.lang.Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
tunnelProcess.destroy();
}
});
// Can reach the destination via ssh tunnel
return new Pair<InetSocketAddress, Process>(newEndpoint, tunnelProcess);
}
LOG.log(Level.FINE, "Failed to opening up tunnel to {0} from {1}. Releasing process..",
new Object[]{endpoint, newEndpoint});
tunnelProcess.destroy();
}
// No way to reach the destination. Return null.
return new Pair<InetSocketAddress, Process>(null, null);
} | [
"private",
"static",
"Pair",
"<",
"InetSocketAddress",
",",
"Process",
">",
"establishSSHTunnelIfNeeded",
"(",
"InetSocketAddress",
"endpoint",
",",
"String",
"tunnelHost",
",",
"TunnelType",
"tunnelType",
",",
"Duration",
"timeout",
",",
"int",
"retryCount",
",",
"Duration",
"retryInterval",
",",
"int",
"verifyCount",
")",
"{",
"if",
"(",
"NetworkUtils",
".",
"isLocationReachable",
"(",
"endpoint",
",",
"timeout",
",",
"retryCount",
",",
"retryInterval",
")",
")",
"{",
"// Already reachable, return original endpoint directly",
"return",
"new",
"Pair",
"<",
"InetSocketAddress",
",",
"Process",
">",
"(",
"endpoint",
",",
"null",
")",
";",
"}",
"else",
"{",
"// Can not reach directly, trying to do ssh tunnel",
"int",
"localFreePort",
"=",
"SysUtils",
".",
"getFreePort",
"(",
")",
";",
"InetSocketAddress",
"newEndpoint",
"=",
"new",
"InetSocketAddress",
"(",
"LOCAL_HOST",
",",
"localFreePort",
")",
";",
"LOG",
".",
"log",
"(",
"Level",
".",
"FINE",
",",
"\"Trying to opening up tunnel to {0} from {1}\"",
",",
"new",
"Object",
"[",
"]",
"{",
"endpoint",
".",
"toString",
"(",
")",
",",
"newEndpoint",
".",
"toString",
"(",
")",
"}",
")",
";",
"// Set up the tunnel process",
"final",
"Process",
"tunnelProcess",
";",
"switch",
"(",
"tunnelType",
")",
"{",
"case",
"PORT_FORWARD",
":",
"tunnelProcess",
"=",
"ShellUtils",
".",
"establishSSHTunnelProcess",
"(",
"tunnelHost",
",",
"localFreePort",
",",
"endpoint",
".",
"getHostString",
"(",
")",
",",
"endpoint",
".",
"getPort",
"(",
")",
")",
";",
"break",
";",
"case",
"SOCKS_PROXY",
":",
"tunnelProcess",
"=",
"ShellUtils",
".",
"establishSocksProxyProcess",
"(",
"tunnelHost",
",",
"localFreePort",
")",
";",
"break",
";",
"default",
":",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Unrecognized TunnelType passed: \"",
"+",
"tunnelType",
")",
";",
"}",
"// Tunnel can take time to setup.",
"// Verify whether the tunnel process is working fine.",
"if",
"(",
"tunnelProcess",
"!=",
"null",
"&&",
"tunnelProcess",
".",
"isAlive",
"(",
")",
"&&",
"NetworkUtils",
".",
"isLocationReachable",
"(",
"newEndpoint",
",",
"timeout",
",",
"verifyCount",
",",
"retryInterval",
")",
")",
"{",
"java",
".",
"lang",
".",
"Runtime",
".",
"getRuntime",
"(",
")",
".",
"addShutdownHook",
"(",
"new",
"Thread",
"(",
")",
"{",
"@",
"Override",
"public",
"void",
"run",
"(",
")",
"{",
"tunnelProcess",
".",
"destroy",
"(",
")",
";",
"}",
"}",
")",
";",
"// Can reach the destination via ssh tunnel",
"return",
"new",
"Pair",
"<",
"InetSocketAddress",
",",
"Process",
">",
"(",
"newEndpoint",
",",
"tunnelProcess",
")",
";",
"}",
"LOG",
".",
"log",
"(",
"Level",
".",
"FINE",
",",
"\"Failed to opening up tunnel to {0} from {1}. Releasing process..\"",
",",
"new",
"Object",
"[",
"]",
"{",
"endpoint",
",",
"newEndpoint",
"}",
")",
";",
"tunnelProcess",
".",
"destroy",
"(",
")",
";",
"}",
"// No way to reach the destination. Return null.",
"return",
"new",
"Pair",
"<",
"InetSocketAddress",
",",
"Process",
">",
"(",
"null",
",",
"null",
")",
";",
"}"
]
| Tests if a network location is reachable. This is best effort and may give false
not reachable.
@param endpoint the endpoint to connect to
@param tunnelHost the host used to tunnel
@param tunnelType what type of tunnel should be established
@param timeout Open connection will wait for this timeout in ms.
@param retryCount In case of connection timeout try retryCount times.
@param retryInterval the interval in ms to retryCount
@param verifyCount In case of longer tunnel setup, try verify times to wait
@return a <new_reachable_endpoint, tunnelProcess> pair.
If the endpoint already reachable, then new_reachable_endpoint equals to original endpoint, and
tunnelProcess is null.
If no way to reach even through ssh tunneling,
then both new_reachable_endpoint and tunnelProcess are null. | [
"Tests",
"if",
"a",
"network",
"location",
"is",
"reachable",
".",
"This",
"is",
"best",
"effort",
"and",
"may",
"give",
"false",
"not",
"reachable",
"."
]
| train | https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/spi/src/java/org/apache/heron/spi/utils/NetworkUtils.java#L470-L526 |
zamrokk/fabric-sdk-java | src/main/java/org/hyperledger/fabric/sdk/MemberServicesImpl.java | MemberServicesImpl.processTCertBatch | private List<TCert> processTCertBatch(GetTCertBatchRequest req, TCertCreateSetResp resp)
throws NoSuchPaddingException, InvalidKeyException, NoSuchAlgorithmException,
IllegalBlockSizeException, BadPaddingException, InvalidAlgorithmParameterException, CryptoException, IOException {
"""
Process a batch of tcerts after having retrieved them from the TCA.
"""
String enrollKey = req.getEnrollment().getKey();
byte[] tCertOwnerKDFKey = resp.getCerts().getKey().toByteArray();
List<Ca.TCert> tCerts = resp.getCerts().getCertsList();
byte[] byte1 = new byte[]{1};
byte[] byte2 = new byte[]{2};
byte[] tCertOwnerEncryptKey = Arrays.copyOfRange(cryptoPrimitives.calculateMac(tCertOwnerKDFKey, byte1), 0, 32);
byte[] expansionKey = cryptoPrimitives.calculateMac(tCertOwnerKDFKey, byte2);
List<TCert> tCertBatch = new ArrayList<>(tCerts.size());
// Loop through certs and extract private keys
for (Ca.TCert tCert : tCerts) {
X509Certificate x509Certificate;
try {
CertificateFactory cf = CertificateFactory.getInstance("X.509");
x509Certificate = (X509Certificate)cf.generateCertificate(tCert.getCert().newInput());
} catch (Exception ex) {
logger.debug("Warning: problem parsing certificate bytes; retrying ... ", ex);
continue;
}
// extract the encrypted bytes from extension attribute
byte[] tCertIndexCT = fromDer(x509Certificate.getExtensionValue(TCERT_ENC_TCERT_INDEX));
byte[] tCertIndex = cryptoPrimitives.aesCBCPKCS7Decrypt(tCertOwnerEncryptKey, tCertIndexCT);
byte[] expansionValue = cryptoPrimitives.calculateMac(expansionKey, tCertIndex);
// compute the private key
BigInteger k = new BigInteger(1, expansionValue);
BigInteger n = ((ECPrivateKey)cryptoPrimitives.ecdsaKeyFromPrivate(Hex.decode(enrollKey)))
.getParameters().getN().subtract(BigInteger.ONE);
k = k.mod(n).add(BigInteger.ONE);
BigInteger D = ((ECPrivateKey) cryptoPrimitives.ecdsaKeyFromPrivate(Hex.decode(enrollKey))).getD().add(k);
D = D.mod(((ECPrivateKey)cryptoPrimitives.ecdsaKeyFromPrivate(Hex.decode(enrollKey))).getParameters().getN());
// Put private and public key in returned tcert
TCert tcert = new TCert(tCert.getCert().toByteArray(), cryptoPrimitives.ecdsaKeyFromBigInt(D));
tCertBatch.add(tcert);
}
if (tCertBatch.size() == 0) {
throw new RuntimeException("Failed fetching TCertBatch. No valid TCert received.");
}
return tCertBatch;
} | java | private List<TCert> processTCertBatch(GetTCertBatchRequest req, TCertCreateSetResp resp)
throws NoSuchPaddingException, InvalidKeyException, NoSuchAlgorithmException,
IllegalBlockSizeException, BadPaddingException, InvalidAlgorithmParameterException, CryptoException, IOException {
String enrollKey = req.getEnrollment().getKey();
byte[] tCertOwnerKDFKey = resp.getCerts().getKey().toByteArray();
List<Ca.TCert> tCerts = resp.getCerts().getCertsList();
byte[] byte1 = new byte[]{1};
byte[] byte2 = new byte[]{2};
byte[] tCertOwnerEncryptKey = Arrays.copyOfRange(cryptoPrimitives.calculateMac(tCertOwnerKDFKey, byte1), 0, 32);
byte[] expansionKey = cryptoPrimitives.calculateMac(tCertOwnerKDFKey, byte2);
List<TCert> tCertBatch = new ArrayList<>(tCerts.size());
// Loop through certs and extract private keys
for (Ca.TCert tCert : tCerts) {
X509Certificate x509Certificate;
try {
CertificateFactory cf = CertificateFactory.getInstance("X.509");
x509Certificate = (X509Certificate)cf.generateCertificate(tCert.getCert().newInput());
} catch (Exception ex) {
logger.debug("Warning: problem parsing certificate bytes; retrying ... ", ex);
continue;
}
// extract the encrypted bytes from extension attribute
byte[] tCertIndexCT = fromDer(x509Certificate.getExtensionValue(TCERT_ENC_TCERT_INDEX));
byte[] tCertIndex = cryptoPrimitives.aesCBCPKCS7Decrypt(tCertOwnerEncryptKey, tCertIndexCT);
byte[] expansionValue = cryptoPrimitives.calculateMac(expansionKey, tCertIndex);
// compute the private key
BigInteger k = new BigInteger(1, expansionValue);
BigInteger n = ((ECPrivateKey)cryptoPrimitives.ecdsaKeyFromPrivate(Hex.decode(enrollKey)))
.getParameters().getN().subtract(BigInteger.ONE);
k = k.mod(n).add(BigInteger.ONE);
BigInteger D = ((ECPrivateKey) cryptoPrimitives.ecdsaKeyFromPrivate(Hex.decode(enrollKey))).getD().add(k);
D = D.mod(((ECPrivateKey)cryptoPrimitives.ecdsaKeyFromPrivate(Hex.decode(enrollKey))).getParameters().getN());
// Put private and public key in returned tcert
TCert tcert = new TCert(tCert.getCert().toByteArray(), cryptoPrimitives.ecdsaKeyFromBigInt(D));
tCertBatch.add(tcert);
}
if (tCertBatch.size() == 0) {
throw new RuntimeException("Failed fetching TCertBatch. No valid TCert received.");
}
return tCertBatch;
} | [
"private",
"List",
"<",
"TCert",
">",
"processTCertBatch",
"(",
"GetTCertBatchRequest",
"req",
",",
"TCertCreateSetResp",
"resp",
")",
"throws",
"NoSuchPaddingException",
",",
"InvalidKeyException",
",",
"NoSuchAlgorithmException",
",",
"IllegalBlockSizeException",
",",
"BadPaddingException",
",",
"InvalidAlgorithmParameterException",
",",
"CryptoException",
",",
"IOException",
"{",
"String",
"enrollKey",
"=",
"req",
".",
"getEnrollment",
"(",
")",
".",
"getKey",
"(",
")",
";",
"byte",
"[",
"]",
"tCertOwnerKDFKey",
"=",
"resp",
".",
"getCerts",
"(",
")",
".",
"getKey",
"(",
")",
".",
"toByteArray",
"(",
")",
";",
"List",
"<",
"Ca",
".",
"TCert",
">",
"tCerts",
"=",
"resp",
".",
"getCerts",
"(",
")",
".",
"getCertsList",
"(",
")",
";",
"byte",
"[",
"]",
"byte1",
"=",
"new",
"byte",
"[",
"]",
"{",
"1",
"}",
";",
"byte",
"[",
"]",
"byte2",
"=",
"new",
"byte",
"[",
"]",
"{",
"2",
"}",
";",
"byte",
"[",
"]",
"tCertOwnerEncryptKey",
"=",
"Arrays",
".",
"copyOfRange",
"(",
"cryptoPrimitives",
".",
"calculateMac",
"(",
"tCertOwnerKDFKey",
",",
"byte1",
")",
",",
"0",
",",
"32",
")",
";",
"byte",
"[",
"]",
"expansionKey",
"=",
"cryptoPrimitives",
".",
"calculateMac",
"(",
"tCertOwnerKDFKey",
",",
"byte2",
")",
";",
"List",
"<",
"TCert",
">",
"tCertBatch",
"=",
"new",
"ArrayList",
"<>",
"(",
"tCerts",
".",
"size",
"(",
")",
")",
";",
"// Loop through certs and extract private keys",
"for",
"(",
"Ca",
".",
"TCert",
"tCert",
":",
"tCerts",
")",
"{",
"X509Certificate",
"x509Certificate",
";",
"try",
"{",
"CertificateFactory",
"cf",
"=",
"CertificateFactory",
".",
"getInstance",
"(",
"\"X.509\"",
")",
";",
"x509Certificate",
"=",
"(",
"X509Certificate",
")",
"cf",
".",
"generateCertificate",
"(",
"tCert",
".",
"getCert",
"(",
")",
".",
"newInput",
"(",
")",
")",
";",
"}",
"catch",
"(",
"Exception",
"ex",
")",
"{",
"logger",
".",
"debug",
"(",
"\"Warning: problem parsing certificate bytes; retrying ... \"",
",",
"ex",
")",
";",
"continue",
";",
"}",
"// extract the encrypted bytes from extension attribute",
"byte",
"[",
"]",
"tCertIndexCT",
"=",
"fromDer",
"(",
"x509Certificate",
".",
"getExtensionValue",
"(",
"TCERT_ENC_TCERT_INDEX",
")",
")",
";",
"byte",
"[",
"]",
"tCertIndex",
"=",
"cryptoPrimitives",
".",
"aesCBCPKCS7Decrypt",
"(",
"tCertOwnerEncryptKey",
",",
"tCertIndexCT",
")",
";",
"byte",
"[",
"]",
"expansionValue",
"=",
"cryptoPrimitives",
".",
"calculateMac",
"(",
"expansionKey",
",",
"tCertIndex",
")",
";",
"// compute the private key",
"BigInteger",
"k",
"=",
"new",
"BigInteger",
"(",
"1",
",",
"expansionValue",
")",
";",
"BigInteger",
"n",
"=",
"(",
"(",
"ECPrivateKey",
")",
"cryptoPrimitives",
".",
"ecdsaKeyFromPrivate",
"(",
"Hex",
".",
"decode",
"(",
"enrollKey",
")",
")",
")",
".",
"getParameters",
"(",
")",
".",
"getN",
"(",
")",
".",
"subtract",
"(",
"BigInteger",
".",
"ONE",
")",
";",
"k",
"=",
"k",
".",
"mod",
"(",
"n",
")",
".",
"add",
"(",
"BigInteger",
".",
"ONE",
")",
";",
"BigInteger",
"D",
"=",
"(",
"(",
"ECPrivateKey",
")",
"cryptoPrimitives",
".",
"ecdsaKeyFromPrivate",
"(",
"Hex",
".",
"decode",
"(",
"enrollKey",
")",
")",
")",
".",
"getD",
"(",
")",
".",
"add",
"(",
"k",
")",
";",
"D",
"=",
"D",
".",
"mod",
"(",
"(",
"(",
"ECPrivateKey",
")",
"cryptoPrimitives",
".",
"ecdsaKeyFromPrivate",
"(",
"Hex",
".",
"decode",
"(",
"enrollKey",
")",
")",
")",
".",
"getParameters",
"(",
")",
".",
"getN",
"(",
")",
")",
";",
"// Put private and public key in returned tcert",
"TCert",
"tcert",
"=",
"new",
"TCert",
"(",
"tCert",
".",
"getCert",
"(",
")",
".",
"toByteArray",
"(",
")",
",",
"cryptoPrimitives",
".",
"ecdsaKeyFromBigInt",
"(",
"D",
")",
")",
";",
"tCertBatch",
".",
"add",
"(",
"tcert",
")",
";",
"}",
"if",
"(",
"tCertBatch",
".",
"size",
"(",
")",
"==",
"0",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"\"Failed fetching TCertBatch. No valid TCert received.\"",
")",
";",
"}",
"return",
"tCertBatch",
";",
"}"
]
| Process a batch of tcerts after having retrieved them from the TCA. | [
"Process",
"a",
"batch",
"of",
"tcerts",
"after",
"having",
"retrieved",
"them",
"from",
"the",
"TCA",
"."
]
| train | https://github.com/zamrokk/fabric-sdk-java/blob/d4993ca602f72d412cd682e1b92e805e48b27afa/src/main/java/org/hyperledger/fabric/sdk/MemberServicesImpl.java#L281-L333 |
gmessner/gitlab4j-api | src/main/java/org/gitlab4j/api/ProjectApi.java | ProjectApi.updatePushRules | public PushRules updatePushRules(Object projectIdOrPath, PushRules pushRule) throws GitLabApiException {
"""
Updates a push rule for the specified project.
<pre><code>PUT /projects/:id/push_rule/:push_rule_id</code></pre>
The following properties on the PushRules instance are utilized when updating the push rule:
<code>
denyDeleteTag (optional) - Deny deleting a tag
memberCheck (optional) - Restrict commits by author (email) to existing GitLab users
preventSecrets (optional) - GitLab will reject any files that are likely to contain secrets
commitMessageRegex (optional) - All commit messages must match this, e.g. Fixed \d+\..*
branchNameRegex (optional) - All branch names must match this, e.g. `(feature
authorEmailRegex (optional) - All commit author emails must match this, e.g. @my-company.com$
fileNameRegex (optional) - All committed filenames must not match this, e.g. `(jar
maxFileSize (optional) - Maximum file size (MB
</code>
@param projectIdOrPath projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance, required
@param pushRule the PushRules instance containing the push rule configuration to update
@return a PushRules instance with the newly created push rule info
@throws GitLabApiException if any exception occurs
"""
GitLabApiForm formData = new GitLabApiForm()
.withParam("deny_delete_tag", pushRule.getDenyDeleteTag())
.withParam("member_check", pushRule.getMemberCheck())
.withParam("prevent_secrets", pushRule.getPreventSecrets())
.withParam("commit_message_regex", pushRule.getCommitMessageRegex())
.withParam("branch_name_regex", pushRule.getBranchNameRegex())
.withParam("author_email_regex", pushRule.getAuthorEmailRegex())
.withParam("file_name_regex", pushRule.getFileNameRegex())
.withParam("max_file_size", pushRule.getMaxFileSize());
final Response response = putWithFormData(Response.Status.OK, formData, "projects", getProjectIdOrPath(projectIdOrPath), "push_rule");
return (response.readEntity(PushRules.class));
} | java | public PushRules updatePushRules(Object projectIdOrPath, PushRules pushRule) throws GitLabApiException {
GitLabApiForm formData = new GitLabApiForm()
.withParam("deny_delete_tag", pushRule.getDenyDeleteTag())
.withParam("member_check", pushRule.getMemberCheck())
.withParam("prevent_secrets", pushRule.getPreventSecrets())
.withParam("commit_message_regex", pushRule.getCommitMessageRegex())
.withParam("branch_name_regex", pushRule.getBranchNameRegex())
.withParam("author_email_regex", pushRule.getAuthorEmailRegex())
.withParam("file_name_regex", pushRule.getFileNameRegex())
.withParam("max_file_size", pushRule.getMaxFileSize());
final Response response = putWithFormData(Response.Status.OK, formData, "projects", getProjectIdOrPath(projectIdOrPath), "push_rule");
return (response.readEntity(PushRules.class));
} | [
"public",
"PushRules",
"updatePushRules",
"(",
"Object",
"projectIdOrPath",
",",
"PushRules",
"pushRule",
")",
"throws",
"GitLabApiException",
"{",
"GitLabApiForm",
"formData",
"=",
"new",
"GitLabApiForm",
"(",
")",
".",
"withParam",
"(",
"\"deny_delete_tag\"",
",",
"pushRule",
".",
"getDenyDeleteTag",
"(",
")",
")",
".",
"withParam",
"(",
"\"member_check\"",
",",
"pushRule",
".",
"getMemberCheck",
"(",
")",
")",
".",
"withParam",
"(",
"\"prevent_secrets\"",
",",
"pushRule",
".",
"getPreventSecrets",
"(",
")",
")",
".",
"withParam",
"(",
"\"commit_message_regex\"",
",",
"pushRule",
".",
"getCommitMessageRegex",
"(",
")",
")",
".",
"withParam",
"(",
"\"branch_name_regex\"",
",",
"pushRule",
".",
"getBranchNameRegex",
"(",
")",
")",
".",
"withParam",
"(",
"\"author_email_regex\"",
",",
"pushRule",
".",
"getAuthorEmailRegex",
"(",
")",
")",
".",
"withParam",
"(",
"\"file_name_regex\"",
",",
"pushRule",
".",
"getFileNameRegex",
"(",
")",
")",
".",
"withParam",
"(",
"\"max_file_size\"",
",",
"pushRule",
".",
"getMaxFileSize",
"(",
")",
")",
";",
"final",
"Response",
"response",
"=",
"putWithFormData",
"(",
"Response",
".",
"Status",
".",
"OK",
",",
"formData",
",",
"\"projects\"",
",",
"getProjectIdOrPath",
"(",
"projectIdOrPath",
")",
",",
"\"push_rule\"",
")",
";",
"return",
"(",
"response",
".",
"readEntity",
"(",
"PushRules",
".",
"class",
")",
")",
";",
"}"
]
| Updates a push rule for the specified project.
<pre><code>PUT /projects/:id/push_rule/:push_rule_id</code></pre>
The following properties on the PushRules instance are utilized when updating the push rule:
<code>
denyDeleteTag (optional) - Deny deleting a tag
memberCheck (optional) - Restrict commits by author (email) to existing GitLab users
preventSecrets (optional) - GitLab will reject any files that are likely to contain secrets
commitMessageRegex (optional) - All commit messages must match this, e.g. Fixed \d+\..*
branchNameRegex (optional) - All branch names must match this, e.g. `(feature
authorEmailRegex (optional) - All commit author emails must match this, e.g. @my-company.com$
fileNameRegex (optional) - All committed filenames must not match this, e.g. `(jar
maxFileSize (optional) - Maximum file size (MB
</code>
@param projectIdOrPath projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance, required
@param pushRule the PushRules instance containing the push rule configuration to update
@return a PushRules instance with the newly created push rule info
@throws GitLabApiException if any exception occurs | [
"Updates",
"a",
"push",
"rule",
"for",
"the",
"specified",
"project",
"."
]
| train | https://github.com/gmessner/gitlab4j-api/blob/ab045070abac0a8f4ccbf17b5ed9bfdef5723eed/src/main/java/org/gitlab4j/api/ProjectApi.java#L2240-L2253 |
lessthanoptimal/ejml | main/ejml-ddense/src/org/ejml/dense/row/NormOps_DDRM.java | NormOps_DDRM.conditionP | public static double conditionP(DMatrixRMaj A , double p ) {
"""
<p>
The condition number of a matrix is used to measure the sensitivity of the linear
system <b>Ax=b</b>. A value near one indicates that it is a well conditioned matrix.<br>
<br>
κ<sub>p</sub> = ||A||<sub>p</sub>||A<sup>-1</sup>||<sub>p</sub>
</p>
<p>
If the matrix is not square then the condition of either A<sup>T</sup>A or AA<sup>T</sup> is computed.
<p>
@param A The matrix.
@param p p-norm
@return The condition number.
"""
if( p == 2 ) {
return conditionP2(A);
} else if( A.numRows == A.numCols ){
// square matrices are the typical case
DMatrixRMaj A_inv = new DMatrixRMaj(A.numRows,A.numCols);
if( !CommonOps_DDRM.invert(A,A_inv) )
throw new IllegalArgumentException("A can't be inverted.");
return normP(A,p) * normP(A_inv,p);
} else {
DMatrixRMaj pinv = new DMatrixRMaj(A.numCols,A.numRows);
CommonOps_DDRM.pinv(A,pinv);
return normP(A,p) * normP(pinv,p);
}
} | java | public static double conditionP(DMatrixRMaj A , double p )
{
if( p == 2 ) {
return conditionP2(A);
} else if( A.numRows == A.numCols ){
// square matrices are the typical case
DMatrixRMaj A_inv = new DMatrixRMaj(A.numRows,A.numCols);
if( !CommonOps_DDRM.invert(A,A_inv) )
throw new IllegalArgumentException("A can't be inverted.");
return normP(A,p) * normP(A_inv,p);
} else {
DMatrixRMaj pinv = new DMatrixRMaj(A.numCols,A.numRows);
CommonOps_DDRM.pinv(A,pinv);
return normP(A,p) * normP(pinv,p);
}
} | [
"public",
"static",
"double",
"conditionP",
"(",
"DMatrixRMaj",
"A",
",",
"double",
"p",
")",
"{",
"if",
"(",
"p",
"==",
"2",
")",
"{",
"return",
"conditionP2",
"(",
"A",
")",
";",
"}",
"else",
"if",
"(",
"A",
".",
"numRows",
"==",
"A",
".",
"numCols",
")",
"{",
"// square matrices are the typical case",
"DMatrixRMaj",
"A_inv",
"=",
"new",
"DMatrixRMaj",
"(",
"A",
".",
"numRows",
",",
"A",
".",
"numCols",
")",
";",
"if",
"(",
"!",
"CommonOps_DDRM",
".",
"invert",
"(",
"A",
",",
"A_inv",
")",
")",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"A can't be inverted.\"",
")",
";",
"return",
"normP",
"(",
"A",
",",
"p",
")",
"*",
"normP",
"(",
"A_inv",
",",
"p",
")",
";",
"}",
"else",
"{",
"DMatrixRMaj",
"pinv",
"=",
"new",
"DMatrixRMaj",
"(",
"A",
".",
"numCols",
",",
"A",
".",
"numRows",
")",
";",
"CommonOps_DDRM",
".",
"pinv",
"(",
"A",
",",
"pinv",
")",
";",
"return",
"normP",
"(",
"A",
",",
"p",
")",
"*",
"normP",
"(",
"pinv",
",",
"p",
")",
";",
"}",
"}"
]
| <p>
The condition number of a matrix is used to measure the sensitivity of the linear
system <b>Ax=b</b>. A value near one indicates that it is a well conditioned matrix.<br>
<br>
κ<sub>p</sub> = ||A||<sub>p</sub>||A<sup>-1</sup>||<sub>p</sub>
</p>
<p>
If the matrix is not square then the condition of either A<sup>T</sup>A or AA<sup>T</sup> is computed.
<p>
@param A The matrix.
@param p p-norm
@return The condition number. | [
"<p",
">",
"The",
"condition",
"number",
"of",
"a",
"matrix",
"is",
"used",
"to",
"measure",
"the",
"sensitivity",
"of",
"the",
"linear",
"system",
"<b",
">",
"Ax",
"=",
"b<",
"/",
"b",
">",
".",
"A",
"value",
"near",
"one",
"indicates",
"that",
"it",
"is",
"a",
"well",
"conditioned",
"matrix",
".",
"<br",
">",
"<br",
">",
"&kappa",
";",
"<sub",
">",
"p<",
"/",
"sub",
">",
"=",
"||A||<sub",
">",
"p<",
"/",
"sub",
">",
"||A<sup",
">",
"-",
"1<",
"/",
"sup",
">",
"||<sub",
">",
"p<",
"/",
"sub",
">",
"<",
"/",
"p",
">",
"<p",
">",
"If",
"the",
"matrix",
"is",
"not",
"square",
"then",
"the",
"condition",
"of",
"either",
"A<sup",
">",
"T<",
"/",
"sup",
">",
"A",
"or",
"AA<sup",
">",
"T<",
"/",
"sup",
">",
"is",
"computed",
".",
"<p",
">"
]
| train | https://github.com/lessthanoptimal/ejml/blob/1444680cc487af5e866730e62f48f5f9636850d9/main/ejml-ddense/src/org/ejml/dense/row/NormOps_DDRM.java#L98-L117 |
wso2/transport-http | components/org.wso2.transport.http.netty/src/main/java/org/wso2/transport/http/netty/contractimpl/common/Util.java | Util.createInboundRespCarbonMsg | public static HttpCarbonMessage createInboundRespCarbonMsg(ChannelHandlerContext ctx,
HttpResponse httpResponseHeaders,
HttpCarbonMessage outboundRequestMsg) {
"""
Create a HttpCarbonMessage using the netty inbound response message.
@param ctx of the inbound response message
@param httpResponseHeaders of the inbound response message
@param outboundRequestMsg is the correlated outbound request message
@return HttpCarbon message
"""
HttpCarbonMessage inboundResponseMsg = new HttpCarbonResponse(httpResponseHeaders, new DefaultListener(ctx));
inboundResponseMsg.setProperty(Constants.POOLED_BYTE_BUFFER_FACTORY,
new PooledDataStreamerFactory(ctx.alloc()));
inboundResponseMsg.setProperty(Constants.DIRECTION, Constants.DIRECTION_RESPONSE);
inboundResponseMsg.setProperty(Constants.HTTP_STATUS_CODE, httpResponseHeaders.status().code());
//copy required properties for service chaining from incoming carbon message to the response carbon message
//copy shared worker pool
inboundResponseMsg.setProperty(Constants.EXECUTOR_WORKER_POOL, outboundRequestMsg
.getProperty(Constants.EXECUTOR_WORKER_POOL));
return inboundResponseMsg;
} | java | public static HttpCarbonMessage createInboundRespCarbonMsg(ChannelHandlerContext ctx,
HttpResponse httpResponseHeaders,
HttpCarbonMessage outboundRequestMsg) {
HttpCarbonMessage inboundResponseMsg = new HttpCarbonResponse(httpResponseHeaders, new DefaultListener(ctx));
inboundResponseMsg.setProperty(Constants.POOLED_BYTE_BUFFER_FACTORY,
new PooledDataStreamerFactory(ctx.alloc()));
inboundResponseMsg.setProperty(Constants.DIRECTION, Constants.DIRECTION_RESPONSE);
inboundResponseMsg.setProperty(Constants.HTTP_STATUS_CODE, httpResponseHeaders.status().code());
//copy required properties for service chaining from incoming carbon message to the response carbon message
//copy shared worker pool
inboundResponseMsg.setProperty(Constants.EXECUTOR_WORKER_POOL, outboundRequestMsg
.getProperty(Constants.EXECUTOR_WORKER_POOL));
return inboundResponseMsg;
} | [
"public",
"static",
"HttpCarbonMessage",
"createInboundRespCarbonMsg",
"(",
"ChannelHandlerContext",
"ctx",
",",
"HttpResponse",
"httpResponseHeaders",
",",
"HttpCarbonMessage",
"outboundRequestMsg",
")",
"{",
"HttpCarbonMessage",
"inboundResponseMsg",
"=",
"new",
"HttpCarbonResponse",
"(",
"httpResponseHeaders",
",",
"new",
"DefaultListener",
"(",
"ctx",
")",
")",
";",
"inboundResponseMsg",
".",
"setProperty",
"(",
"Constants",
".",
"POOLED_BYTE_BUFFER_FACTORY",
",",
"new",
"PooledDataStreamerFactory",
"(",
"ctx",
".",
"alloc",
"(",
")",
")",
")",
";",
"inboundResponseMsg",
".",
"setProperty",
"(",
"Constants",
".",
"DIRECTION",
",",
"Constants",
".",
"DIRECTION_RESPONSE",
")",
";",
"inboundResponseMsg",
".",
"setProperty",
"(",
"Constants",
".",
"HTTP_STATUS_CODE",
",",
"httpResponseHeaders",
".",
"status",
"(",
")",
".",
"code",
"(",
")",
")",
";",
"//copy required properties for service chaining from incoming carbon message to the response carbon message",
"//copy shared worker pool",
"inboundResponseMsg",
".",
"setProperty",
"(",
"Constants",
".",
"EXECUTOR_WORKER_POOL",
",",
"outboundRequestMsg",
".",
"getProperty",
"(",
"Constants",
".",
"EXECUTOR_WORKER_POOL",
")",
")",
";",
"return",
"inboundResponseMsg",
";",
"}"
]
| Create a HttpCarbonMessage using the netty inbound response message.
@param ctx of the inbound response message
@param httpResponseHeaders of the inbound response message
@param outboundRequestMsg is the correlated outbound request message
@return HttpCarbon message | [
"Create",
"a",
"HttpCarbonMessage",
"using",
"the",
"netty",
"inbound",
"response",
"message",
"."
]
| train | https://github.com/wso2/transport-http/blob/c51aa715b473db6c1b82a7d7b22f6e65f74df4c9/components/org.wso2.transport.http.netty/src/main/java/org/wso2/transport/http/netty/contractimpl/common/Util.java#L746-L762 |
gmessner/gitlab4j-api | src/main/java/org/gitlab4j/api/RepositoryApi.java | RepositoryApi.protectBranch | public Branch protectBranch(Object projectIdOrPath, String branchName) throws GitLabApiException {
"""
Protects a single project repository branch. This is an idempotent function,
protecting an already protected repository branch will not produce an error.
<pre><code>GitLab Endpoint: PUT /projects/:id/repository/branches/:branch/protect</code></pre>
@param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance
@param branchName the name of the branch to protect
@return the branch info for the protected branch
@throws GitLabApiException if any exception occurs
"""
Response response = put(Response.Status.OK, null, "projects",
getProjectIdOrPath(projectIdOrPath), "repository", "branches", urlEncode(branchName), "protect");
return (response.readEntity(Branch.class));
} | java | public Branch protectBranch(Object projectIdOrPath, String branchName) throws GitLabApiException {
Response response = put(Response.Status.OK, null, "projects",
getProjectIdOrPath(projectIdOrPath), "repository", "branches", urlEncode(branchName), "protect");
return (response.readEntity(Branch.class));
} | [
"public",
"Branch",
"protectBranch",
"(",
"Object",
"projectIdOrPath",
",",
"String",
"branchName",
")",
"throws",
"GitLabApiException",
"{",
"Response",
"response",
"=",
"put",
"(",
"Response",
".",
"Status",
".",
"OK",
",",
"null",
",",
"\"projects\"",
",",
"getProjectIdOrPath",
"(",
"projectIdOrPath",
")",
",",
"\"repository\"",
",",
"\"branches\"",
",",
"urlEncode",
"(",
"branchName",
")",
",",
"\"protect\"",
")",
";",
"return",
"(",
"response",
".",
"readEntity",
"(",
"Branch",
".",
"class",
")",
")",
";",
"}"
]
| Protects a single project repository branch. This is an idempotent function,
protecting an already protected repository branch will not produce an error.
<pre><code>GitLab Endpoint: PUT /projects/:id/repository/branches/:branch/protect</code></pre>
@param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance
@param branchName the name of the branch to protect
@return the branch info for the protected branch
@throws GitLabApiException if any exception occurs | [
"Protects",
"a",
"single",
"project",
"repository",
"branch",
".",
"This",
"is",
"an",
"idempotent",
"function",
"protecting",
"an",
"already",
"protected",
"repository",
"branch",
"will",
"not",
"produce",
"an",
"error",
"."
]
| train | https://github.com/gmessner/gitlab4j-api/blob/ab045070abac0a8f4ccbf17b5ed9bfdef5723eed/src/main/java/org/gitlab4j/api/RepositoryApi.java#L175-L179 |
Azure/azure-sdk-for-java | cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/PatternsImpl.java | PatternsImpl.getPatternsWithServiceResponseAsync | public Observable<ServiceResponse<List<PatternRuleInfo>>> getPatternsWithServiceResponseAsync(UUID appId, String versionId, GetPatternsOptionalParameter getPatternsOptionalParameter) {
"""
Returns an application version's patterns.
@param appId The application ID.
@param versionId The version ID.
@param getPatternsOptionalParameter 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<PatternRuleInfo> object
"""
if (this.client.endpoint() == null) {
throw new IllegalArgumentException("Parameter this.client.endpoint() is required and cannot be null.");
}
if (appId == null) {
throw new IllegalArgumentException("Parameter appId is required and cannot be null.");
}
if (versionId == null) {
throw new IllegalArgumentException("Parameter versionId is required and cannot be null.");
}
final Integer skip = getPatternsOptionalParameter != null ? getPatternsOptionalParameter.skip() : null;
final Integer take = getPatternsOptionalParameter != null ? getPatternsOptionalParameter.take() : null;
return getPatternsWithServiceResponseAsync(appId, versionId, skip, take);
} | java | public Observable<ServiceResponse<List<PatternRuleInfo>>> getPatternsWithServiceResponseAsync(UUID appId, String versionId, GetPatternsOptionalParameter getPatternsOptionalParameter) {
if (this.client.endpoint() == null) {
throw new IllegalArgumentException("Parameter this.client.endpoint() is required and cannot be null.");
}
if (appId == null) {
throw new IllegalArgumentException("Parameter appId is required and cannot be null.");
}
if (versionId == null) {
throw new IllegalArgumentException("Parameter versionId is required and cannot be null.");
}
final Integer skip = getPatternsOptionalParameter != null ? getPatternsOptionalParameter.skip() : null;
final Integer take = getPatternsOptionalParameter != null ? getPatternsOptionalParameter.take() : null;
return getPatternsWithServiceResponseAsync(appId, versionId, skip, take);
} | [
"public",
"Observable",
"<",
"ServiceResponse",
"<",
"List",
"<",
"PatternRuleInfo",
">",
">",
">",
"getPatternsWithServiceResponseAsync",
"(",
"UUID",
"appId",
",",
"String",
"versionId",
",",
"GetPatternsOptionalParameter",
"getPatternsOptionalParameter",
")",
"{",
"if",
"(",
"this",
".",
"client",
".",
"endpoint",
"(",
")",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Parameter this.client.endpoint() is required and cannot be null.\"",
")",
";",
"}",
"if",
"(",
"appId",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Parameter appId is required and cannot be null.\"",
")",
";",
"}",
"if",
"(",
"versionId",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Parameter versionId is required and cannot be null.\"",
")",
";",
"}",
"final",
"Integer",
"skip",
"=",
"getPatternsOptionalParameter",
"!=",
"null",
"?",
"getPatternsOptionalParameter",
".",
"skip",
"(",
")",
":",
"null",
";",
"final",
"Integer",
"take",
"=",
"getPatternsOptionalParameter",
"!=",
"null",
"?",
"getPatternsOptionalParameter",
".",
"take",
"(",
")",
":",
"null",
";",
"return",
"getPatternsWithServiceResponseAsync",
"(",
"appId",
",",
"versionId",
",",
"skip",
",",
"take",
")",
";",
"}"
]
| Returns an application version's patterns.
@param appId The application ID.
@param versionId The version ID.
@param getPatternsOptionalParameter 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<PatternRuleInfo> object | [
"Returns",
"an",
"application",
"version",
"s",
"patterns",
"."
]
| 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/PatternsImpl.java#L252-L266 |
tvbarthel/Cheerleader | library/src/main/java/fr/tvbarthel/cheerleader/library/offline/OfflinerQueryHandler.java | OfflinerQueryHandler.get | public String get(Context context, String url) {
"""
Retrieve a value saved for offline access.
@param context context used to retrieve the content resolver.
@param url key.
@return retrieved value or null if no entry match the given key.
"""
final Cursor cursor = context.getContentResolver().query(getUri(OfflinerDBHelper.TABLE_CACHE),
OfflinerDBHelper.PARAMS_CACHE, OfflinerDBHelper.REQUEST_URL
+ " = '" + url + "'", null, null);
String result = null;
if (cursor != null) {
if (cursor.getCount() != 0) {
cursor.moveToFirst();
result = cursor.getString(cursor.getColumnIndex(OfflinerDBHelper.REQUEST_RESULT));
}
cursor.close();
}
return result;
} | java | public String get(Context context, String url) {
final Cursor cursor = context.getContentResolver().query(getUri(OfflinerDBHelper.TABLE_CACHE),
OfflinerDBHelper.PARAMS_CACHE, OfflinerDBHelper.REQUEST_URL
+ " = '" + url + "'", null, null);
String result = null;
if (cursor != null) {
if (cursor.getCount() != 0) {
cursor.moveToFirst();
result = cursor.getString(cursor.getColumnIndex(OfflinerDBHelper.REQUEST_RESULT));
}
cursor.close();
}
return result;
} | [
"public",
"String",
"get",
"(",
"Context",
"context",
",",
"String",
"url",
")",
"{",
"final",
"Cursor",
"cursor",
"=",
"context",
".",
"getContentResolver",
"(",
")",
".",
"query",
"(",
"getUri",
"(",
"OfflinerDBHelper",
".",
"TABLE_CACHE",
")",
",",
"OfflinerDBHelper",
".",
"PARAMS_CACHE",
",",
"OfflinerDBHelper",
".",
"REQUEST_URL",
"+",
"\" = '\"",
"+",
"url",
"+",
"\"'\"",
",",
"null",
",",
"null",
")",
";",
"String",
"result",
"=",
"null",
";",
"if",
"(",
"cursor",
"!=",
"null",
")",
"{",
"if",
"(",
"cursor",
".",
"getCount",
"(",
")",
"!=",
"0",
")",
"{",
"cursor",
".",
"moveToFirst",
"(",
")",
";",
"result",
"=",
"cursor",
".",
"getString",
"(",
"cursor",
".",
"getColumnIndex",
"(",
"OfflinerDBHelper",
".",
"REQUEST_RESULT",
")",
")",
";",
"}",
"cursor",
".",
"close",
"(",
")",
";",
"}",
"return",
"result",
";",
"}"
]
| Retrieve a value saved for offline access.
@param context context used to retrieve the content resolver.
@param url key.
@return retrieved value or null if no entry match the given key. | [
"Retrieve",
"a",
"value",
"saved",
"for",
"offline",
"access",
"."
]
| train | https://github.com/tvbarthel/Cheerleader/blob/f61527e4cc44fcd0ed2e1e98aca285f8c236f24e/library/src/main/java/fr/tvbarthel/cheerleader/library/offline/OfflinerQueryHandler.java#L174-L189 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.