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 |
|---|---|---|---|---|---|---|---|---|---|---|
OpenLiberty/open-liberty | dev/com.ibm.jbatch.container/src/com/ibm/jbatch/container/services/impl/AbstractPersistenceManager.java | AbstractPersistenceManager.verifyStatusTransitionIsValid | protected void verifyStatusTransitionIsValid(JobInstanceEntity instance, BatchStatus toStatus) throws BatchIllegalJobStatusTransitionException {
"""
See description of: {@link AbstractPersistenceManager#verifyStatusTransitionIsValid(JobExecutionEntity, BatchStatus)
@param instance
@param toStatus
@throws BatchIllegalJobStatusTransitionException
"""
switch (instance.getBatchStatus()) {
case COMPLETED:
//COMPLETED to ABANDONED is allowed since it's already allowed in released TCK tests.
if (toStatus == BatchStatus.ABANDONED) {
break;
}
case ABANDONED:
throw new BatchIllegalJobStatusTransitionException("Job instance: " + instance.getInstanceId()
+ " cannot be transitioned from Batch Status: " + instance.getBatchStatus().name()
+ " to " + toStatus.name());
case STARTING:
case STARTED:
case STOPPING:
case FAILED:
default:
}
} | java | protected void verifyStatusTransitionIsValid(JobInstanceEntity instance, BatchStatus toStatus) throws BatchIllegalJobStatusTransitionException {
switch (instance.getBatchStatus()) {
case COMPLETED:
//COMPLETED to ABANDONED is allowed since it's already allowed in released TCK tests.
if (toStatus == BatchStatus.ABANDONED) {
break;
}
case ABANDONED:
throw new BatchIllegalJobStatusTransitionException("Job instance: " + instance.getInstanceId()
+ " cannot be transitioned from Batch Status: " + instance.getBatchStatus().name()
+ " to " + toStatus.name());
case STARTING:
case STARTED:
case STOPPING:
case FAILED:
default:
}
} | [
"protected",
"void",
"verifyStatusTransitionIsValid",
"(",
"JobInstanceEntity",
"instance",
",",
"BatchStatus",
"toStatus",
")",
"throws",
"BatchIllegalJobStatusTransitionException",
"{",
"switch",
"(",
"instance",
".",
"getBatchStatus",
"(",
")",
")",
"{",
"case",
"COM... | See description of: {@link AbstractPersistenceManager#verifyStatusTransitionIsValid(JobExecutionEntity, BatchStatus)
@param instance
@param toStatus
@throws BatchIllegalJobStatusTransitionException | [
"See",
"description",
"of",
":",
"{",
"@link",
"AbstractPersistenceManager#verifyStatusTransitionIsValid",
"(",
"JobExecutionEntity",
"BatchStatus",
")"
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.jbatch.container/src/com/ibm/jbatch/container/services/impl/AbstractPersistenceManager.java#L412-L432 |
broadinstitute/barclay | src/main/java/org/broadinstitute/barclay/help/HelpDoclet.java | HelpDoclet.emitOutputFromTemplates | private void emitOutputFromTemplates (
final List<Map<String, String>> groupMaps,
final List<Map<String, String>> featureMaps) {
"""
Actually write out the output files (html and gson file for each feature) and the index file.
"""
try {
/* ------------------------------------------------------------------- */
/* You should do this ONLY ONCE in the whole application life-cycle: */
final Configuration cfg = new Configuration(Configuration.VERSION_2_3_23);
cfg.setObjectWrapper(new DefaultObjectWrapper(Configuration.VERSION_2_3_23));
// We need to set up a scheme to load our settings from wherever they may live.
// This means we need to set up a multi-loader including the classpath and any specified options:
TemplateLoader templateLoader;
// Only add the settings directory if we're supposed to:
if ( useDefaultTemplates ) {
templateLoader = new ClassTemplateLoader(getClass(), DEFAULT_SETTINGS_CLASSPATH);
}
else {
templateLoader = new FileTemplateLoader(new File(settingsDir.getPath()));
}
// Tell freemarker to load our templates as we specified above:
cfg.setTemplateLoader(templateLoader);
// Generate one template file for each work unit
workUnits.stream().forEach(workUnit -> processWorkUnitTemplate(cfg, workUnit, groupMaps, featureMaps));
processIndexTemplate(cfg, new ArrayList<>(workUnits), groupMaps);
} catch (FileNotFoundException e) {
throw new RuntimeException("FileNotFoundException processing javadoc template", e);
} catch (IOException e) {
throw new RuntimeException("IOException processing javadoc template", e);
}
} | java | private void emitOutputFromTemplates (
final List<Map<String, String>> groupMaps,
final List<Map<String, String>> featureMaps)
{
try {
/* ------------------------------------------------------------------- */
/* You should do this ONLY ONCE in the whole application life-cycle: */
final Configuration cfg = new Configuration(Configuration.VERSION_2_3_23);
cfg.setObjectWrapper(new DefaultObjectWrapper(Configuration.VERSION_2_3_23));
// We need to set up a scheme to load our settings from wherever they may live.
// This means we need to set up a multi-loader including the classpath and any specified options:
TemplateLoader templateLoader;
// Only add the settings directory if we're supposed to:
if ( useDefaultTemplates ) {
templateLoader = new ClassTemplateLoader(getClass(), DEFAULT_SETTINGS_CLASSPATH);
}
else {
templateLoader = new FileTemplateLoader(new File(settingsDir.getPath()));
}
// Tell freemarker to load our templates as we specified above:
cfg.setTemplateLoader(templateLoader);
// Generate one template file for each work unit
workUnits.stream().forEach(workUnit -> processWorkUnitTemplate(cfg, workUnit, groupMaps, featureMaps));
processIndexTemplate(cfg, new ArrayList<>(workUnits), groupMaps);
} catch (FileNotFoundException e) {
throw new RuntimeException("FileNotFoundException processing javadoc template", e);
} catch (IOException e) {
throw new RuntimeException("IOException processing javadoc template", e);
}
} | [
"private",
"void",
"emitOutputFromTemplates",
"(",
"final",
"List",
"<",
"Map",
"<",
"String",
",",
"String",
">",
">",
"groupMaps",
",",
"final",
"List",
"<",
"Map",
"<",
"String",
",",
"String",
">",
">",
"featureMaps",
")",
"{",
"try",
"{",
"/* ------... | Actually write out the output files (html and gson file for each feature) and the index file. | [
"Actually",
"write",
"out",
"the",
"output",
"files",
"(",
"html",
"and",
"gson",
"file",
"for",
"each",
"feature",
")",
"and",
"the",
"index",
"file",
"."
] | train | https://github.com/broadinstitute/barclay/blob/7e56d725766b0da3baff23e79a31c3d01c3589c2/src/main/java/org/broadinstitute/barclay/help/HelpDoclet.java#L369-L404 |
jembi/openhim-mediator-engine-java | src/main/java/org/openhim/mediator/engine/RoutingTable.java | RoutingTable.addRoute | public void addRoute(String path, Class<? extends Actor> actorClass) throws RouteAlreadyMappedException {
"""
Add an exact path to the routing table.
@throws RouteAlreadyMappedException
"""
addRoute(new Route(path, false), actorClass);
} | java | public void addRoute(String path, Class<? extends Actor> actorClass) throws RouteAlreadyMappedException {
addRoute(new Route(path, false), actorClass);
} | [
"public",
"void",
"addRoute",
"(",
"String",
"path",
",",
"Class",
"<",
"?",
"extends",
"Actor",
">",
"actorClass",
")",
"throws",
"RouteAlreadyMappedException",
"{",
"addRoute",
"(",
"new",
"Route",
"(",
"path",
",",
"false",
")",
",",
"actorClass",
")",
... | Add an exact path to the routing table.
@throws RouteAlreadyMappedException | [
"Add",
"an",
"exact",
"path",
"to",
"the",
"routing",
"table",
"."
] | train | https://github.com/jembi/openhim-mediator-engine-java/blob/02adc0da4302cbde26cc9a5c1ce91ec6277e4f68/src/main/java/org/openhim/mediator/engine/RoutingTable.java#L61-L63 |
sarl/sarl | main/coreplugins/io.sarl.lang/src-gen/io/sarl/lang/codebuilder/builders/AbstractBuilder.java | AbstractBuilder.newTypeRef | public JvmParameterizedTypeReference newTypeRef(Notifier context, String typeName) {
"""
Replies the type reference for the given name in the given context.
"""
JvmTypeReference typeReference;
try {
typeReference = findType(context, typeName);
getImportManager().addImportFor(typeReference.getType());
return (JvmParameterizedTypeReference) typeReference;
} catch (TypeNotPresentException exception) {
}
final JvmParameterizedTypeReference pref = ExpressionBuilderImpl.parseType(context, typeName, this);
final JvmTypeReference baseType = findType(context, pref.getType().getIdentifier());
final int len = pref.getArguments().size();
final JvmTypeReference[] args = new JvmTypeReference[len];
for (int i = 0; i < len; ++i) {
final JvmTypeReference original = pref.getArguments().get(i);
if (original instanceof JvmAnyTypeReference) {
args[i] = EcoreUtil.copy(original);
} else if (original instanceof JvmWildcardTypeReference) {
final JvmWildcardTypeReference wc = EcoreUtil.copy((JvmWildcardTypeReference) original);
for (final JvmTypeConstraint c : wc.getConstraints()) {
c.setTypeReference(newTypeRef(context, c.getTypeReference().getIdentifier()));
}
args[i] = wc;
} else {
args[i] = newTypeRef(context, original.getIdentifier());
}
}
final TypeReferences typeRefs = getTypeReferences();
return typeRefs.createTypeRef(baseType.getType(), args);
} | java | public JvmParameterizedTypeReference newTypeRef(Notifier context, String typeName) {
JvmTypeReference typeReference;
try {
typeReference = findType(context, typeName);
getImportManager().addImportFor(typeReference.getType());
return (JvmParameterizedTypeReference) typeReference;
} catch (TypeNotPresentException exception) {
}
final JvmParameterizedTypeReference pref = ExpressionBuilderImpl.parseType(context, typeName, this);
final JvmTypeReference baseType = findType(context, pref.getType().getIdentifier());
final int len = pref.getArguments().size();
final JvmTypeReference[] args = new JvmTypeReference[len];
for (int i = 0; i < len; ++i) {
final JvmTypeReference original = pref.getArguments().get(i);
if (original instanceof JvmAnyTypeReference) {
args[i] = EcoreUtil.copy(original);
} else if (original instanceof JvmWildcardTypeReference) {
final JvmWildcardTypeReference wc = EcoreUtil.copy((JvmWildcardTypeReference) original);
for (final JvmTypeConstraint c : wc.getConstraints()) {
c.setTypeReference(newTypeRef(context, c.getTypeReference().getIdentifier()));
}
args[i] = wc;
} else {
args[i] = newTypeRef(context, original.getIdentifier());
}
}
final TypeReferences typeRefs = getTypeReferences();
return typeRefs.createTypeRef(baseType.getType(), args);
} | [
"public",
"JvmParameterizedTypeReference",
"newTypeRef",
"(",
"Notifier",
"context",
",",
"String",
"typeName",
")",
"{",
"JvmTypeReference",
"typeReference",
";",
"try",
"{",
"typeReference",
"=",
"findType",
"(",
"context",
",",
"typeName",
")",
";",
"getImportMan... | Replies the type reference for the given name in the given context. | [
"Replies",
"the",
"type",
"reference",
"for",
"the",
"given",
"name",
"in",
"the",
"given",
"context",
"."
] | train | https://github.com/sarl/sarl/blob/ca00ff994598c730339972def4e19a60e0b8cace/main/coreplugins/io.sarl.lang/src-gen/io/sarl/lang/codebuilder/builders/AbstractBuilder.java#L189-L217 |
kuali/ojb-1.0.4 | src/java/org/apache/ojb/broker/util/interceptor/Interceptor.java | Interceptor.doInvoke | protected Object doInvoke(Object proxy, Method methodToBeInvoked, Object[] args)
throws Throwable {
"""
this method will be invoked after methodToBeInvoked is invoked
"""
Method m =
getRealSubject().getClass().getMethod(
methodToBeInvoked.getName(),
methodToBeInvoked.getParameterTypes());
return m.invoke(getRealSubject(), args);
} | java | protected Object doInvoke(Object proxy, Method methodToBeInvoked, Object[] args)
throws Throwable
{
Method m =
getRealSubject().getClass().getMethod(
methodToBeInvoked.getName(),
methodToBeInvoked.getParameterTypes());
return m.invoke(getRealSubject(), args);
} | [
"protected",
"Object",
"doInvoke",
"(",
"Object",
"proxy",
",",
"Method",
"methodToBeInvoked",
",",
"Object",
"[",
"]",
"args",
")",
"throws",
"Throwable",
"{",
"Method",
"m",
"=",
"getRealSubject",
"(",
")",
".",
"getClass",
"(",
")",
".",
"getMethod",
"(... | this method will be invoked after methodToBeInvoked is invoked | [
"this",
"method",
"will",
"be",
"invoked",
"after",
"methodToBeInvoked",
"is",
"invoked"
] | train | https://github.com/kuali/ojb-1.0.4/blob/9a544372f67ce965f662cdc71609dd03683c8f04/src/java/org/apache/ojb/broker/util/interceptor/Interceptor.java#L62-L70 |
wso2/transport-http | components/org.wso2.transport.http.netty/src/main/java/org/wso2/transport/http/netty/contractimpl/listener/WebSocketServerHandshakeHandler.java | WebSocketServerHandshakeHandler.handleWebSocketHandshake | private void handleWebSocketHandshake(FullHttpRequest fullHttpRequest, ChannelHandlerContext ctx)
throws WebSocketConnectorException {
"""
Handle the WebSocket handshake.
@param fullHttpRequest {@link HttpRequest} of the request.
"""
String extensionsHeader = fullHttpRequest.headers().getAsString(HttpHeaderNames.SEC_WEBSOCKET_EXTENSIONS);
DefaultWebSocketHandshaker webSocketHandshaker =
new DefaultWebSocketHandshaker(ctx, serverConnectorFuture, fullHttpRequest, fullHttpRequest.uri(),
extensionsHeader != null);
// Setting common properties to handshaker
webSocketHandshaker.setHttpCarbonRequest(setupHttpCarbonRequest(fullHttpRequest, ctx));
ctx.channel().config().setAutoRead(false);
serverConnectorFuture.notifyWebSocketListener(webSocketHandshaker);
} | java | private void handleWebSocketHandshake(FullHttpRequest fullHttpRequest, ChannelHandlerContext ctx)
throws WebSocketConnectorException {
String extensionsHeader = fullHttpRequest.headers().getAsString(HttpHeaderNames.SEC_WEBSOCKET_EXTENSIONS);
DefaultWebSocketHandshaker webSocketHandshaker =
new DefaultWebSocketHandshaker(ctx, serverConnectorFuture, fullHttpRequest, fullHttpRequest.uri(),
extensionsHeader != null);
// Setting common properties to handshaker
webSocketHandshaker.setHttpCarbonRequest(setupHttpCarbonRequest(fullHttpRequest, ctx));
ctx.channel().config().setAutoRead(false);
serverConnectorFuture.notifyWebSocketListener(webSocketHandshaker);
} | [
"private",
"void",
"handleWebSocketHandshake",
"(",
"FullHttpRequest",
"fullHttpRequest",
",",
"ChannelHandlerContext",
"ctx",
")",
"throws",
"WebSocketConnectorException",
"{",
"String",
"extensionsHeader",
"=",
"fullHttpRequest",
".",
"headers",
"(",
")",
".",
"getAsStr... | Handle the WebSocket handshake.
@param fullHttpRequest {@link HttpRequest} of the request. | [
"Handle",
"the",
"WebSocket",
"handshake",
"."
] | train | https://github.com/wso2/transport-http/blob/c51aa715b473db6c1b82a7d7b22f6e65f74df4c9/components/org.wso2.transport.http.netty/src/main/java/org/wso2/transport/http/netty/contractimpl/listener/WebSocketServerHandshakeHandler.java#L154-L166 |
structr/structr | structr-ui/src/main/java/org/structr/web/servlet/HtmlServlet.java | HtmlServlet.findFirstNodeByName | private AbstractNode findFirstNodeByName(final SecurityContext securityContext, final HttpServletRequest request, final String path) throws FrameworkException {
"""
Find first node whose name matches the last part of the given path
@param securityContext
@param request
@param path
@return node
@throws FrameworkException
"""
final String name = PathHelper.getName(path);
if (!name.isEmpty()) {
logger.debug("Requested name: {}", name);
final Query query = StructrApp.getInstance(securityContext).nodeQuery();
final ConfigurationProvider config = StructrApp.getConfiguration();
if (!possiblePropertyNamesForEntityResolving.isEmpty()) {
query.and();
resolvePossiblePropertyNamesForObjectResolution(config, query, name);
query.parent();
}
final List<AbstractNode> results = Iterables.toList(query.getResultStream());
logger.debug("{} results", results.size());
request.setAttribute(POSSIBLE_ENTRY_POINTS_KEY, results);
return (results.size() > 0 ? (AbstractNode) results.get(0) : null);
}
return null;
} | java | private AbstractNode findFirstNodeByName(final SecurityContext securityContext, final HttpServletRequest request, final String path) throws FrameworkException {
final String name = PathHelper.getName(path);
if (!name.isEmpty()) {
logger.debug("Requested name: {}", name);
final Query query = StructrApp.getInstance(securityContext).nodeQuery();
final ConfigurationProvider config = StructrApp.getConfiguration();
if (!possiblePropertyNamesForEntityResolving.isEmpty()) {
query.and();
resolvePossiblePropertyNamesForObjectResolution(config, query, name);
query.parent();
}
final List<AbstractNode> results = Iterables.toList(query.getResultStream());
logger.debug("{} results", results.size());
request.setAttribute(POSSIBLE_ENTRY_POINTS_KEY, results);
return (results.size() > 0 ? (AbstractNode) results.get(0) : null);
}
return null;
} | [
"private",
"AbstractNode",
"findFirstNodeByName",
"(",
"final",
"SecurityContext",
"securityContext",
",",
"final",
"HttpServletRequest",
"request",
",",
"final",
"String",
"path",
")",
"throws",
"FrameworkException",
"{",
"final",
"String",
"name",
"=",
"PathHelper",
... | Find first node whose name matches the last part of the given path
@param securityContext
@param request
@param path
@return node
@throws FrameworkException | [
"Find",
"first",
"node",
"whose",
"name",
"matches",
"the",
"last",
"part",
"of",
"the",
"given",
"path"
] | train | https://github.com/structr/structr/blob/c111a1d0c0201c7fea5574ed69aa5a5053185a97/structr-ui/src/main/java/org/structr/web/servlet/HtmlServlet.java#L965-L993 |
kenyee/android-ddp-client | src/com/keysolutions/ddpclient/android/DDPBroadcastReceiver.java | DDPBroadcastReceiver.onError | protected void onError(String title, String msg) {
"""
Override this to hook into error display
Default behavior is to display the error as a dialog in your application
@param title title of error
@param msg detail of error
"""
// override this to override default error handling behavior
AlertDialog.Builder builder = new AlertDialog.Builder(mActivity);
builder.setMessage(msg).setTitle(title);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
AlertDialog dialog = builder.create();
dialog.show();
} | java | protected void onError(String title, String msg) {
// override this to override default error handling behavior
AlertDialog.Builder builder = new AlertDialog.Builder(mActivity);
builder.setMessage(msg).setTitle(title);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
AlertDialog dialog = builder.create();
dialog.show();
} | [
"protected",
"void",
"onError",
"(",
"String",
"title",
",",
"String",
"msg",
")",
"{",
"// override this to override default error handling behavior",
"AlertDialog",
".",
"Builder",
"builder",
"=",
"new",
"AlertDialog",
".",
"Builder",
"(",
"mActivity",
")",
";",
"... | Override this to hook into error display
Default behavior is to display the error as a dialog in your application
@param title title of error
@param msg detail of error | [
"Override",
"this",
"to",
"hook",
"into",
"error",
"display",
"Default",
"behavior",
"is",
"to",
"display",
"the",
"error",
"as",
"a",
"dialog",
"in",
"your",
"application"
] | train | https://github.com/kenyee/android-ddp-client/blob/6ab416e415570a03f96c383497144dd742de3f08/src/com/keysolutions/ddpclient/android/DDPBroadcastReceiver.java#L151-L162 |
heroku/heroku.jar | heroku-api/src/main/java/com/heroku/api/HerokuAPI.java | HerokuAPI.updateBuildpackInstallations | public void updateBuildpackInstallations(String appName, List<String> buildpacks) {
"""
Update the list of buildpacks installed on an app
@param appName See {@link #listApps} for a list of apps that can be used.
@param buildpacks the new list of buildpack names or URLs.
"""
connection.execute(new BuildpackInstallationUpdate(appName, buildpacks), apiKey);
} | java | public void updateBuildpackInstallations(String appName, List<String> buildpacks) {
connection.execute(new BuildpackInstallationUpdate(appName, buildpacks), apiKey);
} | [
"public",
"void",
"updateBuildpackInstallations",
"(",
"String",
"appName",
",",
"List",
"<",
"String",
">",
"buildpacks",
")",
"{",
"connection",
".",
"execute",
"(",
"new",
"BuildpackInstallationUpdate",
"(",
"appName",
",",
"buildpacks",
")",
",",
"apiKey",
"... | Update the list of buildpacks installed on an app
@param appName See {@link #listApps} for a list of apps that can be used.
@param buildpacks the new list of buildpack names or URLs. | [
"Update",
"the",
"list",
"of",
"buildpacks",
"installed",
"on",
"an",
"app"
] | train | https://github.com/heroku/heroku.jar/blob/d9e52991293159498c10c498c6f91fcdd637378e/heroku-api/src/main/java/com/heroku/api/HerokuAPI.java#L518-L520 |
Azure/azure-sdk-for-java | dns/resource-manager/v2017_10_01/src/main/java/com/microsoft/azure/management/dns/v2017_10_01/implementation/ZonesInner.java | ZonesInner.listByResourceGroupAsync | public Observable<Page<ZoneInner>> listByResourceGroupAsync(final String resourceGroupName, final Integer top) {
"""
Lists the DNS zones within a resource group.
@param resourceGroupName The name of the resource group.
@param top The maximum number of record sets to return. If not specified, returns up to 100 record sets.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the PagedList<ZoneInner> object
"""
return listByResourceGroupWithServiceResponseAsync(resourceGroupName, top)
.map(new Func1<ServiceResponse<Page<ZoneInner>>, Page<ZoneInner>>() {
@Override
public Page<ZoneInner> call(ServiceResponse<Page<ZoneInner>> response) {
return response.body();
}
});
} | java | public Observable<Page<ZoneInner>> listByResourceGroupAsync(final String resourceGroupName, final Integer top) {
return listByResourceGroupWithServiceResponseAsync(resourceGroupName, top)
.map(new Func1<ServiceResponse<Page<ZoneInner>>, Page<ZoneInner>>() {
@Override
public Page<ZoneInner> call(ServiceResponse<Page<ZoneInner>> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"Page",
"<",
"ZoneInner",
">",
">",
"listByResourceGroupAsync",
"(",
"final",
"String",
"resourceGroupName",
",",
"final",
"Integer",
"top",
")",
"{",
"return",
"listByResourceGroupWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
... | Lists the DNS zones within a resource group.
@param resourceGroupName The name of the resource group.
@param top The maximum number of record sets to return. If not specified, returns up to 100 record sets.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the PagedList<ZoneInner> object | [
"Lists",
"the",
"DNS",
"zones",
"within",
"a",
"resource",
"group",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/dns/resource-manager/v2017_10_01/src/main/java/com/microsoft/azure/management/dns/v2017_10_01/implementation/ZonesInner.java#L1034-L1042 |
googleapis/google-cloud-java | google-cloud-clients/google-cloud-compute/src/main/java/com/google/cloud/compute/deprecated/InstanceId.java | InstanceId.of | public static InstanceId of(String project, String zone, String instance) {
"""
Returns an instance identity given project, zone and instance names. The instance name must be
1-63 characters long and comply with RFC1035. Specifically, the name must match the regular
expression {@code [a-z]([-a-z0-9]*[a-z0-9])?} which means the first character must be a
lowercase letter, and all following characters must be a dash, lowercase letter, or digit,
except the last character, which cannot be a dash.
@see <a href="https://www.ietf.org/rfc/rfc1035.txt">RFC1035</a>
"""
return new InstanceId(project, zone, instance);
} | java | public static InstanceId of(String project, String zone, String instance) {
return new InstanceId(project, zone, instance);
} | [
"public",
"static",
"InstanceId",
"of",
"(",
"String",
"project",
",",
"String",
"zone",
",",
"String",
"instance",
")",
"{",
"return",
"new",
"InstanceId",
"(",
"project",
",",
"zone",
",",
"instance",
")",
";",
"}"
] | Returns an instance identity given project, zone and instance names. The instance name must be
1-63 characters long and comply with RFC1035. Specifically, the name must match the regular
expression {@code [a-z]([-a-z0-9]*[a-z0-9])?} which means the first character must be a
lowercase letter, and all following characters must be a dash, lowercase letter, or digit,
except the last character, which cannot be a dash.
@see <a href="https://www.ietf.org/rfc/rfc1035.txt">RFC1035</a> | [
"Returns",
"an",
"instance",
"identity",
"given",
"project",
"zone",
"and",
"instance",
"names",
".",
"The",
"instance",
"name",
"must",
"be",
"1",
"-",
"63",
"characters",
"long",
"and",
"comply",
"with",
"RFC1035",
".",
"Specifically",
"the",
"name",
"must... | train | https://github.com/googleapis/google-cloud-java/blob/d2f0bc64a53049040fe9c9d338b12fab3dd1ad6a/google-cloud-clients/google-cloud-compute/src/main/java/com/google/cloud/compute/deprecated/InstanceId.java#L153-L155 |
google/j2objc | xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xalan/templates/OutputProperties.java | OutputProperties.copyFrom | public void copyFrom(Properties src, boolean shouldResetDefaults) {
"""
Copy the keys and values from the source to this object. This will
not copy the default values. This is meant to be used by going from
a higher precedence object to a lower precedence object, so that if a
key already exists, this method will not reset it.
@param src non-null reference to the source properties.
@param shouldResetDefaults true if the defaults should be reset based on
the method property.
"""
Enumeration keys = src.keys();
while (keys.hasMoreElements())
{
String key = (String) keys.nextElement();
if (!isLegalPropertyKey(key))
throw new IllegalArgumentException(XSLMessages.createMessage(XSLTErrorResources.ER_OUTPUT_PROPERTY_NOT_RECOGNIZED, new Object[]{key})); //"output property not recognized: "
Object oldValue = m_properties.get(key);
if (null == oldValue)
{
String val = (String) src.get(key);
if(shouldResetDefaults && key.equals(OutputKeys.METHOD))
{
setMethodDefaults(val);
}
m_properties.put(key, val);
}
else if (key.equals(OutputKeys.CDATA_SECTION_ELEMENTS))
{
m_properties.put(key, (String) oldValue + " " + (String) src.get(key));
}
}
} | java | public void copyFrom(Properties src, boolean shouldResetDefaults)
{
Enumeration keys = src.keys();
while (keys.hasMoreElements())
{
String key = (String) keys.nextElement();
if (!isLegalPropertyKey(key))
throw new IllegalArgumentException(XSLMessages.createMessage(XSLTErrorResources.ER_OUTPUT_PROPERTY_NOT_RECOGNIZED, new Object[]{key})); //"output property not recognized: "
Object oldValue = m_properties.get(key);
if (null == oldValue)
{
String val = (String) src.get(key);
if(shouldResetDefaults && key.equals(OutputKeys.METHOD))
{
setMethodDefaults(val);
}
m_properties.put(key, val);
}
else if (key.equals(OutputKeys.CDATA_SECTION_ELEMENTS))
{
m_properties.put(key, (String) oldValue + " " + (String) src.get(key));
}
}
} | [
"public",
"void",
"copyFrom",
"(",
"Properties",
"src",
",",
"boolean",
"shouldResetDefaults",
")",
"{",
"Enumeration",
"keys",
"=",
"src",
".",
"keys",
"(",
")",
";",
"while",
"(",
"keys",
".",
"hasMoreElements",
"(",
")",
")",
"{",
"String",
"key",
"="... | Copy the keys and values from the source to this object. This will
not copy the default values. This is meant to be used by going from
a higher precedence object to a lower precedence object, so that if a
key already exists, this method will not reset it.
@param src non-null reference to the source properties.
@param shouldResetDefaults true if the defaults should be reset based on
the method property. | [
"Copy",
"the",
"keys",
"and",
"values",
"from",
"the",
"source",
"to",
"this",
"object",
".",
"This",
"will",
"not",
"copy",
"the",
"default",
"values",
".",
"This",
"is",
"meant",
"to",
"be",
"used",
"by",
"going",
"from",
"a",
"higher",
"precedence",
... | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xalan/templates/OutputProperties.java#L592-L621 |
alkacon/opencms-core | src/org/opencms/xml/content/CmsDefaultXmlContentHandler.java | CmsDefaultXmlContentHandler.safeParseBoolean | private boolean safeParseBoolean(String text, boolean defaultValue) {
"""
Parses a boolean from a string and returns a default value if the string couldn't be parsed.<p>
@param text the text from which to get the boolean value
@param defaultValue the value to return if parsing fails
@return the parsed boolean
"""
if (text == null) {
return defaultValue;
}
try {
return Boolean.parseBoolean(text);
} catch (Throwable t) {
return defaultValue;
}
} | java | private boolean safeParseBoolean(String text, boolean defaultValue) {
if (text == null) {
return defaultValue;
}
try {
return Boolean.parseBoolean(text);
} catch (Throwable t) {
return defaultValue;
}
} | [
"private",
"boolean",
"safeParseBoolean",
"(",
"String",
"text",
",",
"boolean",
"defaultValue",
")",
"{",
"if",
"(",
"text",
"==",
"null",
")",
"{",
"return",
"defaultValue",
";",
"}",
"try",
"{",
"return",
"Boolean",
".",
"parseBoolean",
"(",
"text",
")"... | Parses a boolean from a string and returns a default value if the string couldn't be parsed.<p>
@param text the text from which to get the boolean value
@param defaultValue the value to return if parsing fails
@return the parsed boolean | [
"Parses",
"a",
"boolean",
"from",
"a",
"string",
"and",
"returns",
"a",
"default",
"value",
"if",
"the",
"string",
"couldn",
"t",
"be",
"parsed",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/xml/content/CmsDefaultXmlContentHandler.java#L4365-L4375 |
apache/flink | flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/util/MurmurHashUtil.java | MurmurHashUtil.hashUnsafeBytes | public static int hashUnsafeBytes(Object base, long offset, int lengthInBytes) {
"""
Hash unsafe bytes.
@param base base unsafe object
@param offset offset for unsafe object
@param lengthInBytes length in bytes
@return hash code
"""
return hashUnsafeBytes(base, offset, lengthInBytes, DEFAULT_SEED);
} | java | public static int hashUnsafeBytes(Object base, long offset, int lengthInBytes) {
return hashUnsafeBytes(base, offset, lengthInBytes, DEFAULT_SEED);
} | [
"public",
"static",
"int",
"hashUnsafeBytes",
"(",
"Object",
"base",
",",
"long",
"offset",
",",
"int",
"lengthInBytes",
")",
"{",
"return",
"hashUnsafeBytes",
"(",
"base",
",",
"offset",
",",
"lengthInBytes",
",",
"DEFAULT_SEED",
")",
";",
"}"
] | Hash unsafe bytes.
@param base base unsafe object
@param offset offset for unsafe object
@param lengthInBytes length in bytes
@return hash code | [
"Hash",
"unsafe",
"bytes",
"."
] | train | https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/util/MurmurHashUtil.java#L51-L53 |
dita-ot/dita-ot | src/main/java/org/ditang/relaxng/defaults/OxygenRelaxNGSchemaReader.java | OxygenRelaxNGSchemaReader.wrapPattern2 | private static SchemaWrapper wrapPattern2(Pattern start, SchemaPatternBuilder spb, PropertyMap properties)
throws SAXException, IncorrectSchemaException {
"""
Make a schema wrapper.
@param start Start pattern.
@param spb The schema pattern builder.
@param properties The properties map.
@return The schema wrapper.
"""
if (properties.contains(RngProperty.FEASIBLE)) {
//Use a feasible transform
start = FeasibleTransform.transform(spb, start);
}
//Get properties for supported IDs
properties = AbstractSchema.filterProperties(properties, supportedPropertyIds);
Schema schema = new PatternSchema(spb, start, properties);
IdTypeMap idTypeMap = null;
if (spb.hasIdTypes() && properties.contains(RngProperty.CHECK_ID_IDREF)) {
//Check ID/IDREF
ErrorHandler eh = properties.get(ValidateProperty.ERROR_HANDLER);
idTypeMap = new IdTypeMapBuilder(eh, start).getIdTypeMap();
if (idTypeMap == null) {
throw new IncorrectSchemaException();
}
Schema idSchema;
if (properties.contains(RngProperty.FEASIBLE)) {
idSchema = new FeasibleIdTypeMapSchema(idTypeMap, properties);
} else {
idSchema = new IdTypeMapSchema(idTypeMap, properties);
}
schema = new CombineSchema(schema, idSchema, properties);
}
//Wrap the schema
SchemaWrapper sw = new SchemaWrapper(schema);
sw.setStart(start);
sw.setIdTypeMap(idTypeMap);
return sw;
} | java | private static SchemaWrapper wrapPattern2(Pattern start, SchemaPatternBuilder spb, PropertyMap properties)
throws SAXException, IncorrectSchemaException {
if (properties.contains(RngProperty.FEASIBLE)) {
//Use a feasible transform
start = FeasibleTransform.transform(spb, start);
}
//Get properties for supported IDs
properties = AbstractSchema.filterProperties(properties, supportedPropertyIds);
Schema schema = new PatternSchema(spb, start, properties);
IdTypeMap idTypeMap = null;
if (spb.hasIdTypes() && properties.contains(RngProperty.CHECK_ID_IDREF)) {
//Check ID/IDREF
ErrorHandler eh = properties.get(ValidateProperty.ERROR_HANDLER);
idTypeMap = new IdTypeMapBuilder(eh, start).getIdTypeMap();
if (idTypeMap == null) {
throw new IncorrectSchemaException();
}
Schema idSchema;
if (properties.contains(RngProperty.FEASIBLE)) {
idSchema = new FeasibleIdTypeMapSchema(idTypeMap, properties);
} else {
idSchema = new IdTypeMapSchema(idTypeMap, properties);
}
schema = new CombineSchema(schema, idSchema, properties);
}
//Wrap the schema
SchemaWrapper sw = new SchemaWrapper(schema);
sw.setStart(start);
sw.setIdTypeMap(idTypeMap);
return sw;
} | [
"private",
"static",
"SchemaWrapper",
"wrapPattern2",
"(",
"Pattern",
"start",
",",
"SchemaPatternBuilder",
"spb",
",",
"PropertyMap",
"properties",
")",
"throws",
"SAXException",
",",
"IncorrectSchemaException",
"{",
"if",
"(",
"properties",
".",
"contains",
"(",
"... | Make a schema wrapper.
@param start Start pattern.
@param spb The schema pattern builder.
@param properties The properties map.
@return The schema wrapper. | [
"Make",
"a",
"schema",
"wrapper",
"."
] | train | https://github.com/dita-ot/dita-ot/blob/ea776b3c60c03d9f033b6f7ea072349e49dbcdd2/src/main/java/org/ditang/relaxng/defaults/OxygenRelaxNGSchemaReader.java#L174-L205 |
pravega/pravega | segmentstore/server/src/main/java/io/pravega/segmentstore/server/tables/ContainerKeyCache.java | ContainerKeyCache.get | CacheBucketOffset get(long segmentId, UUID keyHash) {
"""
Looks up a cached offset for the given Segment and Key Hash.
@param segmentId The Id of the Segment to look up for.
@param keyHash A UUID representing the Key Hash to look up.
@return A {@link CacheBucketOffset} representing the sought result.
"""
SegmentKeyCache cache;
int generation;
synchronized (this.segmentCaches) {
generation = this.currentCacheGeneration;
cache = this.segmentCaches.get(segmentId);
}
return cache == null ? null : cache.get(keyHash, generation);
} | java | CacheBucketOffset get(long segmentId, UUID keyHash) {
SegmentKeyCache cache;
int generation;
synchronized (this.segmentCaches) {
generation = this.currentCacheGeneration;
cache = this.segmentCaches.get(segmentId);
}
return cache == null ? null : cache.get(keyHash, generation);
} | [
"CacheBucketOffset",
"get",
"(",
"long",
"segmentId",
",",
"UUID",
"keyHash",
")",
"{",
"SegmentKeyCache",
"cache",
";",
"int",
"generation",
";",
"synchronized",
"(",
"this",
".",
"segmentCaches",
")",
"{",
"generation",
"=",
"this",
".",
"currentCacheGeneratio... | Looks up a cached offset for the given Segment and Key Hash.
@param segmentId The Id of the Segment to look up for.
@param keyHash A UUID representing the Key Hash to look up.
@return A {@link CacheBucketOffset} representing the sought result. | [
"Looks",
"up",
"a",
"cached",
"offset",
"for",
"the",
"given",
"Segment",
"and",
"Key",
"Hash",
"."
] | train | https://github.com/pravega/pravega/blob/6e24df7470669b3956a07018f52b2c6b3c2a3503/segmentstore/server/src/main/java/io/pravega/segmentstore/server/tables/ContainerKeyCache.java#L172-L181 |
groovy/groovy-core | src/main/groovy/beans/BindableASTTransformation.java | BindableASTTransformation.createSetterMethod | protected void createSetterMethod(ClassNode declaringClass, PropertyNode propertyNode, String setterName, Statement setterBlock) {
"""
Creates a setter method with the given body.
@param declaringClass the class to which we will add the setter
@param propertyNode the field to back the setter
@param setterName the name of the setter
@param setterBlock the statement representing the setter block
"""
MethodNode setter = new MethodNode(
setterName,
propertyNode.getModifiers(),
ClassHelper.VOID_TYPE,
params(param(propertyNode.getType(), "value")),
ClassNode.EMPTY_ARRAY,
setterBlock);
setter.setSynthetic(true);
// add it to the class
declaringClass.addMethod(setter);
} | java | protected void createSetterMethod(ClassNode declaringClass, PropertyNode propertyNode, String setterName, Statement setterBlock) {
MethodNode setter = new MethodNode(
setterName,
propertyNode.getModifiers(),
ClassHelper.VOID_TYPE,
params(param(propertyNode.getType(), "value")),
ClassNode.EMPTY_ARRAY,
setterBlock);
setter.setSynthetic(true);
// add it to the class
declaringClass.addMethod(setter);
} | [
"protected",
"void",
"createSetterMethod",
"(",
"ClassNode",
"declaringClass",
",",
"PropertyNode",
"propertyNode",
",",
"String",
"setterName",
",",
"Statement",
"setterBlock",
")",
"{",
"MethodNode",
"setter",
"=",
"new",
"MethodNode",
"(",
"setterName",
",",
"pro... | Creates a setter method with the given body.
@param declaringClass the class to which we will add the setter
@param propertyNode the field to back the setter
@param setterName the name of the setter
@param setterBlock the statement representing the setter block | [
"Creates",
"a",
"setter",
"method",
"with",
"the",
"given",
"body",
"."
] | train | https://github.com/groovy/groovy-core/blob/01309f9d4be34ddf93c4a9943b5a97843bff6181/src/main/groovy/beans/BindableASTTransformation.java#L247-L258 |
code4everything/util | src/main/java/com/zhazhapan/util/Checker.java | Checker.checkBean | public static <T> CheckResult<T> checkBean(Object bean) {
"""
验证JavaBean带有 {@link FieldChecking}注解的字段
@param bean JavaBean
@return {@link CheckResult}
@since 1.0.9
"""
return checkBean(bean, new HashMap<>(ValueConsts.TWO_INT));
} | java | public static <T> CheckResult<T> checkBean(Object bean) {
return checkBean(bean, new HashMap<>(ValueConsts.TWO_INT));
} | [
"public",
"static",
"<",
"T",
">",
"CheckResult",
"<",
"T",
">",
"checkBean",
"(",
"Object",
"bean",
")",
"{",
"return",
"checkBean",
"(",
"bean",
",",
"new",
"HashMap",
"<>",
"(",
"ValueConsts",
".",
"TWO_INT",
")",
")",
";",
"}"
] | 验证JavaBean带有 {@link FieldChecking}注解的字段
@param bean JavaBean
@return {@link CheckResult}
@since 1.0.9 | [
"验证JavaBean带有",
"{",
"@link",
"FieldChecking",
"}",
"注解的字段"
] | train | https://github.com/code4everything/util/blob/1fc9f0ead1108f4d7208ba7c000df4244f708418/src/main/java/com/zhazhapan/util/Checker.java#L265-L267 |
mytechia/mytechia_commons | mytechia_commons_library/src/main/java/com/mytechia/commons/util/thread/Threads.java | Threads.findActiveThreadByName | private static Thread findActiveThreadByName(ThreadGroup group, String threadName) {
"""
This method recursively visits all thread groups under 'group',
searching for the active thread with name 'threadName'.
@param group
@param threadName
@return
"""
Thread result = null;
// Get threads in 'group'
int numThreads = group.activeCount();
Thread[] threads = new Thread[numThreads * 2];
numThreads = group.enumerate(threads, false);
// Enumerate each thread in 'group'
for (int i = 0; i < numThreads; i++) {
if (threads[i].getName().equals(threadName)) {
return threads[i];
}
}
// Get thread subgroups of 'group'
int numGroups = group.activeGroupCount();
ThreadGroup[] groups = new ThreadGroup[numGroups * 2];
numGroups = group.enumerate(groups, false);
// Recursively visit each subgroup
for (int i = 0; i < numGroups; i++) {
result = findActiveThreadByName(groups[i], threadName);
if (result != null) {
break;
}
}
return result;
} | java | private static Thread findActiveThreadByName(ThreadGroup group, String threadName)
{
Thread result = null;
// Get threads in 'group'
int numThreads = group.activeCount();
Thread[] threads = new Thread[numThreads * 2];
numThreads = group.enumerate(threads, false);
// Enumerate each thread in 'group'
for (int i = 0; i < numThreads; i++) {
if (threads[i].getName().equals(threadName)) {
return threads[i];
}
}
// Get thread subgroups of 'group'
int numGroups = group.activeGroupCount();
ThreadGroup[] groups = new ThreadGroup[numGroups * 2];
numGroups = group.enumerate(groups, false);
// Recursively visit each subgroup
for (int i = 0; i < numGroups; i++) {
result = findActiveThreadByName(groups[i], threadName);
if (result != null) {
break;
}
}
return result;
} | [
"private",
"static",
"Thread",
"findActiveThreadByName",
"(",
"ThreadGroup",
"group",
",",
"String",
"threadName",
")",
"{",
"Thread",
"result",
"=",
"null",
";",
"// Get threads in 'group'",
"int",
"numThreads",
"=",
"group",
".",
"activeCount",
"(",
")",
";",
... | This method recursively visits all thread groups under 'group',
searching for the active thread with name 'threadName'.
@param group
@param threadName
@return | [
"This",
"method",
"recursively",
"visits",
"all",
"thread",
"groups",
"under",
"group",
"searching",
"for",
"the",
"active",
"thread",
"with",
"name",
"threadName",
"."
] | train | https://github.com/mytechia/mytechia_commons/blob/02251879085f271a1fb51663a1c8eddc8be78ae7/mytechia_commons_library/src/main/java/com/mytechia/commons/util/thread/Threads.java#L65-L96 |
infinispan/infinispan | core/src/main/java/org/infinispan/statetransfer/StateTransferManagerImpl.java | StateTransferManagerImpl.addPartitioner | private CacheTopology addPartitioner(CacheTopology cacheTopology) {
"""
Decorates the given cache topology to add a key partitioner.
The key partitioner may include support for grouping as well.
"""
ConsistentHash currentCH = cacheTopology.getCurrentCH();
currentCH = new PartitionerConsistentHash(currentCH, keyPartitioner);
ConsistentHash pendingCH = cacheTopology.getPendingCH();
if (pendingCH != null) {
pendingCH = new PartitionerConsistentHash(pendingCH, keyPartitioner);
}
ConsistentHash unionCH = cacheTopology.getUnionCH();
if (unionCH != null) {
unionCH = new PartitionerConsistentHash(unionCH, keyPartitioner);
}
return new CacheTopology(cacheTopology.getTopologyId(), cacheTopology.getRebalanceId(), currentCH, pendingCH,
unionCH, cacheTopology.getPhase(), cacheTopology.getActualMembers(), cacheTopology.getMembersPersistentUUIDs());
} | java | private CacheTopology addPartitioner(CacheTopology cacheTopology) {
ConsistentHash currentCH = cacheTopology.getCurrentCH();
currentCH = new PartitionerConsistentHash(currentCH, keyPartitioner);
ConsistentHash pendingCH = cacheTopology.getPendingCH();
if (pendingCH != null) {
pendingCH = new PartitionerConsistentHash(pendingCH, keyPartitioner);
}
ConsistentHash unionCH = cacheTopology.getUnionCH();
if (unionCH != null) {
unionCH = new PartitionerConsistentHash(unionCH, keyPartitioner);
}
return new CacheTopology(cacheTopology.getTopologyId(), cacheTopology.getRebalanceId(), currentCH, pendingCH,
unionCH, cacheTopology.getPhase(), cacheTopology.getActualMembers(), cacheTopology.getMembersPersistentUUIDs());
} | [
"private",
"CacheTopology",
"addPartitioner",
"(",
"CacheTopology",
"cacheTopology",
")",
"{",
"ConsistentHash",
"currentCH",
"=",
"cacheTopology",
".",
"getCurrentCH",
"(",
")",
";",
"currentCH",
"=",
"new",
"PartitionerConsistentHash",
"(",
"currentCH",
",",
"keyPar... | Decorates the given cache topology to add a key partitioner.
The key partitioner may include support for grouping as well. | [
"Decorates",
"the",
"given",
"cache",
"topology",
"to",
"add",
"a",
"key",
"partitioner",
"."
] | train | https://github.com/infinispan/infinispan/blob/7c62b94886c3febb4774ae8376acf2baa0265ab5/core/src/main/java/org/infinispan/statetransfer/StateTransferManagerImpl.java#L159-L172 |
prestodb/presto | presto-parser/src/main/java/com/facebook/presto/sql/tree/QualifiedName.java | QualifiedName.getPrefix | public Optional<QualifiedName> getPrefix() {
"""
For an identifier of the form "a.b.c.d", returns "a.b.c"
For an identifier of the form "a", returns absent
"""
if (parts.size() == 1) {
return Optional.empty();
}
List<String> subList = parts.subList(0, parts.size() - 1);
return Optional.of(new QualifiedName(subList, subList));
} | java | public Optional<QualifiedName> getPrefix()
{
if (parts.size() == 1) {
return Optional.empty();
}
List<String> subList = parts.subList(0, parts.size() - 1);
return Optional.of(new QualifiedName(subList, subList));
} | [
"public",
"Optional",
"<",
"QualifiedName",
">",
"getPrefix",
"(",
")",
"{",
"if",
"(",
"parts",
".",
"size",
"(",
")",
"==",
"1",
")",
"{",
"return",
"Optional",
".",
"empty",
"(",
")",
";",
"}",
"List",
"<",
"String",
">",
"subList",
"=",
"parts"... | For an identifier of the form "a.b.c.d", returns "a.b.c"
For an identifier of the form "a", returns absent | [
"For",
"an",
"identifier",
"of",
"the",
"form",
"a",
".",
"b",
".",
"c",
".",
"d",
"returns",
"a",
".",
"b",
".",
"c",
"For",
"an",
"identifier",
"of",
"the",
"form",
"a",
"returns",
"absent"
] | train | https://github.com/prestodb/presto/blob/89de5e379d8f85e139d292b0add8c537a2a01a88/presto-parser/src/main/java/com/facebook/presto/sql/tree/QualifiedName.java#L82-L90 |
igniterealtime/REST-API-Client | src/main/java/org/igniterealtime/restclient/RestApiClient.java | RestApiClient.deleteAdmin | public Response deleteAdmin(String roomName, String jid) {
"""
Delete admin from chatroom.
@param roomName
the room name
@param jid
the jid
@return the response
"""
return restClient.delete("chatrooms/" + roomName + "/admins/" + jid,
new HashMap<String, String>());
} | java | public Response deleteAdmin(String roomName, String jid) {
return restClient.delete("chatrooms/" + roomName + "/admins/" + jid,
new HashMap<String, String>());
} | [
"public",
"Response",
"deleteAdmin",
"(",
"String",
"roomName",
",",
"String",
"jid",
")",
"{",
"return",
"restClient",
".",
"delete",
"(",
"\"chatrooms/\"",
"+",
"roomName",
"+",
"\"/admins/\"",
"+",
"jid",
",",
"new",
"HashMap",
"<",
"String",
",",
"String... | Delete admin from chatroom.
@param roomName
the room name
@param jid
the jid
@return the response | [
"Delete",
"admin",
"from",
"chatroom",
"."
] | train | https://github.com/igniterealtime/REST-API-Client/blob/fd544dd770ec2ababa47fef51579522ddce09f05/src/main/java/org/igniterealtime/restclient/RestApiClient.java#L288-L291 |
alexa/alexa-skills-kit-sdk-for-java | ask-sdk-core/src/com/amazon/ask/response/ResponseBuilder.java | ResponseBuilder.addVideoAppLaunchDirective | public ResponseBuilder addVideoAppLaunchDirective(String source, String title, String subtitle) {
"""
Adds a VideoApp {@link LaunchDirective} to the response to play a video.
@param source location of video content at a remote HTTPS location
@param title title that can be displayed on VideoApp
@param subtitle subtitle that can be displayed on VideoApp
@return response builder
"""
Metadata metadata = Metadata.builder()
.withSubtitle(subtitle)
.withTitle(title)
.build();
VideoItem videoItem = VideoItem.builder()
.withSource(source)
.withMetadata(metadata)
.build();
LaunchDirective videoDirective = LaunchDirective.builder()
.withVideoItem(videoItem)
.build();
this.shouldEndSession = null;
return addDirective(videoDirective);
} | java | public ResponseBuilder addVideoAppLaunchDirective(String source, String title, String subtitle) {
Metadata metadata = Metadata.builder()
.withSubtitle(subtitle)
.withTitle(title)
.build();
VideoItem videoItem = VideoItem.builder()
.withSource(source)
.withMetadata(metadata)
.build();
LaunchDirective videoDirective = LaunchDirective.builder()
.withVideoItem(videoItem)
.build();
this.shouldEndSession = null;
return addDirective(videoDirective);
} | [
"public",
"ResponseBuilder",
"addVideoAppLaunchDirective",
"(",
"String",
"source",
",",
"String",
"title",
",",
"String",
"subtitle",
")",
"{",
"Metadata",
"metadata",
"=",
"Metadata",
".",
"builder",
"(",
")",
".",
"withSubtitle",
"(",
"subtitle",
")",
".",
... | Adds a VideoApp {@link LaunchDirective} to the response to play a video.
@param source location of video content at a remote HTTPS location
@param title title that can be displayed on VideoApp
@param subtitle subtitle that can be displayed on VideoApp
@return response builder | [
"Adds",
"a",
"VideoApp",
"{",
"@link",
"LaunchDirective",
"}",
"to",
"the",
"response",
"to",
"play",
"a",
"video",
"."
] | train | https://github.com/alexa/alexa-skills-kit-sdk-for-java/blob/c49194da0693898c70f3f2c4a372f5a12da04e3e/ask-sdk-core/src/com/amazon/ask/response/ResponseBuilder.java#L236-L252 |
querydsl/querydsl | querydsl-core/src/main/java/com/querydsl/core/types/dsl/Expressions.java | Expressions.dslTemplate | @Deprecated
public static <T> DslTemplate<T> dslTemplate(Class<? extends T> cl, String template, ImmutableList<?> args) {
"""
Create a new Template expression
@deprecated Use {@link #dslTemplate(Class, String, List)} instead.
@param cl type of expression
@param template template
@param args template parameters
@return template expression
"""
return dslTemplate(cl, createTemplate(template), args);
} | java | @Deprecated
public static <T> DslTemplate<T> dslTemplate(Class<? extends T> cl, String template, ImmutableList<?> args) {
return dslTemplate(cl, createTemplate(template), args);
} | [
"@",
"Deprecated",
"public",
"static",
"<",
"T",
">",
"DslTemplate",
"<",
"T",
">",
"dslTemplate",
"(",
"Class",
"<",
"?",
"extends",
"T",
">",
"cl",
",",
"String",
"template",
",",
"ImmutableList",
"<",
"?",
">",
"args",
")",
"{",
"return",
"dslTempla... | Create a new Template expression
@deprecated Use {@link #dslTemplate(Class, String, List)} instead.
@param cl type of expression
@param template template
@param args template parameters
@return template expression | [
"Create",
"a",
"new",
"Template",
"expression"
] | train | https://github.com/querydsl/querydsl/blob/2bf234caf78549813a1e0f44d9c30ecc5ef734e3/querydsl-core/src/main/java/com/querydsl/core/types/dsl/Expressions.java#L334-L337 |
aws/aws-sdk-java | aws-java-sdk-api-gateway/src/main/java/com/amazonaws/services/apigateway/model/PutGatewayResponseRequest.java | PutGatewayResponseRequest.withResponseTemplates | public PutGatewayResponseRequest withResponseTemplates(java.util.Map<String, String> responseTemplates) {
"""
<p>
<p>
Response templates of the <a>GatewayResponse</a> as a string-to-string map of key-value pairs.
</p>
</p>
@param responseTemplates
Response templates of the <a>GatewayResponse</a> as a string-to-string map of key-value pairs.
@return Returns a reference to this object so that method calls can be chained together.
"""
setResponseTemplates(responseTemplates);
return this;
} | java | public PutGatewayResponseRequest withResponseTemplates(java.util.Map<String, String> responseTemplates) {
setResponseTemplates(responseTemplates);
return this;
} | [
"public",
"PutGatewayResponseRequest",
"withResponseTemplates",
"(",
"java",
".",
"util",
".",
"Map",
"<",
"String",
",",
"String",
">",
"responseTemplates",
")",
"{",
"setResponseTemplates",
"(",
"responseTemplates",
")",
";",
"return",
"this",
";",
"}"
] | <p>
<p>
Response templates of the <a>GatewayResponse</a> as a string-to-string map of key-value pairs.
</p>
</p>
@param responseTemplates
Response templates of the <a>GatewayResponse</a> as a string-to-string map of key-value pairs.
@return Returns a reference to this object so that method calls can be chained together. | [
"<p",
">",
"<p",
">",
"Response",
"templates",
"of",
"the",
"<a",
">",
"GatewayResponse<",
"/",
"a",
">",
"as",
"a",
"string",
"-",
"to",
"-",
"string",
"map",
"of",
"key",
"-",
"value",
"pairs",
".",
"<",
"/",
"p",
">",
"<",
"/",
"p",
">"
] | train | https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-api-gateway/src/main/java/com/amazonaws/services/apigateway/model/PutGatewayResponseRequest.java#L597-L600 |
attribyte/wpdb | src/main/java/org/attribyte/wp/db/DB.java | DB.updatePostExcerpt | public boolean updatePostExcerpt(long postId, final String excerpt) throws SQLException {
"""
Updates the excerpt for a post.
@param postId The post to update.
@param excerpt The new excerpt.
@return Was the post modified?
@throws SQLException on database error or missing post id.
"""
Connection conn = null;
PreparedStatement stmt = null;
Timer.Context ctx = metrics.updatePostTimer.time();
try {
conn = connectionSupplier.getConnection();
stmt = conn.prepareStatement(updatePostExcerptSQL);
stmt.setString(1, excerpt);
stmt.setLong(2, postId);
return stmt.executeUpdate() > 0;
} finally {
ctx.stop();
SQLUtil.closeQuietly(conn, stmt);
}
} | java | public boolean updatePostExcerpt(long postId, final String excerpt) throws SQLException {
Connection conn = null;
PreparedStatement stmt = null;
Timer.Context ctx = metrics.updatePostTimer.time();
try {
conn = connectionSupplier.getConnection();
stmt = conn.prepareStatement(updatePostExcerptSQL);
stmt.setString(1, excerpt);
stmt.setLong(2, postId);
return stmt.executeUpdate() > 0;
} finally {
ctx.stop();
SQLUtil.closeQuietly(conn, stmt);
}
} | [
"public",
"boolean",
"updatePostExcerpt",
"(",
"long",
"postId",
",",
"final",
"String",
"excerpt",
")",
"throws",
"SQLException",
"{",
"Connection",
"conn",
"=",
"null",
";",
"PreparedStatement",
"stmt",
"=",
"null",
";",
"Timer",
".",
"Context",
"ctx",
"=",
... | Updates the excerpt for a post.
@param postId The post to update.
@param excerpt The new excerpt.
@return Was the post modified?
@throws SQLException on database error or missing post id. | [
"Updates",
"the",
"excerpt",
"for",
"a",
"post",
"."
] | train | https://github.com/attribyte/wpdb/blob/b9adf6131dfb67899ebff770c9bfeb001cc42f30/src/main/java/org/attribyte/wp/db/DB.java#L1550-L1564 |
OpenTSDB/opentsdb | src/query/pojo/Validatable.java | Validatable.validatePOJO | <T extends Validatable> void validatePOJO(final T pojo, final String name) {
"""
Validate a single POJO validate
@param pojo The POJO object to validate
@param name name of the field
"""
try {
pojo.validate();
} catch (final IllegalArgumentException e) {
throw new IllegalArgumentException("Invalid " + name, e);
}
} | java | <T extends Validatable> void validatePOJO(final T pojo, final String name) {
try {
pojo.validate();
} catch (final IllegalArgumentException e) {
throw new IllegalArgumentException("Invalid " + name, e);
}
} | [
"<",
"T",
"extends",
"Validatable",
">",
"void",
"validatePOJO",
"(",
"final",
"T",
"pojo",
",",
"final",
"String",
"name",
")",
"{",
"try",
"{",
"pojo",
".",
"validate",
"(",
")",
";",
"}",
"catch",
"(",
"final",
"IllegalArgumentException",
"e",
")",
... | Validate a single POJO validate
@param pojo The POJO object to validate
@param name name of the field | [
"Validate",
"a",
"single",
"POJO",
"validate"
] | train | https://github.com/OpenTSDB/opentsdb/blob/3fc2d491c3c1ad397252c0a80203a69a3f9e3ef3/src/query/pojo/Validatable.java#L52-L58 |
basho/riak-java-client | src/main/java/com/basho/riak/client/api/RiakClient.java | RiakClient.newClient | public static RiakClient newClient(Collection<HostAndPort> hosts, RiakNode.Builder nodeBuilder) throws UnknownHostException {
"""
Static factory method to create a new client instance.
@since 2.0.6
"""
final RiakCluster cluster = new RiakCluster.Builder(hosts, nodeBuilder).build();
cluster.start();
return new RiakClient(cluster);
} | java | public static RiakClient newClient(Collection<HostAndPort> hosts, RiakNode.Builder nodeBuilder) throws UnknownHostException
{
final RiakCluster cluster = new RiakCluster.Builder(hosts, nodeBuilder).build();
cluster.start();
return new RiakClient(cluster);
} | [
"public",
"static",
"RiakClient",
"newClient",
"(",
"Collection",
"<",
"HostAndPort",
">",
"hosts",
",",
"RiakNode",
".",
"Builder",
"nodeBuilder",
")",
"throws",
"UnknownHostException",
"{",
"final",
"RiakCluster",
"cluster",
"=",
"new",
"RiakCluster",
".",
"Buil... | Static factory method to create a new client instance.
@since 2.0.6 | [
"Static",
"factory",
"method",
"to",
"create",
"a",
"new",
"client",
"instance",
"."
] | train | https://github.com/basho/riak-java-client/blob/bed6cd60f360bacf1b873ab92dd74f2526651e71/src/main/java/com/basho/riak/client/api/RiakClient.java#L318-L324 |
CodeNarc/CodeNarc | src/main/java/org/codenarc/rule/AbstractAstVisitorRule.java | AbstractAstVisitorRule.shouldApplyThisRuleTo | protected boolean shouldApplyThisRuleTo(ClassNode classNode) {
"""
Return true if this rule should be applied for the specified ClassNode, based on the
configuration of this rule.
@param classNode - the ClassNode
@return true if this rule should be applied for the specified ClassNode
"""
// TODO Consider caching applyTo, doNotApplyTo and associated WildcardPatterns
boolean shouldApply = true;
String applyTo = getApplyToClassNames();
String doNotApplyTo = getDoNotApplyToClassNames();
if (applyTo != null && applyTo.length() > 0) {
WildcardPattern pattern = new WildcardPattern(applyTo, true);
shouldApply = pattern.matches(classNode.getNameWithoutPackage()) || pattern.matches(classNode.getName());
}
if (shouldApply && doNotApplyTo != null && doNotApplyTo.length() > 0) {
WildcardPattern pattern = new WildcardPattern(doNotApplyTo, true);
shouldApply = !pattern.matches(classNode.getNameWithoutPackage()) && !pattern.matches(classNode.getName());
}
return shouldApply;
} | java | protected boolean shouldApplyThisRuleTo(ClassNode classNode) {
// TODO Consider caching applyTo, doNotApplyTo and associated WildcardPatterns
boolean shouldApply = true;
String applyTo = getApplyToClassNames();
String doNotApplyTo = getDoNotApplyToClassNames();
if (applyTo != null && applyTo.length() > 0) {
WildcardPattern pattern = new WildcardPattern(applyTo, true);
shouldApply = pattern.matches(classNode.getNameWithoutPackage()) || pattern.matches(classNode.getName());
}
if (shouldApply && doNotApplyTo != null && doNotApplyTo.length() > 0) {
WildcardPattern pattern = new WildcardPattern(doNotApplyTo, true);
shouldApply = !pattern.matches(classNode.getNameWithoutPackage()) && !pattern.matches(classNode.getName());
}
return shouldApply;
} | [
"protected",
"boolean",
"shouldApplyThisRuleTo",
"(",
"ClassNode",
"classNode",
")",
"{",
"// TODO Consider caching applyTo, doNotApplyTo and associated WildcardPatterns\r",
"boolean",
"shouldApply",
"=",
"true",
";",
"String",
"applyTo",
"=",
"getApplyToClassNames",
"(",
")",
... | Return true if this rule should be applied for the specified ClassNode, based on the
configuration of this rule.
@param classNode - the ClassNode
@return true if this rule should be applied for the specified ClassNode | [
"Return",
"true",
"if",
"this",
"rule",
"should",
"be",
"applied",
"for",
"the",
"specified",
"ClassNode",
"based",
"on",
"the",
"configuration",
"of",
"this",
"rule",
"."
] | train | https://github.com/CodeNarc/CodeNarc/blob/9a7cec02cb8cbaf845030f2434309e8968f5d7a7/src/main/java/org/codenarc/rule/AbstractAstVisitorRule.java#L121-L139 |
HolmesNL/kafka-spout | src/main/java/nl/minvenj/nfi/storm/kafka/util/ConfigUtils.java | ConfigUtils.getMaxBufSize | public static int getMaxBufSize(final Map<String, Object> stormConfig) {
"""
Retrieves the maximum buffer size to be used from storm's configuration map, or the
{@link #DEFAULT_BUFFER_MAX_MESSAGES} if no such value was found using {@link #CONFIG_BUFFER_MAX_MESSAGES}.
@param stormConfig Storm's configuration map.
@return The maximum buffer size to use.
"""
final Object value = stormConfig.get(CONFIG_BUFFER_MAX_MESSAGES);
if (value != null) {
try {
return Integer.parseInt(String.valueOf(value).trim());
}
catch (final NumberFormatException e) {
LOG.warn("invalid value for '{}' in storm config ({}); falling back to default ({})", CONFIG_BUFFER_MAX_MESSAGES, value, DEFAULT_BUFFER_MAX_MESSAGES);
}
}
return DEFAULT_BUFFER_MAX_MESSAGES;
} | java | public static int getMaxBufSize(final Map<String, Object> stormConfig) {
final Object value = stormConfig.get(CONFIG_BUFFER_MAX_MESSAGES);
if (value != null) {
try {
return Integer.parseInt(String.valueOf(value).trim());
}
catch (final NumberFormatException e) {
LOG.warn("invalid value for '{}' in storm config ({}); falling back to default ({})", CONFIG_BUFFER_MAX_MESSAGES, value, DEFAULT_BUFFER_MAX_MESSAGES);
}
}
return DEFAULT_BUFFER_MAX_MESSAGES;
} | [
"public",
"static",
"int",
"getMaxBufSize",
"(",
"final",
"Map",
"<",
"String",
",",
"Object",
">",
"stormConfig",
")",
"{",
"final",
"Object",
"value",
"=",
"stormConfig",
".",
"get",
"(",
"CONFIG_BUFFER_MAX_MESSAGES",
")",
";",
"if",
"(",
"value",
"!=",
... | Retrieves the maximum buffer size to be used from storm's configuration map, or the
{@link #DEFAULT_BUFFER_MAX_MESSAGES} if no such value was found using {@link #CONFIG_BUFFER_MAX_MESSAGES}.
@param stormConfig Storm's configuration map.
@return The maximum buffer size to use. | [
"Retrieves",
"the",
"maximum",
"buffer",
"size",
"to",
"be",
"used",
"from",
"storm",
"s",
"configuration",
"map",
"or",
"the",
"{",
"@link",
"#DEFAULT_BUFFER_MAX_MESSAGES",
"}",
"if",
"no",
"such",
"value",
"was",
"found",
"using",
"{",
"@link",
"#CONFIG_BUFF... | train | https://github.com/HolmesNL/kafka-spout/blob/bef626b9fab6946a7e0d3c85979ec36ae0870233/src/main/java/nl/minvenj/nfi/storm/kafka/util/ConfigUtils.java#L266-L278 |
line/centraldogma | server/src/main/java/com/linecorp/centraldogma/server/internal/api/HttpApiUtil.java | HttpApiUtil.newResponse | public static HttpResponse newResponse(RequestContext ctx, HttpStatus status,
String format, Object... args) {
"""
Returns a newly created {@link HttpResponse} with the specified {@link HttpStatus} and the formatted
message.
"""
requireNonNull(ctx, "ctx");
requireNonNull(status, "status");
requireNonNull(format, "format");
requireNonNull(args, "args");
return newResponse(ctx, status, String.format(Locale.ENGLISH, format, args));
} | java | public static HttpResponse newResponse(RequestContext ctx, HttpStatus status,
String format, Object... args) {
requireNonNull(ctx, "ctx");
requireNonNull(status, "status");
requireNonNull(format, "format");
requireNonNull(args, "args");
return newResponse(ctx, status, String.format(Locale.ENGLISH, format, args));
} | [
"public",
"static",
"HttpResponse",
"newResponse",
"(",
"RequestContext",
"ctx",
",",
"HttpStatus",
"status",
",",
"String",
"format",
",",
"Object",
"...",
"args",
")",
"{",
"requireNonNull",
"(",
"ctx",
",",
"\"ctx\"",
")",
";",
"requireNonNull",
"(",
"statu... | Returns a newly created {@link HttpResponse} with the specified {@link HttpStatus} and the formatted
message. | [
"Returns",
"a",
"newly",
"created",
"{"
] | train | https://github.com/line/centraldogma/blob/b9e46c67fbc26628c2186ce2f46e7fb303c831e9/server/src/main/java/com/linecorp/centraldogma/server/internal/api/HttpApiUtil.java#L103-L110 |
Azure/azure-sdk-for-java | redis/resource-manager/v2018_03_01/src/main/java/com/microsoft/azure/management/redis/v2018_03_01/implementation/PatchSchedulesInner.java | PatchSchedulesInner.getAsync | public Observable<RedisPatchScheduleInner> getAsync(String resourceGroupName, String name) {
"""
Gets the patching schedule of a redis cache (requires Premium SKU).
@param resourceGroupName The name of the resource group.
@param name The name of the redis cache.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the RedisPatchScheduleInner object
"""
return getWithServiceResponseAsync(resourceGroupName, name).map(new Func1<ServiceResponse<RedisPatchScheduleInner>, RedisPatchScheduleInner>() {
@Override
public RedisPatchScheduleInner call(ServiceResponse<RedisPatchScheduleInner> response) {
return response.body();
}
});
} | java | public Observable<RedisPatchScheduleInner> getAsync(String resourceGroupName, String name) {
return getWithServiceResponseAsync(resourceGroupName, name).map(new Func1<ServiceResponse<RedisPatchScheduleInner>, RedisPatchScheduleInner>() {
@Override
public RedisPatchScheduleInner call(ServiceResponse<RedisPatchScheduleInner> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"RedisPatchScheduleInner",
">",
"getAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"name",
")",
"{",
"return",
"getWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"name",
")",
".",
"map",
"(",
"new",
"Func1",
"<",... | Gets the patching schedule of a redis cache (requires Premium SKU).
@param resourceGroupName The name of the resource group.
@param name The name of the redis cache.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the RedisPatchScheduleInner object | [
"Gets",
"the",
"patching",
"schedule",
"of",
"a",
"redis",
"cache",
"(",
"requires",
"Premium",
"SKU",
")",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/redis/resource-manager/v2018_03_01/src/main/java/com/microsoft/azure/management/redis/v2018_03_01/implementation/PatchSchedulesInner.java#L431-L438 |
medined/d4m | src/main/java/com/codebits/d4m/TableManager.java | TableManager.addSplitsForSha1 | public void addSplitsForSha1() {
"""
Pre-split the Tedge and TedgeText tables.
Helpful when sha1 is used as row value.
"""
Validate.notNull(tableOperations, "tableOperations must not be null");
String hexadecimal = "123456789abcde";
SortedSet<Text> edgeSplits = new TreeSet<>();
SortedSet<Text> textSplits = new TreeSet<>();
Collection<Text> existingEdgeSplits = null;
Collection<Text> existingTextSplits = null;
try {
existingEdgeSplits = tableOperations.listSplits(getEdgeTable());
existingTextSplits = tableOperations.listSplits(getTextTable());
} catch (TableNotFoundException | AccumuloSecurityException | AccumuloException e) {
throw new D4MException("Error reading splits.", e);
}
for (byte b : hexadecimal.getBytes(charset)) {
Text splitPoint = new Text(new byte[]{b});
if (not(existingEdgeSplits.contains(splitPoint))) {
edgeSplits.add(splitPoint);
}
if (not(existingTextSplits.contains(splitPoint))) {
textSplits.add(splitPoint);
}
}
addSplits(getEdgeTable(), edgeSplits);
addSplits(getTextTable(), textSplits);
} | java | public void addSplitsForSha1() {
Validate.notNull(tableOperations, "tableOperations must not be null");
String hexadecimal = "123456789abcde";
SortedSet<Text> edgeSplits = new TreeSet<>();
SortedSet<Text> textSplits = new TreeSet<>();
Collection<Text> existingEdgeSplits = null;
Collection<Text> existingTextSplits = null;
try {
existingEdgeSplits = tableOperations.listSplits(getEdgeTable());
existingTextSplits = tableOperations.listSplits(getTextTable());
} catch (TableNotFoundException | AccumuloSecurityException | AccumuloException e) {
throw new D4MException("Error reading splits.", e);
}
for (byte b : hexadecimal.getBytes(charset)) {
Text splitPoint = new Text(new byte[]{b});
if (not(existingEdgeSplits.contains(splitPoint))) {
edgeSplits.add(splitPoint);
}
if (not(existingTextSplits.contains(splitPoint))) {
textSplits.add(splitPoint);
}
}
addSplits(getEdgeTable(), edgeSplits);
addSplits(getTextTable(), textSplits);
} | [
"public",
"void",
"addSplitsForSha1",
"(",
")",
"{",
"Validate",
".",
"notNull",
"(",
"tableOperations",
",",
"\"tableOperations must not be null\"",
")",
";",
"String",
"hexadecimal",
"=",
"\"123456789abcde\"",
";",
"SortedSet",
"<",
"Text",
">",
"edgeSplits",
"=",... | Pre-split the Tedge and TedgeText tables.
Helpful when sha1 is used as row value. | [
"Pre",
"-",
"split",
"the",
"Tedge",
"and",
"TedgeText",
"tables",
"."
] | train | https://github.com/medined/d4m/blob/b61100609fba6961f6c903fcf96b687122c5bf05/src/main/java/com/codebits/d4m/TableManager.java#L171-L198 |
nohana/Amalgam | amalgam/src/main/java/com/amalgam/app/SupportProgressDialogFragment.java | SupportProgressDialogFragment.newInstance | public static final SupportProgressDialogFragment newInstance(Context context, int title, int message, boolean indeterminate) {
"""
Create a new instance of the {@link com.amalgam.app.SupportProgressDialogFragment}.
@param context the context.
@param title the title text resource.
@param message the message text resource.
@param indeterminate indeterminate progress or not.
@return the instance of the {@link com.amalgam.app.SupportProgressDialogFragment}.
"""
return newInstance(context.getString(title), context.getString(message), indeterminate);
} | java | public static final SupportProgressDialogFragment newInstance(Context context, int title, int message, boolean indeterminate) {
return newInstance(context.getString(title), context.getString(message), indeterminate);
} | [
"public",
"static",
"final",
"SupportProgressDialogFragment",
"newInstance",
"(",
"Context",
"context",
",",
"int",
"title",
",",
"int",
"message",
",",
"boolean",
"indeterminate",
")",
"{",
"return",
"newInstance",
"(",
"context",
".",
"getString",
"(",
"title",
... | Create a new instance of the {@link com.amalgam.app.SupportProgressDialogFragment}.
@param context the context.
@param title the title text resource.
@param message the message text resource.
@param indeterminate indeterminate progress or not.
@return the instance of the {@link com.amalgam.app.SupportProgressDialogFragment}. | [
"Create",
"a",
"new",
"instance",
"of",
"the",
"{",
"@link",
"com",
".",
"amalgam",
".",
"app",
".",
"SupportProgressDialogFragment",
"}",
"."
] | train | https://github.com/nohana/Amalgam/blob/57809ddbfe7897e979cf507982ce0b3aa5e0ed8a/amalgam/src/main/java/com/amalgam/app/SupportProgressDialogFragment.java#L51-L53 |
samskivert/samskivert | src/main/java/com/samskivert/util/DebugChords.java | DebugChords.registerHook | public static void registerHook (int modifierMask, int keyCode, Hook hook) {
"""
Registers the supplied debug hook to be invoked when the specified
key combination is depressed.
@param modifierMask a mask with bits on for all modifiers that must
be present when the specified key code is received (e.g. {@link
KeyEvent#CTRL_DOWN_MASK}|{@link KeyEvent#ALT_DOWN_MASK}).
@param keyCode the code that identifies the normal key that must be
pressed to activate the hook (e.g. {@link KeyEvent#VK_E}).
@param hook the hook to be invoked when the specified key
combination is received.
"""
// store the hooks mapped by key code
ArrayList<Tuple<Integer,Hook>> list = _bindings.get(keyCode);
if (list == null) {
list = new ArrayList<Tuple<Integer,Hook>>();
_bindings.put(keyCode, list);
}
// append the hook and modifier mask to the list
list.add(new Tuple<Integer,Hook>(modifierMask, hook));
} | java | public static void registerHook (int modifierMask, int keyCode, Hook hook)
{
// store the hooks mapped by key code
ArrayList<Tuple<Integer,Hook>> list = _bindings.get(keyCode);
if (list == null) {
list = new ArrayList<Tuple<Integer,Hook>>();
_bindings.put(keyCode, list);
}
// append the hook and modifier mask to the list
list.add(new Tuple<Integer,Hook>(modifierMask, hook));
} | [
"public",
"static",
"void",
"registerHook",
"(",
"int",
"modifierMask",
",",
"int",
"keyCode",
",",
"Hook",
"hook",
")",
"{",
"// store the hooks mapped by key code",
"ArrayList",
"<",
"Tuple",
"<",
"Integer",
",",
"Hook",
">",
">",
"list",
"=",
"_bindings",
"... | Registers the supplied debug hook to be invoked when the specified
key combination is depressed.
@param modifierMask a mask with bits on for all modifiers that must
be present when the specified key code is received (e.g. {@link
KeyEvent#CTRL_DOWN_MASK}|{@link KeyEvent#ALT_DOWN_MASK}).
@param keyCode the code that identifies the normal key that must be
pressed to activate the hook (e.g. {@link KeyEvent#VK_E}).
@param hook the hook to be invoked when the specified key
combination is received. | [
"Registers",
"the",
"supplied",
"debug",
"hook",
"to",
"be",
"invoked",
"when",
"the",
"specified",
"key",
"combination",
"is",
"depressed",
"."
] | train | https://github.com/samskivert/samskivert/blob/a64d9ef42b69819bdb2c66bddac6a64caef928b6/src/main/java/com/samskivert/util/DebugChords.java#L72-L83 |
molgenis/molgenis | molgenis-data-index/src/main/java/org/molgenis/data/index/job/IndexJobService.java | IndexJobService.rebuildIndexOneEntity | private void rebuildIndexOneEntity(String entityTypeId, String untypedEntityId) {
"""
Indexes one single entity instance.
@param entityTypeId the id of the entity's repository
@param untypedEntityId the identifier of the entity to update
"""
LOG.trace("Indexing [{}].[{}]... ", entityTypeId, untypedEntityId);
// convert entity id string to typed entity id
EntityType entityType = dataService.getEntityType(entityTypeId);
if (null != entityType) {
Object entityId = getTypedValue(untypedEntityId, entityType.getIdAttribute());
String entityFullName = entityType.getId();
Entity actualEntity = dataService.findOneById(entityFullName, entityId);
if (null == actualEntity) {
// Delete
LOG.debug("Index delete [{}].[{}].", entityFullName, entityId);
indexService.deleteById(entityType, entityId);
return;
}
boolean indexEntityExists = indexService.hasIndex(entityType);
if (!indexEntityExists) {
LOG.debug("Create mapping of repository [{}] because it was not exist yet", entityTypeId);
indexService.createIndex(entityType);
}
LOG.debug("Index [{}].[{}].", entityTypeId, entityId);
indexService.index(actualEntity.getEntityType(), actualEntity);
} else {
throw new MolgenisDataException("Unknown EntityType for entityTypeId: " + entityTypeId);
}
} | java | private void rebuildIndexOneEntity(String entityTypeId, String untypedEntityId) {
LOG.trace("Indexing [{}].[{}]... ", entityTypeId, untypedEntityId);
// convert entity id string to typed entity id
EntityType entityType = dataService.getEntityType(entityTypeId);
if (null != entityType) {
Object entityId = getTypedValue(untypedEntityId, entityType.getIdAttribute());
String entityFullName = entityType.getId();
Entity actualEntity = dataService.findOneById(entityFullName, entityId);
if (null == actualEntity) {
// Delete
LOG.debug("Index delete [{}].[{}].", entityFullName, entityId);
indexService.deleteById(entityType, entityId);
return;
}
boolean indexEntityExists = indexService.hasIndex(entityType);
if (!indexEntityExists) {
LOG.debug("Create mapping of repository [{}] because it was not exist yet", entityTypeId);
indexService.createIndex(entityType);
}
LOG.debug("Index [{}].[{}].", entityTypeId, entityId);
indexService.index(actualEntity.getEntityType(), actualEntity);
} else {
throw new MolgenisDataException("Unknown EntityType for entityTypeId: " + entityTypeId);
}
} | [
"private",
"void",
"rebuildIndexOneEntity",
"(",
"String",
"entityTypeId",
",",
"String",
"untypedEntityId",
")",
"{",
"LOG",
".",
"trace",
"(",
"\"Indexing [{}].[{}]... \"",
",",
"entityTypeId",
",",
"untypedEntityId",
")",
";",
"// convert entity id string to typed enti... | Indexes one single entity instance.
@param entityTypeId the id of the entity's repository
@param untypedEntityId the identifier of the entity to update | [
"Indexes",
"one",
"single",
"entity",
"instance",
"."
] | train | https://github.com/molgenis/molgenis/blob/b4d0d6b27e6f6c8d7505a3863dc03b589601f987/molgenis-data-index/src/main/java/org/molgenis/data/index/job/IndexJobService.java#L165-L194 |
jmrozanec/cron-utils | src/main/java/com/cronutils/descriptor/DescriptionStrategyFactory.java | DescriptionStrategyFactory.daysOfMonthInstance | public static DescriptionStrategy daysOfMonthInstance(final ResourceBundle bundle, final FieldExpression expression) {
"""
Creates description strategy for days of month.
@param bundle - locale
@param expression - CronFieldExpression
@return - DescriptionStrategy instance, never null
"""
final NominalDescriptionStrategy dom = new NominalDescriptionStrategy(bundle, null, expression);
dom.addDescription(fieldExpression -> {
if (fieldExpression instanceof On) {
final On on = (On) fieldExpression;
switch (on.getSpecialChar().getValue()) {
case W:
return String
.format("%s %s %s ", bundle.getString("the_nearest_weekday_to_the"), on.getTime().getValue(), bundle.getString("of_the_month"));
case L:
return bundle.getString("last_day_of_month");
case LW:
return bundle.getString("last_weekday_of_month");
default:
return "";
}
}
return "";
});
return dom;
} | java | public static DescriptionStrategy daysOfMonthInstance(final ResourceBundle bundle, final FieldExpression expression) {
final NominalDescriptionStrategy dom = new NominalDescriptionStrategy(bundle, null, expression);
dom.addDescription(fieldExpression -> {
if (fieldExpression instanceof On) {
final On on = (On) fieldExpression;
switch (on.getSpecialChar().getValue()) {
case W:
return String
.format("%s %s %s ", bundle.getString("the_nearest_weekday_to_the"), on.getTime().getValue(), bundle.getString("of_the_month"));
case L:
return bundle.getString("last_day_of_month");
case LW:
return bundle.getString("last_weekday_of_month");
default:
return "";
}
}
return "";
});
return dom;
} | [
"public",
"static",
"DescriptionStrategy",
"daysOfMonthInstance",
"(",
"final",
"ResourceBundle",
"bundle",
",",
"final",
"FieldExpression",
"expression",
")",
"{",
"final",
"NominalDescriptionStrategy",
"dom",
"=",
"new",
"NominalDescriptionStrategy",
"(",
"bundle",
",",... | Creates description strategy for days of month.
@param bundle - locale
@param expression - CronFieldExpression
@return - DescriptionStrategy instance, never null | [
"Creates",
"description",
"strategy",
"for",
"days",
"of",
"month",
"."
] | train | https://github.com/jmrozanec/cron-utils/blob/adac5ec8fd9160b082f9762a6eedea0715731170/src/main/java/com/cronutils/descriptor/DescriptionStrategyFactory.java#L74-L95 |
sai-pullabhotla/catatumbo | src/main/java/com/jmethods/catatumbo/impl/DefaultDatastoreReader.java | DefaultDatastoreReader.loadById | public <E> List<E> loadById(Class<E> entityClass, List<Long> identifiers) {
"""
Loads and returns the entities with the given <b>numeric IDs</b>. The entities are assumed to
be a root entities (no parent). The entity kind is determined from the supplied class.
@param entityClass
the entity class
@param identifiers
the IDs of the entities
@return the list of entity objects in the same order as the given list of identifiers. If one
or more requested IDs do not exist in the Cloud Datastore, the corresponding item in
the returned list be <code>null</code>.
@throws EntityManagerException
if any error occurs while inserting.
"""
Key[] nativeKeys = longListToNativeKeys(entityClass, identifiers);
return fetch(entityClass, nativeKeys);
} | java | public <E> List<E> loadById(Class<E> entityClass, List<Long> identifiers) {
Key[] nativeKeys = longListToNativeKeys(entityClass, identifiers);
return fetch(entityClass, nativeKeys);
} | [
"public",
"<",
"E",
">",
"List",
"<",
"E",
">",
"loadById",
"(",
"Class",
"<",
"E",
">",
"entityClass",
",",
"List",
"<",
"Long",
">",
"identifiers",
")",
"{",
"Key",
"[",
"]",
"nativeKeys",
"=",
"longListToNativeKeys",
"(",
"entityClass",
",",
"identi... | Loads and returns the entities with the given <b>numeric IDs</b>. The entities are assumed to
be a root entities (no parent). The entity kind is determined from the supplied class.
@param entityClass
the entity class
@param identifiers
the IDs of the entities
@return the list of entity objects in the same order as the given list of identifiers. If one
or more requested IDs do not exist in the Cloud Datastore, the corresponding item in
the returned list be <code>null</code>.
@throws EntityManagerException
if any error occurs while inserting. | [
"Loads",
"and",
"returns",
"the",
"entities",
"with",
"the",
"given",
"<b",
">",
"numeric",
"IDs<",
"/",
"b",
">",
".",
"The",
"entities",
"are",
"assumed",
"to",
"be",
"a",
"root",
"entities",
"(",
"no",
"parent",
")",
".",
"The",
"entity",
"kind",
... | train | https://github.com/sai-pullabhotla/catatumbo/blob/96d4c6dce3a5009624f7112a398406914dd19165/src/main/java/com/jmethods/catatumbo/impl/DefaultDatastoreReader.java#L209-L212 |
jpelzer/pelzer-util | src/main/java/com/pelzer/util/StringMan.java | StringMan.areStringsEqual | public static boolean areStringsEqual(String s1, String s2) {
"""
null-safe string equality test. If both s1 and s2 are null, returns true.
"""
return s1 != null && s1.equals(s2) || s1 == null && s2 == null;
} | java | public static boolean areStringsEqual(String s1, String s2) {
return s1 != null && s1.equals(s2) || s1 == null && s2 == null;
} | [
"public",
"static",
"boolean",
"areStringsEqual",
"(",
"String",
"s1",
",",
"String",
"s2",
")",
"{",
"return",
"s1",
"!=",
"null",
"&&",
"s1",
".",
"equals",
"(",
"s2",
")",
"||",
"s1",
"==",
"null",
"&&",
"s2",
"==",
"null",
";",
"}"
] | null-safe string equality test. If both s1 and s2 are null, returns true. | [
"null",
"-",
"safe",
"string",
"equality",
"test",
".",
"If",
"both",
"s1",
"and",
"s2",
"are",
"null",
"returns",
"true",
"."
] | train | https://github.com/jpelzer/pelzer-util/blob/ec14f2573fd977d1442dba5d1507a264f5ea9aa6/src/main/java/com/pelzer/util/StringMan.java#L471-L473 |
hyperledger/fabric-sdk-java | src/main/java/org/hyperledger/fabric/sdk/Channel.java | Channel.sendInstallProposal | Collection<ProposalResponse> sendInstallProposal(InstallProposalRequest installProposalRequest)
throws ProposalException, InvalidArgumentException {
"""
Send install chaincode request proposal to all the channels on the peer.
@param installProposalRequest
@return
@throws ProposalException
@throws InvalidArgumentException
"""
return sendInstallProposal(installProposalRequest, getChaincodePeers());
} | java | Collection<ProposalResponse> sendInstallProposal(InstallProposalRequest installProposalRequest)
throws ProposalException, InvalidArgumentException {
return sendInstallProposal(installProposalRequest, getChaincodePeers());
} | [
"Collection",
"<",
"ProposalResponse",
">",
"sendInstallProposal",
"(",
"InstallProposalRequest",
"installProposalRequest",
")",
"throws",
"ProposalException",
",",
"InvalidArgumentException",
"{",
"return",
"sendInstallProposal",
"(",
"installProposalRequest",
",",
"getChainco... | Send install chaincode request proposal to all the channels on the peer.
@param installProposalRequest
@return
@throws ProposalException
@throws InvalidArgumentException | [
"Send",
"install",
"chaincode",
"request",
"proposal",
"to",
"all",
"the",
"channels",
"on",
"the",
"peer",
"."
] | train | https://github.com/hyperledger/fabric-sdk-java/blob/4a2d7b3408b8b0a1ed812aa36942c438159c37a0/src/main/java/org/hyperledger/fabric/sdk/Channel.java#L2512-L2516 |
sarl/sarl | docs/io.sarl.docs.doclet/src/main/java/io/sarl/docs/doclet/references/SarlLinkFactory.java | SarlLinkFactory.updateLinkLabel | protected void updateLinkLabel(LinkInfo linkInfo) {
"""
Update the label of the given link with the SARL notation for lambdas.
@param linkInfo the link information to update.
"""
if (linkInfo.type != null && linkInfo instanceof LinkInfoImpl) {
final LinkInfoImpl impl = (LinkInfoImpl) linkInfo;
final ClassDoc classdoc = linkInfo.type.asClassDoc();
if (classdoc != null) {
final SARLFeatureAccess kw = Utils.getKeywords();
final String name = classdoc.qualifiedName();
if (isPrefix(name, kw.getProceduresName())) {
linkInfo.label = createProcedureLambdaLabel(impl);
} else if (isPrefix(name, kw.getFunctionsName())) {
linkInfo.label = createFunctionLambdaLabel(impl);
}
}
}
} | java | protected void updateLinkLabel(LinkInfo linkInfo) {
if (linkInfo.type != null && linkInfo instanceof LinkInfoImpl) {
final LinkInfoImpl impl = (LinkInfoImpl) linkInfo;
final ClassDoc classdoc = linkInfo.type.asClassDoc();
if (classdoc != null) {
final SARLFeatureAccess kw = Utils.getKeywords();
final String name = classdoc.qualifiedName();
if (isPrefix(name, kw.getProceduresName())) {
linkInfo.label = createProcedureLambdaLabel(impl);
} else if (isPrefix(name, kw.getFunctionsName())) {
linkInfo.label = createFunctionLambdaLabel(impl);
}
}
}
} | [
"protected",
"void",
"updateLinkLabel",
"(",
"LinkInfo",
"linkInfo",
")",
"{",
"if",
"(",
"linkInfo",
".",
"type",
"!=",
"null",
"&&",
"linkInfo",
"instanceof",
"LinkInfoImpl",
")",
"{",
"final",
"LinkInfoImpl",
"impl",
"=",
"(",
"LinkInfoImpl",
")",
"linkInfo... | Update the label of the given link with the SARL notation for lambdas.
@param linkInfo the link information to update. | [
"Update",
"the",
"label",
"of",
"the",
"given",
"link",
"with",
"the",
"SARL",
"notation",
"for",
"lambdas",
"."
] | train | https://github.com/sarl/sarl/blob/ca00ff994598c730339972def4e19a60e0b8cace/docs/io.sarl.docs.doclet/src/main/java/io/sarl/docs/doclet/references/SarlLinkFactory.java#L243-L257 |
JoeKerouac/utils | src/main/java/com/joe/utils/reflect/BeanUtils.java | BeanUtils.getName | private static String getName(JsonProperty jsonProperty, XmlNode xmlNode, Field field) {
"""
从注解获取字段名字,优先使用{@link JsonProperty JsonProperty}
@param jsonProperty json注解
@param xmlNode xml注解
@param field 字段
@return 字段名
"""
String name;
if (jsonProperty != null) {
name = jsonProperty.value();
} else if (xmlNode != null) {
name = xmlNode.name();
} else {
name = field.getName();
}
return name;
} | java | private static String getName(JsonProperty jsonProperty, XmlNode xmlNode, Field field) {
String name;
if (jsonProperty != null) {
name = jsonProperty.value();
} else if (xmlNode != null) {
name = xmlNode.name();
} else {
name = field.getName();
}
return name;
} | [
"private",
"static",
"String",
"getName",
"(",
"JsonProperty",
"jsonProperty",
",",
"XmlNode",
"xmlNode",
",",
"Field",
"field",
")",
"{",
"String",
"name",
";",
"if",
"(",
"jsonProperty",
"!=",
"null",
")",
"{",
"name",
"=",
"jsonProperty",
".",
"value",
... | 从注解获取字段名字,优先使用{@link JsonProperty JsonProperty}
@param jsonProperty json注解
@param xmlNode xml注解
@param field 字段
@return 字段名 | [
"从注解获取字段名字,优先使用",
"{",
"@link",
"JsonProperty",
"JsonProperty",
"}"
] | train | https://github.com/JoeKerouac/utils/blob/45e1b2dc4d736956674fc4dcbe6cf84eaee69278/src/main/java/com/joe/utils/reflect/BeanUtils.java#L380-L390 |
lookfirst/WePay-Java-SDK | src/main/java/com/lookfirst/wepay/WePayApi.java | WePayApi.getToken | public Token getToken(String code, String redirectUrl) throws IOException, WePayException {
"""
Exchange a temporary access code for a (semi-)permanent access token
@param code 'code' field from query string passed to your redirect_uri page
@param redirectUrl Where user went after logging in at WePay (must match value from getAuthorizationUri)
@return json {"user_id":"123456","access_token":"1337h4x0rzabcd12345","token_type":"BEARER"}
"""
TokenRequest request = new TokenRequest();
request.setClientId(key.getClientId());
request.setClientSecret(key.getClientSecret());
request.setRedirectUri(redirectUrl);
request.setCode(code);
return execute(null, request);
} | java | public Token getToken(String code, String redirectUrl) throws IOException, WePayException {
TokenRequest request = new TokenRequest();
request.setClientId(key.getClientId());
request.setClientSecret(key.getClientSecret());
request.setRedirectUri(redirectUrl);
request.setCode(code);
return execute(null, request);
} | [
"public",
"Token",
"getToken",
"(",
"String",
"code",
",",
"String",
"redirectUrl",
")",
"throws",
"IOException",
",",
"WePayException",
"{",
"TokenRequest",
"request",
"=",
"new",
"TokenRequest",
"(",
")",
";",
"request",
".",
"setClientId",
"(",
"key",
".",
... | Exchange a temporary access code for a (semi-)permanent access token
@param code 'code' field from query string passed to your redirect_uri page
@param redirectUrl Where user went after logging in at WePay (must match value from getAuthorizationUri)
@return json {"user_id":"123456","access_token":"1337h4x0rzabcd12345","token_type":"BEARER"} | [
"Exchange",
"a",
"temporary",
"access",
"code",
"for",
"a",
"(",
"semi",
"-",
")",
"permanent",
"access",
"token"
] | train | https://github.com/lookfirst/WePay-Java-SDK/blob/3c0a47d6fa051d531c8fdbbfd54a0ef2891aa8f0/src/main/java/com/lookfirst/wepay/WePayApi.java#L199-L208 |
openbase/jul | exception/src/main/java/org/openbase/jul/exception/printer/ExceptionPrinter.java | ExceptionPrinter.printVerboseMessage | public static void printVerboseMessage(final String message, final Logger logger) {
"""
Method prints the given message only in verbose mode on the INFO channel, otherwise the DEBUG channel is used for printing.
@param message the message to print
@param logger the logger which is used for the message logging.
"""
try {
if (JPService.getProperty(JPVerbose.class).getValue()) {
logger.info(message);
} else {
logger.debug(message);
}
} catch (final JPServiceException ex) {
logger.info(message);
ExceptionPrinter.printHistory("Could not access verbose java property!", ex, logger);
}
} | java | public static void printVerboseMessage(final String message, final Logger logger) {
try {
if (JPService.getProperty(JPVerbose.class).getValue()) {
logger.info(message);
} else {
logger.debug(message);
}
} catch (final JPServiceException ex) {
logger.info(message);
ExceptionPrinter.printHistory("Could not access verbose java property!", ex, logger);
}
} | [
"public",
"static",
"void",
"printVerboseMessage",
"(",
"final",
"String",
"message",
",",
"final",
"Logger",
"logger",
")",
"{",
"try",
"{",
"if",
"(",
"JPService",
".",
"getProperty",
"(",
"JPVerbose",
".",
"class",
")",
".",
"getValue",
"(",
")",
")",
... | Method prints the given message only in verbose mode on the INFO channel, otherwise the DEBUG channel is used for printing.
@param message the message to print
@param logger the logger which is used for the message logging. | [
"Method",
"prints",
"the",
"given",
"message",
"only",
"in",
"verbose",
"mode",
"on",
"the",
"INFO",
"channel",
"otherwise",
"the",
"DEBUG",
"channel",
"is",
"used",
"for",
"printing",
"."
] | train | https://github.com/openbase/jul/blob/662e98c3a853085e475be54c3be3deb72193c72d/exception/src/main/java/org/openbase/jul/exception/printer/ExceptionPrinter.java#L438-L449 |
apache/groovy | src/main/java/org/codehaus/groovy/runtime/memoize/ConcurrentCommonCache.java | ConcurrentCommonCache.doWithReadLock | private <R> R doWithReadLock(Action<K, V, R> action) {
"""
deal with the backed cache guarded by read lock
@param action the content to complete
"""
readLock.lock();
try {
return action.doWith(commonCache);
} finally {
readLock.unlock();
}
} | java | private <R> R doWithReadLock(Action<K, V, R> action) {
readLock.lock();
try {
return action.doWith(commonCache);
} finally {
readLock.unlock();
}
} | [
"private",
"<",
"R",
">",
"R",
"doWithReadLock",
"(",
"Action",
"<",
"K",
",",
"V",
",",
"R",
">",
"action",
")",
"{",
"readLock",
".",
"lock",
"(",
")",
";",
"try",
"{",
"return",
"action",
".",
"doWith",
"(",
"commonCache",
")",
";",
"}",
"fina... | deal with the backed cache guarded by read lock
@param action the content to complete | [
"deal",
"with",
"the",
"backed",
"cache",
"guarded",
"by",
"read",
"lock"
] | train | https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/codehaus/groovy/runtime/memoize/ConcurrentCommonCache.java#L260-L267 |
alkacon/opencms-core | src/org/opencms/file/CmsObject.java | CmsObject.readAncestor | public CmsFolder readAncestor(String resourcename, CmsResourceFilter filter) throws CmsException {
"""
Returns the first ancestor folder matching the filter criteria.<p>
If no folder matching the filter criteria is found, null is returned.<p>
@param resourcename the name of the resource to start (full current site relative path)
@param filter the resource filter to match while reading the ancestors
@return the first ancestor folder matching the filter criteria or null if no folder was found
@throws CmsException if something goes wrong
"""
CmsResource resource = readResource(resourcename, CmsResourceFilter.ALL);
return m_securityManager.readAncestor(m_context, resource, filter);
} | java | public CmsFolder readAncestor(String resourcename, CmsResourceFilter filter) throws CmsException {
CmsResource resource = readResource(resourcename, CmsResourceFilter.ALL);
return m_securityManager.readAncestor(m_context, resource, filter);
} | [
"public",
"CmsFolder",
"readAncestor",
"(",
"String",
"resourcename",
",",
"CmsResourceFilter",
"filter",
")",
"throws",
"CmsException",
"{",
"CmsResource",
"resource",
"=",
"readResource",
"(",
"resourcename",
",",
"CmsResourceFilter",
".",
"ALL",
")",
";",
"return... | Returns the first ancestor folder matching the filter criteria.<p>
If no folder matching the filter criteria is found, null is returned.<p>
@param resourcename the name of the resource to start (full current site relative path)
@param filter the resource filter to match while reading the ancestors
@return the first ancestor folder matching the filter criteria or null if no folder was found
@throws CmsException if something goes wrong | [
"Returns",
"the",
"first",
"ancestor",
"folder",
"matching",
"the",
"filter",
"criteria",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/file/CmsObject.java#L2325-L2329 |
elki-project/elki | addons/batikvis/src/main/java/de/lmu/ifi/dbs/elki/visualization/gui/detail/DetailView.java | DetailView.addBackground | private void addBackground(VisualizerContext context) {
"""
Create a background node. Note: don't call this at arbitrary times - the
background may cover already drawn parts of the image!
@param context
"""
// Make a background
CSSClass cls = new CSSClass(this, "background");
cls.setStatement(SVGConstants.CSS_FILL_PROPERTY, context.getStyleLibrary().getBackgroundColor(StyleLibrary.PAGE));
addCSSClassOrLogError(cls);
Element bg = this.svgElement(SVGConstants.SVG_RECT_TAG, cls.getName());
SVGUtil.setAtt(bg, SVGConstants.SVG_X_ATTRIBUTE, "0");
SVGUtil.setAtt(bg, SVGConstants.SVG_Y_ATTRIBUTE, "0");
SVGUtil.setAtt(bg, SVGConstants.SVG_WIDTH_ATTRIBUTE, "100%");
SVGUtil.setAtt(bg, SVGConstants.SVG_HEIGHT_ATTRIBUTE, "100%");
SVGUtil.setAtt(bg, NO_EXPORT_ATTRIBUTE, NO_EXPORT_ATTRIBUTE);
// Note that we rely on this being called before any other drawing routines.
getRoot().appendChild(bg);
} | java | private void addBackground(VisualizerContext context) {
// Make a background
CSSClass cls = new CSSClass(this, "background");
cls.setStatement(SVGConstants.CSS_FILL_PROPERTY, context.getStyleLibrary().getBackgroundColor(StyleLibrary.PAGE));
addCSSClassOrLogError(cls);
Element bg = this.svgElement(SVGConstants.SVG_RECT_TAG, cls.getName());
SVGUtil.setAtt(bg, SVGConstants.SVG_X_ATTRIBUTE, "0");
SVGUtil.setAtt(bg, SVGConstants.SVG_Y_ATTRIBUTE, "0");
SVGUtil.setAtt(bg, SVGConstants.SVG_WIDTH_ATTRIBUTE, "100%");
SVGUtil.setAtt(bg, SVGConstants.SVG_HEIGHT_ATTRIBUTE, "100%");
SVGUtil.setAtt(bg, NO_EXPORT_ATTRIBUTE, NO_EXPORT_ATTRIBUTE);
// Note that we rely on this being called before any other drawing routines.
getRoot().appendChild(bg);
} | [
"private",
"void",
"addBackground",
"(",
"VisualizerContext",
"context",
")",
"{",
"// Make a background",
"CSSClass",
"cls",
"=",
"new",
"CSSClass",
"(",
"this",
",",
"\"background\"",
")",
";",
"cls",
".",
"setStatement",
"(",
"SVGConstants",
".",
"CSS_FILL_PROP... | Create a background node. Note: don't call this at arbitrary times - the
background may cover already drawn parts of the image!
@param context | [
"Create",
"a",
"background",
"node",
".",
"Note",
":",
"don",
"t",
"call",
"this",
"at",
"arbitrary",
"times",
"-",
"the",
"background",
"may",
"cover",
"already",
"drawn",
"parts",
"of",
"the",
"image!"
] | train | https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/addons/batikvis/src/main/java/de/lmu/ifi/dbs/elki/visualization/gui/detail/DetailView.java#L134-L148 |
Azure/azure-sdk-for-java | cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/ModelsImpl.java | ModelsImpl.getEntitySuggestionsWithServiceResponseAsync | public Observable<ServiceResponse<List<EntitiesSuggestionExample>>> getEntitySuggestionsWithServiceResponseAsync(UUID appId, String versionId, UUID entityId, GetEntitySuggestionsOptionalParameter getEntitySuggestionsOptionalParameter) {
"""
Get suggestion examples that would improve the accuracy of the entity model.
@param appId The application ID.
@param versionId The version ID.
@param entityId The target entity extractor model to enhance.
@param getEntitySuggestionsOptionalParameter 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<EntitiesSuggestionExample> 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.");
}
if (entityId == null) {
throw new IllegalArgumentException("Parameter entityId is required and cannot be null.");
}
final Integer take = getEntitySuggestionsOptionalParameter != null ? getEntitySuggestionsOptionalParameter.take() : null;
return getEntitySuggestionsWithServiceResponseAsync(appId, versionId, entityId, take);
} | java | public Observable<ServiceResponse<List<EntitiesSuggestionExample>>> getEntitySuggestionsWithServiceResponseAsync(UUID appId, String versionId, UUID entityId, GetEntitySuggestionsOptionalParameter getEntitySuggestionsOptionalParameter) {
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.");
}
if (entityId == null) {
throw new IllegalArgumentException("Parameter entityId is required and cannot be null.");
}
final Integer take = getEntitySuggestionsOptionalParameter != null ? getEntitySuggestionsOptionalParameter.take() : null;
return getEntitySuggestionsWithServiceResponseAsync(appId, versionId, entityId, take);
} | [
"public",
"Observable",
"<",
"ServiceResponse",
"<",
"List",
"<",
"EntitiesSuggestionExample",
">",
">",
">",
"getEntitySuggestionsWithServiceResponseAsync",
"(",
"UUID",
"appId",
",",
"String",
"versionId",
",",
"UUID",
"entityId",
",",
"GetEntitySuggestionsOptionalParam... | Get suggestion examples that would improve the accuracy of the entity model.
@param appId The application ID.
@param versionId The version ID.
@param entityId The target entity extractor model to enhance.
@param getEntitySuggestionsOptionalParameter 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<EntitiesSuggestionExample> object | [
"Get",
"suggestion",
"examples",
"that",
"would",
"improve",
"the",
"accuracy",
"of",
"the",
"entity",
"model",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/ModelsImpl.java#L5306-L5322 |
hdbeukel/james-core | src/main/java/org/jamesframework/core/search/algo/tabu/FullTabuMemory.java | FullTabuMemory.registerVisitedSolution | @Override
public void registerVisitedSolution(SolutionType visitedSolution, Move<? super SolutionType> appliedMove) {
"""
A newly visited solution is registered by storing a deep copy of this solution in the full tabu memory.
@param visitedSolution newly visited solution (copied to memory)
@param appliedMove applied move (not used here, allowed to be <code>null</code>)
"""
// store deep copy of newly visited solution
memory.add(Solution.checkedCopy(visitedSolution));
} | java | @Override
public void registerVisitedSolution(SolutionType visitedSolution, Move<? super SolutionType> appliedMove) {
// store deep copy of newly visited solution
memory.add(Solution.checkedCopy(visitedSolution));
} | [
"@",
"Override",
"public",
"void",
"registerVisitedSolution",
"(",
"SolutionType",
"visitedSolution",
",",
"Move",
"<",
"?",
"super",
"SolutionType",
">",
"appliedMove",
")",
"{",
"// store deep copy of newly visited solution",
"memory",
".",
"add",
"(",
"Solution",
"... | A newly visited solution is registered by storing a deep copy of this solution in the full tabu memory.
@param visitedSolution newly visited solution (copied to memory)
@param appliedMove applied move (not used here, allowed to be <code>null</code>) | [
"A",
"newly",
"visited",
"solution",
"is",
"registered",
"by",
"storing",
"a",
"deep",
"copy",
"of",
"this",
"solution",
"in",
"the",
"full",
"tabu",
"memory",
"."
] | train | https://github.com/hdbeukel/james-core/blob/4e85c20c142902373e5b5e8b5d12a2558650f66d/src/main/java/org/jamesframework/core/search/algo/tabu/FullTabuMemory.java#L85-L89 |
PeterisP/LVTagger | src/main/java/edu/stanford/nlp/util/Timing.java | Timing.endTime | public static long endTime(String str, PrintStream stream) {
"""
Print elapsed time on (static) timer (without stopping timer).
@param str Additional prefix string to be printed
@param stream PrintStream on which to write output
@return Number of milliseconds elapsed
"""
long elapsed = endTime();
stream.println(str + " Time elapsed: " + (elapsed) + " ms");
return elapsed;
} | java | public static long endTime(String str, PrintStream stream) {
long elapsed = endTime();
stream.println(str + " Time elapsed: " + (elapsed) + " ms");
return elapsed;
} | [
"public",
"static",
"long",
"endTime",
"(",
"String",
"str",
",",
"PrintStream",
"stream",
")",
"{",
"long",
"elapsed",
"=",
"endTime",
"(",
")",
";",
"stream",
".",
"println",
"(",
"str",
"+",
"\" Time elapsed: \"",
"+",
"(",
"elapsed",
")",
"+",
"\" ms... | Print elapsed time on (static) timer (without stopping timer).
@param str Additional prefix string to be printed
@param stream PrintStream on which to write output
@return Number of milliseconds elapsed | [
"Print",
"elapsed",
"time",
"on",
"(",
"static",
")",
"timer",
"(",
"without",
"stopping",
"timer",
")",
"."
] | train | https://github.com/PeterisP/LVTagger/blob/b3d44bab9ec07ace0d13612c448a6b7298c1f681/src/main/java/edu/stanford/nlp/util/Timing.java#L227-L231 |
kkopacz/agiso-core | bundles/agiso-core-lang/src/main/java/org/agiso/core/lang/util/DateUtils.java | DateUtils.getRandomDate | public static Date getRandomDate(Date begin, Date end, Random random) {
"""
Pobiera pseudolosową datę z okreslonego przedziału czasowego do generacji
której wykorzystany zostanie przekazany generator. Data generowana jest
z dokładnością (ziarnem) wynoszącym 1ms (tj. 1 w reprezentacji daty w formie
liczyby typu <code>long</code>).
@param begin Data początkowa przedziału (włączona do zbioru wynikowego).
@param end Data końcowa przedziału (wyłączona ze zbioru wynikowego).
@param random Generator pseudolosowy wykorzystywany do pozyskania daty.
@return Losowo wygenerowana data z przedziału [begin; end).
"""
long delay = end.getTime() - begin.getTime();
return new Date(begin.getTime() + (Math.abs(random.nextLong() % delay)));
} | java | public static Date getRandomDate(Date begin, Date end, Random random) {
long delay = end.getTime() - begin.getTime();
return new Date(begin.getTime() + (Math.abs(random.nextLong() % delay)));
} | [
"public",
"static",
"Date",
"getRandomDate",
"(",
"Date",
"begin",
",",
"Date",
"end",
",",
"Random",
"random",
")",
"{",
"long",
"delay",
"=",
"end",
".",
"getTime",
"(",
")",
"-",
"begin",
".",
"getTime",
"(",
")",
";",
"return",
"new",
"Date",
"("... | Pobiera pseudolosową datę z okreslonego przedziału czasowego do generacji
której wykorzystany zostanie przekazany generator. Data generowana jest
z dokładnością (ziarnem) wynoszącym 1ms (tj. 1 w reprezentacji daty w formie
liczyby typu <code>long</code>).
@param begin Data początkowa przedziału (włączona do zbioru wynikowego).
@param end Data końcowa przedziału (wyłączona ze zbioru wynikowego).
@param random Generator pseudolosowy wykorzystywany do pozyskania daty.
@return Losowo wygenerowana data z przedziału [begin; end). | [
"Pobiera",
"pseudolosową",
"datę",
"z",
"okreslonego",
"przedziału",
"czasowego",
"do",
"generacji",
"której",
"wykorzystany",
"zostanie",
"przekazany",
"generator",
".",
"Data",
"generowana",
"jest",
"z",
"dokładnością",
"(",
"ziarnem",
")",
"wynoszącym",
"1ms",
"(... | train | https://github.com/kkopacz/agiso-core/blob/b994ec0146be1fe3f10829d69cd719bdbdebe1c5/bundles/agiso-core-lang/src/main/java/org/agiso/core/lang/util/DateUtils.java#L209-L212 |
auth0/auth0-spring-security-api | lib/src/main/java/com/auth0/spring/security/api/JwtWebSecurityConfigurer.java | JwtWebSecurityConfigurer.forHS256WithBase64Secret | @SuppressWarnings( {
"""
Configures application authorization for JWT signed with HS256
@param audience identifier of the API and must match the {@code aud} value in the token
@param issuer of the token for this API and must match the {@code iss} value in the token
@param secret used to sign and verify tokens encoded in Base64
@return JwtWebSecurityConfigurer for further configuration
""""WeakerAccess", "SameParameterValue"})
public static JwtWebSecurityConfigurer forHS256WithBase64Secret(String audience, String issuer, String secret) {
final byte[] secretBytes = new Base64(true).decode(secret);
return new JwtWebSecurityConfigurer(audience, issuer, new JwtAuthenticationProvider(secretBytes, issuer, audience));
} | java | @SuppressWarnings({"WeakerAccess", "SameParameterValue"})
public static JwtWebSecurityConfigurer forHS256WithBase64Secret(String audience, String issuer, String secret) {
final byte[] secretBytes = new Base64(true).decode(secret);
return new JwtWebSecurityConfigurer(audience, issuer, new JwtAuthenticationProvider(secretBytes, issuer, audience));
} | [
"@",
"SuppressWarnings",
"(",
"{",
"\"WeakerAccess\"",
",",
"\"SameParameterValue\"",
"}",
")",
"public",
"static",
"JwtWebSecurityConfigurer",
"forHS256WithBase64Secret",
"(",
"String",
"audience",
",",
"String",
"issuer",
",",
"String",
"secret",
")",
"{",
"final",
... | Configures application authorization for JWT signed with HS256
@param audience identifier of the API and must match the {@code aud} value in the token
@param issuer of the token for this API and must match the {@code iss} value in the token
@param secret used to sign and verify tokens encoded in Base64
@return JwtWebSecurityConfigurer for further configuration | [
"Configures",
"application",
"authorization",
"for",
"JWT",
"signed",
"with",
"HS256"
] | train | https://github.com/auth0/auth0-spring-security-api/blob/cebd4daa0125efd4da9e651cf29aa5ebdb147e2b/lib/src/main/java/com/auth0/spring/security/api/JwtWebSecurityConfigurer.java#L60-L64 |
OpenBEL/openbel-framework | org.openbel.framework.common/src/main/java/org/openbel/framework/common/record/Record.java | Record.readToEntry | public final void readToEntry(byte[] buffer, T t) {
"""
Reads {@code <T>} to the provided {@code buffer}.
@param buffer {@code byte[]}; of size {@link #getRecordSize()}
@param t {@code <T>}
@throws InvalidArgument Thrown if either argument is null or if
{@code buffer} is invalid
"""
if (buffer == null) {
throw new InvalidArgument("buffer", buffer);
} else if (t == null) {
throw new InvalidArgument("cannot read a null entry");
} else if (buffer.length != recordSize) {
final String fmt = "invalid buffer (%d bytes, expected %d)";
final String msg = format(fmt, buffer.length, recordSize);
throw new InvalidArgument(msg);
}
readTo(buffer, t);
} | java | public final void readToEntry(byte[] buffer, T t) {
if (buffer == null) {
throw new InvalidArgument("buffer", buffer);
} else if (t == null) {
throw new InvalidArgument("cannot read a null entry");
} else if (buffer.length != recordSize) {
final String fmt = "invalid buffer (%d bytes, expected %d)";
final String msg = format(fmt, buffer.length, recordSize);
throw new InvalidArgument(msg);
}
readTo(buffer, t);
} | [
"public",
"final",
"void",
"readToEntry",
"(",
"byte",
"[",
"]",
"buffer",
",",
"T",
"t",
")",
"{",
"if",
"(",
"buffer",
"==",
"null",
")",
"{",
"throw",
"new",
"InvalidArgument",
"(",
"\"buffer\"",
",",
"buffer",
")",
";",
"}",
"else",
"if",
"(",
... | Reads {@code <T>} to the provided {@code buffer}.
@param buffer {@code byte[]}; of size {@link #getRecordSize()}
@param t {@code <T>}
@throws InvalidArgument Thrown if either argument is null or if
{@code buffer} is invalid | [
"Reads",
"{",
"@code",
"<T",
">",
"}",
"to",
"the",
"provided",
"{",
"@code",
"buffer",
"}",
"."
] | train | https://github.com/OpenBEL/openbel-framework/blob/149f80b1d6eabb15ab15815b6f745b0afa9fd2d3/org.openbel.framework.common/src/main/java/org/openbel/framework/common/record/Record.java#L263-L274 |
google/j2objc | jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/Transliterator.java | Transliterator.registerClass | public static void registerClass(String ID, Class<? extends Transliterator> transClass, String displayName) {
"""
Registers a subclass of <code>Transliterator</code> with the
system. This subclass must have a public constructor taking no
arguments. When that constructor is called, the resulting
object must return the <code>ID</code> passed to this method if
its <code>getID()</code> method is called.
@param ID the result of <code>getID()</code> for this
transliterator
@param transClass a subclass of <code>Transliterator</code>
@see #unregister
"""
registry.put(ID, transClass, true);
if (displayName != null) {
displayNameCache.put(new CaseInsensitiveString(ID), displayName);
}
} | java | public static void registerClass(String ID, Class<? extends Transliterator> transClass, String displayName) {
registry.put(ID, transClass, true);
if (displayName != null) {
displayNameCache.put(new CaseInsensitiveString(ID), displayName);
}
} | [
"public",
"static",
"void",
"registerClass",
"(",
"String",
"ID",
",",
"Class",
"<",
"?",
"extends",
"Transliterator",
">",
"transClass",
",",
"String",
"displayName",
")",
"{",
"registry",
".",
"put",
"(",
"ID",
",",
"transClass",
",",
"true",
")",
";",
... | Registers a subclass of <code>Transliterator</code> with the
system. This subclass must have a public constructor taking no
arguments. When that constructor is called, the resulting
object must return the <code>ID</code> passed to this method if
its <code>getID()</code> method is called.
@param ID the result of <code>getID()</code> for this
transliterator
@param transClass a subclass of <code>Transliterator</code>
@see #unregister | [
"Registers",
"a",
"subclass",
"of",
"<code",
">",
"Transliterator<",
"/",
"code",
">",
"with",
"the",
"system",
".",
"This",
"subclass",
"must",
"have",
"a",
"public",
"constructor",
"taking",
"no",
"arguments",
".",
"When",
"that",
"constructor",
"is",
"cal... | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/Transliterator.java#L1671-L1676 |
avianey/facebook-api-android-maven | facebook/src/main/java/com/facebook/Session.java | Session.openActiveSessionWithAccessToken | public static Session openActiveSessionWithAccessToken(Context context, AccessToken accessToken,
StatusCallback callback) {
"""
Opens a session based on an existing Facebook access token, and also makes this session
the currently active session. This method should be used
only in instances where an application has previously obtained an access token and wishes
to import it into the Session/TokenCachingStrategy-based session-management system. A primary
example would be an application which previously did not use the Facebook SDK for Android
and implemented its own session-management scheme, but wishes to implement an upgrade path
for existing users so they do not need to log in again when upgrading to a version of
the app that uses the SDK. In general, this method will be called only once, when the app
detects that it has been upgraded -- after that, the usual Session lifecycle methods
should be used to manage the session and its associated token.
<p/>
No validation is done that the token, token source, or permissions are actually valid.
It is the caller's responsibility to ensure that these accurately reflect the state of
the token that has been passed in, or calls to the Facebook API may fail.
@param context the Context to use for creation the session
@param accessToken the access token obtained from Facebook
@param callback a callback that will be called when the session status changes; may be null
@return The new Session or null if one could not be created
"""
Session session = new Session(context, null, null, false);
setActiveSession(session);
session.open(accessToken, callback);
return session;
} | java | public static Session openActiveSessionWithAccessToken(Context context, AccessToken accessToken,
StatusCallback callback) {
Session session = new Session(context, null, null, false);
setActiveSession(session);
session.open(accessToken, callback);
return session;
} | [
"public",
"static",
"Session",
"openActiveSessionWithAccessToken",
"(",
"Context",
"context",
",",
"AccessToken",
"accessToken",
",",
"StatusCallback",
"callback",
")",
"{",
"Session",
"session",
"=",
"new",
"Session",
"(",
"context",
",",
"null",
",",
"null",
","... | Opens a session based on an existing Facebook access token, and also makes this session
the currently active session. This method should be used
only in instances where an application has previously obtained an access token and wishes
to import it into the Session/TokenCachingStrategy-based session-management system. A primary
example would be an application which previously did not use the Facebook SDK for Android
and implemented its own session-management scheme, but wishes to implement an upgrade path
for existing users so they do not need to log in again when upgrading to a version of
the app that uses the SDK. In general, this method will be called only once, when the app
detects that it has been upgraded -- after that, the usual Session lifecycle methods
should be used to manage the session and its associated token.
<p/>
No validation is done that the token, token source, or permissions are actually valid.
It is the caller's responsibility to ensure that these accurately reflect the state of
the token that has been passed in, or calls to the Facebook API may fail.
@param context the Context to use for creation the session
@param accessToken the access token obtained from Facebook
@param callback a callback that will be called when the session status changes; may be null
@return The new Session or null if one could not be created | [
"Opens",
"a",
"session",
"based",
"on",
"an",
"existing",
"Facebook",
"access",
"token",
"and",
"also",
"makes",
"this",
"session",
"the",
"currently",
"active",
"session",
".",
"This",
"method",
"should",
"be",
"used",
"only",
"in",
"instances",
"where",
"a... | train | https://github.com/avianey/facebook-api-android-maven/blob/ae6c7aa7ae45739ee19f18c1983e05f7e35b9ede/facebook/src/main/java/com/facebook/Session.java#L1119-L1127 |
alkacon/opencms-core | src/org/opencms/gwt/CmsGwtActionElement.java | CmsGwtActionElement.createNoCacheScript | public static String createNoCacheScript(String moduleName, String moduleVersion) {
"""
Returns the script tag for the "*.nocache.js".<p>
@param moduleName the module name to get the script tag for
@param moduleVersion the module version
@return the <code>"<script>"</code> tag for the "*.nocache.js".<p>
"""
String result = "<script type=\"text/javascript\" src=\""
+ CmsWorkplace.getResourceUri("ade/" + moduleName + "/" + moduleName + ".nocache.js");
if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(moduleVersion)) {
result += "?version=" + moduleVersion + "_" + OpenCms.getSystemInfo().getVersionNumber().hashCode();
}
result += "\"></script>";
return result;
} | java | public static String createNoCacheScript(String moduleName, String moduleVersion) {
String result = "<script type=\"text/javascript\" src=\""
+ CmsWorkplace.getResourceUri("ade/" + moduleName + "/" + moduleName + ".nocache.js");
if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(moduleVersion)) {
result += "?version=" + moduleVersion + "_" + OpenCms.getSystemInfo().getVersionNumber().hashCode();
}
result += "\"></script>";
return result;
} | [
"public",
"static",
"String",
"createNoCacheScript",
"(",
"String",
"moduleName",
",",
"String",
"moduleVersion",
")",
"{",
"String",
"result",
"=",
"\"<script type=\\\"text/javascript\\\" src=\\\"\"",
"+",
"CmsWorkplace",
".",
"getResourceUri",
"(",
"\"ade/\"",
"+",
"m... | Returns the script tag for the "*.nocache.js".<p>
@param moduleName the module name to get the script tag for
@param moduleVersion the module version
@return the <code>"<script>"</code> tag for the "*.nocache.js".<p> | [
"Returns",
"the",
"script",
"tag",
"for",
"the",
"*",
".",
"nocache",
".",
"js",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/gwt/CmsGwtActionElement.java#L96-L105 |
gallandarakhneorg/afc | advanced/gis/giscore/src/main/java/org/arakhne/afc/gis/mapelement/MapMultiPoint.java | MapMultiPoint.getDistance | @Override
@Pure
public double getDistance(Point2D<?, ?> point) {
"""
Replies the distance between this MapElement and
point.
@param point the point to compute the distance to.
@return the distance. Should be negative depending of the MapElement type.
"""
double mind = Double.MAX_VALUE;
for (final Point2d p : points()) {
final double d = p.getDistance(point);
if (d < mind) {
mind = d;
}
}
return mind;
} | java | @Override
@Pure
public double getDistance(Point2D<?, ?> point) {
double mind = Double.MAX_VALUE;
for (final Point2d p : points()) {
final double d = p.getDistance(point);
if (d < mind) {
mind = d;
}
}
return mind;
} | [
"@",
"Override",
"@",
"Pure",
"public",
"double",
"getDistance",
"(",
"Point2D",
"<",
"?",
",",
"?",
">",
"point",
")",
"{",
"double",
"mind",
"=",
"Double",
".",
"MAX_VALUE",
";",
"for",
"(",
"final",
"Point2d",
"p",
":",
"points",
"(",
")",
")",
... | Replies the distance between this MapElement and
point.
@param point the point to compute the distance to.
@return the distance. Should be negative depending of the MapElement type. | [
"Replies",
"the",
"distance",
"between",
"this",
"MapElement",
"and",
"point",
"."
] | train | https://github.com/gallandarakhneorg/afc/blob/0c7d2e1ddefd4167ef788416d970a6c1ef6f8bbb/advanced/gis/giscore/src/main/java/org/arakhne/afc/gis/mapelement/MapMultiPoint.java#L128-L139 |
lukas-krecan/JsonUnit | json-unit-fluent/src/main/java/net/javacrumbs/jsonunit/fluent/JsonFluentAssert.java | JsonFluentAssert.assertThatJson | public static ConfigurableJsonFluentAssert assertThatJson(Object json) {
"""
Creates a new instance of <code>{@link JsonFluentAssert}</code>.
It is not called assertThat to not clash with StringAssert.
The json parameter is converted to JSON using ObjectMapper.
@param json
@return new JsonFluentAssert object.
"""
return new ConfigurableJsonFluentAssert(convertToJson(json, ACTUAL), getPathPrefix(json));
} | java | public static ConfigurableJsonFluentAssert assertThatJson(Object json) {
return new ConfigurableJsonFluentAssert(convertToJson(json, ACTUAL), getPathPrefix(json));
} | [
"public",
"static",
"ConfigurableJsonFluentAssert",
"assertThatJson",
"(",
"Object",
"json",
")",
"{",
"return",
"new",
"ConfigurableJsonFluentAssert",
"(",
"convertToJson",
"(",
"json",
",",
"ACTUAL",
")",
",",
"getPathPrefix",
"(",
"json",
")",
")",
";",
"}"
] | Creates a new instance of <code>{@link JsonFluentAssert}</code>.
It is not called assertThat to not clash with StringAssert.
The json parameter is converted to JSON using ObjectMapper.
@param json
@return new JsonFluentAssert object. | [
"Creates",
"a",
"new",
"instance",
"of",
"<code",
">",
"{",
"@link",
"JsonFluentAssert",
"}",
"<",
"/",
"code",
">",
".",
"It",
"is",
"not",
"called",
"assertThat",
"to",
"not",
"clash",
"with",
"StringAssert",
".",
"The",
"json",
"parameter",
"is",
"con... | train | https://github.com/lukas-krecan/JsonUnit/blob/2b12ed792e8dd787bddd6f3b8eb2325737435791/json-unit-fluent/src/main/java/net/javacrumbs/jsonunit/fluent/JsonFluentAssert.java#L97-L99 |
morimekta/utils | console-util/src/main/java/net/morimekta/console/util/STTY.java | STTY.setSTTYMode | public STTYModeSwitcher setSTTYMode(STTYMode mode) {
"""
Set the current STTY mode, and return the closable switcher to turn back.
@param mode The STTY mode to set.
@return The mode switcher.
"""
try {
return new STTYModeSwitcher(mode, runtime);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
} | java | public STTYModeSwitcher setSTTYMode(STTYMode mode) {
try {
return new STTYModeSwitcher(mode, runtime);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
} | [
"public",
"STTYModeSwitcher",
"setSTTYMode",
"(",
"STTYMode",
"mode",
")",
"{",
"try",
"{",
"return",
"new",
"STTYModeSwitcher",
"(",
"mode",
",",
"runtime",
")",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"throw",
"new",
"UncheckedIOException",
"... | Set the current STTY mode, and return the closable switcher to turn back.
@param mode The STTY mode to set.
@return The mode switcher. | [
"Set",
"the",
"current",
"STTY",
"mode",
"and",
"return",
"the",
"closable",
"switcher",
"to",
"turn",
"back",
"."
] | train | https://github.com/morimekta/utils/blob/dc987485902f1a7d58169c89c61db97425a6226d/console-util/src/main/java/net/morimekta/console/util/STTY.java#L76-L82 |
JRebirth/JRebirth | org.jrebirth.af/core/src/main/java/org/jrebirth/af/core/key/MultitonKey.java | MultitonKey.generateTypeKey | private String generateTypeKey(final Object object, final KeyGenerator typeGenerator) {
"""
Generate Type key by using the class-level annotation.
@param object the source object
@param typeGenerator the annotation that expressed how generate the string unique key
@return the unique key or null if an error occurred
"""
String objectKey = null;
Method method = null;
try {
method = object.getClass().getMethod(typeGenerator.value());
objectKey = (String) method.invoke(object);
} catch (final NoSuchMethodException e) {
LOGGER.log(METHOD_NOT_FOUND, typeGenerator.value(), object.getClass().getSimpleName(), e);
} catch (final SecurityException e) {
LOGGER.log(NO_KEY_GENERATOR_METHOD, typeGenerator.value(), object.getClass().getSimpleName(), e);
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
LOGGER.log(KEY_GENERATOR_FAILURE, typeGenerator.value(), object.getClass().getSimpleName(), e);
}
return objectKey;
} | java | private String generateTypeKey(final Object object, final KeyGenerator typeGenerator) {
String objectKey = null;
Method method = null;
try {
method = object.getClass().getMethod(typeGenerator.value());
objectKey = (String) method.invoke(object);
} catch (final NoSuchMethodException e) {
LOGGER.log(METHOD_NOT_FOUND, typeGenerator.value(), object.getClass().getSimpleName(), e);
} catch (final SecurityException e) {
LOGGER.log(NO_KEY_GENERATOR_METHOD, typeGenerator.value(), object.getClass().getSimpleName(), e);
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
LOGGER.log(KEY_GENERATOR_FAILURE, typeGenerator.value(), object.getClass().getSimpleName(), e);
}
return objectKey;
} | [
"private",
"String",
"generateTypeKey",
"(",
"final",
"Object",
"object",
",",
"final",
"KeyGenerator",
"typeGenerator",
")",
"{",
"String",
"objectKey",
"=",
"null",
";",
"Method",
"method",
"=",
"null",
";",
"try",
"{",
"method",
"=",
"object",
".",
"getCl... | Generate Type key by using the class-level annotation.
@param object the source object
@param typeGenerator the annotation that expressed how generate the string unique key
@return the unique key or null if an error occurred | [
"Generate",
"Type",
"key",
"by",
"using",
"the",
"class",
"-",
"level",
"annotation",
"."
] | train | https://github.com/JRebirth/JRebirth/blob/93f4fc087b83c73db540333b9686e97b4cec694d/org.jrebirth.af/core/src/main/java/org/jrebirth/af/core/key/MultitonKey.java#L121-L136 |
alkacon/opencms-core | src/org/opencms/workplace/CmsWorkplace.java | CmsWorkplace.initUserSettings | public static CmsWorkplaceSettings initUserSettings(CmsObject cms, CmsWorkplaceSettings settings, boolean update) {
"""
Updates the user settings in the given workplace settings for the current user, reading the user settings
from the database if required.<p>
@param cms the cms object for the current user
@param settings the workplace settings to update (if <code>null</code> a new instance is created)
@param update flag indicating if settings are only updated (user preferences)
@return the current users workplace settings
@see #initWorkplaceSettings(CmsObject, CmsWorkplaceSettings, boolean)
"""
if (settings == null) {
settings = new CmsWorkplaceSettings();
}
// save current workplace user & user settings object
CmsUser user;
if (update) {
try {
// read the user from db to get the latest user information if required
user = cms.readUser(cms.getRequestContext().getCurrentUser().getId());
} catch (CmsException e) {
// can usually be ignored
if (LOG.isInfoEnabled()) {
LOG.info(e.getLocalizedMessage());
}
user = cms.getRequestContext().getCurrentUser();
}
} else {
user = cms.getRequestContext().getCurrentUser();
}
// store the user and it's settings in the Workplace settings
settings.setUser(user);
settings.setUserSettings(new CmsUserSettings(user));
// return the result settings
return settings;
} | java | public static CmsWorkplaceSettings initUserSettings(CmsObject cms, CmsWorkplaceSettings settings, boolean update) {
if (settings == null) {
settings = new CmsWorkplaceSettings();
}
// save current workplace user & user settings object
CmsUser user;
if (update) {
try {
// read the user from db to get the latest user information if required
user = cms.readUser(cms.getRequestContext().getCurrentUser().getId());
} catch (CmsException e) {
// can usually be ignored
if (LOG.isInfoEnabled()) {
LOG.info(e.getLocalizedMessage());
}
user = cms.getRequestContext().getCurrentUser();
}
} else {
user = cms.getRequestContext().getCurrentUser();
}
// store the user and it's settings in the Workplace settings
settings.setUser(user);
settings.setUserSettings(new CmsUserSettings(user));
// return the result settings
return settings;
} | [
"public",
"static",
"CmsWorkplaceSettings",
"initUserSettings",
"(",
"CmsObject",
"cms",
",",
"CmsWorkplaceSettings",
"settings",
",",
"boolean",
"update",
")",
"{",
"if",
"(",
"settings",
"==",
"null",
")",
"{",
"settings",
"=",
"new",
"CmsWorkplaceSettings",
"("... | Updates the user settings in the given workplace settings for the current user, reading the user settings
from the database if required.<p>
@param cms the cms object for the current user
@param settings the workplace settings to update (if <code>null</code> a new instance is created)
@param update flag indicating if settings are only updated (user preferences)
@return the current users workplace settings
@see #initWorkplaceSettings(CmsObject, CmsWorkplaceSettings, boolean) | [
"Updates",
"the",
"user",
"settings",
"in",
"the",
"given",
"workplace",
"settings",
"for",
"the",
"current",
"user",
"reading",
"the",
"user",
"settings",
"from",
"the",
"database",
"if",
"required",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/workplace/CmsWorkplace.java#L854-L882 |
couchbase/couchbase-java-client | src/main/java/com/couchbase/client/java/query/dsl/functions/ArrayFunctions.java | ArrayFunctions.arrayRemove | public static Expression arrayRemove(Expression expression, Expression value) {
"""
Returned expression results in new array with all occurrences of value removed.
"""
return x("ARRAY_REMOVE(" + expression.toString() + ", " + value.toString() + ")");
} | java | public static Expression arrayRemove(Expression expression, Expression value) {
return x("ARRAY_REMOVE(" + expression.toString() + ", " + value.toString() + ")");
} | [
"public",
"static",
"Expression",
"arrayRemove",
"(",
"Expression",
"expression",
",",
"Expression",
"value",
")",
"{",
"return",
"x",
"(",
"\"ARRAY_REMOVE(\"",
"+",
"expression",
".",
"toString",
"(",
")",
"+",
"\", \"",
"+",
"value",
".",
"toString",
"(",
... | Returned expression results in new array with all occurrences of value removed. | [
"Returned",
"expression",
"results",
"in",
"new",
"array",
"with",
"all",
"occurrences",
"of",
"value",
"removed",
"."
] | train | https://github.com/couchbase/couchbase-java-client/blob/f36a0ee0c66923bdde47838ca543e50cbaa99e14/src/main/java/com/couchbase/client/java/query/dsl/functions/ArrayFunctions.java#L344-L346 |
liferay/com-liferay-commerce | commerce-price-list-service/src/main/java/com/liferay/commerce/price/list/service/persistence/impl/CommercePriceListAccountRelPersistenceImpl.java | CommercePriceListAccountRelPersistenceImpl.removeByUUID_G | @Override
public CommercePriceListAccountRel removeByUUID_G(String uuid, long groupId)
throws NoSuchPriceListAccountRelException {
"""
Removes the commerce price list account rel where uuid = ? and groupId = ? from the database.
@param uuid the uuid
@param groupId the group ID
@return the commerce price list account rel that was removed
"""
CommercePriceListAccountRel commercePriceListAccountRel = findByUUID_G(uuid,
groupId);
return remove(commercePriceListAccountRel);
} | java | @Override
public CommercePriceListAccountRel removeByUUID_G(String uuid, long groupId)
throws NoSuchPriceListAccountRelException {
CommercePriceListAccountRel commercePriceListAccountRel = findByUUID_G(uuid,
groupId);
return remove(commercePriceListAccountRel);
} | [
"@",
"Override",
"public",
"CommercePriceListAccountRel",
"removeByUUID_G",
"(",
"String",
"uuid",
",",
"long",
"groupId",
")",
"throws",
"NoSuchPriceListAccountRelException",
"{",
"CommercePriceListAccountRel",
"commercePriceListAccountRel",
"=",
"findByUUID_G",
"(",
"uuid",... | Removes the commerce price list account rel where uuid = ? and groupId = ? from the database.
@param uuid the uuid
@param groupId the group ID
@return the commerce price list account rel that was removed | [
"Removes",
"the",
"commerce",
"price",
"list",
"account",
"rel",
"where",
"uuid",
"=",
"?",
";",
"and",
"groupId",
"=",
"?",
";",
"from",
"the",
"database",
"."
] | train | https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-price-list-service/src/main/java/com/liferay/commerce/price/list/service/persistence/impl/CommercePriceListAccountRelPersistenceImpl.java#L824-L831 |
googleads/googleads-java-lib | examples/admanager_axis/src/main/java/admanager/axis/v201808/packageservice/GetInProgressPackages.java | GetInProgressPackages.runExample | public static void runExample(AdManagerServices adManagerServices, AdManagerSession session)
throws RemoteException {
"""
Runs the example.
@param adManagerServices the services factory.
@param session the session.
@throws ApiException if the API request failed with one or more service errors.
@throws RemoteException if the API request failed due to other errors.
"""
PackageServiceInterface packageService =
adManagerServices.get(session, PackageServiceInterface.class);
// Create a statement to select packages.
StatementBuilder statementBuilder = new StatementBuilder()
.where("status = :status")
.orderBy("id ASC")
.limit(StatementBuilder.SUGGESTED_PAGE_LIMIT)
.withBindVariableValue("status", PackageStatus.IN_PROGRESS.toString());
// Retrieve a small amount of packages at a time, paging through
// until all packages have been retrieved.
int totalResultSetSize = 0;
do {
PackagePage page =
packageService.getPackagesByStatement(statementBuilder.toStatement());
if (page.getResults() != null) {
// Print out some information for each package.
totalResultSetSize = page.getTotalResultSetSize();
int i = page.getStartIndex();
for (Package pkg : page.getResults()) {
System.out.printf(
"%d) Package with ID %d, name '%s', and proposal ID %d was found.%n",
i++,
pkg.getId(),
pkg.getName(),
pkg.getProposalId()
);
}
}
statementBuilder.increaseOffsetBy(StatementBuilder.SUGGESTED_PAGE_LIMIT);
} while (statementBuilder.getOffset() < totalResultSetSize);
System.out.printf("Number of results found: %d%n", totalResultSetSize);
} | java | public static void runExample(AdManagerServices adManagerServices, AdManagerSession session)
throws RemoteException {
PackageServiceInterface packageService =
adManagerServices.get(session, PackageServiceInterface.class);
// Create a statement to select packages.
StatementBuilder statementBuilder = new StatementBuilder()
.where("status = :status")
.orderBy("id ASC")
.limit(StatementBuilder.SUGGESTED_PAGE_LIMIT)
.withBindVariableValue("status", PackageStatus.IN_PROGRESS.toString());
// Retrieve a small amount of packages at a time, paging through
// until all packages have been retrieved.
int totalResultSetSize = 0;
do {
PackagePage page =
packageService.getPackagesByStatement(statementBuilder.toStatement());
if (page.getResults() != null) {
// Print out some information for each package.
totalResultSetSize = page.getTotalResultSetSize();
int i = page.getStartIndex();
for (Package pkg : page.getResults()) {
System.out.printf(
"%d) Package with ID %d, name '%s', and proposal ID %d was found.%n",
i++,
pkg.getId(),
pkg.getName(),
pkg.getProposalId()
);
}
}
statementBuilder.increaseOffsetBy(StatementBuilder.SUGGESTED_PAGE_LIMIT);
} while (statementBuilder.getOffset() < totalResultSetSize);
System.out.printf("Number of results found: %d%n", totalResultSetSize);
} | [
"public",
"static",
"void",
"runExample",
"(",
"AdManagerServices",
"adManagerServices",
",",
"AdManagerSession",
"session",
")",
"throws",
"RemoteException",
"{",
"PackageServiceInterface",
"packageService",
"=",
"adManagerServices",
".",
"get",
"(",
"session",
",",
"P... | Runs the example.
@param adManagerServices the services factory.
@param session the session.
@throws ApiException if the API request failed with one or more service errors.
@throws RemoteException if the API request failed due to other errors. | [
"Runs",
"the",
"example",
"."
] | train | https://github.com/googleads/googleads-java-lib/blob/967957cc4f6076514e3a7926fe653e4f1f7cc9c9/examples/admanager_axis/src/main/java/admanager/axis/v201808/packageservice/GetInProgressPackages.java#L52-L90 |
azkaban/azkaban | azkaban-db/src/main/java/azkaban/db/MySQLDataSource.java | MySQLDataSource.getConnection | @Override
public Connection getConnection() throws SQLException {
"""
This method overrides {@link BasicDataSource#getConnection()}, in order to have retry logics.
We don't make the call synchronized in order to guarantee normal cases performance.
"""
this.dbMetrics.markDBConnection();
final long startMs = System.currentTimeMillis();
Connection connection = null;
int retryAttempt = 1;
while (retryAttempt < AzDBUtil.MAX_DB_RETRY_COUNT) {
try {
/**
* when DB connection could not be fetched (e.g., network issue), or connection can not be validated,
* {@link BasicDataSource} throws a SQL Exception. {@link BasicDataSource#dataSource} will be reset to null.
* createDataSource() will create a new dataSource.
* Every Attempt generates a thread-hanging-time, about 75 seconds, which is hard coded, and can not be changed.
*/
connection = createDataSource().getConnection();
/**
* If connection is null or connection is read only, retry to find available connection.
* When DB fails over from master to slave, master is set to read-only mode. We must keep
* finding correct data source and sql connection.
*/
if (connection == null || isReadOnly(connection)) {
throw new SQLException("Failed to find DB connection Or connection is read only. ");
} else {
// Evalaute how long it takes to get DB Connection.
this.dbMetrics.setDBConnectionTime(System.currentTimeMillis() - startMs);
return connection;
}
} catch (final SQLException ex) {
/**
* invalidate connection and reconstruct it later. if remote IP address is not reachable,
* it will get hang for a while and throw exception.
*/
this.dbMetrics.markDBFailConnection();
try {
invalidateConnection(connection);
} catch (final Exception e) {
logger.error( "can not invalidate connection.", e);
}
logger.error( "Failed to find write-enabled DB connection. Wait 15 seconds and retry."
+ " No.Attempt = " + retryAttempt, ex);
/**
* When database is completed down, DB connection fails to be fetched immediately. So we need
* to sleep 15 seconds for retry.
*/
sleep(1000L * 15);
retryAttempt++;
}
}
return connection;
} | java | @Override
public Connection getConnection() throws SQLException {
this.dbMetrics.markDBConnection();
final long startMs = System.currentTimeMillis();
Connection connection = null;
int retryAttempt = 1;
while (retryAttempt < AzDBUtil.MAX_DB_RETRY_COUNT) {
try {
/**
* when DB connection could not be fetched (e.g., network issue), or connection can not be validated,
* {@link BasicDataSource} throws a SQL Exception. {@link BasicDataSource#dataSource} will be reset to null.
* createDataSource() will create a new dataSource.
* Every Attempt generates a thread-hanging-time, about 75 seconds, which is hard coded, and can not be changed.
*/
connection = createDataSource().getConnection();
/**
* If connection is null or connection is read only, retry to find available connection.
* When DB fails over from master to slave, master is set to read-only mode. We must keep
* finding correct data source and sql connection.
*/
if (connection == null || isReadOnly(connection)) {
throw new SQLException("Failed to find DB connection Or connection is read only. ");
} else {
// Evalaute how long it takes to get DB Connection.
this.dbMetrics.setDBConnectionTime(System.currentTimeMillis() - startMs);
return connection;
}
} catch (final SQLException ex) {
/**
* invalidate connection and reconstruct it later. if remote IP address is not reachable,
* it will get hang for a while and throw exception.
*/
this.dbMetrics.markDBFailConnection();
try {
invalidateConnection(connection);
} catch (final Exception e) {
logger.error( "can not invalidate connection.", e);
}
logger.error( "Failed to find write-enabled DB connection. Wait 15 seconds and retry."
+ " No.Attempt = " + retryAttempt, ex);
/**
* When database is completed down, DB connection fails to be fetched immediately. So we need
* to sleep 15 seconds for retry.
*/
sleep(1000L * 15);
retryAttempt++;
}
}
return connection;
} | [
"@",
"Override",
"public",
"Connection",
"getConnection",
"(",
")",
"throws",
"SQLException",
"{",
"this",
".",
"dbMetrics",
".",
"markDBConnection",
"(",
")",
";",
"final",
"long",
"startMs",
"=",
"System",
".",
"currentTimeMillis",
"(",
")",
";",
"Connection... | This method overrides {@link BasicDataSource#getConnection()}, in order to have retry logics.
We don't make the call synchronized in order to guarantee normal cases performance. | [
"This",
"method",
"overrides",
"{"
] | train | https://github.com/azkaban/azkaban/blob/d258ea7d6e66807c6eff79c5325d6d3443618dff/azkaban-db/src/main/java/azkaban/db/MySQLDataSource.java#L61-L114 |
OpenLiberty/open-liberty | dev/com.ibm.ws.dynacache/src/com/ibm/ws/cache/InvalidationAuditDaemon.java | InvalidationAuditDaemon.filterExternalCacheFragmentList | public ArrayList filterExternalCacheFragmentList(String cacheName, ArrayList incomingList) {
"""
This ensures all incoming ExternalCacheFragments have not been
invalidated.
@param incomingList The unfiltered list of ExternalCacheFragments.
@return The filtered list of ExternalCacheFragments.
"""
InvalidationTableList invalidationTableList = getInvalidationTableList(cacheName);
try {
invalidationTableList.readWriteLock.readLock().lock();
Iterator it = incomingList.iterator();
while (it.hasNext()) {
ExternalInvalidation externalCacheFragment = (ExternalInvalidation) it.next();
if (null == internalFilterExternalCacheFragment(cacheName, invalidationTableList, externalCacheFragment)) {
if (tc.isDebugEnabled()) {
Tr.debug(tc, "filterExternalCacheFragmentList(): Filtered OUT cacheName=" + cacheName + " uri=" + externalCacheFragment.getUri());
}
it.remove();
}
}
return incomingList;
} finally {
invalidationTableList.readWriteLock.readLock().unlock();
}
} | java | public ArrayList filterExternalCacheFragmentList(String cacheName, ArrayList incomingList) {
InvalidationTableList invalidationTableList = getInvalidationTableList(cacheName);
try {
invalidationTableList.readWriteLock.readLock().lock();
Iterator it = incomingList.iterator();
while (it.hasNext()) {
ExternalInvalidation externalCacheFragment = (ExternalInvalidation) it.next();
if (null == internalFilterExternalCacheFragment(cacheName, invalidationTableList, externalCacheFragment)) {
if (tc.isDebugEnabled()) {
Tr.debug(tc, "filterExternalCacheFragmentList(): Filtered OUT cacheName=" + cacheName + " uri=" + externalCacheFragment.getUri());
}
it.remove();
}
}
return incomingList;
} finally {
invalidationTableList.readWriteLock.readLock().unlock();
}
} | [
"public",
"ArrayList",
"filterExternalCacheFragmentList",
"(",
"String",
"cacheName",
",",
"ArrayList",
"incomingList",
")",
"{",
"InvalidationTableList",
"invalidationTableList",
"=",
"getInvalidationTableList",
"(",
"cacheName",
")",
";",
"try",
"{",
"invalidationTableLis... | This ensures all incoming ExternalCacheFragments have not been
invalidated.
@param incomingList The unfiltered list of ExternalCacheFragments.
@return The filtered list of ExternalCacheFragments. | [
"This",
"ensures",
"all",
"incoming",
"ExternalCacheFragments",
"have",
"not",
"been",
"invalidated",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.dynacache/src/com/ibm/ws/cache/InvalidationAuditDaemon.java#L273-L293 |
UrielCh/ovh-java-sdk | ovh-java-sdk-order/src/main/java/net/minidev/ovh/api/ApiOvhOrder.java | ApiOvhOrder.email_exchange_organizationName_service_exchangeService_accountUpgrade_GET | public ArrayList<String> email_exchange_organizationName_service_exchangeService_accountUpgrade_GET(String organizationName, String exchangeService, OvhAccountQuotaEnum newQuota, String primaryEmailAddress) throws IOException {
"""
Get allowed durations for 'accountUpgrade' option
REST: GET /order/email/exchange/{organizationName}/service/{exchangeService}/accountUpgrade
@param newQuota [required] New storage quota for that account
@param primaryEmailAddress [required] The account you wish to upgrade
@param organizationName [required] The internal name of your exchange organization
@param exchangeService [required] The internal name of your exchange service
"""
String qPath = "/order/email/exchange/{organizationName}/service/{exchangeService}/accountUpgrade";
StringBuilder sb = path(qPath, organizationName, exchangeService);
query(sb, "newQuota", newQuota);
query(sb, "primaryEmailAddress", primaryEmailAddress);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, t1);
} | java | public ArrayList<String> email_exchange_organizationName_service_exchangeService_accountUpgrade_GET(String organizationName, String exchangeService, OvhAccountQuotaEnum newQuota, String primaryEmailAddress) throws IOException {
String qPath = "/order/email/exchange/{organizationName}/service/{exchangeService}/accountUpgrade";
StringBuilder sb = path(qPath, organizationName, exchangeService);
query(sb, "newQuota", newQuota);
query(sb, "primaryEmailAddress", primaryEmailAddress);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, t1);
} | [
"public",
"ArrayList",
"<",
"String",
">",
"email_exchange_organizationName_service_exchangeService_accountUpgrade_GET",
"(",
"String",
"organizationName",
",",
"String",
"exchangeService",
",",
"OvhAccountQuotaEnum",
"newQuota",
",",
"String",
"primaryEmailAddress",
")",
"thro... | Get allowed durations for 'accountUpgrade' option
REST: GET /order/email/exchange/{organizationName}/service/{exchangeService}/accountUpgrade
@param newQuota [required] New storage quota for that account
@param primaryEmailAddress [required] The account you wish to upgrade
@param organizationName [required] The internal name of your exchange organization
@param exchangeService [required] The internal name of your exchange service | [
"Get",
"allowed",
"durations",
"for",
"accountUpgrade",
"option"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-order/src/main/java/net/minidev/ovh/api/ApiOvhOrder.java#L3965-L3972 |
ModeShape/modeshape | modeshape-common/src/main/java/org/modeshape/common/util/CheckArg.java | CheckArg.hasSizeOfAtLeast | public static void hasSizeOfAtLeast( Object[] argument,
int minimumSize,
String name ) {
"""
Check that the array contains at least the supplied number of elements
@param argument the array
@param minimumSize the minimum size
@param name The name of the argument
@throws IllegalArgumentException If the array has a size smaller than the supplied value
"""
isNotNull(argument, name);
if (argument.length < minimumSize) {
throw new IllegalArgumentException(CommonI18n.argumentMustBeOfMinimumSize.text(name, Object[].class.getSimpleName(),
argument.length, minimumSize));
}
} | java | public static void hasSizeOfAtLeast( Object[] argument,
int minimumSize,
String name ) {
isNotNull(argument, name);
if (argument.length < minimumSize) {
throw new IllegalArgumentException(CommonI18n.argumentMustBeOfMinimumSize.text(name, Object[].class.getSimpleName(),
argument.length, minimumSize));
}
} | [
"public",
"static",
"void",
"hasSizeOfAtLeast",
"(",
"Object",
"[",
"]",
"argument",
",",
"int",
"minimumSize",
",",
"String",
"name",
")",
"{",
"isNotNull",
"(",
"argument",
",",
"name",
")",
";",
"if",
"(",
"argument",
".",
"length",
"<",
"minimumSize",
... | Check that the array contains at least the supplied number of elements
@param argument the array
@param minimumSize the minimum size
@param name The name of the argument
@throws IllegalArgumentException If the array has a size smaller than the supplied value | [
"Check",
"that",
"the",
"array",
"contains",
"at",
"least",
"the",
"supplied",
"number",
"of",
"elements"
] | train | https://github.com/ModeShape/modeshape/blob/794cfdabb67a90f24629c4fff0424a6125f8f95b/modeshape-common/src/main/java/org/modeshape/common/util/CheckArg.java#L797-L805 |
Azure/azure-sdk-for-java | eventgrid/resource-manager/v2019_01_01/src/main/java/com/microsoft/azure/management/eventgrid/v2019_01_01/implementation/TopicsInner.java | TopicsInner.createOrUpdate | public TopicInner createOrUpdate(String resourceGroupName, String topicName, TopicInner topicInfo) {
"""
Create a topic.
Asynchronously creates a new topic with the specified parameters.
@param resourceGroupName The name of the resource group within the user's subscription.
@param topicName Name of the topic
@param topicInfo Topic information
@throws IllegalArgumentException thrown if parameters fail the validation
@throws CloudException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the TopicInner object if successful.
"""
return createOrUpdateWithServiceResponseAsync(resourceGroupName, topicName, topicInfo).toBlocking().last().body();
} | java | public TopicInner createOrUpdate(String resourceGroupName, String topicName, TopicInner topicInfo) {
return createOrUpdateWithServiceResponseAsync(resourceGroupName, topicName, topicInfo).toBlocking().last().body();
} | [
"public",
"TopicInner",
"createOrUpdate",
"(",
"String",
"resourceGroupName",
",",
"String",
"topicName",
",",
"TopicInner",
"topicInfo",
")",
"{",
"return",
"createOrUpdateWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"topicName",
",",
"topicInfo",
")",
"."... | Create a topic.
Asynchronously creates a new topic with the specified parameters.
@param resourceGroupName The name of the resource group within the user's subscription.
@param topicName Name of the topic
@param topicInfo Topic information
@throws IllegalArgumentException thrown if parameters fail the validation
@throws CloudException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the TopicInner object if successful. | [
"Create",
"a",
"topic",
".",
"Asynchronously",
"creates",
"a",
"new",
"topic",
"with",
"the",
"specified",
"parameters",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/eventgrid/resource-manager/v2019_01_01/src/main/java/com/microsoft/azure/management/eventgrid/v2019_01_01/implementation/TopicsInner.java#L221-L223 |
codeprimate-software/cp-elements | src/main/java/org/cp/elements/lang/RuntimeExceptionsFactory.java | RuntimeExceptionsFactory.newNullPointerException | public static NullPointerException newNullPointerException(Throwable cause, String message, Object... args) {
"""
Constructs and initializes a new {@link NullPointerException} with the given {@link Throwable cause}
and {@link String message} formatted with the given {@link Object[] arguments}.
@param cause {@link Throwable} identified as the reason this {@link NullPointerException} was thrown.
@param message {@link String} describing the {@link NullPointerException exception}.
@param args {@link Object[] arguments} used to replace format placeholders in the {@link String message}.
@return a new {@link NullPointerException} with the given {@link Throwable cause} and {@link String message}.
@see java.lang.NullPointerException
"""
return (NullPointerException) new NullPointerException(format(message, args)).initCause(cause);
} | java | public static NullPointerException newNullPointerException(Throwable cause, String message, Object... args) {
return (NullPointerException) new NullPointerException(format(message, args)).initCause(cause);
} | [
"public",
"static",
"NullPointerException",
"newNullPointerException",
"(",
"Throwable",
"cause",
",",
"String",
"message",
",",
"Object",
"...",
"args",
")",
"{",
"return",
"(",
"NullPointerException",
")",
"new",
"NullPointerException",
"(",
"format",
"(",
"messag... | Constructs and initializes a new {@link NullPointerException} with the given {@link Throwable cause}
and {@link String message} formatted with the given {@link Object[] arguments}.
@param cause {@link Throwable} identified as the reason this {@link NullPointerException} was thrown.
@param message {@link String} describing the {@link NullPointerException exception}.
@param args {@link Object[] arguments} used to replace format placeholders in the {@link String message}.
@return a new {@link NullPointerException} with the given {@link Throwable cause} and {@link String message}.
@see java.lang.NullPointerException | [
"Constructs",
"and",
"initializes",
"a",
"new",
"{",
"@link",
"NullPointerException",
"}",
"with",
"the",
"given",
"{",
"@link",
"Throwable",
"cause",
"}",
"and",
"{",
"@link",
"String",
"message",
"}",
"formatted",
"with",
"the",
"given",
"{",
"@link",
"Obj... | train | https://github.com/codeprimate-software/cp-elements/blob/f2163c149fbbef05015e688132064ebcac7c49ab/src/main/java/org/cp/elements/lang/RuntimeExceptionsFactory.java#L176-L178 |
bbottema/simple-java-mail | modules/simple-java-mail/src/main/java/org/simplejavamail/mailer/internal/MailerImpl.java | MailerImpl.createMailSession | @SuppressWarnings("WeakerAccess")
public static Session createMailSession(@Nonnull final ServerConfig serverConfig, @Nonnull final TransportStrategy transportStrategy) {
"""
Instantiates and configures the {@link Session} instance. Delegates resolving transport protocol specific properties to the given {@link
TransportStrategy} in two ways: <ol> <li>request an initial property list which the strategy may pre-populate</li> <li>by requesting the
property names according to the respective transport protocol it handles (for the host property for example it would be
<em>"mail.smtp.host"</em> for SMTP and <em>"mail.smtps.host"</em> for SMTPS)</li> </ol>
<p>
Furthermore adds proxy SOCKS properties if a proxy configuration was provided, overwriting any SOCKS properties already present.
@param serverConfig Remote SMTP server details.
@param transportStrategy The transport protocol strategy enum that actually handles the session configuration. Session configuration meaning
setting the right properties for the appropriate transport type (ie. <em>"mail.smtp.host"</em> for SMTP,
<em>"mail.smtps.host"</em> for SMTPS).
@return A fully configured <code>Session</code> instance complete with transport protocol settings.
@see TransportStrategy#generateProperties()
@see TransportStrategy#propertyNameHost()
@see TransportStrategy#propertyNamePort()
@see TransportStrategy#propertyNameUsername()
@see TransportStrategy#propertyNameAuthenticate()
"""
final Properties props = transportStrategy.generateProperties();
props.put(transportStrategy.propertyNameHost(), serverConfig.getHost());
props.put(transportStrategy.propertyNamePort(), String.valueOf(serverConfig.getPort()));
if (serverConfig.getUsername() != null) {
props.put(transportStrategy.propertyNameUsername(), serverConfig.getUsername());
}
if (serverConfig.getPassword() != null) {
props.put(transportStrategy.propertyNameAuthenticate(), "true");
return Session.getInstance(props, new SmtpAuthenticator(serverConfig));
} else {
return Session.getInstance(props);
}
} | java | @SuppressWarnings("WeakerAccess")
public static Session createMailSession(@Nonnull final ServerConfig serverConfig, @Nonnull final TransportStrategy transportStrategy) {
final Properties props = transportStrategy.generateProperties();
props.put(transportStrategy.propertyNameHost(), serverConfig.getHost());
props.put(transportStrategy.propertyNamePort(), String.valueOf(serverConfig.getPort()));
if (serverConfig.getUsername() != null) {
props.put(transportStrategy.propertyNameUsername(), serverConfig.getUsername());
}
if (serverConfig.getPassword() != null) {
props.put(transportStrategy.propertyNameAuthenticate(), "true");
return Session.getInstance(props, new SmtpAuthenticator(serverConfig));
} else {
return Session.getInstance(props);
}
} | [
"@",
"SuppressWarnings",
"(",
"\"WeakerAccess\"",
")",
"public",
"static",
"Session",
"createMailSession",
"(",
"@",
"Nonnull",
"final",
"ServerConfig",
"serverConfig",
",",
"@",
"Nonnull",
"final",
"TransportStrategy",
"transportStrategy",
")",
"{",
"final",
"Propert... | Instantiates and configures the {@link Session} instance. Delegates resolving transport protocol specific properties to the given {@link
TransportStrategy} in two ways: <ol> <li>request an initial property list which the strategy may pre-populate</li> <li>by requesting the
property names according to the respective transport protocol it handles (for the host property for example it would be
<em>"mail.smtp.host"</em> for SMTP and <em>"mail.smtps.host"</em> for SMTPS)</li> </ol>
<p>
Furthermore adds proxy SOCKS properties if a proxy configuration was provided, overwriting any SOCKS properties already present.
@param serverConfig Remote SMTP server details.
@param transportStrategy The transport protocol strategy enum that actually handles the session configuration. Session configuration meaning
setting the right properties for the appropriate transport type (ie. <em>"mail.smtp.host"</em> for SMTP,
<em>"mail.smtps.host"</em> for SMTPS).
@return A fully configured <code>Session</code> instance complete with transport protocol settings.
@see TransportStrategy#generateProperties()
@see TransportStrategy#propertyNameHost()
@see TransportStrategy#propertyNamePort()
@see TransportStrategy#propertyNameUsername()
@see TransportStrategy#propertyNameAuthenticate() | [
"Instantiates",
"and",
"configures",
"the",
"{",
"@link",
"Session",
"}",
"instance",
".",
"Delegates",
"resolving",
"transport",
"protocol",
"specific",
"properties",
"to",
"the",
"given",
"{",
"@link",
"TransportStrategy",
"}",
"in",
"two",
"ways",
":",
"<ol",... | train | https://github.com/bbottema/simple-java-mail/blob/b03635328aeecd525e35eddfef8f5b9a184559d8/modules/simple-java-mail/src/main/java/org/simplejavamail/mailer/internal/MailerImpl.java#L113-L129 |
betfair/cougar | cougar-codegen-plugin/src/main/java/com/betfair/cougar/codegen/IdlToDSMojo.java | IdlToDSMojo.generateJavaCode | private void generateJavaCode(Service service, Document iddDoc) throws Exception {
"""
The original concept of the IDLReader (other devs) has gone away a bit, so there could be
some refactoring around this.
"""
IDLReader reader = new IDLReader();
Document extensionDoc = parseExtensionFile(service.getServiceName());
String packageName = derivePackageName(service, iddDoc);
reader.init(iddDoc, extensionDoc, service.getServiceName(), packageName, getBaseDir(),
generatedSourceDir, getLog(), service.getOutputDir(), isClient(), isServer());
runMerge(reader);
// also create the stripped down, combined version of the IDD doc
getLog().debug("Generating combined IDD sans comments...");
Document combinedIDDDoc = parseIddFromString(reader.serialize());
// WARNING: this absolutely has to be run after a call to reader.runMerge (called by runMerge above) as otherwise the version will be null...
generateExposedIDD(combinedIDDDoc, reader.getInterfaceName(), reader.getInterfaceMajorMinorVersion());
// generate WSDL/XSD
getLog().debug("Generating wsdl...");
generateWsdl(iddDoc, reader.getInterfaceName(), reader.getInterfaceMajorMinorVersion());
getLog().debug("Generating xsd...");
generateXsd(iddDoc, reader.getInterfaceName(), reader.getInterfaceMajorMinorVersion());
} | java | private void generateJavaCode(Service service, Document iddDoc) throws Exception {
IDLReader reader = new IDLReader();
Document extensionDoc = parseExtensionFile(service.getServiceName());
String packageName = derivePackageName(service, iddDoc);
reader.init(iddDoc, extensionDoc, service.getServiceName(), packageName, getBaseDir(),
generatedSourceDir, getLog(), service.getOutputDir(), isClient(), isServer());
runMerge(reader);
// also create the stripped down, combined version of the IDD doc
getLog().debug("Generating combined IDD sans comments...");
Document combinedIDDDoc = parseIddFromString(reader.serialize());
// WARNING: this absolutely has to be run after a call to reader.runMerge (called by runMerge above) as otherwise the version will be null...
generateExposedIDD(combinedIDDDoc, reader.getInterfaceName(), reader.getInterfaceMajorMinorVersion());
// generate WSDL/XSD
getLog().debug("Generating wsdl...");
generateWsdl(iddDoc, reader.getInterfaceName(), reader.getInterfaceMajorMinorVersion());
getLog().debug("Generating xsd...");
generateXsd(iddDoc, reader.getInterfaceName(), reader.getInterfaceMajorMinorVersion());
} | [
"private",
"void",
"generateJavaCode",
"(",
"Service",
"service",
",",
"Document",
"iddDoc",
")",
"throws",
"Exception",
"{",
"IDLReader",
"reader",
"=",
"new",
"IDLReader",
"(",
")",
";",
"Document",
"extensionDoc",
"=",
"parseExtensionFile",
"(",
"service",
".... | The original concept of the IDLReader (other devs) has gone away a bit, so there could be
some refactoring around this. | [
"The",
"original",
"concept",
"of",
"the",
"IDLReader",
"(",
"other",
"devs",
")",
"has",
"gone",
"away",
"a",
"bit",
"so",
"there",
"could",
"be",
"some",
"refactoring",
"around",
"this",
"."
] | train | https://github.com/betfair/cougar/blob/08d1fe338fbd0e8572a9c2305bb5796402d5b1f5/cougar-codegen-plugin/src/main/java/com/betfair/cougar/codegen/IdlToDSMojo.java#L445-L469 |
deeplearning4j/deeplearning4j | nd4j/nd4j-backends/nd4j-backend-impls/nd4j-native/src/main/java/org/nd4j/linalg/cpu/nativecpu/blas/SparseCpuLevel1.java | SparseCpuLevel1.isamin | @Override
protected int isamin(long N, INDArray X, int incX) {
"""
Find the index of the element with minimum absolute value
@param N The number of elements in vector X
@param X a vector
@param incX The increment of X
@return the index of the element with minimum absolute value
"""
return (int) cblas_isamin((int) N, (FloatPointer) X.data().addressPointer(), incX);
} | java | @Override
protected int isamin(long N, INDArray X, int incX) {
return (int) cblas_isamin((int) N, (FloatPointer) X.data().addressPointer(), incX);
} | [
"@",
"Override",
"protected",
"int",
"isamin",
"(",
"long",
"N",
",",
"INDArray",
"X",
",",
"int",
"incX",
")",
"{",
"return",
"(",
"int",
")",
"cblas_isamin",
"(",
"(",
"int",
")",
"N",
",",
"(",
"FloatPointer",
")",
"X",
".",
"data",
"(",
")",
... | Find the index of the element with minimum absolute value
@param N The number of elements in vector X
@param X a vector
@param incX The increment of X
@return the index of the element with minimum absolute value | [
"Find",
"the",
"index",
"of",
"the",
"element",
"with",
"minimum",
"absolute",
"value"
] | train | https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/nd4j/nd4j-backends/nd4j-backend-impls/nd4j-native/src/main/java/org/nd4j/linalg/cpu/nativecpu/blas/SparseCpuLevel1.java#L163-L166 |
reactor/reactor-netty | src/main/java/reactor/netty/tcp/TcpClient.java | TcpClient.doOnConnect | public final TcpClient doOnConnect(Consumer<? super Bootstrap> doOnConnect) {
"""
Setup a callback called when {@link Channel} is about to connect.
@param doOnConnect a runnable observing connected events
@return a new {@link TcpClient}
"""
Objects.requireNonNull(doOnConnect, "doOnConnect");
return new TcpClientDoOn(this, doOnConnect, null, null);
} | java | public final TcpClient doOnConnect(Consumer<? super Bootstrap> doOnConnect) {
Objects.requireNonNull(doOnConnect, "doOnConnect");
return new TcpClientDoOn(this, doOnConnect, null, null);
} | [
"public",
"final",
"TcpClient",
"doOnConnect",
"(",
"Consumer",
"<",
"?",
"super",
"Bootstrap",
">",
"doOnConnect",
")",
"{",
"Objects",
".",
"requireNonNull",
"(",
"doOnConnect",
",",
"\"doOnConnect\"",
")",
";",
"return",
"new",
"TcpClientDoOn",
"(",
"this",
... | Setup a callback called when {@link Channel} is about to connect.
@param doOnConnect a runnable observing connected events
@return a new {@link TcpClient} | [
"Setup",
"a",
"callback",
"called",
"when",
"{",
"@link",
"Channel",
"}",
"is",
"about",
"to",
"connect",
"."
] | train | https://github.com/reactor/reactor-netty/blob/4ed14316e1d7fca3cecd18d6caa5f2251e159e49/src/main/java/reactor/netty/tcp/TcpClient.java#L238-L241 |
LMAX-Exchange/disruptor | src/main/java/com/lmax/disruptor/RingBuffer.java | RingBuffer.createSingleProducer | public static <E> RingBuffer<E> createSingleProducer(EventFactory<E> factory, int bufferSize) {
"""
Create a new single producer RingBuffer using the default wait strategy {@link BlockingWaitStrategy}.
@param <E> Class of the event stored in the ring buffer.
@param factory used to create the events within the ring buffer.
@param bufferSize number of elements to create within the ring buffer.
@return a constructed ring buffer.
@throws IllegalArgumentException if <code>bufferSize</code> is less than 1 or not a power of 2
@see MultiProducerSequencer
"""
return createSingleProducer(factory, bufferSize, new BlockingWaitStrategy());
} | java | public static <E> RingBuffer<E> createSingleProducer(EventFactory<E> factory, int bufferSize)
{
return createSingleProducer(factory, bufferSize, new BlockingWaitStrategy());
} | [
"public",
"static",
"<",
"E",
">",
"RingBuffer",
"<",
"E",
">",
"createSingleProducer",
"(",
"EventFactory",
"<",
"E",
">",
"factory",
",",
"int",
"bufferSize",
")",
"{",
"return",
"createSingleProducer",
"(",
"factory",
",",
"bufferSize",
",",
"new",
"Block... | Create a new single producer RingBuffer using the default wait strategy {@link BlockingWaitStrategy}.
@param <E> Class of the event stored in the ring buffer.
@param factory used to create the events within the ring buffer.
@param bufferSize number of elements to create within the ring buffer.
@return a constructed ring buffer.
@throws IllegalArgumentException if <code>bufferSize</code> is less than 1 or not a power of 2
@see MultiProducerSequencer | [
"Create",
"a",
"new",
"single",
"producer",
"RingBuffer",
"using",
"the",
"default",
"wait",
"strategy",
"{",
"@link",
"BlockingWaitStrategy",
"}",
"."
] | train | https://github.com/LMAX-Exchange/disruptor/blob/4266d00c5250190313446fdd7c8aa7a4edb5c818/src/main/java/com/lmax/disruptor/RingBuffer.java#L189-L192 |
yavijava/yavijava | src/main/java/com/vmware/vim25/mo/HostStorageSystem.java | HostStorageSystem.setNFSUser | public void setNFSUser(String user, String password) throws HostConfigFault, RuntimeFault, RemoteException {
"""
Set NFS username and password on the host. The specified password is stored encrypted at the host and overwrites
any previous password configuration. This information is only needed when the host has mounted NFS volumes with
security types that require user credentials for accessing data. The password is used to acquire credentials that
the NFS client needs to use in order to secure NFS traffic using RPCSECGSS. The client will access files on all
volumes mounted on this host (that are mounted with the relevant security type) on behalf of specified user.
<p>
At present, this API supports only file system NFSv4.1.
@param user Username
@param password Passowrd
@throws HostConfigFault
@throws RuntimeFault
@throws RemoteException
@since 6.0
"""
getVimService().setNFSUser(getMOR(), user, password);
} | java | public void setNFSUser(String user, String password) throws HostConfigFault, RuntimeFault, RemoteException {
getVimService().setNFSUser(getMOR(), user, password);
} | [
"public",
"void",
"setNFSUser",
"(",
"String",
"user",
",",
"String",
"password",
")",
"throws",
"HostConfigFault",
",",
"RuntimeFault",
",",
"RemoteException",
"{",
"getVimService",
"(",
")",
".",
"setNFSUser",
"(",
"getMOR",
"(",
")",
",",
"user",
",",
"pa... | Set NFS username and password on the host. The specified password is stored encrypted at the host and overwrites
any previous password configuration. This information is only needed when the host has mounted NFS volumes with
security types that require user credentials for accessing data. The password is used to acquire credentials that
the NFS client needs to use in order to secure NFS traffic using RPCSECGSS. The client will access files on all
volumes mounted on this host (that are mounted with the relevant security type) on behalf of specified user.
<p>
At present, this API supports only file system NFSv4.1.
@param user Username
@param password Passowrd
@throws HostConfigFault
@throws RuntimeFault
@throws RemoteException
@since 6.0 | [
"Set",
"NFS",
"username",
"and",
"password",
"on",
"the",
"host",
".",
"The",
"specified",
"password",
"is",
"stored",
"encrypted",
"at",
"the",
"host",
"and",
"overwrites",
"any",
"previous",
"password",
"configuration",
".",
"This",
"information",
"is",
"onl... | train | https://github.com/yavijava/yavijava/blob/27fd2c5826115782d5eeb934f86e3e39240179cd/src/main/java/com/vmware/vim25/mo/HostStorageSystem.java#L535-L537 |
ppicas/custom-typeface | library/src/main/java/cat/ppicas/customtypeface/CustomTypefaceFactory.java | CustomTypefaceFactory.onCreateView | @Override
public View onCreateView(String name, Context context, AttributeSet attrs) {
"""
Implements {@link LayoutInflater.Factory} interface. Inflate the {@link View} for the
specified tag name and apply custom {@link Typeface} if is required. This
method first will delegate to the {@code LayoutInflater.Factory} if it was specified on the
constructor. When the {@code View} is created, this method will call {@link
CustomTypeface#applyTypeface(View, AttributeSet)} on it.
<p>
This method can be used to delegate the implementation of {@link
LayoutInflater.Factory#onCreateView}
or {@link LayoutInflater.Factory2#onCreateView}.
</p>
@param name Tag name to be inflated.
@param context The context the view is being created in.
@param attrs Inflation attributes as specified in XML file.
@return Newly created view.
@see LayoutInflater.Factory
@see CustomTypeface#applyTypeface(View, AttributeSet)
"""
String prefix = null;
if (name.indexOf('.') == -1) {
prefix = "android.widget.";
}
try {
View view = null;
if (mFactory != null) {
view = mFactory.onCreateView(name, context, attrs);
}
if (view == null) {
view = createView(name, prefix, context, attrs);
}
mCustomTypeface.applyTypeface(view, attrs);
return view;
} catch (ClassNotFoundException e) {
return null;
}
} | java | @Override
public View onCreateView(String name, Context context, AttributeSet attrs) {
String prefix = null;
if (name.indexOf('.') == -1) {
prefix = "android.widget.";
}
try {
View view = null;
if (mFactory != null) {
view = mFactory.onCreateView(name, context, attrs);
}
if (view == null) {
view = createView(name, prefix, context, attrs);
}
mCustomTypeface.applyTypeface(view, attrs);
return view;
} catch (ClassNotFoundException e) {
return null;
}
} | [
"@",
"Override",
"public",
"View",
"onCreateView",
"(",
"String",
"name",
",",
"Context",
"context",
",",
"AttributeSet",
"attrs",
")",
"{",
"String",
"prefix",
"=",
"null",
";",
"if",
"(",
"name",
".",
"indexOf",
"(",
"'",
"'",
")",
"==",
"-",
"1",
... | Implements {@link LayoutInflater.Factory} interface. Inflate the {@link View} for the
specified tag name and apply custom {@link Typeface} if is required. This
method first will delegate to the {@code LayoutInflater.Factory} if it was specified on the
constructor. When the {@code View} is created, this method will call {@link
CustomTypeface#applyTypeface(View, AttributeSet)} on it.
<p>
This method can be used to delegate the implementation of {@link
LayoutInflater.Factory#onCreateView}
or {@link LayoutInflater.Factory2#onCreateView}.
</p>
@param name Tag name to be inflated.
@param context The context the view is being created in.
@param attrs Inflation attributes as specified in XML file.
@return Newly created view.
@see LayoutInflater.Factory
@see CustomTypeface#applyTypeface(View, AttributeSet) | [
"Implements",
"{",
"@link",
"LayoutInflater",
".",
"Factory",
"}",
"interface",
".",
"Inflate",
"the",
"{",
"@link",
"View",
"}",
"for",
"the",
"specified",
"tag",
"name",
"and",
"apply",
"custom",
"{",
"@link",
"Typeface",
"}",
"if",
"is",
"required",
"."... | train | https://github.com/ppicas/custom-typeface/blob/3a2a68cc8584a72076c545a8b7c9f741f6002241/library/src/main/java/cat/ppicas/customtypeface/CustomTypefaceFactory.java#L133-L152 |
apache/flink | flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/util/SegmentsUtil.java | SegmentsUtil.setDouble | public static void setDouble(MemorySegment[] segments, int offset, double value) {
"""
set double from segments.
@param segments target segments.
@param offset value offset.
"""
if (inFirstSegment(segments, offset, 8)) {
segments[0].putDouble(offset, value);
} else {
setDoubleMultiSegments(segments, offset, value);
}
} | java | public static void setDouble(MemorySegment[] segments, int offset, double value) {
if (inFirstSegment(segments, offset, 8)) {
segments[0].putDouble(offset, value);
} else {
setDoubleMultiSegments(segments, offset, value);
}
} | [
"public",
"static",
"void",
"setDouble",
"(",
"MemorySegment",
"[",
"]",
"segments",
",",
"int",
"offset",
",",
"double",
"value",
")",
"{",
"if",
"(",
"inFirstSegment",
"(",
"segments",
",",
"offset",
",",
"8",
")",
")",
"{",
"segments",
"[",
"0",
"]"... | set double from segments.
@param segments target segments.
@param offset value offset. | [
"set",
"double",
"from",
"segments",
"."
] | train | https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/util/SegmentsUtil.java#L930-L936 |
sarl/sarl | main/coreplugins/io.sarl.lang/src/io/sarl/lang/formatting2/SARLFormatter.java | SARLFormatter._format | protected void _format(SarlSkill skill, IFormattableDocument document) {
"""
Format the given SARL skill.
@param skill the SARL component.
@param document the document.
"""
formatAnnotations(skill, document, XbaseFormatterPreferenceKeys.newLineAfterClassAnnotations);
formatModifiers(skill, document);
final ISemanticRegionsFinder regionFor = this.textRegionExtensions.regionFor(skill);
document.append(regionFor.keyword(this.keywords.getSkillKeyword()), ONE_SPACE);
document.surround(regionFor.keyword(this.keywords.getExtendsKeyword()), ONE_SPACE);
document.format(skill.getExtends());
document.surround(regionFor.keyword(this.keywords.getImplementsKeyword()), ONE_SPACE);
formatCommaSeparatedList(skill.getImplements(), document);
formatBody(skill, document);
} | java | protected void _format(SarlSkill skill, IFormattableDocument document) {
formatAnnotations(skill, document, XbaseFormatterPreferenceKeys.newLineAfterClassAnnotations);
formatModifiers(skill, document);
final ISemanticRegionsFinder regionFor = this.textRegionExtensions.regionFor(skill);
document.append(regionFor.keyword(this.keywords.getSkillKeyword()), ONE_SPACE);
document.surround(regionFor.keyword(this.keywords.getExtendsKeyword()), ONE_SPACE);
document.format(skill.getExtends());
document.surround(regionFor.keyword(this.keywords.getImplementsKeyword()), ONE_SPACE);
formatCommaSeparatedList(skill.getImplements(), document);
formatBody(skill, document);
} | [
"protected",
"void",
"_format",
"(",
"SarlSkill",
"skill",
",",
"IFormattableDocument",
"document",
")",
"{",
"formatAnnotations",
"(",
"skill",
",",
"document",
",",
"XbaseFormatterPreferenceKeys",
".",
"newLineAfterClassAnnotations",
")",
";",
"formatModifiers",
"(",
... | Format the given SARL skill.
@param skill the SARL component.
@param document the document. | [
"Format",
"the",
"given",
"SARL",
"skill",
"."
] | train | https://github.com/sarl/sarl/blob/ca00ff994598c730339972def4e19a60e0b8cace/main/coreplugins/io.sarl.lang/src/io/sarl/lang/formatting2/SARLFormatter.java#L268-L282 |
ManfredTremmel/gwt-commons-lang3 | src/main/java/org/apache/commons/lang3/ClassUtils.java | ClassUtils.getPackageName | public static String getPackageName(final Object object, final String valueIfNull) {
"""
<p>Gets the package name of an {@code Object}.</p>
@param object the class to get the package name for, may be null
@param valueIfNull the value to return if null
@return the package name of the object, or the null value
"""
if (object == null) {
return valueIfNull;
}
return getPackageName(object.getClass());
} | java | public static String getPackageName(final Object object, final String valueIfNull) {
if (object == null) {
return valueIfNull;
}
return getPackageName(object.getClass());
} | [
"public",
"static",
"String",
"getPackageName",
"(",
"final",
"Object",
"object",
",",
"final",
"String",
"valueIfNull",
")",
"{",
"if",
"(",
"object",
"==",
"null",
")",
"{",
"return",
"valueIfNull",
";",
"}",
"return",
"getPackageName",
"(",
"object",
".",... | <p>Gets the package name of an {@code Object}.</p>
@param object the class to get the package name for, may be null
@param valueIfNull the value to return if null
@return the package name of the object, or the null value | [
"<p",
">",
"Gets",
"the",
"package",
"name",
"of",
"an",
"{",
"@code",
"Object",
"}",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/ManfredTremmel/gwt-commons-lang3/blob/9e2dfbbda3668cfa5d935fe76479d1426c294504/src/main/java/org/apache/commons/lang3/ClassUtils.java#L354-L359 |
mapsforge/mapsforge | mapsforge-poi-writer/src/main/java/org/mapsforge/poi/writer/PoiWriter.java | PoiWriter.getTagValue | String getTagValue(Collection<Tag> tags, String key) {
"""
Returns value of given tag in a set of tags.
@param tags collection of tags
@param key tag key
@return Tag value or null if not exists
"""
for (Tag tag : tags) {
if (tag.getKey().toLowerCase(Locale.ENGLISH).equals(key.toLowerCase(Locale.ENGLISH))) {
return tag.getValue();
}
}
return null;
} | java | String getTagValue(Collection<Tag> tags, String key) {
for (Tag tag : tags) {
if (tag.getKey().toLowerCase(Locale.ENGLISH).equals(key.toLowerCase(Locale.ENGLISH))) {
return tag.getValue();
}
}
return null;
} | [
"String",
"getTagValue",
"(",
"Collection",
"<",
"Tag",
">",
"tags",
",",
"String",
"key",
")",
"{",
"for",
"(",
"Tag",
"tag",
":",
"tags",
")",
"{",
"if",
"(",
"tag",
".",
"getKey",
"(",
")",
".",
"toLowerCase",
"(",
"Locale",
".",
"ENGLISH",
")",... | Returns value of given tag in a set of tags.
@param tags collection of tags
@param key tag key
@return Tag value or null if not exists | [
"Returns",
"value",
"of",
"given",
"tag",
"in",
"a",
"set",
"of",
"tags",
"."
] | train | https://github.com/mapsforge/mapsforge/blob/c49c83f7f727552f793dff15cefa532ade030842/mapsforge-poi-writer/src/main/java/org/mapsforge/poi/writer/PoiWriter.java#L295-L302 |
phax/ph-web | ph-servlet/src/main/java/com/helger/servlet/response/UnifiedResponseDefaultSettings.java | UnifiedResponseDefaultSettings.setResponseHeader | public static void setResponseHeader (@Nonnull @Nonempty final String sName, @Nonnull @Nonempty final String sValue) {
"""
Sets a response header to the response according to the passed name and
value. An existing header entry with the same name is overridden.
@param sName
Name of the header. May neither be <code>null</code> nor empty.
@param sValue
Value of the header. May neither be <code>null</code> nor empty.
"""
ValueEnforcer.notEmpty (sName, "Name");
ValueEnforcer.notEmpty (sValue, "Value");
s_aRWLock.writeLocked ( () -> s_aResponseHeaderMap.setHeader (sName, sValue));
} | java | public static void setResponseHeader (@Nonnull @Nonempty final String sName, @Nonnull @Nonempty final String sValue)
{
ValueEnforcer.notEmpty (sName, "Name");
ValueEnforcer.notEmpty (sValue, "Value");
s_aRWLock.writeLocked ( () -> s_aResponseHeaderMap.setHeader (sName, sValue));
} | [
"public",
"static",
"void",
"setResponseHeader",
"(",
"@",
"Nonnull",
"@",
"Nonempty",
"final",
"String",
"sName",
",",
"@",
"Nonnull",
"@",
"Nonempty",
"final",
"String",
"sValue",
")",
"{",
"ValueEnforcer",
".",
"notEmpty",
"(",
"sName",
",",
"\"Name\"",
"... | Sets a response header to the response according to the passed name and
value. An existing header entry with the same name is overridden.
@param sName
Name of the header. May neither be <code>null</code> nor empty.
@param sValue
Value of the header. May neither be <code>null</code> nor empty. | [
"Sets",
"a",
"response",
"header",
"to",
"the",
"response",
"according",
"to",
"the",
"passed",
"name",
"and",
"value",
".",
"An",
"existing",
"header",
"entry",
"with",
"the",
"same",
"name",
"is",
"overridden",
"."
] | train | https://github.com/phax/ph-web/blob/d445fd25184605b62682c93c9782409acf0ae813/ph-servlet/src/main/java/com/helger/servlet/response/UnifiedResponseDefaultSettings.java#L217-L224 |
webmetrics/browsermob-proxy | src/main/java/org/xbill/DNS/DNSInput.java | DNSInput.readByteArray | public void
readByteArray(byte [] b, int off, int len) throws WireParseException {
"""
Reads a byte array of a specified length from the stream into an existing
array.
@param b The array to read into.
@param off The offset of the array to start copying data into.
@param len The number of bytes to copy.
@throws WireParseException The end of the stream was reached.
"""
require(len);
System.arraycopy(array, pos, b, off, len);
pos += len;
} | java | public void
readByteArray(byte [] b, int off, int len) throws WireParseException {
require(len);
System.arraycopy(array, pos, b, off, len);
pos += len;
} | [
"public",
"void",
"readByteArray",
"(",
"byte",
"[",
"]",
"b",
",",
"int",
"off",
",",
"int",
"len",
")",
"throws",
"WireParseException",
"{",
"require",
"(",
"len",
")",
";",
"System",
".",
"arraycopy",
"(",
"array",
",",
"pos",
",",
"b",
",",
"off"... | Reads a byte array of a specified length from the stream into an existing
array.
@param b The array to read into.
@param off The offset of the array to start copying data into.
@param len The number of bytes to copy.
@throws WireParseException The end of the stream was reached. | [
"Reads",
"a",
"byte",
"array",
"of",
"a",
"specified",
"length",
"from",
"the",
"stream",
"into",
"an",
"existing",
"array",
"."
] | train | https://github.com/webmetrics/browsermob-proxy/blob/a9252e62246ac33d55d51b993ba1159404e7d389/src/main/java/org/xbill/DNS/DNSInput.java#L168-L173 |
Azure/azure-sdk-for-java | notificationhubs/resource-manager/v2017_04_01/src/main/java/com/microsoft/azure/management/notificationhubs/v2017_04_01/implementation/NotificationHubsInner.java | NotificationHubsInner.listAuthorizationRulesAsync | public Observable<Page<SharedAccessAuthorizationRuleResourceInner>> listAuthorizationRulesAsync(final String resourceGroupName, final String namespaceName, final String notificationHubName) {
"""
Gets the authorization rules for a NotificationHub.
@param resourceGroupName The name of the resource group.
@param namespaceName The namespace name
@param notificationHubName The notification hub name.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the PagedList<SharedAccessAuthorizationRuleResourceInner> object
"""
return listAuthorizationRulesWithServiceResponseAsync(resourceGroupName, namespaceName, notificationHubName)
.map(new Func1<ServiceResponse<Page<SharedAccessAuthorizationRuleResourceInner>>, Page<SharedAccessAuthorizationRuleResourceInner>>() {
@Override
public Page<SharedAccessAuthorizationRuleResourceInner> call(ServiceResponse<Page<SharedAccessAuthorizationRuleResourceInner>> response) {
return response.body();
}
});
} | java | public Observable<Page<SharedAccessAuthorizationRuleResourceInner>> listAuthorizationRulesAsync(final String resourceGroupName, final String namespaceName, final String notificationHubName) {
return listAuthorizationRulesWithServiceResponseAsync(resourceGroupName, namespaceName, notificationHubName)
.map(new Func1<ServiceResponse<Page<SharedAccessAuthorizationRuleResourceInner>>, Page<SharedAccessAuthorizationRuleResourceInner>>() {
@Override
public Page<SharedAccessAuthorizationRuleResourceInner> call(ServiceResponse<Page<SharedAccessAuthorizationRuleResourceInner>> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"Page",
"<",
"SharedAccessAuthorizationRuleResourceInner",
">",
">",
"listAuthorizationRulesAsync",
"(",
"final",
"String",
"resourceGroupName",
",",
"final",
"String",
"namespaceName",
",",
"final",
"String",
"notificationHubName",
")",
"{",
... | Gets the authorization rules for a NotificationHub.
@param resourceGroupName The name of the resource group.
@param namespaceName The namespace name
@param notificationHubName The notification hub name.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the PagedList<SharedAccessAuthorizationRuleResourceInner> object | [
"Gets",
"the",
"authorization",
"rules",
"for",
"a",
"NotificationHub",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/notificationhubs/resource-manager/v2017_04_01/src/main/java/com/microsoft/azure/management/notificationhubs/v2017_04_01/implementation/NotificationHubsInner.java#L1373-L1381 |
alkacon/opencms-core | src/org/opencms/db/CmsSecurityManager.java | CmsSecurityManager.getLock | public CmsLock getLock(CmsRequestContext context, CmsResource resource) throws CmsException {
"""
Returns the lock state of a resource.<p>
@param context the current request context
@param resource the resource to return the lock state for
@return the lock state of the resource
@throws CmsException if something goes wrong
"""
CmsDbContext dbc = m_dbContextFactory.getDbContext(context);
CmsLock result = null;
try {
result = m_driverManager.getLock(dbc, resource);
} catch (Exception e) {
dbc.report(null, Messages.get().container(Messages.ERR_GET_LOCK_1, context.getSitePath(resource)), e);
} finally {
dbc.clear();
}
return result;
} | java | public CmsLock getLock(CmsRequestContext context, CmsResource resource) throws CmsException {
CmsDbContext dbc = m_dbContextFactory.getDbContext(context);
CmsLock result = null;
try {
result = m_driverManager.getLock(dbc, resource);
} catch (Exception e) {
dbc.report(null, Messages.get().container(Messages.ERR_GET_LOCK_1, context.getSitePath(resource)), e);
} finally {
dbc.clear();
}
return result;
} | [
"public",
"CmsLock",
"getLock",
"(",
"CmsRequestContext",
"context",
",",
"CmsResource",
"resource",
")",
"throws",
"CmsException",
"{",
"CmsDbContext",
"dbc",
"=",
"m_dbContextFactory",
".",
"getDbContext",
"(",
"context",
")",
";",
"CmsLock",
"result",
"=",
"nul... | Returns the lock state of a resource.<p>
@param context the current request context
@param resource the resource to return the lock state for
@return the lock state of the resource
@throws CmsException if something goes wrong | [
"Returns",
"the",
"lock",
"state",
"of",
"a",
"resource",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/db/CmsSecurityManager.java#L2246-L2258 |
phax/ph-commons | ph-security/src/main/java/com/helger/security/keystore/KeyStoreHelper.java | KeyStoreHelper.loadSecretKey | @Nonnull
public static LoadedKey <KeyStore.SecretKeyEntry> loadSecretKey (@Nonnull final KeyStore aKeyStore,
@Nonnull final String sKeyStorePath,
@Nullable final String sKeyStoreKeyAlias,
@Nullable final char [] aKeyStoreKeyPassword) {
"""
Load the specified secret key entry from the provided key store.
@param aKeyStore
The key store to load the key from. May not be <code>null</code>.
@param sKeyStorePath
Key store path. For nice error messages only. May be
<code>null</code>.
@param sKeyStoreKeyAlias
The alias to be resolved in the key store. Must be non-
<code>null</code> to succeed.
@param aKeyStoreKeyPassword
The key password for the key store. Must be non-<code>null</code> to
succeed.
@return The key loading result. Never <code>null</code>.
"""
return _loadKey (aKeyStore, sKeyStorePath, sKeyStoreKeyAlias, aKeyStoreKeyPassword, KeyStore.SecretKeyEntry.class);
} | java | @Nonnull
public static LoadedKey <KeyStore.SecretKeyEntry> loadSecretKey (@Nonnull final KeyStore aKeyStore,
@Nonnull final String sKeyStorePath,
@Nullable final String sKeyStoreKeyAlias,
@Nullable final char [] aKeyStoreKeyPassword)
{
return _loadKey (aKeyStore, sKeyStorePath, sKeyStoreKeyAlias, aKeyStoreKeyPassword, KeyStore.SecretKeyEntry.class);
} | [
"@",
"Nonnull",
"public",
"static",
"LoadedKey",
"<",
"KeyStore",
".",
"SecretKeyEntry",
">",
"loadSecretKey",
"(",
"@",
"Nonnull",
"final",
"KeyStore",
"aKeyStore",
",",
"@",
"Nonnull",
"final",
"String",
"sKeyStorePath",
",",
"@",
"Nullable",
"final",
"String"... | Load the specified secret key entry from the provided key store.
@param aKeyStore
The key store to load the key from. May not be <code>null</code>.
@param sKeyStorePath
Key store path. For nice error messages only. May be
<code>null</code>.
@param sKeyStoreKeyAlias
The alias to be resolved in the key store. Must be non-
<code>null</code> to succeed.
@param aKeyStoreKeyPassword
The key password for the key store. Must be non-<code>null</code> to
succeed.
@return The key loading result. Never <code>null</code>. | [
"Load",
"the",
"specified",
"secret",
"key",
"entry",
"from",
"the",
"provided",
"key",
"store",
"."
] | train | https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-security/src/main/java/com/helger/security/keystore/KeyStoreHelper.java#L360-L367 |
Guichaguri/MinimalFTP | src/main/java/com/guichaguri/minimalftp/FTPServer.java | FTPServer.listen | public void listen(InetAddress address, int port) throws IOException {
"""
Starts the FTP server asynchronously.
@param address The server address or {@code null} for a local address
@param port The server port or {@code 0} to automatically allocate the port
@throws IOException When an error occurs while starting the server
"""
if(auth == null) throw new NullPointerException("The Authenticator is null");
if(socket != null) throw new IOException("Server already started");
socket = Utils.createServer(port, 50, address, ssl, !explicitSecurity);
serverThread = new ServerThread();
serverThread.setDaemon(true);
serverThread.start();
} | java | public void listen(InetAddress address, int port) throws IOException {
if(auth == null) throw new NullPointerException("The Authenticator is null");
if(socket != null) throw new IOException("Server already started");
socket = Utils.createServer(port, 50, address, ssl, !explicitSecurity);
serverThread = new ServerThread();
serverThread.setDaemon(true);
serverThread.start();
} | [
"public",
"void",
"listen",
"(",
"InetAddress",
"address",
",",
"int",
"port",
")",
"throws",
"IOException",
"{",
"if",
"(",
"auth",
"==",
"null",
")",
"throw",
"new",
"NullPointerException",
"(",
"\"The Authenticator is null\"",
")",
";",
"if",
"(",
"socket",... | Starts the FTP server asynchronously.
@param address The server address or {@code null} for a local address
@param port The server port or {@code 0} to automatically allocate the port
@throws IOException When an error occurs while starting the server | [
"Starts",
"the",
"FTP",
"server",
"asynchronously",
"."
] | train | https://github.com/Guichaguri/MinimalFTP/blob/ddd81e26ec88079ee4c37fe53d8efe420996e9b1/src/main/java/com/guichaguri/minimalftp/FTPServer.java#L197-L206 |
deeplearning4j/deeplearning4j | nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/samediff/ops/SDBaseOps.java | SDBaseOps.onesLike | public SDVariable onesLike(String name, SDVariable input) {
"""
Return a variable of all 1s, with the same shape as the input variable. Note that this is dynamic:
if the input shape changes in later execution, the returned variable's shape will also be updated
@param name Name of the new SDVariable
@param input Input SDVariable
@return A new SDVariable with the same (dynamic) shape as the input
"""
return onesLike(name, input, input.dataType());
} | java | public SDVariable onesLike(String name, SDVariable input) {
return onesLike(name, input, input.dataType());
} | [
"public",
"SDVariable",
"onesLike",
"(",
"String",
"name",
",",
"SDVariable",
"input",
")",
"{",
"return",
"onesLike",
"(",
"name",
",",
"input",
",",
"input",
".",
"dataType",
"(",
")",
")",
";",
"}"
] | Return a variable of all 1s, with the same shape as the input variable. Note that this is dynamic:
if the input shape changes in later execution, the returned variable's shape will also be updated
@param name Name of the new SDVariable
@param input Input SDVariable
@return A new SDVariable with the same (dynamic) shape as the input | [
"Return",
"a",
"variable",
"of",
"all",
"1s",
"with",
"the",
"same",
"shape",
"as",
"the",
"input",
"variable",
".",
"Note",
"that",
"this",
"is",
"dynamic",
":",
"if",
"the",
"input",
"shape",
"changes",
"in",
"later",
"execution",
"the",
"returned",
"v... | 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#L1528-L1530 |
LableOrg/java-uniqueid | uniqueid-core/src/main/java/org/lable/oss/uniqueid/ParameterUtil.java | ParameterUtil.assertNotNullEightBytes | public static void assertNotNullEightBytes(byte[] bytes) {
"""
Thrown an {@link IllegalArgumentException} when the byte array does not contain exactly eight bytes.
@param bytes Byte array.
"""
if (bytes == null) {
throw new IllegalArgumentException("Expected 8 bytes, but got null.");
}
if (bytes.length != 8) {
throw new IllegalArgumentException(String.format("Expected 8 bytes, but got: %d bytes.", bytes.length));
}
} | java | public static void assertNotNullEightBytes(byte[] bytes) {
if (bytes == null) {
throw new IllegalArgumentException("Expected 8 bytes, but got null.");
}
if (bytes.length != 8) {
throw new IllegalArgumentException(String.format("Expected 8 bytes, but got: %d bytes.", bytes.length));
}
} | [
"public",
"static",
"void",
"assertNotNullEightBytes",
"(",
"byte",
"[",
"]",
"bytes",
")",
"{",
"if",
"(",
"bytes",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Expected 8 bytes, but got null.\"",
")",
";",
"}",
"if",
"(",
"byte... | Thrown an {@link IllegalArgumentException} when the byte array does not contain exactly eight bytes.
@param bytes Byte array. | [
"Thrown",
"an",
"{",
"@link",
"IllegalArgumentException",
"}",
"when",
"the",
"byte",
"array",
"does",
"not",
"contain",
"exactly",
"eight",
"bytes",
"."
] | train | https://github.com/LableOrg/java-uniqueid/blob/554e30b2277765f365e7c7f598108de0ab5744f4/uniqueid-core/src/main/java/org/lable/oss/uniqueid/ParameterUtil.java#L43-L50 |
allengeorge/libraft | libraft-agent/src/main/java/io/libraft/agent/persistence/JDBCLog.java | JDBCLog.setupCustomCommandSerializerAndDeserializer | public synchronized void setupCustomCommandSerializerAndDeserializer(CommandSerializer commandSerializer, CommandDeserializer commandDeserializer) {
"""
Set the {@code CommandSerializer} and {@code CommandDeserializer} used by this {@code JDBCLog} instance.
This <strong>overrides</strong> the serializer/deserializer pair specified in the instance constructor.
@param commandSerializer instance of {@code CommandSerializer} that will
will serialize {@code Command} instances to the database
@param commandDeserializer instance of {@code CommandDeserializer}
that will deserialize database rows that contain {@code Command}
instances into their corresponding Java representation
@throws IllegalStateException if this method is called <strong>after</strong>
a successful call to {@link JDBCLog#initialize()}
@see io.libraft.Command
"""
checkState(!isInitialized());
this.commandSerializer = commandSerializer;
this.commandDeserializer = commandDeserializer;
} | java | public synchronized void setupCustomCommandSerializerAndDeserializer(CommandSerializer commandSerializer, CommandDeserializer commandDeserializer) {
checkState(!isInitialized());
this.commandSerializer = commandSerializer;
this.commandDeserializer = commandDeserializer;
} | [
"public",
"synchronized",
"void",
"setupCustomCommandSerializerAndDeserializer",
"(",
"CommandSerializer",
"commandSerializer",
",",
"CommandDeserializer",
"commandDeserializer",
")",
"{",
"checkState",
"(",
"!",
"isInitialized",
"(",
")",
")",
";",
"this",
".",
"commandS... | Set the {@code CommandSerializer} and {@code CommandDeserializer} used by this {@code JDBCLog} instance.
This <strong>overrides</strong> the serializer/deserializer pair specified in the instance constructor.
@param commandSerializer instance of {@code CommandSerializer} that will
will serialize {@code Command} instances to the database
@param commandDeserializer instance of {@code CommandDeserializer}
that will deserialize database rows that contain {@code Command}
instances into their corresponding Java representation
@throws IllegalStateException if this method is called <strong>after</strong>
a successful call to {@link JDBCLog#initialize()}
@see io.libraft.Command | [
"Set",
"the",
"{",
"@code",
"CommandSerializer",
"}",
"and",
"{",
"@code",
"CommandDeserializer",
"}",
"used",
"by",
"this",
"{",
"@code",
"JDBCLog",
"}",
"instance",
".",
"This",
"<strong",
">",
"overrides<",
"/",
"strong",
">",
"the",
"serializer",
"/",
... | train | https://github.com/allengeorge/libraft/blob/00d68bb5e68d4020af59df3c8a9a14380108ac89/libraft-agent/src/main/java/io/libraft/agent/persistence/JDBCLog.java#L123-L128 |
wso2/transport-http | components/org.wso2.transport.http.netty/src/main/java/org/wso2/transport/http/netty/contractimpl/common/states/Http2StateUtil.java | Http2StateUtil.releaseDataFrame | public static void releaseDataFrame(Http2SourceHandler http2SourceHandler, Http2DataFrame dataFrame) {
"""
Releases the {@link io.netty.buffer.ByteBuf} content.
@param http2SourceHandler the HTTP2 source handler
@param dataFrame the HTTP2 data frame to be released
"""
int streamId = dataFrame.getStreamId();
HttpCarbonMessage sourceReqCMsg = http2SourceHandler.getStreamIdRequestMap().get(streamId);
if (sourceReqCMsg != null) {
sourceReqCMsg.addHttpContent(new DefaultLastHttpContent());
http2SourceHandler.getStreamIdRequestMap().remove(streamId);
}
dataFrame.getData().release();
} | java | public static void releaseDataFrame(Http2SourceHandler http2SourceHandler, Http2DataFrame dataFrame) {
int streamId = dataFrame.getStreamId();
HttpCarbonMessage sourceReqCMsg = http2SourceHandler.getStreamIdRequestMap().get(streamId);
if (sourceReqCMsg != null) {
sourceReqCMsg.addHttpContent(new DefaultLastHttpContent());
http2SourceHandler.getStreamIdRequestMap().remove(streamId);
}
dataFrame.getData().release();
} | [
"public",
"static",
"void",
"releaseDataFrame",
"(",
"Http2SourceHandler",
"http2SourceHandler",
",",
"Http2DataFrame",
"dataFrame",
")",
"{",
"int",
"streamId",
"=",
"dataFrame",
".",
"getStreamId",
"(",
")",
";",
"HttpCarbonMessage",
"sourceReqCMsg",
"=",
"http2Sour... | Releases the {@link io.netty.buffer.ByteBuf} content.
@param http2SourceHandler the HTTP2 source handler
@param dataFrame the HTTP2 data frame to be released | [
"Releases",
"the",
"{",
"@link",
"io",
".",
"netty",
".",
"buffer",
".",
"ByteBuf",
"}",
"content",
"."
] | 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/states/Http2StateUtil.java#L229-L237 |
eclipse/hawkbit | hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/RepositoryApplicationConfiguration.java | RepositoryApplicationConfiguration.controllerManagement | @Bean
@ConditionalOnMissingBean
ControllerManagement controllerManagement(final ScheduledExecutorService executorService,
final RepositoryProperties repositoryProperties) {
"""
{@link JpaControllerManagement} bean.
@return a new {@link ControllerManagement}
"""
return new JpaControllerManagement(executorService, repositoryProperties);
} | java | @Bean
@ConditionalOnMissingBean
ControllerManagement controllerManagement(final ScheduledExecutorService executorService,
final RepositoryProperties repositoryProperties) {
return new JpaControllerManagement(executorService, repositoryProperties);
} | [
"@",
"Bean",
"@",
"ConditionalOnMissingBean",
"ControllerManagement",
"controllerManagement",
"(",
"final",
"ScheduledExecutorService",
"executorService",
",",
"final",
"RepositoryProperties",
"repositoryProperties",
")",
"{",
"return",
"new",
"JpaControllerManagement",
"(",
... | {@link JpaControllerManagement} bean.
@return a new {@link ControllerManagement} | [
"{",
"@link",
"JpaControllerManagement",
"}",
"bean",
"."
] | train | https://github.com/eclipse/hawkbit/blob/9884452ad42f3b4827461606d8a9215c8625a7fe/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/RepositoryApplicationConfiguration.java#L690-L695 |
netty/netty | common/src/main/java/io/netty/util/AsciiString.java | AsciiString.toLowerCase | public AsciiString toLowerCase() {
"""
Converts the characters in this string to lowercase, using the default Locale.
@return a new string containing the lowercase characters equivalent to the characters in this string.
"""
boolean lowercased = true;
int i, j;
final int len = length() + arrayOffset();
for (i = arrayOffset(); i < len; ++i) {
byte b = value[i];
if (b >= 'A' && b <= 'Z') {
lowercased = false;
break;
}
}
// Check if this string does not contain any uppercase characters.
if (lowercased) {
return this;
}
final byte[] newValue = PlatformDependent.allocateUninitializedArray(length());
for (i = 0, j = arrayOffset(); i < newValue.length; ++i, ++j) {
newValue[i] = toLowerCase(value[j]);
}
return new AsciiString(newValue, false);
} | java | public AsciiString toLowerCase() {
boolean lowercased = true;
int i, j;
final int len = length() + arrayOffset();
for (i = arrayOffset(); i < len; ++i) {
byte b = value[i];
if (b >= 'A' && b <= 'Z') {
lowercased = false;
break;
}
}
// Check if this string does not contain any uppercase characters.
if (lowercased) {
return this;
}
final byte[] newValue = PlatformDependent.allocateUninitializedArray(length());
for (i = 0, j = arrayOffset(); i < newValue.length; ++i, ++j) {
newValue[i] = toLowerCase(value[j]);
}
return new AsciiString(newValue, false);
} | [
"public",
"AsciiString",
"toLowerCase",
"(",
")",
"{",
"boolean",
"lowercased",
"=",
"true",
";",
"int",
"i",
",",
"j",
";",
"final",
"int",
"len",
"=",
"length",
"(",
")",
"+",
"arrayOffset",
"(",
")",
";",
"for",
"(",
"i",
"=",
"arrayOffset",
"(",
... | Converts the characters in this string to lowercase, using the default Locale.
@return a new string containing the lowercase characters equivalent to the characters in this string. | [
"Converts",
"the",
"characters",
"in",
"this",
"string",
"to",
"lowercase",
"using",
"the",
"default",
"Locale",
"."
] | train | https://github.com/netty/netty/blob/ba06eafa1c1824bd154f1a380019e7ea2edf3c4c/common/src/main/java/io/netty/util/AsciiString.java#L928-L951 |
gallandarakhneorg/afc | advanced/gis/gisbus/src/main/java/org/arakhne/afc/gis/bus/network/BusNetwork.java | BusNetwork.getNearestBusHub | @Pure
public final BusHub getNearestBusHub(Point2D<?, ?> point) {
"""
Replies the nearest bus hub to the given point.
@param point the point
@return the nearest bus hub or <code>null</code> if none was found.
"""
return getNearestBusHub(point.getX(), point.getY());
} | java | @Pure
public final BusHub getNearestBusHub(Point2D<?, ?> point) {
return getNearestBusHub(point.getX(), point.getY());
} | [
"@",
"Pure",
"public",
"final",
"BusHub",
"getNearestBusHub",
"(",
"Point2D",
"<",
"?",
",",
"?",
">",
"point",
")",
"{",
"return",
"getNearestBusHub",
"(",
"point",
".",
"getX",
"(",
")",
",",
"point",
".",
"getY",
"(",
")",
")",
";",
"}"
] | Replies the nearest bus hub to the given point.
@param point the point
@return the nearest bus hub or <code>null</code> if none was found. | [
"Replies",
"the",
"nearest",
"bus",
"hub",
"to",
"the",
"given",
"point",
"."
] | train | https://github.com/gallandarakhneorg/afc/blob/0c7d2e1ddefd4167ef788416d970a6c1ef6f8bbb/advanced/gis/gisbus/src/main/java/org/arakhne/afc/gis/bus/network/BusNetwork.java#L1348-L1351 |
apache/incubator-druid | indexing-service/src/main/java/org/apache/druid/indexing/overlord/TaskLockbox.java | TaskLockbox.revokeLock | private void revokeLock(String taskId, TaskLock lock) {
"""
Mark the lock as revoked. Note that revoked locks are NOT removed. Instead, they are maintained in {@link #running}
and {@link #taskStorage} as the normal locks do. This is to check locks are revoked when they are requested to be
acquired and notify to the callers if revoked. Revoked locks are removed by calling
{@link #unlock(Task, Interval)}.
@param taskId an id of the task holding the lock
@param lock lock to be revoked
"""
giant.lock();
try {
if (!activeTasks.contains(taskId)) {
throw new ISE("Cannot revoke lock for inactive task[%s]", taskId);
}
final Task task = taskStorage.getTask(taskId).orNull();
if (task == null) {
throw new ISE("Cannot revoke lock for unknown task[%s]", taskId);
}
log.info("Revoking task lock[%s] for task[%s]", lock, taskId);
if (lock.isRevoked()) {
log.warn("TaskLock[%s] is already revoked", lock);
} else {
final TaskLock revokedLock = lock.revokedCopy();
taskStorage.replaceLock(taskId, lock, revokedLock);
final List<TaskLockPosse> possesHolder = running.get(task.getDataSource()).get(lock.getInterval().getStart()).get(lock.getInterval());
final TaskLockPosse foundPosse = possesHolder.stream()
.filter(posse -> posse.getTaskLock().equals(lock))
.findFirst()
.orElseThrow(
() -> new ISE("Failed to find lock posse for lock[%s]", lock)
);
possesHolder.remove(foundPosse);
possesHolder.add(foundPosse.withTaskLock(revokedLock));
log.info("Revoked taskLock[%s]", lock);
}
}
finally {
giant.unlock();
}
} | java | private void revokeLock(String taskId, TaskLock lock)
{
giant.lock();
try {
if (!activeTasks.contains(taskId)) {
throw new ISE("Cannot revoke lock for inactive task[%s]", taskId);
}
final Task task = taskStorage.getTask(taskId).orNull();
if (task == null) {
throw new ISE("Cannot revoke lock for unknown task[%s]", taskId);
}
log.info("Revoking task lock[%s] for task[%s]", lock, taskId);
if (lock.isRevoked()) {
log.warn("TaskLock[%s] is already revoked", lock);
} else {
final TaskLock revokedLock = lock.revokedCopy();
taskStorage.replaceLock(taskId, lock, revokedLock);
final List<TaskLockPosse> possesHolder = running.get(task.getDataSource()).get(lock.getInterval().getStart()).get(lock.getInterval());
final TaskLockPosse foundPosse = possesHolder.stream()
.filter(posse -> posse.getTaskLock().equals(lock))
.findFirst()
.orElseThrow(
() -> new ISE("Failed to find lock posse for lock[%s]", lock)
);
possesHolder.remove(foundPosse);
possesHolder.add(foundPosse.withTaskLock(revokedLock));
log.info("Revoked taskLock[%s]", lock);
}
}
finally {
giant.unlock();
}
} | [
"private",
"void",
"revokeLock",
"(",
"String",
"taskId",
",",
"TaskLock",
"lock",
")",
"{",
"giant",
".",
"lock",
"(",
")",
";",
"try",
"{",
"if",
"(",
"!",
"activeTasks",
".",
"contains",
"(",
"taskId",
")",
")",
"{",
"throw",
"new",
"ISE",
"(",
... | Mark the lock as revoked. Note that revoked locks are NOT removed. Instead, they are maintained in {@link #running}
and {@link #taskStorage} as the normal locks do. This is to check locks are revoked when they are requested to be
acquired and notify to the callers if revoked. Revoked locks are removed by calling
{@link #unlock(Task, Interval)}.
@param taskId an id of the task holding the lock
@param lock lock to be revoked | [
"Mark",
"the",
"lock",
"as",
"revoked",
".",
"Note",
"that",
"revoked",
"locks",
"are",
"NOT",
"removed",
".",
"Instead",
"they",
"are",
"maintained",
"in",
"{",
"@link",
"#running",
"}",
"and",
"{",
"@link",
"#taskStorage",
"}",
"as",
"the",
"normal",
"... | train | https://github.com/apache/incubator-druid/blob/f776b9408962b9006cfcfe4d6c1794751972cc8e/indexing-service/src/main/java/org/apache/druid/indexing/overlord/TaskLockbox.java#L672-L709 |
flow/commons | src/main/java/com/flowpowered/commons/store/block/impl/AtomicVariableWidthArray.java | AtomicVariableWidthArray.compareAndSet | public final boolean compareAndSet(int i, int expect, int update) {
"""
Sets the element at the given index, but only if the previous value was the expected value.
@param i the index
@param expect the expected value
@param update the new value
@return true on success
"""
if (fullWidth) {
return array.compareAndSet(i, expect, update);
}
boolean success = false;
int index = getIndex(i);
int subIndex = getSubIndex(i);
while (!success) {
int prev = array.get(index);
if (unPack(prev, subIndex) != expect) {
return false;
}
int next = pack(prev, update, subIndex);
success = array.compareAndSet(index, prev, next);
}
return true;
} | java | public final boolean compareAndSet(int i, int expect, int update) {
if (fullWidth) {
return array.compareAndSet(i, expect, update);
}
boolean success = false;
int index = getIndex(i);
int subIndex = getSubIndex(i);
while (!success) {
int prev = array.get(index);
if (unPack(prev, subIndex) != expect) {
return false;
}
int next = pack(prev, update, subIndex);
success = array.compareAndSet(index, prev, next);
}
return true;
} | [
"public",
"final",
"boolean",
"compareAndSet",
"(",
"int",
"i",
",",
"int",
"expect",
",",
"int",
"update",
")",
"{",
"if",
"(",
"fullWidth",
")",
"{",
"return",
"array",
".",
"compareAndSet",
"(",
"i",
",",
"expect",
",",
"update",
")",
";",
"}",
"b... | Sets the element at the given index, but only if the previous value was the expected value.
@param i the index
@param expect the expected value
@param update the new value
@return true on success | [
"Sets",
"the",
"element",
"at",
"the",
"given",
"index",
"but",
"only",
"if",
"the",
"previous",
"value",
"was",
"the",
"expected",
"value",
"."
] | train | https://github.com/flow/commons/blob/0690efdac06fd728fcd7e9cf10f2b1319379c45b/src/main/java/com/flowpowered/commons/store/block/impl/AtomicVariableWidthArray.java#L169-L187 |
Impetus/Kundera | src/jpa-engine/core/src/main/java/com/impetus/kundera/persistence/event/EntityEventDispatcher.java | EntityEventDispatcher.fireEventListeners | public void fireEventListeners(EntityMetadata metadata, Object entity, Class<?> event) {
"""
Fire event listeners.
@param metadata
the metadata
@param entity
the entity
@param event
the event
@throws PersistenceException
the persistence exception
"""
// handle external listeners first
List<? extends CallbackMethod> callBackMethods = metadata.getCallbackMethods(event);
if (null != callBackMethods && !callBackMethods.isEmpty() && null != entity)
{
log.debug("Callback >> " + event.getSimpleName() + " on " + metadata.getEntityClazz().getName());
for (CallbackMethod callback : callBackMethods)
{
log.debug("Firing >> " + callback);
callback.invoke(entity);
}
}
} | java | public void fireEventListeners(EntityMetadata metadata, Object entity, Class<?> event)
{
// handle external listeners first
List<? extends CallbackMethod> callBackMethods = metadata.getCallbackMethods(event);
if (null != callBackMethods && !callBackMethods.isEmpty() && null != entity)
{
log.debug("Callback >> " + event.getSimpleName() + " on " + metadata.getEntityClazz().getName());
for (CallbackMethod callback : callBackMethods)
{
log.debug("Firing >> " + callback);
callback.invoke(entity);
}
}
} | [
"public",
"void",
"fireEventListeners",
"(",
"EntityMetadata",
"metadata",
",",
"Object",
"entity",
",",
"Class",
"<",
"?",
">",
"event",
")",
"{",
"// handle external listeners first\r",
"List",
"<",
"?",
"extends",
"CallbackMethod",
">",
"callBackMethods",
"=",
... | Fire event listeners.
@param metadata
the metadata
@param entity
the entity
@param event
the event
@throws PersistenceException
the persistence exception | [
"Fire",
"event",
"listeners",
"."
] | train | https://github.com/Impetus/Kundera/blob/268958ab1ec09d14ec4d9184f0c8ded7a9158908/src/jpa-engine/core/src/main/java/com/impetus/kundera/persistence/event/EntityEventDispatcher.java#L49-L66 |
gwtbootstrap3/gwtbootstrap3-extras | src/main/java/org/gwtbootstrap3/extras/summernote/client/ui/base/SummernoteOptions.java | SummernoteOptions.newToolbarGroup | static final JsArrayMixed newToolbarGroup(String name, ToolbarButton... buttons) {
"""
Creates a new toolbar group.
@param name
@param buttons
@return
"""
JsArrayString arr = JavaScriptObject.createArray().cast();
for (ToolbarButton button : buttons) {
arr.push(button.getId());
}
return getToolbarGroup(name, arr);
} | java | static final JsArrayMixed newToolbarGroup(String name, ToolbarButton... buttons) {
JsArrayString arr = JavaScriptObject.createArray().cast();
for (ToolbarButton button : buttons) {
arr.push(button.getId());
}
return getToolbarGroup(name, arr);
} | [
"static",
"final",
"JsArrayMixed",
"newToolbarGroup",
"(",
"String",
"name",
",",
"ToolbarButton",
"...",
"buttons",
")",
"{",
"JsArrayString",
"arr",
"=",
"JavaScriptObject",
".",
"createArray",
"(",
")",
".",
"cast",
"(",
")",
";",
"for",
"(",
"ToolbarButton... | Creates a new toolbar group.
@param name
@param buttons
@return | [
"Creates",
"a",
"new",
"toolbar",
"group",
"."
] | train | https://github.com/gwtbootstrap3/gwtbootstrap3-extras/blob/8e42aaffd2a082e9cb23a14c37a3c87b7cbdfa94/src/main/java/org/gwtbootstrap3/extras/summernote/client/ui/base/SummernoteOptions.java#L115-L121 |
SonarSource/sonarqube | server/sonar-server/src/main/java/org/sonar/server/plugins/ws/PluginWSCommons.java | PluginWSCommons.writeUpdate | static void writeUpdate(JsonWriter jsonWriter, PluginUpdate pluginUpdate) {
"""
Write an "update" object to the specified jsonwriter.
<pre>
"update": {
"status": "COMPATIBLE",
"requires": [
{
"key": "java",
"name": "Java",
"description": "SonarQube rule engine."
}
]
}
</pre>
"""
jsonWriter.name(OBJECT_UPDATE).beginObject();
writeUpdateProperties(jsonWriter, pluginUpdate);
jsonWriter.endObject();
} | java | static void writeUpdate(JsonWriter jsonWriter, PluginUpdate pluginUpdate) {
jsonWriter.name(OBJECT_UPDATE).beginObject();
writeUpdateProperties(jsonWriter, pluginUpdate);
jsonWriter.endObject();
} | [
"static",
"void",
"writeUpdate",
"(",
"JsonWriter",
"jsonWriter",
",",
"PluginUpdate",
"pluginUpdate",
")",
"{",
"jsonWriter",
".",
"name",
"(",
"OBJECT_UPDATE",
")",
".",
"beginObject",
"(",
")",
";",
"writeUpdateProperties",
"(",
"jsonWriter",
",",
"pluginUpdate... | Write an "update" object to the specified jsonwriter.
<pre>
"update": {
"status": "COMPATIBLE",
"requires": [
{
"key": "java",
"name": "Java",
"description": "SonarQube rule engine."
}
]
}
</pre> | [
"Write",
"an",
"update",
"object",
"to",
"the",
"specified",
"jsonwriter",
".",
"<pre",
">",
"update",
":",
"{",
"status",
":",
"COMPATIBLE",
"requires",
":",
"[",
"{",
"key",
":",
"java",
"name",
":",
"Java",
"description",
":",
"SonarQube",
"rule",
"en... | train | https://github.com/SonarSource/sonarqube/blob/2fffa4c2f79ae3714844d7742796e82822b6a98a/server/sonar-server/src/main/java/org/sonar/server/plugins/ws/PluginWSCommons.java#L174-L180 |
VoltDB/voltdb | examples/geospatial/client/geospatial/AdBrokerBenchmark.java | AdBrokerBenchmark.runBenchmark | public void runBenchmark() throws Exception {
"""
Core benchmark code.
Connect. Initialize. Run the loop. Cleanup. Print Results.
@throws Exception if anything unexpected happens.
"""
System.out.print(HORIZONTAL_RULE);
System.out.println(" Setup & Initialization");
System.out.println(HORIZONTAL_RULE);
// connect to one or more servers, loop until success
connect(m_client, m_config.servers);
System.out.print("\n\n" + HORIZONTAL_RULE);
System.out.println(" Starting Benchmark");
System.out.println(HORIZONTAL_RULE);
System.out.println("\nStarting bid generator\n");
BidGenerator bidGenerator = new BidGenerator(m_client);
long usDelay = (long) ((1.0 / BID_FREQUENCY_PER_SECOND) * 1000000.0);
m_scheduler.scheduleWithFixedDelay(bidGenerator, 0, usDelay, TimeUnit.MICROSECONDS);
System.out.println("\nStarting nibble deleter to delete expired data\n");
NibbleDeleter deleter = new NibbleDeleter(m_client, m_config.displayinterval + 1);
// Run once a second
m_scheduler.scheduleWithFixedDelay(deleter, 1, 1, TimeUnit.SECONDS);
System.out.println("\nWarming up...");
final long warmupEndTime = System.currentTimeMillis() + (1000l * m_config.warmup);
while (warmupEndTime > System.currentTimeMillis()) {
requestAd();
}
// reset the stats
m_fullStatsContext.fetchAndResetBaseline();
m_periodicStatsContext.fetchAndResetBaseline();
// print periodic statistics to the console
m_benchmarkStartTS = System.currentTimeMillis();
schedulePeriodicStats();
// Run the benchmark loop for the requested duration
// The throughput may be throttled depending on client configuration
System.out.println("\nRunning benchmark...");
final long benchmarkEndTime = System.currentTimeMillis() + (1000l * m_config.duration);
while (benchmarkEndTime > System.currentTimeMillis()) {
requestAd();
}
printResults();
shutdown();
} | java | public void runBenchmark() throws Exception {
System.out.print(HORIZONTAL_RULE);
System.out.println(" Setup & Initialization");
System.out.println(HORIZONTAL_RULE);
// connect to one or more servers, loop until success
connect(m_client, m_config.servers);
System.out.print("\n\n" + HORIZONTAL_RULE);
System.out.println(" Starting Benchmark");
System.out.println(HORIZONTAL_RULE);
System.out.println("\nStarting bid generator\n");
BidGenerator bidGenerator = new BidGenerator(m_client);
long usDelay = (long) ((1.0 / BID_FREQUENCY_PER_SECOND) * 1000000.0);
m_scheduler.scheduleWithFixedDelay(bidGenerator, 0, usDelay, TimeUnit.MICROSECONDS);
System.out.println("\nStarting nibble deleter to delete expired data\n");
NibbleDeleter deleter = new NibbleDeleter(m_client, m_config.displayinterval + 1);
// Run once a second
m_scheduler.scheduleWithFixedDelay(deleter, 1, 1, TimeUnit.SECONDS);
System.out.println("\nWarming up...");
final long warmupEndTime = System.currentTimeMillis() + (1000l * m_config.warmup);
while (warmupEndTime > System.currentTimeMillis()) {
requestAd();
}
// reset the stats
m_fullStatsContext.fetchAndResetBaseline();
m_periodicStatsContext.fetchAndResetBaseline();
// print periodic statistics to the console
m_benchmarkStartTS = System.currentTimeMillis();
schedulePeriodicStats();
// Run the benchmark loop for the requested duration
// The throughput may be throttled depending on client configuration
System.out.println("\nRunning benchmark...");
final long benchmarkEndTime = System.currentTimeMillis() + (1000l * m_config.duration);
while (benchmarkEndTime > System.currentTimeMillis()) {
requestAd();
}
printResults();
shutdown();
} | [
"public",
"void",
"runBenchmark",
"(",
")",
"throws",
"Exception",
"{",
"System",
".",
"out",
".",
"print",
"(",
"HORIZONTAL_RULE",
")",
";",
"System",
".",
"out",
".",
"println",
"(",
"\" Setup & Initialization\"",
")",
";",
"System",
".",
"out",
".",
"pr... | Core benchmark code.
Connect. Initialize. Run the loop. Cleanup. Print Results.
@throws Exception if anything unexpected happens. | [
"Core",
"benchmark",
"code",
".",
"Connect",
".",
"Initialize",
".",
"Run",
"the",
"loop",
".",
"Cleanup",
".",
"Print",
"Results",
"."
] | train | https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/examples/geospatial/client/geospatial/AdBrokerBenchmark.java#L412-L458 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.