repository_name stringlengths 7 58 | func_path_in_repository stringlengths 18 201 | func_name stringlengths 4 126 | whole_func_string stringlengths 75 3.57k | language stringclasses 1
value | func_code_string stringlengths 75 3.57k | func_code_tokens listlengths 21 599 | func_documentation_string stringlengths 61 1.95k | func_documentation_tokens listlengths 1 478 | split_name stringclasses 1
value | func_code_url stringlengths 111 308 |
|---|---|---|---|---|---|---|---|---|---|---|
deeplearning4j/deeplearning4j | deeplearning4j/deeplearning4j-nn/src/main/java/org/deeplearning4j/nn/multilayer/MultiLayerNetwork.java | MultiLayerNetwork.feedForwardToLayer | public List<INDArray> feedForwardToLayer(int layerNum, INDArray input) {
try{
return ffToLayerActivationsDetached(false, FwdPassType.STANDARD, false, layerNum, input, mask, null, true);
} catch (OutOfMemoryError e) {
CrashReportingUtil.writeMemoryCrashDump(this, e);
throw e;
}
} | java | public List<INDArray> feedForwardToLayer(int layerNum, INDArray input) {
try{
return ffToLayerActivationsDetached(false, FwdPassType.STANDARD, false, layerNum, input, mask, null, true);
} catch (OutOfMemoryError e) {
CrashReportingUtil.writeMemoryCrashDump(this, e);
throw e;
}
} | [
"public",
"List",
"<",
"INDArray",
">",
"feedForwardToLayer",
"(",
"int",
"layerNum",
",",
"INDArray",
"input",
")",
"{",
"try",
"{",
"return",
"ffToLayerActivationsDetached",
"(",
"false",
",",
"FwdPassType",
".",
"STANDARD",
",",
"false",
",",
"layerNum",
",... | Compute the activations from the input to the specified layer.<br>
To compute activations for all layers, use feedForward(...) methods<br>
Note: output list includes the original input. So list.get(0) is always the original input, and
list.get(i+1) is the activations of the ith layer.
@param layerNum Index of the last layer to calculate activations for. Layers are zero-indexed.
feedForwardToLayer(i,input) will return the activations for layers 0..i (inclusive)
@param input Input to the network
@return list of activations. | [
"Compute",
"the",
"activations",
"from",
"the",
"input",
"to",
"the",
"specified",
"layer",
".",
"<br",
">",
"To",
"compute",
"activations",
"for",
"all",
"layers",
"use",
"feedForward",
"(",
"...",
")",
"methods<br",
">",
"Note",
":",
"output",
"list",
"i... | train | https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/deeplearning4j/deeplearning4j-nn/src/main/java/org/deeplearning4j/nn/multilayer/MultiLayerNetwork.java#L900-L907 |
spring-projects/spring-social | spring-social-security/src/main/java/org/springframework/social/security/SocialAuthenticationFilter.java | SocialAuthenticationFilter.setPostFailureUrl | public void setPostFailureUrl(String postFailureUrl) {
AuthenticationFailureHandler failureHandler = getFailureHandler();
if (failureHandler instanceof SocialAuthenticationFailureHandler) {
failureHandler = ((SocialAuthenticationFailureHandler)failureHandler).getDelegate();
}
if (failureHandler instanceof SimpleUrlAuthenticationFailureHandler) {
SimpleUrlAuthenticationFailureHandler h = (SimpleUrlAuthenticationFailureHandler) failureHandler;
h.setDefaultFailureUrl(postFailureUrl);
} else {
throw new IllegalStateException("can't set postFailureUrl on unknown failureHandler, type is " + failureHandler.getClass().getName());
}
} | java | public void setPostFailureUrl(String postFailureUrl) {
AuthenticationFailureHandler failureHandler = getFailureHandler();
if (failureHandler instanceof SocialAuthenticationFailureHandler) {
failureHandler = ((SocialAuthenticationFailureHandler)failureHandler).getDelegate();
}
if (failureHandler instanceof SimpleUrlAuthenticationFailureHandler) {
SimpleUrlAuthenticationFailureHandler h = (SimpleUrlAuthenticationFailureHandler) failureHandler;
h.setDefaultFailureUrl(postFailureUrl);
} else {
throw new IllegalStateException("can't set postFailureUrl on unknown failureHandler, type is " + failureHandler.getClass().getName());
}
} | [
"public",
"void",
"setPostFailureUrl",
"(",
"String",
"postFailureUrl",
")",
"{",
"AuthenticationFailureHandler",
"failureHandler",
"=",
"getFailureHandler",
"(",
")",
";",
"if",
"(",
"failureHandler",
"instanceof",
"SocialAuthenticationFailureHandler",
")",
"{",
"failure... | The URL to redirect to if authentication fails or if authorization is denied by the user.
@param postFailureUrl The failure URL. Defaults to "/signin" (relative to the servlet context). | [
"The",
"URL",
"to",
"redirect",
"to",
"if",
"authentication",
"fails",
"or",
"if",
"authorization",
"is",
"denied",
"by",
"the",
"user",
"."
] | train | https://github.com/spring-projects/spring-social/blob/e41cfecb288022b83c79413b58f52511c3c9d4fc/spring-social-security/src/main/java/org/springframework/social/security/SocialAuthenticationFilter.java#L140-L153 |
Netflix/Hystrix | hystrix-core/src/main/java/com/netflix/hystrix/strategy/executionhook/HystrixCommandExecutionHook.java | HystrixCommandExecutionHook.onRunError | @Deprecated
public <T> Exception onRunError(HystrixCommand<T> commandInstance, Exception e) {
// pass-thru by default
return e;
} | java | @Deprecated
public <T> Exception onRunError(HystrixCommand<T> commandInstance, Exception e) {
// pass-thru by default
return e;
} | [
"@",
"Deprecated",
"public",
"<",
"T",
">",
"Exception",
"onRunError",
"(",
"HystrixCommand",
"<",
"T",
">",
"commandInstance",
",",
"Exception",
"e",
")",
"{",
"// pass-thru by default",
"return",
"e",
";",
"}"
] | DEPRECATED: Change usages of this to {@link #onExecutionError}
Invoked after failed execution of {@link HystrixCommand#run()} with thrown Exception.
@param commandInstance
The executing HystrixCommand instance.
@param e
Exception thrown by {@link HystrixCommand#run()}
@return Exception that can be decorated, replaced or just returned as a pass-thru.
@since 1.2 | [
"DEPRECATED",
":",
"Change",
"usages",
"of",
"this",
"to",
"{",
"@link",
"#onExecutionError",
"}"
] | train | https://github.com/Netflix/Hystrix/blob/3cb21589895e9f8f87cfcdbc9d96d9f63d48b848/hystrix-core/src/main/java/com/netflix/hystrix/strategy/executionhook/HystrixCommandExecutionHook.java#L317-L321 |
foundation-runtime/service-directory | 2.0/sd-api/src/main/java/com/cisco/oss/foundation/directory/connect/DirectoryConnection.java | DirectoryConnection.queuePacket | private Packet queuePacket(ProtocolHeader header, Protocol protocol,
ProtocolCallback cb, Object context, ServiceDirectoryFuture future, WatcherRegistration wr)
{
Packet packet = new Packet(header, protocol, wr);
PacketLatency.initPacket(packet);
header.createTime = packet.createTime;
packet.cb = cb;
packet.context = context;
packet.future = future;
if (! clientSocket.isConnected() || closing) {
onLossPacket(packet);
} else {
synchronized (pendingQueue) {
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("Add the packet in queuePacket, type=" + header.getType());
}
header.setXid(xid.incrementAndGet());
try{
PacketLatency.queuePacket(packet);
clientSocket.sendPacket(header, protocol);
pendingQueue.add(packet);
PacketLatency.sendPacket(packet);
} catch(IOException e){
LOGGER.error("ClientSocket send packet failed.");
if(LOGGER.isTraceEnabled()){
LOGGER.trace("ClientSocket send packet failed.", e);
}
if(packet != null){
onLossPacket(packet);
}
}
}
}
return packet;
} | java | private Packet queuePacket(ProtocolHeader header, Protocol protocol,
ProtocolCallback cb, Object context, ServiceDirectoryFuture future, WatcherRegistration wr)
{
Packet packet = new Packet(header, protocol, wr);
PacketLatency.initPacket(packet);
header.createTime = packet.createTime;
packet.cb = cb;
packet.context = context;
packet.future = future;
if (! clientSocket.isConnected() || closing) {
onLossPacket(packet);
} else {
synchronized (pendingQueue) {
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("Add the packet in queuePacket, type=" + header.getType());
}
header.setXid(xid.incrementAndGet());
try{
PacketLatency.queuePacket(packet);
clientSocket.sendPacket(header, protocol);
pendingQueue.add(packet);
PacketLatency.sendPacket(packet);
} catch(IOException e){
LOGGER.error("ClientSocket send packet failed.");
if(LOGGER.isTraceEnabled()){
LOGGER.trace("ClientSocket send packet failed.", e);
}
if(packet != null){
onLossPacket(packet);
}
}
}
}
return packet;
} | [
"private",
"Packet",
"queuePacket",
"(",
"ProtocolHeader",
"header",
",",
"Protocol",
"protocol",
",",
"ProtocolCallback",
"cb",
",",
"Object",
"context",
",",
"ServiceDirectoryFuture",
"future",
",",
"WatcherRegistration",
"wr",
")",
"{",
"Packet",
"packet",
"=",
... | Queue the Packet to Connection.
The DirectoryConnect Queue the Packet to the internal Queue and send it to remote
Directory Server.
@param header
the ProtocolHeader.
@param protocol
the Protocol.
@param cb
the Callback.
@param context
the context Object of the Callback.
@param future
the Future.
@param wr
WatcherRegistration
@return
the queued Packet. | [
"Queue",
"the",
"Packet",
"to",
"Connection",
"."
] | train | https://github.com/foundation-runtime/service-directory/blob/a7bdefe173dc99e75eff4a24e07e6407e62f2ed4/2.0/sd-api/src/main/java/com/cisco/oss/foundation/directory/connect/DirectoryConnection.java#L428-L466 |
alkacon/opencms-core | src/org/opencms/util/CmsMacroResolver.java | CmsMacroResolver.updateProperties | private static void updateProperties(CmsObject cms, CmsResource resource, CmsMacroResolver macroResolver)
throws CmsException {
Iterator<CmsProperty> it = cms.readPropertyObjects(resource, false).iterator();
while (it.hasNext()) {
CmsProperty property = it.next();
String resValue = null;
if (property.getResourceValue() != null) {
resValue = macroResolver.resolveMacros(property.getResourceValue());
}
String strValue = null;
if (property.getStructureValue() != null) {
strValue = macroResolver.resolveMacros(property.getStructureValue());
}
CmsProperty newProperty = new CmsProperty(property.getName(), strValue, resValue);
cms.writePropertyObject(cms.getSitePath(resource), newProperty);
}
} | java | private static void updateProperties(CmsObject cms, CmsResource resource, CmsMacroResolver macroResolver)
throws CmsException {
Iterator<CmsProperty> it = cms.readPropertyObjects(resource, false).iterator();
while (it.hasNext()) {
CmsProperty property = it.next();
String resValue = null;
if (property.getResourceValue() != null) {
resValue = macroResolver.resolveMacros(property.getResourceValue());
}
String strValue = null;
if (property.getStructureValue() != null) {
strValue = macroResolver.resolveMacros(property.getStructureValue());
}
CmsProperty newProperty = new CmsProperty(property.getName(), strValue, resValue);
cms.writePropertyObject(cms.getSitePath(resource), newProperty);
}
} | [
"private",
"static",
"void",
"updateProperties",
"(",
"CmsObject",
"cms",
",",
"CmsResource",
"resource",
",",
"CmsMacroResolver",
"macroResolver",
")",
"throws",
"CmsException",
"{",
"Iterator",
"<",
"CmsProperty",
">",
"it",
"=",
"cms",
".",
"readPropertyObjects",... | Updates all properties of the given resource with the given macro resolver.<p>
@param cms the cms context
@param resource the resource to update the properties for
@param macroResolver the macro resolver to use
@throws CmsException if something goes wrong | [
"Updates",
"all",
"properties",
"of",
"the",
"given",
"resource",
"with",
"the",
"given",
"macro",
"resolver",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/util/CmsMacroResolver.java#L750-L767 |
Nexmo/nexmo-java | src/main/java/com/nexmo/client/sms/SmsClient.java | SmsClient.searchMessages | public SearchSmsResponse searchMessages(Date date, String to) throws IOException, NexmoClientException {
return this.searchMessages(new SmsDateSearchRequest(date, to));
} | java | public SearchSmsResponse searchMessages(Date date, String to) throws IOException, NexmoClientException {
return this.searchMessages(new SmsDateSearchRequest(date, to));
} | [
"public",
"SearchSmsResponse",
"searchMessages",
"(",
"Date",
"date",
",",
"String",
"to",
")",
"throws",
"IOException",
",",
"NexmoClientException",
"{",
"return",
"this",
".",
"searchMessages",
"(",
"new",
"SmsDateSearchRequest",
"(",
"date",
",",
"to",
")",
"... | Search for completed SMS transactions by date and recipient MSISDN.
@param date the date of the SMS message to be looked up
@param to the MSISDN number of the SMS recipient
@return SMS data matching the provided criteria | [
"Search",
"for",
"completed",
"SMS",
"transactions",
"by",
"date",
"and",
"recipient",
"MSISDN",
"."
] | train | https://github.com/Nexmo/nexmo-java/blob/7427eff6d6baa5a5bd9197fa096bcf2564191cf5/src/main/java/com/nexmo/client/sms/SmsClient.java#L114-L116 |
javagl/ND | nd-arrays/src/main/java/de/javagl/nd/arrays/d/DoubleArraysND.java | DoubleArraysND.wrap | public static MutableDoubleArrayND wrap(
MutableDoubleTuple t, IntTuple size)
{
Objects.requireNonNull(t, "The tuple is null");
Objects.requireNonNull(size, "The size is null");
int totalSize = IntTupleFunctions.reduce(size, 1, (a, b) -> a * b);
if (t.getSize() != totalSize)
{
throw new IllegalArgumentException(
"The tuple has a size of " + t.getSize() + ", the expected " +
"array size is " + size + " (total: " + totalSize + ")");
}
return new MutableTupleDoubleArrayND(t, size);
} | java | public static MutableDoubleArrayND wrap(
MutableDoubleTuple t, IntTuple size)
{
Objects.requireNonNull(t, "The tuple is null");
Objects.requireNonNull(size, "The size is null");
int totalSize = IntTupleFunctions.reduce(size, 1, (a, b) -> a * b);
if (t.getSize() != totalSize)
{
throw new IllegalArgumentException(
"The tuple has a size of " + t.getSize() + ", the expected " +
"array size is " + size + " (total: " + totalSize + ")");
}
return new MutableTupleDoubleArrayND(t, size);
} | [
"public",
"static",
"MutableDoubleArrayND",
"wrap",
"(",
"MutableDoubleTuple",
"t",
",",
"IntTuple",
"size",
")",
"{",
"Objects",
".",
"requireNonNull",
"(",
"t",
",",
"\"The tuple is null\"",
")",
";",
"Objects",
".",
"requireNonNull",
"(",
"size",
",",
"\"The ... | Creates a <i>view</i> on the given tuple as a {@link DoubleArrayND}.
Changes in the given tuple will be visible in the returned array,
and vice versa.
@param t The tuple
@param size The size of the array
@return The view on the tuple
@throws NullPointerException If any argument is <code>null</code>
@throws IllegalArgumentException If the
{@link DoubleTuple#getSize() size} of the tuple does not match the
given array size (that is, the product of all elements of the given
tuple). | [
"Creates",
"a",
"<i",
">",
"view<",
"/",
"i",
">",
"on",
"the",
"given",
"tuple",
"as",
"a",
"{",
"@link",
"DoubleArrayND",
"}",
".",
"Changes",
"in",
"the",
"given",
"tuple",
"will",
"be",
"visible",
"in",
"the",
"returned",
"array",
"and",
"vice",
... | train | https://github.com/javagl/ND/blob/bcb655aaf5fc88af6194f73a27cca079186ff559/nd-arrays/src/main/java/de/javagl/nd/arrays/d/DoubleArraysND.java#L141-L154 |
alkacon/opencms-core | src/org/opencms/ade/configuration/CmsADEManager.java | CmsADEManager.getPermissionInfo | public CmsPermissionInfo getPermissionInfo(CmsObject cms, CmsResource resource, String contextPath)
throws CmsException {
boolean hasView = cms.hasPermissions(
resource,
CmsPermissionSet.ACCESS_VIEW,
false,
CmsResourceFilter.ALL.addRequireVisible());
boolean hasWrite = false;
if (hasView) {
try {
I_CmsResourceType type = OpenCms.getResourceManager().getResourceType(resource.getTypeId());
CmsExplorerTypeSettings settings = OpenCms.getWorkplaceManager().getExplorerTypeSetting(
type.getTypeName());
hasView = (settings == null)
|| settings.getAccess().getPermissions(cms, resource).requiresViewPermission();
if (hasView
&& CmsResourceTypeXmlContent.isXmlContent(resource)
&& !CmsResourceTypeXmlContainerPage.isContainerPage(resource)) {
if (contextPath == null) {
contextPath = resource.getRootPath();
}
CmsResourceTypeConfig localConfigData = lookupConfiguration(cms, contextPath).getResourceType(
type.getTypeName());
if (localConfigData != null) {
Map<CmsUUID, CmsElementView> elmenetViews = getElementViews(cms);
hasView = elmenetViews.containsKey(localConfigData.getElementView())
&& elmenetViews.get(localConfigData.getElementView()).hasPermission(cms, resource);
}
}
// the user may only have write permissions if he is allowed to view the resource
hasWrite = hasView
&& cms.hasPermissions(
resource,
CmsPermissionSet.ACCESS_WRITE,
false,
CmsResourceFilter.IGNORE_EXPIRATION)
&& ((settings == null)
|| settings.getAccess().getPermissions(cms, resource).requiresWritePermission());
} catch (CmsLoaderException e) {
LOG.warn(e.getLocalizedMessage(), e);
hasWrite = false;
}
}
String noEdit = new CmsResourceUtil(cms, resource).getNoEditReason(
OpenCms.getWorkplaceManager().getWorkplaceLocale(cms),
true);
return new CmsPermissionInfo(hasView, hasWrite, noEdit);
} | java | public CmsPermissionInfo getPermissionInfo(CmsObject cms, CmsResource resource, String contextPath)
throws CmsException {
boolean hasView = cms.hasPermissions(
resource,
CmsPermissionSet.ACCESS_VIEW,
false,
CmsResourceFilter.ALL.addRequireVisible());
boolean hasWrite = false;
if (hasView) {
try {
I_CmsResourceType type = OpenCms.getResourceManager().getResourceType(resource.getTypeId());
CmsExplorerTypeSettings settings = OpenCms.getWorkplaceManager().getExplorerTypeSetting(
type.getTypeName());
hasView = (settings == null)
|| settings.getAccess().getPermissions(cms, resource).requiresViewPermission();
if (hasView
&& CmsResourceTypeXmlContent.isXmlContent(resource)
&& !CmsResourceTypeXmlContainerPage.isContainerPage(resource)) {
if (contextPath == null) {
contextPath = resource.getRootPath();
}
CmsResourceTypeConfig localConfigData = lookupConfiguration(cms, contextPath).getResourceType(
type.getTypeName());
if (localConfigData != null) {
Map<CmsUUID, CmsElementView> elmenetViews = getElementViews(cms);
hasView = elmenetViews.containsKey(localConfigData.getElementView())
&& elmenetViews.get(localConfigData.getElementView()).hasPermission(cms, resource);
}
}
// the user may only have write permissions if he is allowed to view the resource
hasWrite = hasView
&& cms.hasPermissions(
resource,
CmsPermissionSet.ACCESS_WRITE,
false,
CmsResourceFilter.IGNORE_EXPIRATION)
&& ((settings == null)
|| settings.getAccess().getPermissions(cms, resource).requiresWritePermission());
} catch (CmsLoaderException e) {
LOG.warn(e.getLocalizedMessage(), e);
hasWrite = false;
}
}
String noEdit = new CmsResourceUtil(cms, resource).getNoEditReason(
OpenCms.getWorkplaceManager().getWorkplaceLocale(cms),
true);
return new CmsPermissionInfo(hasView, hasWrite, noEdit);
} | [
"public",
"CmsPermissionInfo",
"getPermissionInfo",
"(",
"CmsObject",
"cms",
",",
"CmsResource",
"resource",
",",
"String",
"contextPath",
")",
"throws",
"CmsException",
"{",
"boolean",
"hasView",
"=",
"cms",
".",
"hasPermissions",
"(",
"resource",
",",
"CmsPermissi... | Returns the permission info for the given resource.<p>
@param cms the cms context
@param resource the resource
@param contextPath the context path
@return the permission info
@throws CmsException if checking the permissions fails | [
"Returns",
"the",
"permission",
"info",
"for",
"the",
"given",
"resource",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ade/configuration/CmsADEManager.java#L795-L844 |
couchbase/couchbase-jvm-core | src/main/java/com/couchbase/client/core/tracing/ThresholdLogSpanContext.java | ThresholdLogSpanContext.baggageItem | public ThresholdLogSpanContext baggageItem(final String item, final String value) {
baggageItems.put(item, value);
return this;
} | java | public ThresholdLogSpanContext baggageItem(final String item, final String value) {
baggageItems.put(item, value);
return this;
} | [
"public",
"ThresholdLogSpanContext",
"baggageItem",
"(",
"final",
"String",
"item",
",",
"final",
"String",
"value",
")",
"{",
"baggageItems",
".",
"put",
"(",
"item",
",",
"value",
")",
";",
"return",
"this",
";",
"}"
] | Stores the given baggage item/value.
If an item already exists, it will be overridden.
@param item the item to store.
@param value the value to store.
@return this {@link ThresholdLogSpanContext} for chaining purposes. | [
"Stores",
"the",
"given",
"baggage",
"item",
"/",
"value",
"."
] | train | https://github.com/couchbase/couchbase-jvm-core/blob/97f0427112c2168fee1d6499904f5fa0e24c6797/src/main/java/com/couchbase/client/core/tracing/ThresholdLogSpanContext.java#L61-L64 |
Netflix/eureka | eureka-client/src/main/java/com/netflix/discovery/shared/Applications.java | Applications.getReconcileHashCode | public static String getReconcileHashCode(Map<String, AtomicInteger> instanceCountMap) {
StringBuilder reconcileHashCode = new StringBuilder(75);
for (Map.Entry<String, AtomicInteger> mapEntry : instanceCountMap.entrySet()) {
reconcileHashCode.append(mapEntry.getKey()).append(STATUS_DELIMITER).append(mapEntry.getValue().get())
.append(STATUS_DELIMITER);
}
return reconcileHashCode.toString();
} | java | public static String getReconcileHashCode(Map<String, AtomicInteger> instanceCountMap) {
StringBuilder reconcileHashCode = new StringBuilder(75);
for (Map.Entry<String, AtomicInteger> mapEntry : instanceCountMap.entrySet()) {
reconcileHashCode.append(mapEntry.getKey()).append(STATUS_DELIMITER).append(mapEntry.getValue().get())
.append(STATUS_DELIMITER);
}
return reconcileHashCode.toString();
} | [
"public",
"static",
"String",
"getReconcileHashCode",
"(",
"Map",
"<",
"String",
",",
"AtomicInteger",
">",
"instanceCountMap",
")",
"{",
"StringBuilder",
"reconcileHashCode",
"=",
"new",
"StringBuilder",
"(",
"75",
")",
";",
"for",
"(",
"Map",
".",
"Entry",
"... | Gets the reconciliation hashcode. The hashcode is used to determine
whether the applications list has changed since the last time it was
acquired.
@param instanceCountMap
the instance count map to use for generating the hash
@return the hash code for this instance | [
"Gets",
"the",
"reconciliation",
"hashcode",
".",
"The",
"hashcode",
"is",
"used",
"to",
"determine",
"whether",
"the",
"applications",
"list",
"has",
"changed",
"since",
"the",
"last",
"time",
"it",
"was",
"acquired",
"."
] | train | https://github.com/Netflix/eureka/blob/48446d956be09df6650a3c00b7ebd7e2d1e1544f/eureka-client/src/main/java/com/netflix/discovery/shared/Applications.java#L265-L272 |
Azure/azure-sdk-for-java | network/resource-manager/v2018_04_01/src/main/java/com/microsoft/azure/management/network/v2018_04_01/implementation/VpnConnectionsInner.java | VpnConnectionsInner.getAsync | public Observable<VpnConnectionInner> getAsync(String resourceGroupName, String gatewayName, String connectionName) {
return getWithServiceResponseAsync(resourceGroupName, gatewayName, connectionName).map(new Func1<ServiceResponse<VpnConnectionInner>, VpnConnectionInner>() {
@Override
public VpnConnectionInner call(ServiceResponse<VpnConnectionInner> response) {
return response.body();
}
});
} | java | public Observable<VpnConnectionInner> getAsync(String resourceGroupName, String gatewayName, String connectionName) {
return getWithServiceResponseAsync(resourceGroupName, gatewayName, connectionName).map(new Func1<ServiceResponse<VpnConnectionInner>, VpnConnectionInner>() {
@Override
public VpnConnectionInner call(ServiceResponse<VpnConnectionInner> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"VpnConnectionInner",
">",
"getAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"gatewayName",
",",
"String",
"connectionName",
")",
"{",
"return",
"getWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"gatewayName",
",",
... | Retrieves the details of a vpn connection.
@param resourceGroupName The resource group name of the VpnGateway.
@param gatewayName The name of the gateway.
@param connectionName The name of the vpn connection.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the VpnConnectionInner object | [
"Retrieves",
"the",
"details",
"of",
"a",
"vpn",
"connection",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2018_04_01/src/main/java/com/microsoft/azure/management/network/v2018_04_01/implementation/VpnConnectionsInner.java#L132-L139 |
RestComm/jss7 | map/map-impl/src/main/java/org/restcomm/protocols/ss7/map/MAPProviderImpl.java | MAPProviderImpl.fireTCAbortV1 | protected void fireTCAbortV1(Dialog tcapDialog, boolean returnMessageOnError) throws MAPException {
if (this.getTCAPProvider().getPreviewMode()) {
return;
}
TCUserAbortRequest tcUserAbort = this.getTCAPProvider().getDialogPrimitiveFactory().createUAbort(tcapDialog);
if (returnMessageOnError)
tcUserAbort.setReturnMessageOnError(true);
try {
tcapDialog.send(tcUserAbort);
} catch (TCAPSendException e) {
throw new MAPException(e.getMessage(), e);
}
} | java | protected void fireTCAbortV1(Dialog tcapDialog, boolean returnMessageOnError) throws MAPException {
if (this.getTCAPProvider().getPreviewMode()) {
return;
}
TCUserAbortRequest tcUserAbort = this.getTCAPProvider().getDialogPrimitiveFactory().createUAbort(tcapDialog);
if (returnMessageOnError)
tcUserAbort.setReturnMessageOnError(true);
try {
tcapDialog.send(tcUserAbort);
} catch (TCAPSendException e) {
throw new MAPException(e.getMessage(), e);
}
} | [
"protected",
"void",
"fireTCAbortV1",
"(",
"Dialog",
"tcapDialog",
",",
"boolean",
"returnMessageOnError",
")",
"throws",
"MAPException",
"{",
"if",
"(",
"this",
".",
"getTCAPProvider",
"(",
")",
".",
"getPreviewMode",
"(",
")",
")",
"{",
"return",
";",
"}",
... | Issue TC-U-ABORT without any apdu - for MAP V1
@param tcapDialog
@param returnMessageOnError
@throws MAPException | [
"Issue",
"TC",
"-",
"U",
"-",
"ABORT",
"without",
"any",
"apdu",
"-",
"for",
"MAP",
"V1"
] | train | https://github.com/RestComm/jss7/blob/402b4b3984e581c581e309cb5f6a858fde6dbc33/map/map-impl/src/main/java/org/restcomm/protocols/ss7/map/MAPProviderImpl.java#L2139-L2154 |
apache/groovy | src/main/java/org/codehaus/groovy/control/CompilerConfiguration.java | CompilerConfiguration.setOptimizationOptions | public void setOptimizationOptions(Map<String, Boolean> options) {
if (options == null) throw new IllegalArgumentException("provided option map must not be null");
optimizationOptions = options;
} | java | public void setOptimizationOptions(Map<String, Boolean> options) {
if (options == null) throw new IllegalArgumentException("provided option map must not be null");
optimizationOptions = options;
} | [
"public",
"void",
"setOptimizationOptions",
"(",
"Map",
"<",
"String",
",",
"Boolean",
">",
"options",
")",
"{",
"if",
"(",
"options",
"==",
"null",
")",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"provided option map must not be null\"",
")",
";",
"optimi... | Sets the optimization options for this configuration.
No entry or a true for that entry means to enable that optimization,
a false means the optimization is disabled.
Valid keys are "all" and "int".
@param options the options.
@throws IllegalArgumentException if the options are null | [
"Sets",
"the",
"optimization",
"options",
"for",
"this",
"configuration",
".",
"No",
"entry",
"or",
"a",
"true",
"for",
"that",
"entry",
"means",
"to",
"enable",
"that",
"optimization",
"a",
"false",
"means",
"the",
"optimization",
"is",
"disabled",
".",
"Va... | train | https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/codehaus/groovy/control/CompilerConfiguration.java#L1047-L1050 |
TheCoder4eu/BootsFaces-OSP | src/main/java/net/bootsfaces/component/selectBooleanCheckbox/SelectBooleanCheckboxRenderer.java | SelectBooleanCheckboxRenderer.encodeBegin | @Override
public void encodeBegin(FacesContext context, UIComponent component) throws IOException {
if (!component.isRendered()) {
return;
}
SelectBooleanCheckbox selectBooleanCheckbox = (SelectBooleanCheckbox) component;
ResponseWriter rw = context.getResponseWriter();
String clientId = selectBooleanCheckbox.getClientId(context);
String span = null;
if (!isHorizontalForm(component)) {
span = startColSpanDiv(rw, selectBooleanCheckbox);
}
rw.startElement("div", component);
rw.writeAttribute("id", clientId, null);
writeAttribute(rw,"class", getWithFeedback(InputMode.DEFAULT, component), "class");
if (null != selectBooleanCheckbox.getDir()) {
rw.writeAttribute("dir", selectBooleanCheckbox.getDir(), "dir");
}
addLabel(rw, clientId, selectBooleanCheckbox);
renderInputTag(context, rw, clientId, selectBooleanCheckbox);
rw.endElement("div");
closeColSpanDiv(rw, span);
Tooltip.activateTooltips(context, selectBooleanCheckbox);
} | java | @Override
public void encodeBegin(FacesContext context, UIComponent component) throws IOException {
if (!component.isRendered()) {
return;
}
SelectBooleanCheckbox selectBooleanCheckbox = (SelectBooleanCheckbox) component;
ResponseWriter rw = context.getResponseWriter();
String clientId = selectBooleanCheckbox.getClientId(context);
String span = null;
if (!isHorizontalForm(component)) {
span = startColSpanDiv(rw, selectBooleanCheckbox);
}
rw.startElement("div", component);
rw.writeAttribute("id", clientId, null);
writeAttribute(rw,"class", getWithFeedback(InputMode.DEFAULT, component), "class");
if (null != selectBooleanCheckbox.getDir()) {
rw.writeAttribute("dir", selectBooleanCheckbox.getDir(), "dir");
}
addLabel(rw, clientId, selectBooleanCheckbox);
renderInputTag(context, rw, clientId, selectBooleanCheckbox);
rw.endElement("div");
closeColSpanDiv(rw, span);
Tooltip.activateTooltips(context, selectBooleanCheckbox);
} | [
"@",
"Override",
"public",
"void",
"encodeBegin",
"(",
"FacesContext",
"context",
",",
"UIComponent",
"component",
")",
"throws",
"IOException",
"{",
"if",
"(",
"!",
"component",
".",
"isRendered",
"(",
")",
")",
"{",
"return",
";",
"}",
"SelectBooleanCheckbox... | This methods generates the HTML code of the current
b:selectBooleanCheckbox.
@param context
the FacesContext.
@param component
the current b:selectBooleanCheckbox.
@throws IOException
thrown if something goes wrong when writing the HTML code. | [
"This",
"methods",
"generates",
"the",
"HTML",
"code",
"of",
"the",
"current",
"b",
":",
"selectBooleanCheckbox",
"."
] | train | https://github.com/TheCoder4eu/BootsFaces-OSP/blob/d1a70952bc240979b5272fa4fe1c7f100873add0/src/main/java/net/bootsfaces/component/selectBooleanCheckbox/SelectBooleanCheckboxRenderer.java#L103-L132 |
eduarddrenth/ConfigurableReports | src/main/java/com/vectorprint/report/itext/BaseReportGenerator.java | BaseReportGenerator.createReportBody | protected void createReportBody(Document document, RD data, com.itextpdf.text.pdf.PdfWriter writer) throws DocumentException, VectorPrintException {
processData(data);
} | java | protected void createReportBody(Document document, RD data, com.itextpdf.text.pdf.PdfWriter writer) throws DocumentException, VectorPrintException {
processData(data);
} | [
"protected",
"void",
"createReportBody",
"(",
"Document",
"document",
",",
"RD",
"data",
",",
"com",
".",
"itextpdf",
".",
"text",
".",
"pdf",
".",
"PdfWriter",
"writer",
")",
"throws",
"DocumentException",
",",
"VectorPrintException",
"{",
"processData",
"(",
... | Calls {@link #processData(com.vectorprint.report.data.ReportDataHolder) }. If you don't want to use the {@link DataCollector} /
{@link ReportDataHolder} mechanism extend this class, override this method and provide it's name in a setting
{@link ReportConstants#REPORTCLASS}.
@throws com.vectorprint.VectorPrintException
@see com.vectorprint.report.itext.annotations.Element
@param document
@param data may be null, for example when no {@link DataCollector} is used
@param writer the value of writer
@throws DocumentException | [
"Calls",
"{",
"@link",
"#processData",
"(",
"com",
".",
"vectorprint",
".",
"report",
".",
"data",
".",
"ReportDataHolder",
")",
"}",
".",
"If",
"you",
"don",
"t",
"want",
"to",
"use",
"the",
"{",
"@link",
"DataCollector",
"}",
"/",
"{",
"@link",
"Repo... | train | https://github.com/eduarddrenth/ConfigurableReports/blob/b5fb7a89e16d9b35f557f3bf620594f821fa1552/src/main/java/com/vectorprint/report/itext/BaseReportGenerator.java#L336-L338 |
apache/flink | flink-core/src/main/java/org/apache/flink/util/ShutdownHookUtil.java | ShutdownHookUtil.addShutdownHook | public static Thread addShutdownHook(
final AutoCloseable service,
final String serviceName,
final Logger logger) {
checkNotNull(service);
checkNotNull(logger);
final Thread shutdownHook = new Thread(() -> {
try {
service.close();
} catch (Throwable t) {
logger.error("Error during shutdown of {} via JVM shutdown hook.", serviceName, t);
}
}, serviceName + " shutdown hook");
return addShutdownHookThread(shutdownHook, serviceName, logger) ? shutdownHook : null;
} | java | public static Thread addShutdownHook(
final AutoCloseable service,
final String serviceName,
final Logger logger) {
checkNotNull(service);
checkNotNull(logger);
final Thread shutdownHook = new Thread(() -> {
try {
service.close();
} catch (Throwable t) {
logger.error("Error during shutdown of {} via JVM shutdown hook.", serviceName, t);
}
}, serviceName + " shutdown hook");
return addShutdownHookThread(shutdownHook, serviceName, logger) ? shutdownHook : null;
} | [
"public",
"static",
"Thread",
"addShutdownHook",
"(",
"final",
"AutoCloseable",
"service",
",",
"final",
"String",
"serviceName",
",",
"final",
"Logger",
"logger",
")",
"{",
"checkNotNull",
"(",
"service",
")",
";",
"checkNotNull",
"(",
"logger",
")",
";",
"fi... | Adds a shutdown hook to the JVM and returns the Thread, which has been registered. | [
"Adds",
"a",
"shutdown",
"hook",
"to",
"the",
"JVM",
"and",
"returns",
"the",
"Thread",
"which",
"has",
"been",
"registered",
"."
] | train | https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-core/src/main/java/org/apache/flink/util/ShutdownHookUtil.java#L33-L50 |
BorderTech/wcomponents | wcomponents-examples/src/main/java/com/github/bordertech/wcomponents/examples/theme/WRowExample.java | WRowExample.addAppLevelCSSExample | private void addAppLevelCSSExample() {
String htmlClass = "my_local_class";
add(new WHeading(HeadingLevel.H2, "App defined widths"));
add(new ExplanatoryText("This example shows the use of a htmlClass and app-specific CSS (in this case inline)"
+ " to style the columns including responsive widths"
+ " which kick in at 1000px and 900px"));
WRow row = new WRow();
row.setHtmlClass(htmlClass);
add(row);
WColumn col1 = new WColumn();
String col1HtmlClass = "my_col1";
col1.setHtmlClass(col1HtmlClass);
col1.add(new ExplanatoryText("This is some text content in the first column."));
row.add(col1);
WColumn col2 = new WColumn();
String col2HtmlClass = "my_col2";
col2.setHtmlClass(col2HtmlClass);
col2.add(new ExplanatoryText("Some content in column 2."));
row.add(col2);
WColumn col3 = new WColumn();
col3.add(new ExplanatoryText("Some content in column 3."));
row.add(col3);
String columnClass = ".wc-column";
String rowSelector = "." + htmlClass;
String columnSelector = rowSelector + " > " + columnClass; // .column is the local name of WColumn's XML element and is part of the client side API.
String css = columnSelector + " {width: 20%; background-color: #f0f0f0; padding: 0.5em;}"
+ columnSelector + " + " + columnClass + " {margin-left: 0.5em}"
+ columnSelector + "." + col2.getHtmlClass() + " {width: 60%;}"
+ "@media only screen and (max-width: 1000px) {" //when the screen goes below 1000px wide
+ rowSelector + " {display: block;}"
+ columnSelector + " {display: inline-block; box-sizing: border-box;}"
+ columnSelector + " + " + columnClass + " {margin-left: 0}"
+ columnSelector + "." + col1.getHtmlClass() + " {display: block; width: 100%; margin-bottom: 0.5em;} "
+ columnSelector + " ~ " + columnClass + " {width: calc(50% - 0.25em); background-color: #f0f000}"
+ "." + col2.getHtmlClass() + " {margin-right: 0.25em}"
+ "." + col2.getHtmlClass() + " + " + columnClass + " {margin-left: 0.25em;}"
+ "}\n@media only screen and (max-width: 900px) {" //when the screen goes below 900px wide;
+ columnSelector + " {width: 100% !important; margin-left: 0 !important; margin-right: 0 !important; background-color: #ff0 !important;}" //the importants are becauseI am lazy
+ "." + col2.getHtmlClass() + " {margin-bottom: 0.5em;}\n}";
WText cssText = new WText("<style type='text/css'>" + css + "</style>");
cssText.setEncodeText(false);
add(cssText);
} | java | private void addAppLevelCSSExample() {
String htmlClass = "my_local_class";
add(new WHeading(HeadingLevel.H2, "App defined widths"));
add(new ExplanatoryText("This example shows the use of a htmlClass and app-specific CSS (in this case inline)"
+ " to style the columns including responsive widths"
+ " which kick in at 1000px and 900px"));
WRow row = new WRow();
row.setHtmlClass(htmlClass);
add(row);
WColumn col1 = new WColumn();
String col1HtmlClass = "my_col1";
col1.setHtmlClass(col1HtmlClass);
col1.add(new ExplanatoryText("This is some text content in the first column."));
row.add(col1);
WColumn col2 = new WColumn();
String col2HtmlClass = "my_col2";
col2.setHtmlClass(col2HtmlClass);
col2.add(new ExplanatoryText("Some content in column 2."));
row.add(col2);
WColumn col3 = new WColumn();
col3.add(new ExplanatoryText("Some content in column 3."));
row.add(col3);
String columnClass = ".wc-column";
String rowSelector = "." + htmlClass;
String columnSelector = rowSelector + " > " + columnClass; // .column is the local name of WColumn's XML element and is part of the client side API.
String css = columnSelector + " {width: 20%; background-color: #f0f0f0; padding: 0.5em;}"
+ columnSelector + " + " + columnClass + " {margin-left: 0.5em}"
+ columnSelector + "." + col2.getHtmlClass() + " {width: 60%;}"
+ "@media only screen and (max-width: 1000px) {" //when the screen goes below 1000px wide
+ rowSelector + " {display: block;}"
+ columnSelector + " {display: inline-block; box-sizing: border-box;}"
+ columnSelector + " + " + columnClass + " {margin-left: 0}"
+ columnSelector + "." + col1.getHtmlClass() + " {display: block; width: 100%; margin-bottom: 0.5em;} "
+ columnSelector + " ~ " + columnClass + " {width: calc(50% - 0.25em); background-color: #f0f000}"
+ "." + col2.getHtmlClass() + " {margin-right: 0.25em}"
+ "." + col2.getHtmlClass() + " + " + columnClass + " {margin-left: 0.25em;}"
+ "}\n@media only screen and (max-width: 900px) {" //when the screen goes below 900px wide;
+ columnSelector + " {width: 100% !important; margin-left: 0 !important; margin-right: 0 !important; background-color: #ff0 !important;}" //the importants are becauseI am lazy
+ "." + col2.getHtmlClass() + " {margin-bottom: 0.5em;}\n}";
WText cssText = new WText("<style type='text/css'>" + css + "</style>");
cssText.setEncodeText(false);
add(cssText);
} | [
"private",
"void",
"addAppLevelCSSExample",
"(",
")",
"{",
"String",
"htmlClass",
"=",
"\"my_local_class\"",
";",
"add",
"(",
"new",
"WHeading",
"(",
"HeadingLevel",
".",
"H2",
",",
"\"App defined widths\"",
")",
")",
";",
"add",
"(",
"new",
"ExplanatoryText",
... | Build an example with undefined column widths then use application-level CSS and a htmlClass property to define the widths. | [
"Build",
"an",
"example",
"with",
"undefined",
"column",
"widths",
"then",
"use",
"application",
"-",
"level",
"CSS",
"and",
"a",
"htmlClass",
"property",
"to",
"define",
"the",
"widths",
"."
] | train | https://github.com/BorderTech/wcomponents/blob/d1a2b2243270067db030feb36ca74255aaa94436/wcomponents-examples/src/main/java/com/github/bordertech/wcomponents/examples/theme/WRowExample.java#L160-L208 |
j-easy/easy-random | easy-random-core/src/main/java/org/jeasy/random/randomizers/range/LocalDateTimeRangeRandomizer.java | LocalDateTimeRangeRandomizer.aNewLocalDateTimeRangeRandomizer | public static LocalDateTimeRangeRandomizer aNewLocalDateTimeRangeRandomizer(final LocalDateTime min, final LocalDateTime max, final long seed) {
return new LocalDateTimeRangeRandomizer(min, max, seed);
} | java | public static LocalDateTimeRangeRandomizer aNewLocalDateTimeRangeRandomizer(final LocalDateTime min, final LocalDateTime max, final long seed) {
return new LocalDateTimeRangeRandomizer(min, max, seed);
} | [
"public",
"static",
"LocalDateTimeRangeRandomizer",
"aNewLocalDateTimeRangeRandomizer",
"(",
"final",
"LocalDateTime",
"min",
",",
"final",
"LocalDateTime",
"max",
",",
"final",
"long",
"seed",
")",
"{",
"return",
"new",
"LocalDateTimeRangeRandomizer",
"(",
"min",
",",
... | Create a new {@link LocalDateTimeRangeRandomizer}.
@param min min value
@param max max value
@param seed initial seed
@return a new {@link LocalDateTimeRangeRandomizer}. | [
"Create",
"a",
"new",
"{",
"@link",
"LocalDateTimeRangeRandomizer",
"}",
"."
] | train | https://github.com/j-easy/easy-random/blob/816b0d6a74c7288af111e70ae1b0b57d7fe3b59d/easy-random-core/src/main/java/org/jeasy/random/randomizers/range/LocalDateTimeRangeRandomizer.java#L85-L87 |
prometheus/client_java | simpleclient_pushgateway/src/main/java/io/prometheus/client/exporter/PushGateway.java | PushGateway.pushAdd | public void pushAdd(CollectorRegistry registry, String job) throws IOException {
doRequest(registry, job, null, "POST");
} | java | public void pushAdd(CollectorRegistry registry, String job) throws IOException {
doRequest(registry, job, null, "POST");
} | [
"public",
"void",
"pushAdd",
"(",
"CollectorRegistry",
"registry",
",",
"String",
"job",
")",
"throws",
"IOException",
"{",
"doRequest",
"(",
"registry",
",",
"job",
",",
"null",
",",
"\"POST\"",
")",
";",
"}"
] | Pushes all metrics in a registry, replacing only previously pushed metrics of the same name and job and no grouping key.
<p>
This uses the POST HTTP method. | [
"Pushes",
"all",
"metrics",
"in",
"a",
"registry",
"replacing",
"only",
"previously",
"pushed",
"metrics",
"of",
"the",
"same",
"name",
"and",
"job",
"and",
"no",
"grouping",
"key",
".",
"<p",
">",
"This",
"uses",
"the",
"POST",
"HTTP",
"method",
"."
] | train | https://github.com/prometheus/client_java/blob/4e0e7527b048f1ffd0382dcb74c0b9dab23b4d9f/simpleclient_pushgateway/src/main/java/io/prometheus/client/exporter/PushGateway.java#L157-L159 |
jbundle/jbundle | base/screen/model/src/main/java/org/jbundle/base/screen/model/MenuScreen.java | MenuScreen.getURLMenu | public String getURLMenu()
{
String strMenu = this.getProperty(DBParams.URL);
if ((strMenu != null) && (strMenu.length() > 0))
{ // Look to see if this URL has a menu associated with it.
strMenu = Utility.getDomainFromURL(strMenu, null);
// Now I have the domain name, try to lookup the menu name...
Record recMenu = this.getMainRecord();
recMenu.setKeyArea(MenusModel.CODE_KEY);
try {
while (strMenu.length() > 0)
{
recMenu.getField(MenusModel.CODE).setString(strMenu);
if (recMenu.seek("="))
return recMenu.getField(MenusModel.CODE).toString();
if (strMenu.indexOf('.') == strMenu.lastIndexOf('.'))
break; // xyz.com = stop looking
strMenu = strMenu.substring(strMenu.indexOf('.') + 1); // Remove the next top level domain (ie., www)
}
} catch (DBException ex) {
ex.printStackTrace();
}
}
return null;
} | java | public String getURLMenu()
{
String strMenu = this.getProperty(DBParams.URL);
if ((strMenu != null) && (strMenu.length() > 0))
{ // Look to see if this URL has a menu associated with it.
strMenu = Utility.getDomainFromURL(strMenu, null);
// Now I have the domain name, try to lookup the menu name...
Record recMenu = this.getMainRecord();
recMenu.setKeyArea(MenusModel.CODE_KEY);
try {
while (strMenu.length() > 0)
{
recMenu.getField(MenusModel.CODE).setString(strMenu);
if (recMenu.seek("="))
return recMenu.getField(MenusModel.CODE).toString();
if (strMenu.indexOf('.') == strMenu.lastIndexOf('.'))
break; // xyz.com = stop looking
strMenu = strMenu.substring(strMenu.indexOf('.') + 1); // Remove the next top level domain (ie., www)
}
} catch (DBException ex) {
ex.printStackTrace();
}
}
return null;
} | [
"public",
"String",
"getURLMenu",
"(",
")",
"{",
"String",
"strMenu",
"=",
"this",
".",
"getProperty",
"(",
"DBParams",
".",
"URL",
")",
";",
"if",
"(",
"(",
"strMenu",
"!=",
"null",
")",
"&&",
"(",
"strMenu",
".",
"length",
"(",
")",
">",
"0",
")"... | From the URL, get the menu.
First try the app URL, then try the host URL (ie., www.tourgeek.com/fred then www.tourgeek.com).
@return The menu name. | [
"From",
"the",
"URL",
"get",
"the",
"menu",
".",
"First",
"try",
"the",
"app",
"URL",
"then",
"try",
"the",
"host",
"URL",
"(",
"ie",
".",
"www",
".",
"tourgeek",
".",
"com",
"/",
"fred",
"then",
"www",
".",
"tourgeek",
".",
"com",
")",
"."
] | train | https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/base/screen/model/src/main/java/org/jbundle/base/screen/model/MenuScreen.java#L254-L279 |
JOML-CI/JOML | src/org/joml/Matrix3x2f.java | Matrix3x2f.scale | public Matrix3x2f scale(Vector2fc xy, Matrix3x2f dest) {
return scale(xy.x(), xy.y(), dest);
} | java | public Matrix3x2f scale(Vector2fc xy, Matrix3x2f dest) {
return scale(xy.x(), xy.y(), dest);
} | [
"public",
"Matrix3x2f",
"scale",
"(",
"Vector2fc",
"xy",
",",
"Matrix3x2f",
"dest",
")",
"{",
"return",
"scale",
"(",
"xy",
".",
"x",
"(",
")",
",",
"xy",
".",
"y",
"(",
")",
",",
"dest",
")",
";",
"}"
] | Apply scaling to this matrix by scaling the base axes by the given <code>xy</code> factors
and store the result in <code>dest</code>.
<p>
If <code>M</code> is <code>this</code> matrix and <code>S</code> the scaling matrix,
then the new matrix will be <code>M * S</code>. So when transforming a
vector <code>v</code> with the new matrix by using <code>M * S * v</code>, the scaling will be applied first!
@param xy
the factors of the x and y component, respectively
@param dest
will hold the result
@return dest | [
"Apply",
"scaling",
"to",
"this",
"matrix",
"by",
"scaling",
"the",
"base",
"axes",
"by",
"the",
"given",
"<code",
">",
"xy<",
"/",
"code",
">",
"factors",
"and",
"store",
"the",
"result",
"in",
"<code",
">",
"dest<",
"/",
"code",
">",
".",
"<p",
">"... | train | https://github.com/JOML-CI/JOML/blob/ce2652fc236b42bda3875c591f8e6645048a678f/src/org/joml/Matrix3x2f.java#L1280-L1282 |
haraldk/TwelveMonkeys | common/common-image/src/main/java/com/twelvemonkeys/image/MagickUtil.java | MagickUtil.grayToBuffered | private static BufferedImage grayToBuffered(MagickImage pImage, boolean pAlpha) throws MagickException {
Dimension size = pImage.getDimension();
int length = size.width * size.height;
int bands = pAlpha ? 2 : 1;
byte[] pixels = new byte[length * bands];
// TODO: Make a fix for 16 bit TYPE_USHORT_GRAY?!
// Note: The ordering AI or I corresponds to BufferedImage
// TYPE_CUSTOM and TYPE_BYTE_GRAY respectively
pImage.dispatchImage(0, 0, size.width, size.height, pAlpha ? "AI" : "I", pixels);
// Init databuffer with array, to avoid allocation of empty array
DataBuffer buffer = new DataBufferByte(pixels, pixels.length);
int[] bandOffsets = pAlpha ? new int[] {1, 0} : new int[] {0};
WritableRaster raster =
Raster.createInterleavedRaster(buffer, size.width, size.height,
size.width * bands, bands, bandOffsets, LOCATION_UPPER_LEFT);
return new BufferedImage(pAlpha ? CM_GRAY_ALPHA : CM_GRAY_OPAQUE, raster, pAlpha, null);
} | java | private static BufferedImage grayToBuffered(MagickImage pImage, boolean pAlpha) throws MagickException {
Dimension size = pImage.getDimension();
int length = size.width * size.height;
int bands = pAlpha ? 2 : 1;
byte[] pixels = new byte[length * bands];
// TODO: Make a fix for 16 bit TYPE_USHORT_GRAY?!
// Note: The ordering AI or I corresponds to BufferedImage
// TYPE_CUSTOM and TYPE_BYTE_GRAY respectively
pImage.dispatchImage(0, 0, size.width, size.height, pAlpha ? "AI" : "I", pixels);
// Init databuffer with array, to avoid allocation of empty array
DataBuffer buffer = new DataBufferByte(pixels, pixels.length);
int[] bandOffsets = pAlpha ? new int[] {1, 0} : new int[] {0};
WritableRaster raster =
Raster.createInterleavedRaster(buffer, size.width, size.height,
size.width * bands, bands, bandOffsets, LOCATION_UPPER_LEFT);
return new BufferedImage(pAlpha ? CM_GRAY_ALPHA : CM_GRAY_OPAQUE, raster, pAlpha, null);
} | [
"private",
"static",
"BufferedImage",
"grayToBuffered",
"(",
"MagickImage",
"pImage",
",",
"boolean",
"pAlpha",
")",
"throws",
"MagickException",
"{",
"Dimension",
"size",
"=",
"pImage",
".",
"getDimension",
"(",
")",
";",
"int",
"length",
"=",
"size",
".",
"w... | Converts a gray {@code MagickImage} to a {@code BufferedImage}, of
type {@code TYPE_USHORT_GRAY} or {@code TYPE_BYTE_GRAY}.
@param pImage the original {@code MagickImage}
@param pAlpha keep alpha channel
@return a new {@code BufferedImage}
@throws MagickException if an exception occurs during conversion
@see BufferedImage | [
"Converts",
"a",
"gray",
"{",
"@code",
"MagickImage",
"}",
"to",
"a",
"{",
"@code",
"BufferedImage",
"}",
"of",
"type",
"{",
"@code",
"TYPE_USHORT_GRAY",
"}",
"or",
"{",
"@code",
"TYPE_BYTE_GRAY",
"}",
"."
] | train | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/common/common-image/src/main/java/com/twelvemonkeys/image/MagickUtil.java#L409-L430 |
pmlopes/yoke | framework/src/main/java/com/jetdrone/vertx/yoke/sockjs/impl/EventBusBridgeImpl.java | EventBusBridgeImpl.checkMatches | private boolean checkMatches(boolean inbound, String address, Object body) {
List<PermittedOptions> matches = inbound ? inboundPermitted : outboundPermitted;
for (PermittedOptions matchHolder : matches) {
String matchAddress = matchHolder.getAddress();
String matchRegex;
if (matchAddress == null) {
matchRegex = matchHolder.getAddressRegex();
} else {
matchRegex = null;
}
boolean addressOK;
if (matchAddress == null) {
addressOK = matchRegex == null || regexMatches(matchRegex, address);
} else {
addressOK = matchAddress.equals(address);
}
if (addressOK) {
return structureMatches(matchHolder.getMatch(), body);
}
}
return false;
} | java | private boolean checkMatches(boolean inbound, String address, Object body) {
List<PermittedOptions> matches = inbound ? inboundPermitted : outboundPermitted;
for (PermittedOptions matchHolder : matches) {
String matchAddress = matchHolder.getAddress();
String matchRegex;
if (matchAddress == null) {
matchRegex = matchHolder.getAddressRegex();
} else {
matchRegex = null;
}
boolean addressOK;
if (matchAddress == null) {
addressOK = matchRegex == null || regexMatches(matchRegex, address);
} else {
addressOK = matchAddress.equals(address);
}
if (addressOK) {
return structureMatches(matchHolder.getMatch(), body);
}
}
return false;
} | [
"private",
"boolean",
"checkMatches",
"(",
"boolean",
"inbound",
",",
"String",
"address",
",",
"Object",
"body",
")",
"{",
"List",
"<",
"PermittedOptions",
">",
"matches",
"=",
"inbound",
"?",
"inboundPermitted",
":",
"outboundPermitted",
";",
"for",
"(",
"Pe... | /*
Empty inboundPermitted means reject everything - this is the default.
If at least one match is supplied and all the fields of any match match then the message inboundPermitted,
this means that specifying one match with a JSON empty object means everything is accepted | [
"/",
"*",
"Empty",
"inboundPermitted",
"means",
"reject",
"everything",
"-",
"this",
"is",
"the",
"default",
".",
"If",
"at",
"least",
"one",
"match",
"is",
"supplied",
"and",
"all",
"the",
"fields",
"of",
"any",
"match",
"match",
"then",
"the",
"message",... | train | https://github.com/pmlopes/yoke/blob/fe8a64036f09fb745f0644faddd46162d64faf3c/framework/src/main/java/com/jetdrone/vertx/yoke/sockjs/impl/EventBusBridgeImpl.java#L423-L448 |
spotbugs/spotbugs | spotbugs/src/gui/main/edu/umd/cs/findbugs/gui2/MainFrameComponentFactory.java | MainFrameComponentFactory.createSourceCodePanel | JPanel createSourceCodePanel() {
Font sourceFont = new Font("Monospaced", Font.PLAIN, (int) Driver.getFontSize());
mainFrame.getSourceCodeTextPane().setFont(sourceFont);
mainFrame.getSourceCodeTextPane().setEditable(false);
mainFrame.getSourceCodeTextPane().getCaret().setSelectionVisible(true);
mainFrame.getSourceCodeTextPane().setDocument(SourceCodeDisplay.SOURCE_NOT_RELEVANT);
JScrollPane sourceCodeScrollPane = new JScrollPane(mainFrame.getSourceCodeTextPane());
sourceCodeScrollPane.getVerticalScrollBar().setUnitIncrement(20);
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
panel.add(sourceCodeScrollPane, BorderLayout.CENTER);
panel.revalidate();
if (MainFrame.GUI2_DEBUG) {
System.out.println("Created source code panel");
}
return panel;
} | java | JPanel createSourceCodePanel() {
Font sourceFont = new Font("Monospaced", Font.PLAIN, (int) Driver.getFontSize());
mainFrame.getSourceCodeTextPane().setFont(sourceFont);
mainFrame.getSourceCodeTextPane().setEditable(false);
mainFrame.getSourceCodeTextPane().getCaret().setSelectionVisible(true);
mainFrame.getSourceCodeTextPane().setDocument(SourceCodeDisplay.SOURCE_NOT_RELEVANT);
JScrollPane sourceCodeScrollPane = new JScrollPane(mainFrame.getSourceCodeTextPane());
sourceCodeScrollPane.getVerticalScrollBar().setUnitIncrement(20);
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
panel.add(sourceCodeScrollPane, BorderLayout.CENTER);
panel.revalidate();
if (MainFrame.GUI2_DEBUG) {
System.out.println("Created source code panel");
}
return panel;
} | [
"JPanel",
"createSourceCodePanel",
"(",
")",
"{",
"Font",
"sourceFont",
"=",
"new",
"Font",
"(",
"\"Monospaced\"",
",",
"Font",
".",
"PLAIN",
",",
"(",
"int",
")",
"Driver",
".",
"getFontSize",
"(",
")",
")",
";",
"mainFrame",
".",
"getSourceCodeTextPane",
... | Creates the source code panel, but does not put anything in it. | [
"Creates",
"the",
"source",
"code",
"panel",
"but",
"does",
"not",
"put",
"anything",
"in",
"it",
"."
] | train | https://github.com/spotbugs/spotbugs/blob/f6365c6eea6515035bded38efa4a7c8b46ccf28c/spotbugs/src/gui/main/edu/umd/cs/findbugs/gui2/MainFrameComponentFactory.java#L137-L155 |
couchbase/couchbase-java-client | src/main/java/com/couchbase/client/java/util/retry/Retry.java | Retry.wrapForRetry | public static <T> Observable<T> wrapForRetry(Observable<T> source, int maxAttempts, Delay retryDelay) {
return wrapForRetry(source, new RetryWithDelayHandler(maxAttempts, retryDelay));
} | java | public static <T> Observable<T> wrapForRetry(Observable<T> source, int maxAttempts, Delay retryDelay) {
return wrapForRetry(source, new RetryWithDelayHandler(maxAttempts, retryDelay));
} | [
"public",
"static",
"<",
"T",
">",
"Observable",
"<",
"T",
">",
"wrapForRetry",
"(",
"Observable",
"<",
"T",
">",
"source",
",",
"int",
"maxAttempts",
",",
"Delay",
"retryDelay",
")",
"{",
"return",
"wrapForRetry",
"(",
"source",
",",
"new",
"RetryWithDela... | Wrap an {@link Observable} so that it will retry on all errors. The retry will occur for a maximum number of
attempts and with a provided {@link Delay} between each attempt.
@param source the {@link Observable} to wrap.
@param maxAttempts the maximum number of times to attempt a retry. It will be capped at <code>{@link Integer#MAX_VALUE} - 1</code>.
@param retryDelay the {@link Delay} between each attempt.
@param <T> the type of items emitted by the source Observable.
@return the wrapped retrying Observable. | [
"Wrap",
"an",
"{",
"@link",
"Observable",
"}",
"so",
"that",
"it",
"will",
"retry",
"on",
"all",
"errors",
".",
"The",
"retry",
"will",
"occur",
"for",
"a",
"maximum",
"number",
"of",
"attempts",
"and",
"with",
"a",
"provided",
"{",
"@link",
"Delay",
"... | train | https://github.com/couchbase/couchbase-java-client/blob/f36a0ee0c66923bdde47838ca543e50cbaa99e14/src/main/java/com/couchbase/client/java/util/retry/Retry.java#L65-L67 |
languagetool-org/languagetool | languagetool-core/src/main/java/org/languagetool/rules/patterns/PatternToken.java | PatternToken.setStringPosException | public void setStringPosException(
String token, boolean regExp, boolean inflected,
boolean negation, boolean scopeNext, boolean scopePrevious,
String posToken, boolean posRegExp, boolean posNegation, Boolean caseSensitivity) {
PatternToken exception = new PatternToken(token, caseSensitivity == null ? caseSensitive : caseSensitivity, regExp, inflected);
exception.setNegation(negation);
exception.setPosToken(new PosToken(posToken, posRegExp, posNegation));
exception.exceptionValidNext = scopeNext;
setException(exception, scopePrevious);
} | java | public void setStringPosException(
String token, boolean regExp, boolean inflected,
boolean negation, boolean scopeNext, boolean scopePrevious,
String posToken, boolean posRegExp, boolean posNegation, Boolean caseSensitivity) {
PatternToken exception = new PatternToken(token, caseSensitivity == null ? caseSensitive : caseSensitivity, regExp, inflected);
exception.setNegation(negation);
exception.setPosToken(new PosToken(posToken, posRegExp, posNegation));
exception.exceptionValidNext = scopeNext;
setException(exception, scopePrevious);
} | [
"public",
"void",
"setStringPosException",
"(",
"String",
"token",
",",
"boolean",
"regExp",
",",
"boolean",
"inflected",
",",
"boolean",
"negation",
",",
"boolean",
"scopeNext",
",",
"boolean",
"scopePrevious",
",",
"String",
"posToken",
",",
"boolean",
"posRegEx... | Sets a string and/or pos exception for matching tokens.
@param token The string in the exception.
@param regExp True if the string is specified as a regular expression.
@param inflected True if the string is a base form (lemma).
@param negation True if the exception is negated.
@param scopeNext True if the exception scope is next tokens.
@param scopePrevious True if the exception should match only a single previous token.
@param posToken The part of the speech tag in the exception.
@param posRegExp True if the POS is specified as a regular expression.
@param posNegation True if the POS exception is negated.
@param caseSensitivity if null, use this element's setting for case sensitivity, otherwise the specified value
@since 2.9 | [
"Sets",
"a",
"string",
"and",
"/",
"or",
"pos",
"exception",
"for",
"matching",
"tokens",
"."
] | train | https://github.com/languagetool-org/languagetool/blob/b7a3d63883d242fb2525877c6382681c57a0a142/languagetool-core/src/main/java/org/languagetool/rules/patterns/PatternToken.java#L332-L341 |
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.listCompositeEntitiesWithServiceResponseAsync | public Observable<ServiceResponse<List<CompositeEntityExtractor>>> listCompositeEntitiesWithServiceResponseAsync(UUID appId, String versionId, ListCompositeEntitiesOptionalParameter listCompositeEntitiesOptionalParameter) {
if (this.client.endpoint() == null) {
throw new IllegalArgumentException("Parameter this.client.endpoint() is required and cannot be null.");
}
if (appId == null) {
throw new IllegalArgumentException("Parameter appId is required and cannot be null.");
}
if (versionId == null) {
throw new IllegalArgumentException("Parameter versionId is required and cannot be null.");
}
final Integer skip = listCompositeEntitiesOptionalParameter != null ? listCompositeEntitiesOptionalParameter.skip() : null;
final Integer take = listCompositeEntitiesOptionalParameter != null ? listCompositeEntitiesOptionalParameter.take() : null;
return listCompositeEntitiesWithServiceResponseAsync(appId, versionId, skip, take);
} | java | public Observable<ServiceResponse<List<CompositeEntityExtractor>>> listCompositeEntitiesWithServiceResponseAsync(UUID appId, String versionId, ListCompositeEntitiesOptionalParameter listCompositeEntitiesOptionalParameter) {
if (this.client.endpoint() == null) {
throw new IllegalArgumentException("Parameter this.client.endpoint() is required and cannot be null.");
}
if (appId == null) {
throw new IllegalArgumentException("Parameter appId is required and cannot be null.");
}
if (versionId == null) {
throw new IllegalArgumentException("Parameter versionId is required and cannot be null.");
}
final Integer skip = listCompositeEntitiesOptionalParameter != null ? listCompositeEntitiesOptionalParameter.skip() : null;
final Integer take = listCompositeEntitiesOptionalParameter != null ? listCompositeEntitiesOptionalParameter.take() : null;
return listCompositeEntitiesWithServiceResponseAsync(appId, versionId, skip, take);
} | [
"public",
"Observable",
"<",
"ServiceResponse",
"<",
"List",
"<",
"CompositeEntityExtractor",
">",
">",
">",
"listCompositeEntitiesWithServiceResponseAsync",
"(",
"UUID",
"appId",
",",
"String",
"versionId",
",",
"ListCompositeEntitiesOptionalParameter",
"listCompositeEntitie... | Gets information about the composite entity models.
@param appId The application ID.
@param versionId The version ID.
@param listCompositeEntitiesOptionalParameter 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<CompositeEntityExtractor> object | [
"Gets",
"information",
"about",
"the",
"composite",
"entity",
"models",
"."
] | 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#L1688-L1702 |
pgjdbc/pgjdbc | pgjdbc/src/main/java/org/postgresql/jdbc/EscapedFunctions2.java | EscapedFunctions2.sqluser | public static void sqluser(StringBuilder buf, List<? extends CharSequence> parsedArgs) throws SQLException {
zeroArgumentFunctionCall(buf, "user", "user", parsedArgs);
} | java | public static void sqluser(StringBuilder buf, List<? extends CharSequence> parsedArgs) throws SQLException {
zeroArgumentFunctionCall(buf, "user", "user", parsedArgs);
} | [
"public",
"static",
"void",
"sqluser",
"(",
"StringBuilder",
"buf",
",",
"List",
"<",
"?",
"extends",
"CharSequence",
">",
"parsedArgs",
")",
"throws",
"SQLException",
"{",
"zeroArgumentFunctionCall",
"(",
"buf",
",",
"\"user\"",
",",
"\"user\"",
",",
"parsedArg... | user translation
@param buf The buffer to append into
@param parsedArgs arguments
@throws SQLException if something wrong happens | [
"user",
"translation"
] | train | https://github.com/pgjdbc/pgjdbc/blob/95ba7b261e39754674c5817695ae5ebf9a341fae/pgjdbc/src/main/java/org/postgresql/jdbc/EscapedFunctions2.java#L637-L639 |
jboss-integration/fuse-bxms-integ | switchyard/switchyard-component-common-knowledge/src/main/java/org/switchyard/component/common/knowledge/runtime/KnowledgeRuntimeManagerRegistry.java | KnowledgeRuntimeManagerRegistry.getRuntimeManager | public static final synchronized KnowledgeRuntimeManager getRuntimeManager(QName serviceDomainName, QName serviceName) {
if (serviceDomainName == null) {
serviceDomainName = ROOT_DOMAIN;
}
Map<QName, KnowledgeRuntimeManager> reg = REGISTRY.get(serviceDomainName);
return reg != null ? reg.get(serviceName) : null;
} | java | public static final synchronized KnowledgeRuntimeManager getRuntimeManager(QName serviceDomainName, QName serviceName) {
if (serviceDomainName == null) {
serviceDomainName = ROOT_DOMAIN;
}
Map<QName, KnowledgeRuntimeManager> reg = REGISTRY.get(serviceDomainName);
return reg != null ? reg.get(serviceName) : null;
} | [
"public",
"static",
"final",
"synchronized",
"KnowledgeRuntimeManager",
"getRuntimeManager",
"(",
"QName",
"serviceDomainName",
",",
"QName",
"serviceName",
")",
"{",
"if",
"(",
"serviceDomainName",
"==",
"null",
")",
"{",
"serviceDomainName",
"=",
"ROOT_DOMAIN",
";",... | Gets a runtime manager.
@param serviceDomainName the service domain name
@param serviceName the service name
@return the runtime manager | [
"Gets",
"a",
"runtime",
"manager",
"."
] | train | https://github.com/jboss-integration/fuse-bxms-integ/blob/ca5c012bf867ea15d1250f0991af3cd7e708aaaf/switchyard/switchyard-component-common-knowledge/src/main/java/org/switchyard/component/common/knowledge/runtime/KnowledgeRuntimeManagerRegistry.java#L35-L41 |
alkacon/opencms-core | src/org/opencms/file/collectors/CmsPriorityResourceCollector.java | CmsPriorityResourceCollector.allInFolderPriorityDate | protected List<CmsResource> allInFolderPriorityDate(
CmsObject cms,
String param,
boolean tree,
boolean asc,
int numResults) throws CmsException {
CmsCollectorData data = new CmsCollectorData(param);
String foldername = CmsResource.getFolderPath(data.getFileName());
CmsResourceFilter filter = CmsResourceFilter.DEFAULT.addRequireType(data.getType()).addExcludeFlags(
CmsResource.FLAG_TEMPFILE);
if (data.isExcludeTimerange() && !cms.getRequestContext().getCurrentProject().isOnlineProject()) {
// include all not yet released and expired resources in an offline project
filter = filter.addExcludeTimerange();
}
List<CmsResource> result = cms.readResources(foldername, filter, tree);
// create priority comparator to use to sort the resources
CmsPriorityDateResourceComparator comparator = new CmsPriorityDateResourceComparator(cms, asc);
Collections.sort(result, comparator);
return shrinkToFit(result, data.getCount(), numResults);
} | java | protected List<CmsResource> allInFolderPriorityDate(
CmsObject cms,
String param,
boolean tree,
boolean asc,
int numResults) throws CmsException {
CmsCollectorData data = new CmsCollectorData(param);
String foldername = CmsResource.getFolderPath(data.getFileName());
CmsResourceFilter filter = CmsResourceFilter.DEFAULT.addRequireType(data.getType()).addExcludeFlags(
CmsResource.FLAG_TEMPFILE);
if (data.isExcludeTimerange() && !cms.getRequestContext().getCurrentProject().isOnlineProject()) {
// include all not yet released and expired resources in an offline project
filter = filter.addExcludeTimerange();
}
List<CmsResource> result = cms.readResources(foldername, filter, tree);
// create priority comparator to use to sort the resources
CmsPriorityDateResourceComparator comparator = new CmsPriorityDateResourceComparator(cms, asc);
Collections.sort(result, comparator);
return shrinkToFit(result, data.getCount(), numResults);
} | [
"protected",
"List",
"<",
"CmsResource",
">",
"allInFolderPriorityDate",
"(",
"CmsObject",
"cms",
",",
"String",
"param",
",",
"boolean",
"tree",
",",
"boolean",
"asc",
",",
"int",
"numResults",
")",
"throws",
"CmsException",
"{",
"CmsCollectorData",
"data",
"="... | Returns a list of all resource in a specified folder sorted by priority, then date ascending or descending.<p>
@param cms the current OpenCms user context
@param param the folder name to use
@param tree if true, look in folder and all child folders, if false, look only in given folder
@param asc if true, the date sort order is ascending, otherwise descending
@param numResults the number of results
@return all resources in the folder matching the given criteria
@throws CmsException if something goes wrong | [
"Returns",
"a",
"list",
"of",
"all",
"resource",
"in",
"a",
"specified",
"folder",
"sorted",
"by",
"priority",
"then",
"date",
"ascending",
"or",
"descending",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/file/collectors/CmsPriorityResourceCollector.java#L224-L247 |
hawkular/hawkular-agent | hawkular-dmr-client/src/main/java/org/hawkular/dmrclient/SocketBindingJBossASClient.java | SocketBindingJBossASClient.setPortOffset | public void setPortOffset(String socketBindingGroupName, String sysPropName, int offset) throws Exception {
String offsetValue;
if (sysPropName != null) {
offsetValue = "${" + sysPropName + ":" + offset + "}";
} else {
offsetValue = String.valueOf(offset);
}
Address addr = Address.root().add(SOCKET_BINDING_GROUP, socketBindingGroupName);
ModelNode request = createWriteAttributeRequest(PORT_OFFSET, offsetValue, addr);
ModelNode results = execute(request);
if (!isSuccess(results)) {
throw new FailureException(results);
}
return; // everything is OK
} | java | public void setPortOffset(String socketBindingGroupName, String sysPropName, int offset) throws Exception {
String offsetValue;
if (sysPropName != null) {
offsetValue = "${" + sysPropName + ":" + offset + "}";
} else {
offsetValue = String.valueOf(offset);
}
Address addr = Address.root().add(SOCKET_BINDING_GROUP, socketBindingGroupName);
ModelNode request = createWriteAttributeRequest(PORT_OFFSET, offsetValue, addr);
ModelNode results = execute(request);
if (!isSuccess(results)) {
throw new FailureException(results);
}
return; // everything is OK
} | [
"public",
"void",
"setPortOffset",
"(",
"String",
"socketBindingGroupName",
",",
"String",
"sysPropName",
",",
"int",
"offset",
")",
"throws",
"Exception",
"{",
"String",
"offsetValue",
";",
"if",
"(",
"sysPropName",
"!=",
"null",
")",
"{",
"offsetValue",
"=",
... | Sets the port offset for the socket bindings found in the named socket binding group.
If sysPropName is null, this simply sets the offset explicitly to the given offset.
If sysPropName is not null, this sets the offset to the expression "${sysPropName:offset}".
You typically will want to use the standard {@link #JBOSS_SYSPROP_PORT_OFFSET} system property
name as the sysPropName to follow the normal out-of-box JBossAS configuration, though you don't have to.
@param socketBindingGroupName name of the socket binding group whose port offset is to be set
@param sysPropName the name of the system property whose value is to be the port offset
@param offset the default port offset if the sysPropName is not defined
@throws Exception any error | [
"Sets",
"the",
"port",
"offset",
"for",
"the",
"socket",
"bindings",
"found",
"in",
"the",
"named",
"socket",
"binding",
"group",
".",
"If",
"sysPropName",
"is",
"null",
"this",
"simply",
"sets",
"the",
"offset",
"explicitly",
"to",
"the",
"given",
"offset",... | train | https://github.com/hawkular/hawkular-agent/blob/a7a88fc7e4f12302e4c4306d1c91e11f81c8b811/hawkular-dmr-client/src/main/java/org/hawkular/dmrclient/SocketBindingJBossASClient.java#L185-L200 |
indeedeng/util | util-core/src/main/java/com/indeed/util/core/reference/AtomicSharedReference.java | AtomicSharedReference.mapWithCopyQuietly | public @Nullable <Z> Z mapWithCopyQuietly(Function<T, Z> function) {
final @Nullable SharedReference<T> localRef = getCopy();
try {
if (localRef == null) {
return function.apply(null);
} else {
return function.apply(localRef.get());
}
} finally {
if (localRef != null) Closeables2.closeQuietly(localRef, log);
}
} | java | public @Nullable <Z> Z mapWithCopyQuietly(Function<T, Z> function) {
final @Nullable SharedReference<T> localRef = getCopy();
try {
if (localRef == null) {
return function.apply(null);
} else {
return function.apply(localRef.get());
}
} finally {
if (localRef != null) Closeables2.closeQuietly(localRef, log);
}
} | [
"public",
"@",
"Nullable",
"<",
"Z",
">",
"Z",
"mapWithCopyQuietly",
"(",
"Function",
"<",
"T",
",",
"Z",
">",
"function",
")",
"{",
"final",
"@",
"Nullable",
"SharedReference",
"<",
"T",
">",
"localRef",
"=",
"getCopy",
"(",
")",
";",
"try",
"{",
"i... | Just like mapWithCopy() except that this silently swallows any exception
that calling close() on the copy might throw.
@param function The function to apply to the value of the local reference.
@param <Z> The type of object produced by the function.
@return The value that was produced by the supplied {@code function}. | [
"Just",
"like",
"mapWithCopy",
"()",
"except",
"that",
"this",
"silently",
"swallows",
"any",
"exception",
"that",
"calling",
"close",
"()",
"on",
"the",
"copy",
"might",
"throw",
"."
] | train | https://github.com/indeedeng/util/blob/332008426cf14b57e7fc3e817d9423e3f84fb922/util-core/src/main/java/com/indeed/util/core/reference/AtomicSharedReference.java#L170-L181 |
google/closure-compiler | src/com/google/javascript/jscomp/ChangeVerifier.java | ChangeVerifier.associateClones | private void associateClones(Node n, Node snapshot) {
// TODO(johnlenz): determine if MODULE_BODY is useful here.
if (n.isRoot() || NodeUtil.isChangeScopeRoot(n)) {
clonesByCurrent.put(n, snapshot);
}
Node child = n.getFirstChild();
Node snapshotChild = snapshot.getFirstChild();
while (child != null) {
associateClones(child, snapshotChild);
child = child.getNext();
snapshotChild = snapshotChild.getNext();
}
} | java | private void associateClones(Node n, Node snapshot) {
// TODO(johnlenz): determine if MODULE_BODY is useful here.
if (n.isRoot() || NodeUtil.isChangeScopeRoot(n)) {
clonesByCurrent.put(n, snapshot);
}
Node child = n.getFirstChild();
Node snapshotChild = snapshot.getFirstChild();
while (child != null) {
associateClones(child, snapshotChild);
child = child.getNext();
snapshotChild = snapshotChild.getNext();
}
} | [
"private",
"void",
"associateClones",
"(",
"Node",
"n",
",",
"Node",
"snapshot",
")",
"{",
"// TODO(johnlenz): determine if MODULE_BODY is useful here.",
"if",
"(",
"n",
".",
"isRoot",
"(",
")",
"||",
"NodeUtil",
".",
"isChangeScopeRoot",
"(",
"n",
")",
")",
"{"... | Given an AST and its copy, map the root node of each scope of main to the
corresponding root node of clone | [
"Given",
"an",
"AST",
"and",
"its",
"copy",
"map",
"the",
"root",
"node",
"of",
"each",
"scope",
"of",
"main",
"to",
"the",
"corresponding",
"root",
"node",
"of",
"clone"
] | train | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/ChangeVerifier.java#L62-L75 |
wildfly/wildfly-core | controller/src/main/java/org/jboss/as/controller/CapabilityRegistry.java | CapabilityRegistry.registerPossibleCapability | @Override
public void registerPossibleCapability(Capability capability, PathAddress registrationPoint) {
final CapabilityId capabilityId = new CapabilityId(capability.getName(), CapabilityScope.GLOBAL);
RegistrationPoint point = new RegistrationPoint(registrationPoint, null);
CapabilityRegistration<?> capabilityRegistration = new CapabilityRegistration<>(capability, CapabilityScope.GLOBAL, point);
writeLock.lock();
try {
possibleCapabilities.computeIfPresent(capabilityId, (capabilityId1, currentRegistration) -> {
RegistrationPoint rp = capabilityRegistration.getOldestRegistrationPoint();
// The actual capability must be the same, and we must not already have a registration
// from this resource
if (!Objects.equals(capabilityRegistration.getCapability(), currentRegistration.getCapability())
|| !currentRegistration.addRegistrationPoint(rp)) {
throw ControllerLogger.MGMT_OP_LOGGER.capabilityAlreadyRegisteredInContext(capabilityId.getName(),
capabilityId.getScope().getName());
}
return currentRegistration;
});
possibleCapabilities.putIfAbsent(capabilityId, capabilityRegistration);
modified = true;
} finally {
writeLock.unlock();
}
} | java | @Override
public void registerPossibleCapability(Capability capability, PathAddress registrationPoint) {
final CapabilityId capabilityId = new CapabilityId(capability.getName(), CapabilityScope.GLOBAL);
RegistrationPoint point = new RegistrationPoint(registrationPoint, null);
CapabilityRegistration<?> capabilityRegistration = new CapabilityRegistration<>(capability, CapabilityScope.GLOBAL, point);
writeLock.lock();
try {
possibleCapabilities.computeIfPresent(capabilityId, (capabilityId1, currentRegistration) -> {
RegistrationPoint rp = capabilityRegistration.getOldestRegistrationPoint();
// The actual capability must be the same, and we must not already have a registration
// from this resource
if (!Objects.equals(capabilityRegistration.getCapability(), currentRegistration.getCapability())
|| !currentRegistration.addRegistrationPoint(rp)) {
throw ControllerLogger.MGMT_OP_LOGGER.capabilityAlreadyRegisteredInContext(capabilityId.getName(),
capabilityId.getScope().getName());
}
return currentRegistration;
});
possibleCapabilities.putIfAbsent(capabilityId, capabilityRegistration);
modified = true;
} finally {
writeLock.unlock();
}
} | [
"@",
"Override",
"public",
"void",
"registerPossibleCapability",
"(",
"Capability",
"capability",
",",
"PathAddress",
"registrationPoint",
")",
"{",
"final",
"CapabilityId",
"capabilityId",
"=",
"new",
"CapabilityId",
"(",
"capability",
".",
"getName",
"(",
")",
","... | Registers a capability with the system. Any
{@link org.jboss.as.controller.capability.AbstractCapability#getRequirements() requirements}
associated with the capability will be recorded as requirements.
@param capability the capability. Cannot be {@code null} | [
"Registers",
"a",
"capability",
"with",
"the",
"system",
".",
"Any",
"{",
"@link",
"org",
".",
"jboss",
".",
"as",
".",
"controller",
".",
"capability",
".",
"AbstractCapability#getRequirements",
"()",
"requirements",
"}",
"associated",
"with",
"the",
"capabilit... | train | https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/controller/src/main/java/org/jboss/as/controller/CapabilityRegistry.java#L561-L584 |
erlang/otp | lib/jinterface/java_src/com/ericsson/otp/erlang/OtpInputStream.java | OtpInputStream.read_string | public String read_string() throws OtpErlangDecodeException {
int tag;
int len;
byte[] strbuf;
int[] intbuf;
tag = read1skip_version();
switch (tag) {
case OtpExternal.stringTag:
len = read2BE();
strbuf = new byte[len];
this.readN(strbuf);
return OtpErlangString.newString(strbuf);
case OtpExternal.nilTag:
return "";
case OtpExternal.listTag: // List when unicode +
len = read4BE();
intbuf = new int[len];
for (int i = 0; i < len; i++) {
intbuf[i] = read_int();
if (!OtpErlangString.isValidCodePoint(intbuf[i])) {
throw new OtpErlangDecodeException("Invalid CodePoint: "
+ intbuf[i]);
}
}
read_nil();
return new String(intbuf, 0, intbuf.length);
default:
throw new OtpErlangDecodeException(
"Wrong tag encountered, expected " + OtpExternal.stringTag
+ " or " + OtpExternal.listTag + ", got " + tag);
}
} | java | public String read_string() throws OtpErlangDecodeException {
int tag;
int len;
byte[] strbuf;
int[] intbuf;
tag = read1skip_version();
switch (tag) {
case OtpExternal.stringTag:
len = read2BE();
strbuf = new byte[len];
this.readN(strbuf);
return OtpErlangString.newString(strbuf);
case OtpExternal.nilTag:
return "";
case OtpExternal.listTag: // List when unicode +
len = read4BE();
intbuf = new int[len];
for (int i = 0; i < len; i++) {
intbuf[i] = read_int();
if (!OtpErlangString.isValidCodePoint(intbuf[i])) {
throw new OtpErlangDecodeException("Invalid CodePoint: "
+ intbuf[i]);
}
}
read_nil();
return new String(intbuf, 0, intbuf.length);
default:
throw new OtpErlangDecodeException(
"Wrong tag encountered, expected " + OtpExternal.stringTag
+ " or " + OtpExternal.listTag + ", got " + tag);
}
} | [
"public",
"String",
"read_string",
"(",
")",
"throws",
"OtpErlangDecodeException",
"{",
"int",
"tag",
";",
"int",
"len",
";",
"byte",
"[",
"]",
"strbuf",
";",
"int",
"[",
"]",
"intbuf",
";",
"tag",
"=",
"read1skip_version",
"(",
")",
";",
"switch",
"(",
... | Read a string from the stream.
@return the value of the string.
@exception OtpErlangDecodeException
if the next term in the stream is not a string. | [
"Read",
"a",
"string",
"from",
"the",
"stream",
"."
] | train | https://github.com/erlang/otp/blob/ac6084fd83240355f72e94adbf303e57832d1fab/lib/jinterface/java_src/com/ericsson/otp/erlang/OtpInputStream.java#L1115-L1146 |
google/j2objc | jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/util/CharsTrie.java | CharsTrie.readValue | private static int readValue(CharSequence chars, int pos, int leadUnit) {
int value;
if(leadUnit<kMinTwoUnitValueLead) {
value=leadUnit;
} else if(leadUnit<kThreeUnitValueLead) {
value=((leadUnit-kMinTwoUnitValueLead)<<16)|chars.charAt(pos);
} else {
value=(chars.charAt(pos)<<16)|chars.charAt(pos+1);
}
return value;
} | java | private static int readValue(CharSequence chars, int pos, int leadUnit) {
int value;
if(leadUnit<kMinTwoUnitValueLead) {
value=leadUnit;
} else if(leadUnit<kThreeUnitValueLead) {
value=((leadUnit-kMinTwoUnitValueLead)<<16)|chars.charAt(pos);
} else {
value=(chars.charAt(pos)<<16)|chars.charAt(pos+1);
}
return value;
} | [
"private",
"static",
"int",
"readValue",
"(",
"CharSequence",
"chars",
",",
"int",
"pos",
",",
"int",
"leadUnit",
")",
"{",
"int",
"value",
";",
"if",
"(",
"leadUnit",
"<",
"kMinTwoUnitValueLead",
")",
"{",
"value",
"=",
"leadUnit",
";",
"}",
"else",
"if... | pos is already after the leadUnit, and the lead unit has bit 15 reset. | [
"pos",
"is",
"already",
"after",
"the",
"leadUnit",
"and",
"the",
"lead",
"unit",
"has",
"bit",
"15",
"reset",
"."
] | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/util/CharsTrie.java#L627-L637 |
google/error-prone-javac | src/jdk.compiler/share/classes/com/sun/tools/javah/Gen.java | Gen.wrapWriter | protected PrintWriter wrapWriter(OutputStream o) throws Util.Exit {
try {
return new PrintWriter(new OutputStreamWriter(o, "ISO8859_1"), true);
} catch (UnsupportedEncodingException use) {
util.bug("encoding.iso8859_1.not.found");
return null; /* dead code */
}
} | java | protected PrintWriter wrapWriter(OutputStream o) throws Util.Exit {
try {
return new PrintWriter(new OutputStreamWriter(o, "ISO8859_1"), true);
} catch (UnsupportedEncodingException use) {
util.bug("encoding.iso8859_1.not.found");
return null; /* dead code */
}
} | [
"protected",
"PrintWriter",
"wrapWriter",
"(",
"OutputStream",
"o",
")",
"throws",
"Util",
".",
"Exit",
"{",
"try",
"{",
"return",
"new",
"PrintWriter",
"(",
"new",
"OutputStreamWriter",
"(",
"o",
",",
"\"ISO8859_1\"",
")",
",",
"true",
")",
";",
"}",
"cat... | We explicitly need to write ASCII files because that is what C
compilers understand. | [
"We",
"explicitly",
"need",
"to",
"write",
"ASCII",
"files",
"because",
"that",
"is",
"what",
"C",
"compilers",
"understand",
"."
] | train | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.compiler/share/classes/com/sun/tools/javah/Gen.java#L141-L148 |
michel-kraemer/citeproc-java | citeproc-java/src/main/java/de/undercouch/citeproc/CSL.java | CSL.setOutputFormat | public void setOutputFormat(String format) {
try {
runner.callMethod(engine, "setOutputFormat", format);
outputFormat = format;
} catch (ScriptRunnerException e) {
throw new IllegalArgumentException("Could not set output format", e);
}
} | java | public void setOutputFormat(String format) {
try {
runner.callMethod(engine, "setOutputFormat", format);
outputFormat = format;
} catch (ScriptRunnerException e) {
throw new IllegalArgumentException("Could not set output format", e);
}
} | [
"public",
"void",
"setOutputFormat",
"(",
"String",
"format",
")",
"{",
"try",
"{",
"runner",
".",
"callMethod",
"(",
"engine",
",",
"\"setOutputFormat\"",
",",
"format",
")",
";",
"outputFormat",
"=",
"format",
";",
"}",
"catch",
"(",
"ScriptRunnerException",... | Sets the processor's output format
@param format the format (one of <code>"html"</code>,
<code>"text"</code>, <code>"asciidoc"</code>, <code>"fo"</code>,
or <code>"rtf"</code>) | [
"Sets",
"the",
"processor",
"s",
"output",
"format"
] | train | https://github.com/michel-kraemer/citeproc-java/blob/1d5bf0e7bbb2bdc47309530babf0ecaba838bf10/citeproc-java/src/main/java/de/undercouch/citeproc/CSL.java#L564-L571 |
geomajas/geomajas-project-geometry | jts/src/main/java/org/geomajas/geometry/conversion/jts/GeometryConverterService.java | GeometryConverterService.fromJts | public static Coordinate fromJts(com.vividsolutions.jts.geom.Coordinate coordinate) throws JtsConversionException {
if (coordinate == null) {
throw new JtsConversionException("Cannot convert null argument");
}
return new Coordinate(coordinate.x, coordinate.y);
} | java | public static Coordinate fromJts(com.vividsolutions.jts.geom.Coordinate coordinate) throws JtsConversionException {
if (coordinate == null) {
throw new JtsConversionException("Cannot convert null argument");
}
return new Coordinate(coordinate.x, coordinate.y);
} | [
"public",
"static",
"Coordinate",
"fromJts",
"(",
"com",
".",
"vividsolutions",
".",
"jts",
".",
"geom",
".",
"Coordinate",
"coordinate",
")",
"throws",
"JtsConversionException",
"{",
"if",
"(",
"coordinate",
"==",
"null",
")",
"{",
"throw",
"new",
"JtsConvers... | Convert a GTS coordinate to a Geomajas coordinate.
@param coordinate jTS coordinate
@return Geomajas coordinate
@throws JtsConversionException conversion failed | [
"Convert",
"a",
"GTS",
"coordinate",
"to",
"a",
"Geomajas",
"coordinate",
"."
] | train | https://github.com/geomajas/geomajas-project-geometry/blob/09a214fede69c9c01e41630828c4abbb551a557d/jts/src/main/java/org/geomajas/geometry/conversion/jts/GeometryConverterService.java#L208-L213 |
whitesource/fs-agent | src/main/java/org/whitesource/agent/dependency/resolver/ruby/RubyDependencyResolver.java | RubyDependencyResolver.versionCompare | public static int versionCompare(String str1, String str2) {
String[] vals1 = str1.split("\\.");
String[] vals2 = str2.split("\\.");
int i = 0;
// set index to first non-equal ordinal or length of shortest version string
while (i < vals1.length && i < vals2.length && vals1[i].equals(vals2[i])) {
i++;
}
// compare first non-equal ordinal number
if (i < vals1.length && i < vals2.length) {
int diff = Integer.valueOf(vals1[i]).compareTo(Integer.valueOf(vals2[i]));
return Integer.signum(diff);
}
// the strings are equal or one string is a substring of the other
// e.g. "1.2.3" = "1.2.3" or "1.2.3" < "1.2.3.4"
return Integer.signum(vals1.length - vals2.length);
} | java | public static int versionCompare(String str1, String str2) {
String[] vals1 = str1.split("\\.");
String[] vals2 = str2.split("\\.");
int i = 0;
// set index to first non-equal ordinal or length of shortest version string
while (i < vals1.length && i < vals2.length && vals1[i].equals(vals2[i])) {
i++;
}
// compare first non-equal ordinal number
if (i < vals1.length && i < vals2.length) {
int diff = Integer.valueOf(vals1[i]).compareTo(Integer.valueOf(vals2[i]));
return Integer.signum(diff);
}
// the strings are equal or one string is a substring of the other
// e.g. "1.2.3" = "1.2.3" or "1.2.3" < "1.2.3.4"
return Integer.signum(vals1.length - vals2.length);
} | [
"public",
"static",
"int",
"versionCompare",
"(",
"String",
"str1",
",",
"String",
"str2",
")",
"{",
"String",
"[",
"]",
"vals1",
"=",
"str1",
".",
"split",
"(",
"\"\\\\.\"",
")",
";",
"String",
"[",
"]",
"vals2",
"=",
"str2",
".",
"split",
"(",
"\"\... | /*
The result is a negative integer if str1 is _numerically_ less than str2.
The result is a positive integer if str1 is _numerically_ greater than str2.
The result is zero if the strings are _numerically_ equal. | [
"/",
"*",
"The",
"result",
"is",
"a",
"negative",
"integer",
"if",
"str1",
"is",
"_numerically_",
"less",
"than",
"str2",
".",
"The",
"result",
"is",
"a",
"positive",
"integer",
"if",
"str1",
"is",
"_numerically_",
"greater",
"than",
"str2",
".",
"The",
... | train | https://github.com/whitesource/fs-agent/blob/d6ee4842c4f08f4aeda7eb2307b24c49b6bed0e1/src/main/java/org/whitesource/agent/dependency/resolver/ruby/RubyDependencyResolver.java#L507-L523 |
stephenc/simple-java-mail | src/main/java/org/codemonkey/simplejavamail/Mailer.java | Mailer.setEmbeddedImages | private void setEmbeddedImages(final Email email, final MimeMultipart multipartRelated)
throws MessagingException {
for (final AttachmentResource embeddedImage : email.getEmbeddedImages()) {
multipartRelated.addBodyPart(getBodyPartFromDatasource(embeddedImage, Part.INLINE));
}
} | java | private void setEmbeddedImages(final Email email, final MimeMultipart multipartRelated)
throws MessagingException {
for (final AttachmentResource embeddedImage : email.getEmbeddedImages()) {
multipartRelated.addBodyPart(getBodyPartFromDatasource(embeddedImage, Part.INLINE));
}
} | [
"private",
"void",
"setEmbeddedImages",
"(",
"final",
"Email",
"email",
",",
"final",
"MimeMultipart",
"multipartRelated",
")",
"throws",
"MessagingException",
"{",
"for",
"(",
"final",
"AttachmentResource",
"embeddedImage",
":",
"email",
".",
"getEmbeddedImages",
"("... | Fills the {@link Message} instance with the embedded images from the {@link Email}.
@param email The message in which the embedded images are defined.
@param multipartRelated The branch in the email structure in which we'll stuff the embedded images.
@throws MessagingException See {@link MimeMultipart#addBodyPart(BodyPart)} and
{@link #getBodyPartFromDatasource(AttachmentResource, String)} | [
"Fills",
"the",
"{",
"@link",
"Message",
"}",
"instance",
"with",
"the",
"embedded",
"images",
"from",
"the",
"{",
"@link",
"Email",
"}",
"."
] | train | https://github.com/stephenc/simple-java-mail/blob/8c5897e6bbc23c11e7c7eb5064f407625c653923/src/main/java/org/codemonkey/simplejavamail/Mailer.java#L344-L349 |
lessthanoptimal/ejml | main/ejml-dsparse/src/org/ejml/sparse/csc/RandomMatrices_DSCC.java | RandomMatrices_DSCC.triangle | public static DMatrixSparseCSC triangle( boolean upper , int N , double minFill , double maxFill , Random rand ) {
int nz = (int)(((N-1)*(N-1)/2)*(rand.nextDouble()*(maxFill-minFill)+minFill))+N;
if( upper ) {
return triangleUpper(N,0,nz,-1,1,rand);
} else {
return triangleLower(N,0,nz,-1,1,rand);
}
} | java | public static DMatrixSparseCSC triangle( boolean upper , int N , double minFill , double maxFill , Random rand ) {
int nz = (int)(((N-1)*(N-1)/2)*(rand.nextDouble()*(maxFill-minFill)+minFill))+N;
if( upper ) {
return triangleUpper(N,0,nz,-1,1,rand);
} else {
return triangleLower(N,0,nz,-1,1,rand);
}
} | [
"public",
"static",
"DMatrixSparseCSC",
"triangle",
"(",
"boolean",
"upper",
",",
"int",
"N",
",",
"double",
"minFill",
",",
"double",
"maxFill",
",",
"Random",
"rand",
")",
"{",
"int",
"nz",
"=",
"(",
"int",
")",
"(",
"(",
"(",
"N",
"-",
"1",
")",
... | Creates a triangular matrix where the amount of fill is randomly selected too.
@param upper true for upper triangular and false for lower
@param N number of rows and columns
er * @param minFill minimum fill fraction
@param maxFill maximum fill fraction
@param rand random number generator
@return Random matrix | [
"Creates",
"a",
"triangular",
"matrix",
"where",
"the",
"amount",
"of",
"fill",
"is",
"randomly",
"selected",
"too",
"."
] | train | https://github.com/lessthanoptimal/ejml/blob/1444680cc487af5e866730e62f48f5f9636850d9/main/ejml-dsparse/src/org/ejml/sparse/csc/RandomMatrices_DSCC.java#L236-L244 |
UrielCh/ovh-java-sdk | ovh-java-sdk-cloud/src/main/java/net/minidev/ovh/api/ApiOvhCloud.java | ApiOvhCloud.project_serviceName_acl_accountId_GET | public OvhAcl project_serviceName_acl_accountId_GET(String serviceName, String accountId) throws IOException {
String qPath = "/cloud/project/{serviceName}/acl/{accountId}";
StringBuilder sb = path(qPath, serviceName, accountId);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, OvhAcl.class);
} | java | public OvhAcl project_serviceName_acl_accountId_GET(String serviceName, String accountId) throws IOException {
String qPath = "/cloud/project/{serviceName}/acl/{accountId}";
StringBuilder sb = path(qPath, serviceName, accountId);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, OvhAcl.class);
} | [
"public",
"OvhAcl",
"project_serviceName_acl_accountId_GET",
"(",
"String",
"serviceName",
",",
"String",
"accountId",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/cloud/project/{serviceName}/acl/{accountId}\"",
";",
"StringBuilder",
"sb",
"=",
"path",
"... | Get this object properties
REST: GET /cloud/project/{serviceName}/acl/{accountId}
@param serviceName [required] The project id
@param accountId [required] OVH customer unique identifier | [
"Get",
"this",
"object",
"properties"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-cloud/src/main/java/net/minidev/ovh/api/ApiOvhCloud.java#L320-L325 |
glookast/commons-timecode | src/main/java/com/glookast/commons/timecode/Timecode.java | Timecode.valueOf | public static Timecode valueOf(String timecode, int timecodeBase) throws IllegalArgumentException
{
return valueOf(timecode, timecodeBase, StringType.NORMAL);
} | java | public static Timecode valueOf(String timecode, int timecodeBase) throws IllegalArgumentException
{
return valueOf(timecode, timecodeBase, StringType.NORMAL);
} | [
"public",
"static",
"Timecode",
"valueOf",
"(",
"String",
"timecode",
",",
"int",
"timecodeBase",
")",
"throws",
"IllegalArgumentException",
"{",
"return",
"valueOf",
"(",
"timecode",
",",
"timecodeBase",
",",
"StringType",
".",
"NORMAL",
")",
";",
"}"
] | Returns a Timecode instance for given timecode string and timecode base. Acceptable inputs are
the normal representation HH:MM:SS:FF for non drop frame and HH:MM:SS:FF for drop frame
@param timecode
@param timecodeBase
@return the timecode
@throws IllegalArgumentException | [
"Returns",
"a",
"Timecode",
"instance",
"for",
"given",
"timecode",
"string",
"and",
"timecode",
"base",
".",
"Acceptable",
"inputs",
"are",
"the",
"normal",
"representation",
"HH",
":",
"MM",
":",
"SS",
":",
"FF",
"for",
"non",
"drop",
"frame",
"and",
"HH... | train | https://github.com/glookast/commons-timecode/blob/ec2f682a51d1cc435d0b42d80de48ff15adb4ee8/src/main/java/com/glookast/commons/timecode/Timecode.java#L97-L100 |
fozziethebeat/S-Space | src/main/java/edu/ucla/sspace/index/RandomIndexVectorGenerator.java | RandomIndexVectorGenerator.generate | public TernaryVector generate() {
HashSet<Integer> pos = new HashSet<Integer>();
HashSet<Integer> neg = new HashSet<Integer>();
// Randomly decide how many bits to set in the index vector based on the
// variance.
int bitsToSet = numVectorValues +
(int)(RANDOM.nextDouble() * variance *
((RANDOM.nextDouble() > .5) ? 1 : -1));
for (int i = 0; i < bitsToSet; ++i) {
boolean picked = false;
// loop to ensure we actually pick the full number of bits
while (!picked) {
// pick some random index
int index = RANDOM.nextInt(indexVectorLength);
// check that we haven't already added this index
if (pos.contains(index) || neg.contains(index))
continue;
// decide positive or negative
((RANDOM.nextDouble() > .5) ? pos : neg).add(index);
picked = true;
}
}
int[] positive = new int[pos.size()];
int[] negative = new int[neg.size()];
Iterator<Integer> it = pos.iterator();
for (int i = 0; i < positive.length; ++i)
positive[i] = it.next();
it = neg.iterator();
for (int i = 0; i < negative.length; ++i)
negative[i] = it.next();
// sort so we can use a binary search in getValue()
Arrays.sort(positive);
Arrays.sort(negative);
return new TernaryVector(indexVectorLength, positive, negative);
} | java | public TernaryVector generate() {
HashSet<Integer> pos = new HashSet<Integer>();
HashSet<Integer> neg = new HashSet<Integer>();
// Randomly decide how many bits to set in the index vector based on the
// variance.
int bitsToSet = numVectorValues +
(int)(RANDOM.nextDouble() * variance *
((RANDOM.nextDouble() > .5) ? 1 : -1));
for (int i = 0; i < bitsToSet; ++i) {
boolean picked = false;
// loop to ensure we actually pick the full number of bits
while (!picked) {
// pick some random index
int index = RANDOM.nextInt(indexVectorLength);
// check that we haven't already added this index
if (pos.contains(index) || neg.contains(index))
continue;
// decide positive or negative
((RANDOM.nextDouble() > .5) ? pos : neg).add(index);
picked = true;
}
}
int[] positive = new int[pos.size()];
int[] negative = new int[neg.size()];
Iterator<Integer> it = pos.iterator();
for (int i = 0; i < positive.length; ++i)
positive[i] = it.next();
it = neg.iterator();
for (int i = 0; i < negative.length; ++i)
negative[i] = it.next();
// sort so we can use a binary search in getValue()
Arrays.sort(positive);
Arrays.sort(negative);
return new TernaryVector(indexVectorLength, positive, negative);
} | [
"public",
"TernaryVector",
"generate",
"(",
")",
"{",
"HashSet",
"<",
"Integer",
">",
"pos",
"=",
"new",
"HashSet",
"<",
"Integer",
">",
"(",
")",
";",
"HashSet",
"<",
"Integer",
">",
"neg",
"=",
"new",
"HashSet",
"<",
"Integer",
">",
"(",
")",
";",
... | Creates an {@code TernaryVector} with the provided length.
@param length the length of the index vector
@return an index vector | [
"Creates",
"an",
"{",
"@code",
"TernaryVector",
"}",
"with",
"the",
"provided",
"length",
"."
] | train | https://github.com/fozziethebeat/S-Space/blob/a608102737dfd3d59038a9ead33fe60356bc6029/src/main/java/edu/ucla/sspace/index/RandomIndexVectorGenerator.java#L170-L212 |
bazaarvoice/emodb | sor/src/main/java/com/bazaarvoice/emodb/sor/db/astyanax/CqlDataReaderDAO.java | CqlDataReaderDAO.deltaQuery | private Iterator<Iterable<Row>> deltaQuery(DeltaPlacement placement, Statement statement, boolean singleRow,
String errorContext, Object... errorContextArgs) {
return doDeltaQuery(placement, statement, singleRow, false, errorContext, errorContextArgs);
} | java | private Iterator<Iterable<Row>> deltaQuery(DeltaPlacement placement, Statement statement, boolean singleRow,
String errorContext, Object... errorContextArgs) {
return doDeltaQuery(placement, statement, singleRow, false, errorContext, errorContextArgs);
} | [
"private",
"Iterator",
"<",
"Iterable",
"<",
"Row",
">",
">",
"deltaQuery",
"(",
"DeltaPlacement",
"placement",
",",
"Statement",
"statement",
",",
"boolean",
"singleRow",
",",
"String",
"errorContext",
",",
"Object",
"...",
"errorContextArgs",
")",
"{",
"return... | Synchronously executes the provided statement. The statement must query the delta table as returned from
{@link com.bazaarvoice.emodb.sor.db.astyanax.DeltaPlacement#getDeltaTableDDL()} | [
"Synchronously",
"executes",
"the",
"provided",
"statement",
".",
"The",
"statement",
"must",
"query",
"the",
"delta",
"table",
"as",
"returned",
"from",
"{"
] | train | https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/sor/src/main/java/com/bazaarvoice/emodb/sor/db/astyanax/CqlDataReaderDAO.java#L233-L236 |
tvesalainen/lpg | src/main/java/org/vesalainen/grammar/Grammar.java | Grammar.addRule | protected void addRule(String reducerString, String nonterminal, String document, String... rhs)
{
ExecutableElement reducer = null;
if (reducerString != null && !reducerString.isEmpty())
{
reducer = El.getExecutableElement(reducerString);
if (reducer == null)
{
throw new IllegalArgumentException(reducerString+" method not found");
}
}
addRule(reducer, nonterminal, document, false, parseRhs(rhs));
} | java | protected void addRule(String reducerString, String nonterminal, String document, String... rhs)
{
ExecutableElement reducer = null;
if (reducerString != null && !reducerString.isEmpty())
{
reducer = El.getExecutableElement(reducerString);
if (reducer == null)
{
throw new IllegalArgumentException(reducerString+" method not found");
}
}
addRule(reducer, nonterminal, document, false, parseRhs(rhs));
} | [
"protected",
"void",
"addRule",
"(",
"String",
"reducerString",
",",
"String",
"nonterminal",
",",
"String",
"document",
",",
"String",
"...",
"rhs",
")",
"{",
"ExecutableElement",
"reducer",
"=",
"null",
";",
"if",
"(",
"reducerString",
"!=",
"null",
"&&",
... | Adds new rule if the same rule doesn't exist already.
@param nonterminal Left hand side of the rule.
@param rhs Strings in BnfGrammarFactory format.
@see BnfGrammarFactory | [
"Adds",
"new",
"rule",
"if",
"the",
"same",
"rule",
"doesn",
"t",
"exist",
"already",
"."
] | train | https://github.com/tvesalainen/lpg/blob/0917b8d295e9772b9f8a0affc258a08530cd567a/src/main/java/org/vesalainen/grammar/Grammar.java#L231-L243 |
Ordinastie/MalisisCore | src/main/java/net/malisis/core/renderer/font/StringWalker.java | StringWalker.checkFormatting | protected void checkFormatting()
{
//previous character was formatting, keep format field set
if (FontOptions.getFormatting(currentText, charIndex - 1) != null)
return;
format = FontOptions.getFormatting(currentText, charIndex);
if (format == null)
return;
if (applyStyles)
applyStyle(format);
if (skipChars && !litteral)
{
globalIndex += 2;
charIndex += 2;
checkFormatting();
}
} | java | protected void checkFormatting()
{
//previous character was formatting, keep format field set
if (FontOptions.getFormatting(currentText, charIndex - 1) != null)
return;
format = FontOptions.getFormatting(currentText, charIndex);
if (format == null)
return;
if (applyStyles)
applyStyle(format);
if (skipChars && !litteral)
{
globalIndex += 2;
charIndex += 2;
checkFormatting();
}
} | [
"protected",
"void",
"checkFormatting",
"(",
")",
"{",
"//previous character was formatting, keep format field set",
"if",
"(",
"FontOptions",
".",
"getFormatting",
"(",
"currentText",
",",
"charIndex",
"-",
"1",
")",
"!=",
"null",
")",
"return",
";",
"format",
"=",... | Checks if there is {@link TextFormatting} at the current index and applies the corresponding style.<br>
Advances the index by 2. | [
"Checks",
"if",
"there",
"is",
"{"
] | train | https://github.com/Ordinastie/MalisisCore/blob/4f8e1fa462d5c372fc23414482ba9f429881cc54/src/main/java/net/malisis/core/renderer/font/StringWalker.java#L220-L238 |
liyiorg/weixin-popular | src/main/java/weixin/popular/api/ComponentAPI.java | ComponentAPI.api_component_token | public static ComponentAccessToken api_component_token(String component_appid, String component_appsecret, String component_verify_ticket) {
String postJsonData = String.format("{\"component_appid\":\"%1$s\" ,\"component_appsecret\": \"%2$s\",\"component_verify_ticket\": \"%3$s\"}",
component_appid,
component_appsecret,
component_verify_ticket);
HttpUriRequest httpUriRequest = RequestBuilder.post()
.setHeader(jsonHeader)
.setUri(BASE_URI + "/cgi-bin/component/api_component_token")
.setEntity(new StringEntity(postJsonData, Charset.forName("utf-8")))
.build();
return LocalHttpClient.executeJsonResult(httpUriRequest, ComponentAccessToken.class);
} | java | public static ComponentAccessToken api_component_token(String component_appid, String component_appsecret, String component_verify_ticket) {
String postJsonData = String.format("{\"component_appid\":\"%1$s\" ,\"component_appsecret\": \"%2$s\",\"component_verify_ticket\": \"%3$s\"}",
component_appid,
component_appsecret,
component_verify_ticket);
HttpUriRequest httpUriRequest = RequestBuilder.post()
.setHeader(jsonHeader)
.setUri(BASE_URI + "/cgi-bin/component/api_component_token")
.setEntity(new StringEntity(postJsonData, Charset.forName("utf-8")))
.build();
return LocalHttpClient.executeJsonResult(httpUriRequest, ComponentAccessToken.class);
} | [
"public",
"static",
"ComponentAccessToken",
"api_component_token",
"(",
"String",
"component_appid",
",",
"String",
"component_appsecret",
",",
"String",
"component_verify_ticket",
")",
"{",
"String",
"postJsonData",
"=",
"String",
".",
"format",
"(",
"\"{\\\"component_ap... | 获取公众号第三方平台access_token
@param component_appid 公众号第三方平台appid
@param component_appsecret 公众号第三方平台appsecret
@param component_verify_ticket 微信后台推送的ticket,此ticket会定时推送,具体请见本页末尾的推送说明
@return 公众号第三方平台access_token | [
"获取公众号第三方平台access_token"
] | train | https://github.com/liyiorg/weixin-popular/blob/c64255292d41463bdb671938feaabf42a335d82c/src/main/java/weixin/popular/api/ComponentAPI.java#L108-L119 |
datumbox/datumbox-framework | datumbox-framework-core/src/main/java/com/datumbox/framework/core/mathematics/regularization/ElasticNetRegularizer.java | ElasticNetRegularizer.estimatePenalty | public static <K> double estimatePenalty(double l1, double l2, Map<K, Double> weights) {
double penalty = 0.0;
penalty += L2Regularizer.estimatePenalty(l2, weights);
penalty += L1Regularizer.estimatePenalty(l1, weights);
return penalty;
} | java | public static <K> double estimatePenalty(double l1, double l2, Map<K, Double> weights) {
double penalty = 0.0;
penalty += L2Regularizer.estimatePenalty(l2, weights);
penalty += L1Regularizer.estimatePenalty(l1, weights);
return penalty;
} | [
"public",
"static",
"<",
"K",
">",
"double",
"estimatePenalty",
"(",
"double",
"l1",
",",
"double",
"l2",
",",
"Map",
"<",
"K",
",",
"Double",
">",
"weights",
")",
"{",
"double",
"penalty",
"=",
"0.0",
";",
"penalty",
"+=",
"L2Regularizer",
".",
"estim... | Estimates the penalty by adding the ElasticNet regularization.
@param l1
@param l2
@param weights
@param <K>
@return | [
"Estimates",
"the",
"penalty",
"by",
"adding",
"the",
"ElasticNet",
"regularization",
"."
] | train | https://github.com/datumbox/datumbox-framework/blob/909dff0476e80834f05ecdde0624dd2390e9b0ca/datumbox-framework-core/src/main/java/com/datumbox/framework/core/mathematics/regularization/ElasticNetRegularizer.java#L54-L59 |
aws/aws-sdk-java | aws-java-sdk-dynamodb/src/main/java/com/amazonaws/services/dynamodbv2/document/utils/ValueMap.java | ValueMap.withJSON | public ValueMap withJSON(String key, String jsonValue) {
super.put(key, valueConformer.transform(Jackson.fromJsonString(jsonValue, Object.class)));
return this;
} | java | public ValueMap withJSON(String key, String jsonValue) {
super.put(key, valueConformer.transform(Jackson.fromJsonString(jsonValue, Object.class)));
return this;
} | [
"public",
"ValueMap",
"withJSON",
"(",
"String",
"key",
",",
"String",
"jsonValue",
")",
"{",
"super",
".",
"put",
"(",
"key",
",",
"valueConformer",
".",
"transform",
"(",
"Jackson",
".",
"fromJsonString",
"(",
"jsonValue",
",",
"Object",
".",
"class",
")... | Sets the value of the specified key to an object represented by the JSON
structure passed. | [
"Sets",
"the",
"value",
"of",
"the",
"specified",
"key",
"to",
"an",
"object",
"represented",
"by",
"the",
"JSON",
"structure",
"passed",
"."
] | train | https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-dynamodb/src/main/java/com/amazonaws/services/dynamodbv2/document/utils/ValueMap.java#L203-L206 |
eclipse/xtext-lib | org.eclipse.xtext.xbase.lib/src/org/eclipse/xtext/xbase/lib/FunctionExtensions.java | FunctionExtensions.andThen | public static Procedure0 andThen(final Procedure0 before, final Procedure0 after) {
if (after == null)
throw new NullPointerException("after");
if (before == null)
throw new NullPointerException("before");
return new Procedures.Procedure0() {
@Override
public void apply() {
before.apply();
after.apply();
}
};
} | java | public static Procedure0 andThen(final Procedure0 before, final Procedure0 after) {
if (after == null)
throw new NullPointerException("after");
if (before == null)
throw new NullPointerException("before");
return new Procedures.Procedure0() {
@Override
public void apply() {
before.apply();
after.apply();
}
};
} | [
"public",
"static",
"Procedure0",
"andThen",
"(",
"final",
"Procedure0",
"before",
",",
"final",
"Procedure0",
"after",
")",
"{",
"if",
"(",
"after",
"==",
"null",
")",
"throw",
"new",
"NullPointerException",
"(",
"\"after\"",
")",
";",
"if",
"(",
"before",
... | Returns a composed {@code Procedure1} that performs, in sequence, the {@code before}
operation followed by the {@code after} operation. If performing either
operation throws an exception, it is relayed to the caller of the
composed operation. If performing the {@code before} operation throws an exception,
the {@code after} operation will not be performed.
@param before the operation to perform first
@param after the operation to perform afterwards
@return a composed {@code Procedure1} that performs in sequence the {@code before}
operation followed by the {@code after} operation
@throws NullPointerException if {@code before} or {@code after} is null
@since 2.9 | [
"Returns",
"a",
"composed",
"{",
"@code",
"Procedure1",
"}",
"that",
"performs",
"in",
"sequence",
"the",
"{",
"@code",
"before",
"}",
"operation",
"followed",
"by",
"the",
"{",
"@code",
"after",
"}",
"operation",
".",
"If",
"performing",
"either",
"operatio... | train | https://github.com/eclipse/xtext-lib/blob/7063572e1f1bd713a3aa53bdf3a8dc60e25c169a/org.eclipse.xtext.xbase.lib/src/org/eclipse/xtext/xbase/lib/FunctionExtensions.java#L294-L306 |
morimekta/utils | diff-util/src/main/java/net/morimekta/diff/Bisect.java | Bisect.fromDelta | public static Bisect fromDelta(String text1, String delta)
throws IllegalArgumentException {
return new Bisect(changesFromDelta(text1, delta));
} | java | public static Bisect fromDelta(String text1, String delta)
throws IllegalArgumentException {
return new Bisect(changesFromDelta(text1, delta));
} | [
"public",
"static",
"Bisect",
"fromDelta",
"(",
"String",
"text1",
",",
"String",
"delta",
")",
"throws",
"IllegalArgumentException",
"{",
"return",
"new",
"Bisect",
"(",
"changesFromDelta",
"(",
"text1",
",",
"delta",
")",
")",
";",
"}"
] | Given the original text1, and an encoded string which describes the
operations required to transform text1 into text2, compute the full diff.
@param text1 Source string for the diff.
@param delta Delta text.
@return Array of DiffBase objects or null if invalid.
@throws IllegalArgumentException If invalid input. | [
"Given",
"the",
"original",
"text1",
"and",
"an",
"encoded",
"string",
"which",
"describes",
"the",
"operations",
"required",
"to",
"transform",
"text1",
"into",
"text2",
"compute",
"the",
"full",
"diff",
"."
] | train | https://github.com/morimekta/utils/blob/dc987485902f1a7d58169c89c61db97425a6226d/diff-util/src/main/java/net/morimekta/diff/Bisect.java#L79-L82 |
zackpollard/JavaTelegramBot-API | core/src/main/java/pro/zackpollard/telegrambot/api/TelegramBot.java | TelegramBot.editMessageReplyMarkup | public Message editMessageReplyMarkup(String chatId, Long messageId, InlineReplyMarkup inlineReplyMarkup) {
if(inlineReplyMarkup != null && chatId != null && messageId != null) {
JSONObject jsonResponse = this.editMessageReplyMarkup(chatId, messageId, null, inlineReplyMarkup);
if(jsonResponse != null) {
return MessageImpl.createMessage(jsonResponse.getJSONObject("result"), this);
}
}
return null;
} | java | public Message editMessageReplyMarkup(String chatId, Long messageId, InlineReplyMarkup inlineReplyMarkup) {
if(inlineReplyMarkup != null && chatId != null && messageId != null) {
JSONObject jsonResponse = this.editMessageReplyMarkup(chatId, messageId, null, inlineReplyMarkup);
if(jsonResponse != null) {
return MessageImpl.createMessage(jsonResponse.getJSONObject("result"), this);
}
}
return null;
} | [
"public",
"Message",
"editMessageReplyMarkup",
"(",
"String",
"chatId",
",",
"Long",
"messageId",
",",
"InlineReplyMarkup",
"inlineReplyMarkup",
")",
"{",
"if",
"(",
"inlineReplyMarkup",
"!=",
"null",
"&&",
"chatId",
"!=",
"null",
"&&",
"messageId",
"!=",
"null",
... | This allows you to edit the InlineReplyMarkup of any message that you have sent previously.
@param chatId The chat ID of the chat containing the message you want to edit
@param messageId The message ID of the message you want to edit
@param inlineReplyMarkup Any InlineReplyMarkup object you want to edit into the message
@return A new Message object representing the edited message | [
"This",
"allows",
"you",
"to",
"edit",
"the",
"InlineReplyMarkup",
"of",
"any",
"message",
"that",
"you",
"have",
"sent",
"previously",
"."
] | train | https://github.com/zackpollard/JavaTelegramBot-API/blob/9d100f351824042ca5fc0ea735d1fa376a13e81d/core/src/main/java/pro/zackpollard/telegrambot/api/TelegramBot.java#L858-L871 |
alkacon/opencms-core | src/org/opencms/main/CmsShellCommands.java | CmsShellCommands.importModuleFromDefault | public void importModuleFromDefault(String importFile) throws Exception {
String exportPath = OpenCms.getSystemInfo().getPackagesRfsPath();
String fileName = OpenCms.getSystemInfo().getAbsoluteRfsPathRelativeToWebInf(
exportPath + CmsSystemInfo.FOLDER_MODULES + importFile);
CmsImportParameters params = new CmsImportParameters(fileName, "/", true);
OpenCms.getImportExportManager().importData(
m_cms,
new CmsShellReport(m_cms.getRequestContext().getLocale()),
params);
} | java | public void importModuleFromDefault(String importFile) throws Exception {
String exportPath = OpenCms.getSystemInfo().getPackagesRfsPath();
String fileName = OpenCms.getSystemInfo().getAbsoluteRfsPathRelativeToWebInf(
exportPath + CmsSystemInfo.FOLDER_MODULES + importFile);
CmsImportParameters params = new CmsImportParameters(fileName, "/", true);
OpenCms.getImportExportManager().importData(
m_cms,
new CmsShellReport(m_cms.getRequestContext().getLocale()),
params);
} | [
"public",
"void",
"importModuleFromDefault",
"(",
"String",
"importFile",
")",
"throws",
"Exception",
"{",
"String",
"exportPath",
"=",
"OpenCms",
".",
"getSystemInfo",
"(",
")",
".",
"getPackagesRfsPath",
"(",
")",
";",
"String",
"fileName",
"=",
"OpenCms",
"."... | Imports a module (zipfile) from the default module directory,
creating a temporary project for this.<p>
@param importFile the name of the import module located in the default module directory
@throws Exception if something goes wrong
@see org.opencms.importexport.CmsImportExportManager#importData(CmsObject, I_CmsReport, CmsImportParameters) | [
"Imports",
"a",
"module",
"(",
"zipfile",
")",
"from",
"the",
"default",
"module",
"directory",
"creating",
"a",
"temporary",
"project",
"for",
"this",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/main/CmsShellCommands.java#L882-L894 |
ironjacamar/ironjacamar | codegenerator/src/main/java/org/ironjacamar/codegenerator/code/McfCodeGen.java | McfCodeGen.writeManagedConnection | private void writeManagedConnection(Definition def, Writer out, int indent) throws IOException
{
writeWithIndent(out, indent, "/**\n");
writeWithIndent(out, indent, " * Creates a new physical connection to the underlying EIS resource manager.\n");
writeWithIndent(out, indent, " *\n");
writeWithIndent(out, indent, " * @param subject Caller's security information\n");
writeWithIndent(out, indent,
" * @param cxRequestInfo Additional resource adapter " + "specific connection request information\n");
writeWithIndent(out, indent, " * @throws ResourceException generic exception\n");
writeWithIndent(out, indent, " * @return ManagedConnection instance \n");
writeWithIndent(out, indent, " */\n");
writeWithIndent(out, indent, "public ManagedConnection createManagedConnection(Subject subject,\n");
writeIndent(out, indent + 2);
out.write("ConnectionRequestInfo cxRequestInfo) throws ResourceException");
writeLeftCurlyBracket(out, indent);
writeLogging(def, out, indent + 1, "trace", "createManagedConnection", "subject", "cxRequestInfo");
writeWithIndent(out, indent + 1, "return new " + def.getMcfDefs().get(getNumOfMcf()).getMcClass() + "(this);");
writeRightCurlyBracket(out, indent);
writeEol(out);
writeWithIndent(out, indent, "/**\n");
writeWithIndent(out, indent, " * Returns a matched connection from the candidate set of connections. \n");
writeWithIndent(out, indent, " *\n");
writeWithIndent(out, indent, " * @param connectionSet Candidate connection set\n");
writeWithIndent(out, indent, " * @param subject Caller's security information\n");
writeWithIndent(out, indent,
" * @param cxRequestInfo Additional resource adapter " + "specific connection request information\n");
writeWithIndent(out, indent, " * @throws ResourceException generic exception\n");
writeWithIndent(out, indent,
" * @return ManagedConnection if resource adapter finds an acceptable match otherwise null \n");
writeWithIndent(out, indent, " */\n");
writeWithIndent(out, indent, "public ManagedConnection matchManagedConnections(Set connectionSet,\n");
writeIndent(out, indent + 2);
out.write("Subject subject, ConnectionRequestInfo cxRequestInfo) throws ResourceException");
writeLeftCurlyBracket(out, indent);
writeLogging(def, out, indent + 1, "trace", "matchManagedConnections", "connectionSet", "subject",
"cxRequestInfo");
writeWithIndent(out, indent + 1, "ManagedConnection result = null;\n");
writeWithIndent(out, indent + 1, "Iterator it = connectionSet.iterator();\n");
writeWithIndent(out, indent + 1, "while (result == null && it.hasNext())");
writeLeftCurlyBracket(out, indent + 1);
writeIndent(out, indent + 2);
out.write("ManagedConnection mc = (ManagedConnection)it.next();\n");
writeIndent(out, indent + 2);
out.write("if (mc instanceof " + def.getMcfDefs().get(getNumOfMcf()).getMcClass() + ")");
writeLeftCurlyBracket(out, indent + 2);
writeIndent(out, indent + 3);
out.write("result = mc;");
writeRightCurlyBracket(out, indent + 2);
writeRightCurlyBracket(out, indent + 1);
writeWithIndent(out, indent + 1, "return result;");
writeRightCurlyBracket(out, indent);
writeEol(out);
} | java | private void writeManagedConnection(Definition def, Writer out, int indent) throws IOException
{
writeWithIndent(out, indent, "/**\n");
writeWithIndent(out, indent, " * Creates a new physical connection to the underlying EIS resource manager.\n");
writeWithIndent(out, indent, " *\n");
writeWithIndent(out, indent, " * @param subject Caller's security information\n");
writeWithIndent(out, indent,
" * @param cxRequestInfo Additional resource adapter " + "specific connection request information\n");
writeWithIndent(out, indent, " * @throws ResourceException generic exception\n");
writeWithIndent(out, indent, " * @return ManagedConnection instance \n");
writeWithIndent(out, indent, " */\n");
writeWithIndent(out, indent, "public ManagedConnection createManagedConnection(Subject subject,\n");
writeIndent(out, indent + 2);
out.write("ConnectionRequestInfo cxRequestInfo) throws ResourceException");
writeLeftCurlyBracket(out, indent);
writeLogging(def, out, indent + 1, "trace", "createManagedConnection", "subject", "cxRequestInfo");
writeWithIndent(out, indent + 1, "return new " + def.getMcfDefs().get(getNumOfMcf()).getMcClass() + "(this);");
writeRightCurlyBracket(out, indent);
writeEol(out);
writeWithIndent(out, indent, "/**\n");
writeWithIndent(out, indent, " * Returns a matched connection from the candidate set of connections. \n");
writeWithIndent(out, indent, " *\n");
writeWithIndent(out, indent, " * @param connectionSet Candidate connection set\n");
writeWithIndent(out, indent, " * @param subject Caller's security information\n");
writeWithIndent(out, indent,
" * @param cxRequestInfo Additional resource adapter " + "specific connection request information\n");
writeWithIndent(out, indent, " * @throws ResourceException generic exception\n");
writeWithIndent(out, indent,
" * @return ManagedConnection if resource adapter finds an acceptable match otherwise null \n");
writeWithIndent(out, indent, " */\n");
writeWithIndent(out, indent, "public ManagedConnection matchManagedConnections(Set connectionSet,\n");
writeIndent(out, indent + 2);
out.write("Subject subject, ConnectionRequestInfo cxRequestInfo) throws ResourceException");
writeLeftCurlyBracket(out, indent);
writeLogging(def, out, indent + 1, "trace", "matchManagedConnections", "connectionSet", "subject",
"cxRequestInfo");
writeWithIndent(out, indent + 1, "ManagedConnection result = null;\n");
writeWithIndent(out, indent + 1, "Iterator it = connectionSet.iterator();\n");
writeWithIndent(out, indent + 1, "while (result == null && it.hasNext())");
writeLeftCurlyBracket(out, indent + 1);
writeIndent(out, indent + 2);
out.write("ManagedConnection mc = (ManagedConnection)it.next();\n");
writeIndent(out, indent + 2);
out.write("if (mc instanceof " + def.getMcfDefs().get(getNumOfMcf()).getMcClass() + ")");
writeLeftCurlyBracket(out, indent + 2);
writeIndent(out, indent + 3);
out.write("result = mc;");
writeRightCurlyBracket(out, indent + 2);
writeRightCurlyBracket(out, indent + 1);
writeWithIndent(out, indent + 1, "return result;");
writeRightCurlyBracket(out, indent);
writeEol(out);
} | [
"private",
"void",
"writeManagedConnection",
"(",
"Definition",
"def",
",",
"Writer",
"out",
",",
"int",
"indent",
")",
"throws",
"IOException",
"{",
"writeWithIndent",
"(",
"out",
",",
"indent",
",",
"\"/**\\n\"",
")",
";",
"writeWithIndent",
"(",
"out",
",",... | Output ConnectionFactory method
@param def definition
@param out Writer
@param indent space number
@throws IOException ioException | [
"Output",
"ConnectionFactory",
"method"
] | train | https://github.com/ironjacamar/ironjacamar/blob/f0389ee7e62aa8b40ba09b251edad76d220ea796/codegenerator/src/main/java/org/ironjacamar/codegenerator/code/McfCodeGen.java#L246-L302 |
GwtMaterialDesign/gwt-material-addins | src/main/java/gwt/material/design/addins/client/avatar/MaterialAvatar.java | MaterialAvatar.setDimension | public void setDimension(int width, int height) {
setWidth(String.valueOf(width));
setHeight(String.valueOf(height));
reload();
} | java | public void setDimension(int width, int height) {
setWidth(String.valueOf(width));
setHeight(String.valueOf(height));
reload();
} | [
"public",
"void",
"setDimension",
"(",
"int",
"width",
",",
"int",
"height",
")",
"{",
"setWidth",
"(",
"String",
".",
"valueOf",
"(",
"width",
")",
")",
";",
"setHeight",
"(",
"String",
".",
"valueOf",
"(",
"height",
")",
")",
";",
"reload",
"(",
")... | Allowing to set the dimension of the Avatar component.
@param width - the width dimension of the avatar without any Unit suffix (e.i 100)
@param height - the height dimension of the avatar without any Unit suffix (e.i 100) | [
"Allowing",
"to",
"set",
"the",
"dimension",
"of",
"the",
"Avatar",
"component",
"."
] | train | https://github.com/GwtMaterialDesign/gwt-material-addins/blob/11aec9d92918225f70f936285d0ae94f2178c36e/src/main/java/gwt/material/design/addins/client/avatar/MaterialAvatar.java#L160-L164 |
Mozu/mozu-java | mozu-java-core/src/main/java/com/mozu/api/urls/content/documentlists/DocumentTreeUrl.java | DocumentTreeUrl.updateTreeDocumentContentUrl | public static MozuUrl updateTreeDocumentContentUrl(String documentListName, String documentName)
{
UrlFormatter formatter = new UrlFormatter("/api/content/documentlists/{documentListName}/documentTree/{documentName}/content?folderPath={folderPath}&folderId={folderId}");
formatter.formatUrl("documentListName", documentListName);
formatter.formatUrl("documentName", documentName);
return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ;
} | java | public static MozuUrl updateTreeDocumentContentUrl(String documentListName, String documentName)
{
UrlFormatter formatter = new UrlFormatter("/api/content/documentlists/{documentListName}/documentTree/{documentName}/content?folderPath={folderPath}&folderId={folderId}");
formatter.formatUrl("documentListName", documentListName);
formatter.formatUrl("documentName", documentName);
return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ;
} | [
"public",
"static",
"MozuUrl",
"updateTreeDocumentContentUrl",
"(",
"String",
"documentListName",
",",
"String",
"documentName",
")",
"{",
"UrlFormatter",
"formatter",
"=",
"new",
"UrlFormatter",
"(",
"\"/api/content/documentlists/{documentListName}/documentTree/{documentName}/co... | Get Resource Url for UpdateTreeDocumentContent
@param documentListName Name of content documentListName to delete
@param documentName The name of the document in the site.
@return String Resource Url | [
"Get",
"Resource",
"Url",
"for",
"UpdateTreeDocumentContent"
] | train | https://github.com/Mozu/mozu-java/blob/5beadde73601a859f845e3e2fc1077b39c8bea83/mozu-java-core/src/main/java/com/mozu/api/urls/content/documentlists/DocumentTreeUrl.java#L82-L88 |
FasterXML/woodstox | src/main/java/com/ctc/wstx/sr/Attribute.java | Attribute.hasQName | protected boolean hasQName(String uri, String localName)
{
if (localName != mLocalName && !localName.equals(mLocalName)) {
return false;
}
if (mNamespaceURI == uri) {
return true;
}
if (uri == null) {
return (mNamespaceURI == null) || mNamespaceURI.length() == 0;
}
return (mNamespaceURI != null && uri.equals(mNamespaceURI));
} | java | protected boolean hasQName(String uri, String localName)
{
if (localName != mLocalName && !localName.equals(mLocalName)) {
return false;
}
if (mNamespaceURI == uri) {
return true;
}
if (uri == null) {
return (mNamespaceURI == null) || mNamespaceURI.length() == 0;
}
return (mNamespaceURI != null && uri.equals(mNamespaceURI));
} | [
"protected",
"boolean",
"hasQName",
"(",
"String",
"uri",
",",
"String",
"localName",
")",
"{",
"if",
"(",
"localName",
"!=",
"mLocalName",
"&&",
"!",
"localName",
".",
"equals",
"(",
"mLocalName",
")",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
... | @param uri Namespace URI of the attribute, if any; MUST be
given as null if no namespace
@param localName Local name to match. Note: is NOT guaranteed
to have been interned
@return True if qualified name of this attribute is the same
as what arguments describe | [
"@param",
"uri",
"Namespace",
"URI",
"of",
"the",
"attribute",
"if",
"any",
";",
"MUST",
"be",
"given",
"as",
"null",
"if",
"no",
"namespace",
"@param",
"localName",
"Local",
"name",
"to",
"match",
".",
"Note",
":",
"is",
"NOT",
"guaranteed",
"to",
"have... | train | https://github.com/FasterXML/woodstox/blob/ffcaabdc06672d9564c48c25d601d029b7fd6548/src/main/java/com/ctc/wstx/sr/Attribute.java#L103-L115 |
AltBeacon/android-beacon-library | lib/src/main/java/org/altbeacon/bluetooth/BluetoothCrashResolver.java | BluetoothCrashResolver.notifyScannedDevice | @TargetApi(18)
public void notifyScannedDevice(BluetoothDevice device, BluetoothAdapter.LeScanCallback scanner) {
int oldSize, newSize;
oldSize = distinctBluetoothAddresses.size();
synchronized(distinctBluetoothAddresses) {
distinctBluetoothAddresses.add(device.getAddress());
}
newSize = distinctBluetoothAddresses.size();
if (oldSize != newSize && newSize % 100 == 0) {
LogManager.d(TAG, "Distinct Bluetooth devices seen: %s", distinctBluetoothAddresses.size());
}
if (distinctBluetoothAddresses.size() > getCrashRiskDeviceCount()) {
if (PREEMPTIVE_ACTION_ENABLED && !recoveryInProgress) {
LogManager.w(TAG, "Large number of Bluetooth devices detected: %s Proactively "
+ "attempting to clear out address list to prevent a crash",
distinctBluetoothAddresses.size());
LogManager.w(TAG, "Stopping LE Scan");
BluetoothAdapter.getDefaultAdapter().stopLeScan(scanner);
startRecovery();
processStateChange();
}
}
} | java | @TargetApi(18)
public void notifyScannedDevice(BluetoothDevice device, BluetoothAdapter.LeScanCallback scanner) {
int oldSize, newSize;
oldSize = distinctBluetoothAddresses.size();
synchronized(distinctBluetoothAddresses) {
distinctBluetoothAddresses.add(device.getAddress());
}
newSize = distinctBluetoothAddresses.size();
if (oldSize != newSize && newSize % 100 == 0) {
LogManager.d(TAG, "Distinct Bluetooth devices seen: %s", distinctBluetoothAddresses.size());
}
if (distinctBluetoothAddresses.size() > getCrashRiskDeviceCount()) {
if (PREEMPTIVE_ACTION_ENABLED && !recoveryInProgress) {
LogManager.w(TAG, "Large number of Bluetooth devices detected: %s Proactively "
+ "attempting to clear out address list to prevent a crash",
distinctBluetoothAddresses.size());
LogManager.w(TAG, "Stopping LE Scan");
BluetoothAdapter.getDefaultAdapter().stopLeScan(scanner);
startRecovery();
processStateChange();
}
}
} | [
"@",
"TargetApi",
"(",
"18",
")",
"public",
"void",
"notifyScannedDevice",
"(",
"BluetoothDevice",
"device",
",",
"BluetoothAdapter",
".",
"LeScanCallback",
"scanner",
")",
"{",
"int",
"oldSize",
",",
"newSize",
";",
"oldSize",
"=",
"distinctBluetoothAddresses",
"... | Call this method from your BluetoothAdapter.LeScanCallback method.
Doing so is optional, but if you do, this class will be able to count the number of
distinct Bluetooth devices scanned, and prevent crashes before they happen.
This works very well if the app containing this class is the only one running bluetooth
LE scans on the device, or it is constantly doing scans (e.g. is in the foreground for
extended periods of time.)
This will not work well if the application using this class is only scanning periodically
(e.g. when in the background to save battery) and another application is also scanning on
the same device, because this class will only get the counts from this application.
Future augmentation of this class may improve this by somehow centralizing the list of
unique scanned devices.
@param device | [
"Call",
"this",
"method",
"from",
"your",
"BluetoothAdapter",
".",
"LeScanCallback",
"method",
".",
"Doing",
"so",
"is",
"optional",
"but",
"if",
"you",
"do",
"this",
"class",
"will",
"be",
"able",
"to",
"count",
"the",
"number",
"of",
"distinct",
"Bluetooth... | train | https://github.com/AltBeacon/android-beacon-library/blob/f7f3a323ea7415d53e7bd695ff6a01f1501d5dc3/lib/src/main/java/org/altbeacon/bluetooth/BluetoothCrashResolver.java#L175-L200 |
Backendless/Android-SDK | src/com/backendless/utils/ReflectionUtil.java | ReflectionUtil.hasField | public static boolean hasField( Class clazz, String fieldName )
{
try
{
clazz.getDeclaredField( fieldName );
return true;
}
catch( NoSuchFieldException nfe )
{
if( clazz.getSuperclass() != null )
{
return hasField( clazz.getSuperclass(), fieldName );
}
else
{
return false;
}
}
} | java | public static boolean hasField( Class clazz, String fieldName )
{
try
{
clazz.getDeclaredField( fieldName );
return true;
}
catch( NoSuchFieldException nfe )
{
if( clazz.getSuperclass() != null )
{
return hasField( clazz.getSuperclass(), fieldName );
}
else
{
return false;
}
}
} | [
"public",
"static",
"boolean",
"hasField",
"(",
"Class",
"clazz",
",",
"String",
"fieldName",
")",
"{",
"try",
"{",
"clazz",
".",
"getDeclaredField",
"(",
"fieldName",
")",
";",
"return",
"true",
";",
"}",
"catch",
"(",
"NoSuchFieldException",
"nfe",
")",
... | Checks whether given class contains a field with given name.
Recursively checks superclasses.
@param clazz Class in which to search for a field
@param fieldName name of the field
@return {@code true} if given class or one of its superclasses contains field with given name, else {@code false} | [
"Checks",
"whether",
"given",
"class",
"contains",
"a",
"field",
"with",
"given",
"name",
".",
"Recursively",
"checks",
"superclasses",
"."
] | train | https://github.com/Backendless/Android-SDK/blob/3af1e9a378f19d890db28a833f7fc8595b924cc3/src/com/backendless/utils/ReflectionUtil.java#L142-L160 |
dbracewell/mango | src/main/java/com/davidbracewell/config/Config.java | Config.toPythonConfigParser | public static Resource toPythonConfigParser(@NonNull String sectionName, @NonNull Resource output) throws IOException {
try (BufferedWriter writer = new BufferedWriter(output.writer())) {
writer.write("[");
writer.write(sectionName);
writer.write("]\n");
for (Map.Entry<String, String> e : Sorting.sortMapEntries(getInstance().properties,
Map.Entry.comparingByKey())) {
writer.write(e.getKey());
writer.write(" : ");
writer.write(e.getValue().replaceAll("\n", "\n\t\t\t"));
writer.write("\n");
}
}
return output;
} | java | public static Resource toPythonConfigParser(@NonNull String sectionName, @NonNull Resource output) throws IOException {
try (BufferedWriter writer = new BufferedWriter(output.writer())) {
writer.write("[");
writer.write(sectionName);
writer.write("]\n");
for (Map.Entry<String, String> e : Sorting.sortMapEntries(getInstance().properties,
Map.Entry.comparingByKey())) {
writer.write(e.getKey());
writer.write(" : ");
writer.write(e.getValue().replaceAll("\n", "\n\t\t\t"));
writer.write("\n");
}
}
return output;
} | [
"public",
"static",
"Resource",
"toPythonConfigParser",
"(",
"@",
"NonNull",
"String",
"sectionName",
",",
"@",
"NonNull",
"Resource",
"output",
")",
"throws",
"IOException",
"{",
"try",
"(",
"BufferedWriter",
"writer",
"=",
"new",
"BufferedWriter",
"(",
"output",... | Converts the config into an ini format easily consumed by Python with the given section name
@param sectionName The section name to write properties under
@param output the resource to output the ini file to
@return the resource writen to
@throws IOException Something went wrong writing the config file | [
"Converts",
"the",
"config",
"into",
"an",
"ini",
"format",
"easily",
"consumed",
"by",
"Python",
"with",
"the",
"given",
"section",
"name"
] | train | https://github.com/dbracewell/mango/blob/2cec08826f1fccd658694dd03abce10fc97618ec/src/main/java/com/davidbracewell/config/Config.java#L784-L798 |
OpenLiberty/open-liberty | dev/com.ibm.ws.security.jaas.common/src/com/ibm/wsspi/security/auth/callback/WSMappingCallbackHandler.java | WSMappingCallbackHandler.handle | @Override
public void handle(Callback[] callbacks) throws UnsupportedCallbackException {
for (Callback callback : callbacks) {
if (callback instanceof WSManagedConnectionFactoryCallback) {
((WSManagedConnectionFactoryCallback) callback).setManagedConnectionFactory(managedConnectionFactory);
} else if (callback instanceof WSMappingPropertiesCallback) {
((WSMappingPropertiesCallback) callback).setProperties(properties);
} else {
// TODO: Issue a warning with translated message
// Use translated message for the the UnsupportedCallbackException
throw new UnsupportedCallbackException(callback, "Unrecognized Callback");
}
}
} | java | @Override
public void handle(Callback[] callbacks) throws UnsupportedCallbackException {
for (Callback callback : callbacks) {
if (callback instanceof WSManagedConnectionFactoryCallback) {
((WSManagedConnectionFactoryCallback) callback).setManagedConnectionFactory(managedConnectionFactory);
} else if (callback instanceof WSMappingPropertiesCallback) {
((WSMappingPropertiesCallback) callback).setProperties(properties);
} else {
// TODO: Issue a warning with translated message
// Use translated message for the the UnsupportedCallbackException
throw new UnsupportedCallbackException(callback, "Unrecognized Callback");
}
}
} | [
"@",
"Override",
"public",
"void",
"handle",
"(",
"Callback",
"[",
"]",
"callbacks",
")",
"throws",
"UnsupportedCallbackException",
"{",
"for",
"(",
"Callback",
"callback",
":",
"callbacks",
")",
"{",
"if",
"(",
"callback",
"instanceof",
"WSManagedConnectionFactor... | <p>
Return a properties object and a reference of the target
<code>ManagedConnectionFactory</code> via <code>Callback[]</code>. | [
"<p",
">",
"Return",
"a",
"properties",
"object",
"and",
"a",
"reference",
"of",
"the",
"target",
"<code",
">",
"ManagedConnectionFactory<",
"/",
"code",
">",
"via",
"<code",
">",
"Callback",
"[]",
"<",
"/",
"code",
">",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.security.jaas.common/src/com/ibm/wsspi/security/auth/callback/WSMappingCallbackHandler.java#L56-L69 |
couchbase/couchbase-java-client | src/main/java/com/couchbase/client/java/query/dsl/functions/ArrayFunctions.java | ArrayFunctions.arrayRemove | public static Expression arrayRemove(String expression, Expression value) {
return arrayRemove(x(expression), value);
} | java | public static Expression arrayRemove(String expression, Expression value) {
return arrayRemove(x(expression), value);
} | [
"public",
"static",
"Expression",
"arrayRemove",
"(",
"String",
"expression",
",",
"Expression",
"value",
")",
"{",
"return",
"arrayRemove",
"(",
"x",
"(",
"expression",
")",
",",
"value",
")",
";",
"}"
] | 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#L351-L353 |
AgNO3/jcifs-ng | src/main/java/jcifs/util/transport/Transport.java | Transport.readn | public static int readn ( InputStream in, byte[] b, int off, int len ) throws IOException {
int i = 0, n = -5;
if ( off + len > b.length ) {
throw new IOException("Buffer too short, bufsize " + b.length + " read " + len);
}
while ( i < len ) {
n = in.read(b, off + i, len - i);
if ( n <= 0 ) {
break;
}
i += n;
}
return i;
} | java | public static int readn ( InputStream in, byte[] b, int off, int len ) throws IOException {
int i = 0, n = -5;
if ( off + len > b.length ) {
throw new IOException("Buffer too short, bufsize " + b.length + " read " + len);
}
while ( i < len ) {
n = in.read(b, off + i, len - i);
if ( n <= 0 ) {
break;
}
i += n;
}
return i;
} | [
"public",
"static",
"int",
"readn",
"(",
"InputStream",
"in",
",",
"byte",
"[",
"]",
"b",
",",
"int",
"off",
",",
"int",
"len",
")",
"throws",
"IOException",
"{",
"int",
"i",
"=",
"0",
",",
"n",
"=",
"-",
"5",
";",
"if",
"(",
"off",
"+",
"len",... | Read bytes from the input stream into a buffer
@param in
@param b
@param off
@param len
@return number of bytes read
@throws IOException | [
"Read",
"bytes",
"from",
"the",
"input",
"stream",
"into",
"a",
"buffer"
] | train | https://github.com/AgNO3/jcifs-ng/blob/0311107a077ea372527ae74839eec8042197332f/src/main/java/jcifs/util/transport/Transport.java#L62-L78 |
mojohaus/jaxb2-maven-plugin | src/main/java/org/codehaus/mojo/jaxb2/shared/filters/Filters.java | Filters.rejectAtLeastOnce | public static <T> boolean rejectAtLeastOnce(final T object, final List<Filter<T>> filters) {
// Check sanity
Validate.notNull(filters, "filters");
boolean rejectedByAtLeastOneFilter = false;
for (Filter<T> current : filters) {
if (!current.accept(object)) {
rejectedByAtLeastOneFilter = true;
break;
}
}
// All done.
return rejectedByAtLeastOneFilter;
} | java | public static <T> boolean rejectAtLeastOnce(final T object, final List<Filter<T>> filters) {
// Check sanity
Validate.notNull(filters, "filters");
boolean rejectedByAtLeastOneFilter = false;
for (Filter<T> current : filters) {
if (!current.accept(object)) {
rejectedByAtLeastOneFilter = true;
break;
}
}
// All done.
return rejectedByAtLeastOneFilter;
} | [
"public",
"static",
"<",
"T",
">",
"boolean",
"rejectAtLeastOnce",
"(",
"final",
"T",
"object",
",",
"final",
"List",
"<",
"Filter",
"<",
"T",
">",
">",
"filters",
")",
"{",
"// Check sanity",
"Validate",
".",
"notNull",
"(",
"filters",
",",
"\"filters\"",... | Algorithms for rejecting the supplied object if at least one of the supplied Filters does not accept it.
@param object The object to reject (or not).
@param filters The non-null list of Filters to examine the supplied object.
@param <T> The Filter type.
@return {@code true} if at least one of the filters returns false from its accept method.
@see Filter#accept(Object) | [
"Algorithms",
"for",
"rejecting",
"the",
"supplied",
"object",
"if",
"at",
"least",
"one",
"of",
"the",
"supplied",
"Filters",
"does",
"not",
"accept",
"it",
"."
] | train | https://github.com/mojohaus/jaxb2-maven-plugin/blob/e3c4e47943b15282e5a6e850bbfb1588d8452a0a/src/main/java/org/codehaus/mojo/jaxb2/shared/filters/Filters.java#L77-L92 |
codeprimate-software/cp-elements | src/main/java/org/cp/elements/lang/ElementsExceptionsFactory.java | ElementsExceptionsFactory.newTypeNotFoundException | public static TypeNotFoundException newTypeNotFoundException(Throwable cause, String message, Object... args) {
return new TypeNotFoundException(format(message, args), cause);
} | java | public static TypeNotFoundException newTypeNotFoundException(Throwable cause, String message, Object... args) {
return new TypeNotFoundException(format(message, args), cause);
} | [
"public",
"static",
"TypeNotFoundException",
"newTypeNotFoundException",
"(",
"Throwable",
"cause",
",",
"String",
"message",
",",
"Object",
"...",
"args",
")",
"{",
"return",
"new",
"TypeNotFoundException",
"(",
"format",
"(",
"message",
",",
"args",
")",
",",
... | Constructs and initializes a new {@link TypeNotFoundException} 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 TypeNotFoundException} was thrown.
@param message {@link String} describing the {@link TypeNotFoundException exception}.
@param args {@link Object[] arguments} used to replace format placeholders in the {@link String message}.
@return a new {@link TypeNotFoundException} with the given {@link Throwable cause} and {@link String message}.
@see org.cp.elements.lang.TypeNotFoundException | [
"Constructs",
"and",
"initializes",
"a",
"new",
"{",
"@link",
"TypeNotFoundException",
"}",
"with",
"the",
"given",
"{",
"@link",
"Throwable",
"cause",
"}",
"and",
"{",
"@link",
"String",
"message",
"}",
"formatted",
"with",
"the",
"given",
"{",
"@link",
"Ob... | train | https://github.com/codeprimate-software/cp-elements/blob/f2163c149fbbef05015e688132064ebcac7c49ab/src/main/java/org/cp/elements/lang/ElementsExceptionsFactory.java#L539-L541 |
sargue/mailgun | src/main/java/net/sargue/mailgun/Configuration.java | Configuration.addDefaultParameter | public Configuration addDefaultParameter(String name, String value) {
defaultParameters.add(name, value);
return this;
} | java | public Configuration addDefaultParameter(String name, String value) {
defaultParameters.add(name, value);
return this;
} | [
"public",
"Configuration",
"addDefaultParameter",
"(",
"String",
"name",
",",
"String",
"value",
")",
"{",
"defaultParameters",
".",
"add",
"(",
"name",
",",
"value",
")",
";",
"return",
"this",
";",
"}"
] | Adds a new value to the specified default parameter.
<p>
This is only used if the parameter is not specified when building
the specific mail.
<p>
Please note that parameters are multivalued. This method adds a new
value. To set a new value you need to clear the default parameter first.
@param name the name of the parameter
@param value the new value to add to the parameter
@return this configuration
@see #clearDefaultParameter(String) | [
"Adds",
"a",
"new",
"value",
"to",
"the",
"specified",
"default",
"parameter",
".",
"<p",
">",
"This",
"is",
"only",
"used",
"if",
"the",
"parameter",
"is",
"not",
"specified",
"when",
"building",
"the",
"specific",
"mail",
".",
"<p",
">",
"Please",
"not... | train | https://github.com/sargue/mailgun/blob/2ffb0a156f3f3666eb1bb2db661451b9377c3d11/src/main/java/net/sargue/mailgun/Configuration.java#L215-L218 |
jlinn/quartz-redis-jobstore | src/main/java/net/joelinn/quartz/jobstore/AbstractRedisStorage.java | AbstractRedisStorage.pauseJob | public void pauseJob(JobKey jobKey, T jedis) throws JobPersistenceException {
for (OperableTrigger trigger : getTriggersForJob(jobKey, jedis)) {
pauseTrigger(trigger.getKey(), jedis);
}
} | java | public void pauseJob(JobKey jobKey, T jedis) throws JobPersistenceException {
for (OperableTrigger trigger : getTriggersForJob(jobKey, jedis)) {
pauseTrigger(trigger.getKey(), jedis);
}
} | [
"public",
"void",
"pauseJob",
"(",
"JobKey",
"jobKey",
",",
"T",
"jedis",
")",
"throws",
"JobPersistenceException",
"{",
"for",
"(",
"OperableTrigger",
"trigger",
":",
"getTriggersForJob",
"(",
"jobKey",
",",
"jedis",
")",
")",
"{",
"pauseTrigger",
"(",
"trigg... | Pause a job by pausing all of its triggers
@param jobKey the key of the job to be paused
@param jedis a thread-safe Redis connection | [
"Pause",
"a",
"job",
"by",
"pausing",
"all",
"of",
"its",
"triggers"
] | train | https://github.com/jlinn/quartz-redis-jobstore/blob/be9a52ee776d8a09866fe99fd9718bc13a0cb992/src/main/java/net/joelinn/quartz/jobstore/AbstractRedisStorage.java#L529-L533 |
spring-projects/spring-data-solr | src/main/java/org/springframework/data/solr/core/QueryParserBase.java | QueryParserBase.prependJoin | protected String prependJoin(String queryString, @Nullable SolrDataQuery query, @Nullable Class<?> domainType) {
if (query == null || query.getJoin() == null) {
return queryString;
}
String fromIndex = query.getJoin().getFromIndex() != null ? " fromIndex=" + query.getJoin().getFromIndex() : "";
return "{!join from=" + getMappedFieldName(query.getJoin().getFrom(), domainType) + " to="
+ getMappedFieldName(query.getJoin().getTo(), domainType) + fromIndex + "}" + queryString;
} | java | protected String prependJoin(String queryString, @Nullable SolrDataQuery query, @Nullable Class<?> domainType) {
if (query == null || query.getJoin() == null) {
return queryString;
}
String fromIndex = query.getJoin().getFromIndex() != null ? " fromIndex=" + query.getJoin().getFromIndex() : "";
return "{!join from=" + getMappedFieldName(query.getJoin().getFrom(), domainType) + " to="
+ getMappedFieldName(query.getJoin().getTo(), domainType) + fromIndex + "}" + queryString;
} | [
"protected",
"String",
"prependJoin",
"(",
"String",
"queryString",
",",
"@",
"Nullable",
"SolrDataQuery",
"query",
",",
"@",
"Nullable",
"Class",
"<",
"?",
">",
"domainType",
")",
"{",
"if",
"(",
"query",
"==",
"null",
"||",
"query",
".",
"getJoin",
"(",
... | Prepend {@code !join from= to=} to given queryString
@param queryString
@param query
@param domainType
@return | [
"Prepend",
"{",
"@code",
"!join",
"from",
"=",
"to",
"=",
"}",
"to",
"given",
"queryString"
] | train | https://github.com/spring-projects/spring-data-solr/blob/20be5cb82498b70134dfda6c1a91ad21f8e657e0/src/main/java/org/springframework/data/solr/core/QueryParserBase.java#L403-L411 |
JM-Lab/utils-java8 | src/main/java/kr/jm/utils/datastructure/JMMap.java | JMMap.removeAllIfByEntry | public static <K, V> List<V> removeAllIfByEntry(Map<K, V> map,
Predicate<? super Entry<K, V>> filter) {
return getEntryStreamWithFilter(map, filter).map(Entry::getKey)
.collect(toList()).stream().map(map::remove)
.collect(toList());
} | java | public static <K, V> List<V> removeAllIfByEntry(Map<K, V> map,
Predicate<? super Entry<K, V>> filter) {
return getEntryStreamWithFilter(map, filter).map(Entry::getKey)
.collect(toList()).stream().map(map::remove)
.collect(toList());
} | [
"public",
"static",
"<",
"K",
",",
"V",
">",
"List",
"<",
"V",
">",
"removeAllIfByEntry",
"(",
"Map",
"<",
"K",
",",
"V",
">",
"map",
",",
"Predicate",
"<",
"?",
"super",
"Entry",
"<",
"K",
",",
"V",
">",
">",
"filter",
")",
"{",
"return",
"get... | Remove all if by entry list.
@param <K> the type parameter
@param <V> the type parameter
@param map the map
@param filter the filter
@return the list | [
"Remove",
"all",
"if",
"by",
"entry",
"list",
"."
] | train | https://github.com/JM-Lab/utils-java8/blob/9e407b3f28a7990418a1e877229fa8344f4d78a5/src/main/java/kr/jm/utils/datastructure/JMMap.java#L47-L52 |
cdk/cdk | tool/sdg/src/main/java/org/openscience/cdk/layout/OverlapResolver.java | OverlapResolver.getOverlapScore | public double getOverlapScore(IAtomContainer ac, Vector overlappingAtoms, Vector overlappingBonds) {
double overlapScore = 0;
overlapScore = getAtomOverlapScore(ac, overlappingAtoms);
//overlapScore += getBondOverlapScore(ac, overlappingBonds);
return overlapScore;
} | java | public double getOverlapScore(IAtomContainer ac, Vector overlappingAtoms, Vector overlappingBonds) {
double overlapScore = 0;
overlapScore = getAtomOverlapScore(ac, overlappingAtoms);
//overlapScore += getBondOverlapScore(ac, overlappingBonds);
return overlapScore;
} | [
"public",
"double",
"getOverlapScore",
"(",
"IAtomContainer",
"ac",
",",
"Vector",
"overlappingAtoms",
",",
"Vector",
"overlappingBonds",
")",
"{",
"double",
"overlapScore",
"=",
"0",
";",
"overlapScore",
"=",
"getAtomOverlapScore",
"(",
"ac",
",",
"overlappingAtoms... | Calculates a score based on the overlap of atoms and intersection of bonds.
The overlap is calculated by summing up the distances between all pairs of
atoms, if they are less than half the standard bondlength apart.
@param ac The Atomcontainer to work on
@param overlappingAtoms Description of the Parameter
@param overlappingBonds Description of the Parameter
@return The overlapScore value | [
"Calculates",
"a",
"score",
"based",
"on",
"the",
"overlap",
"of",
"atoms",
"and",
"intersection",
"of",
"bonds",
".",
"The",
"overlap",
"is",
"calculated",
"by",
"summing",
"up",
"the",
"distances",
"between",
"all",
"pairs",
"of",
"atoms",
"if",
"they",
... | train | https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/tool/sdg/src/main/java/org/openscience/cdk/layout/OverlapResolver.java#L162-L167 |
lessthanoptimal/BoofCV | main/boofcv-sfm/src/main/java/boofcv/alg/sfm/d3/VisOdomDualTrackPnP.java | VisOdomDualTrackPnP.selectCandidateTracks | private void selectCandidateTracks() {
// mark tracks in right frame that are active
List<PointTrack> activeRight = trackerRight.getActiveTracks(null);
for( PointTrack t : activeRight ) {
RightTrackInfo info = t.getCookie();
info.lastActiveList = tick;
}
int mutualActive = 0;
List<PointTrack> activeLeft = trackerLeft.getActiveTracks(null);
candidates.clear();
for( PointTrack left : activeLeft ) {
LeftTrackInfo info = left.getCookie();
// if( info == null || info.right == null ) {
// System.out.println("Oh Crap");
// }
// for each active left track, see if its right track has been marked as active
RightTrackInfo infoRight = info.right.getCookie();
if( infoRight.lastActiveList != tick ) {
continue;
}
// check epipolar constraint and see if it is still valid
if( stereoCheck.checkPixel(left, info.right) ) {
info.lastConsistent = tick;
candidates.add(left);
}
mutualActive++;
}
// System.out.println("Active Tracks: Left "+trackerLeft.getActiveTracks(null).size()+" right "+
// trackerRight.getActiveTracks(null).size());
// System.out.println("All Tracks: Left "+trackerLeft.getAllTracks(null).size()+" right "+
// trackerRight.getAllTracks(null).size());
// System.out.println("Candidates = "+candidates.size()+" mutual active = "+mutualActive);
} | java | private void selectCandidateTracks() {
// mark tracks in right frame that are active
List<PointTrack> activeRight = trackerRight.getActiveTracks(null);
for( PointTrack t : activeRight ) {
RightTrackInfo info = t.getCookie();
info.lastActiveList = tick;
}
int mutualActive = 0;
List<PointTrack> activeLeft = trackerLeft.getActiveTracks(null);
candidates.clear();
for( PointTrack left : activeLeft ) {
LeftTrackInfo info = left.getCookie();
// if( info == null || info.right == null ) {
// System.out.println("Oh Crap");
// }
// for each active left track, see if its right track has been marked as active
RightTrackInfo infoRight = info.right.getCookie();
if( infoRight.lastActiveList != tick ) {
continue;
}
// check epipolar constraint and see if it is still valid
if( stereoCheck.checkPixel(left, info.right) ) {
info.lastConsistent = tick;
candidates.add(left);
}
mutualActive++;
}
// System.out.println("Active Tracks: Left "+trackerLeft.getActiveTracks(null).size()+" right "+
// trackerRight.getActiveTracks(null).size());
// System.out.println("All Tracks: Left "+trackerLeft.getAllTracks(null).size()+" right "+
// trackerRight.getAllTracks(null).size());
// System.out.println("Candidates = "+candidates.size()+" mutual active = "+mutualActive);
} | [
"private",
"void",
"selectCandidateTracks",
"(",
")",
"{",
"// mark tracks in right frame that are active",
"List",
"<",
"PointTrack",
">",
"activeRight",
"=",
"trackerRight",
".",
"getActiveTracks",
"(",
"null",
")",
";",
"for",
"(",
"PointTrack",
"t",
":",
"active... | Searches for tracks which are active and meet the epipolar constraints | [
"Searches",
"for",
"tracks",
"which",
"are",
"active",
"and",
"meet",
"the",
"epipolar",
"constraints"
] | train | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-sfm/src/main/java/boofcv/alg/sfm/d3/VisOdomDualTrackPnP.java#L307-L344 |
mebigfatguy/fb-contrib | src/main/java/com/mebigfatguy/fbcontrib/detect/JPAIssues.java | JPAIssues.visitMethod | @Override
public void visitMethod(Method obj) {
if (getMethod().isSynthetic()) {
return;
}
methodTransType = getTransactionalType(obj);
if ((methodTransType != TransactionalType.NONE) && !obj.isPublic()) {
bugReporter
.reportBug(new BugInstance(this, BugType.JPAI_TRANSACTION_ON_NON_PUBLIC_METHOD.name(), NORMAL_PRIORITY).addClass(this).addMethod(cls, obj));
}
if ((methodTransType == TransactionalType.WRITE) && (runtimeExceptionClass != null)) {
try {
Set<JavaClass> annotatedRollBackExceptions = getAnnotatedRollbackExceptions(obj);
Set<JavaClass> declaredExceptions = getDeclaredExceptions(obj);
reportExceptionMismatch(obj, annotatedRollBackExceptions, declaredExceptions, false, BugType.JPAI_NON_SPECIFIED_TRANSACTION_EXCEPTION_HANDLING);
reportExceptionMismatch(obj, declaredExceptions, annotatedRollBackExceptions, true, BugType.JPAI_UNNECESSARY_TRANSACTION_EXCEPTION_HANDLING);
} catch (ClassNotFoundException cnfe) {
bugReporter.reportMissingClass(cnfe);
}
}
super.visitMethod(obj);
} | java | @Override
public void visitMethod(Method obj) {
if (getMethod().isSynthetic()) {
return;
}
methodTransType = getTransactionalType(obj);
if ((methodTransType != TransactionalType.NONE) && !obj.isPublic()) {
bugReporter
.reportBug(new BugInstance(this, BugType.JPAI_TRANSACTION_ON_NON_PUBLIC_METHOD.name(), NORMAL_PRIORITY).addClass(this).addMethod(cls, obj));
}
if ((methodTransType == TransactionalType.WRITE) && (runtimeExceptionClass != null)) {
try {
Set<JavaClass> annotatedRollBackExceptions = getAnnotatedRollbackExceptions(obj);
Set<JavaClass> declaredExceptions = getDeclaredExceptions(obj);
reportExceptionMismatch(obj, annotatedRollBackExceptions, declaredExceptions, false, BugType.JPAI_NON_SPECIFIED_TRANSACTION_EXCEPTION_HANDLING);
reportExceptionMismatch(obj, declaredExceptions, annotatedRollBackExceptions, true, BugType.JPAI_UNNECESSARY_TRANSACTION_EXCEPTION_HANDLING);
} catch (ClassNotFoundException cnfe) {
bugReporter.reportMissingClass(cnfe);
}
}
super.visitMethod(obj);
} | [
"@",
"Override",
"public",
"void",
"visitMethod",
"(",
"Method",
"obj",
")",
"{",
"if",
"(",
"getMethod",
"(",
")",
".",
"isSynthetic",
"(",
")",
")",
"{",
"return",
";",
"}",
"methodTransType",
"=",
"getTransactionalType",
"(",
"obj",
")",
";",
"if",
... | implements the visitor to look for non public methods that have an @Transactional annotation applied to it. Spring only scans public methods for special
handling. It also looks to see if the exceptions thrown by the method line up with the declared exceptions handled in the @Transactional annotation.
@param obj
the currently parse method | [
"implements",
"the",
"visitor",
"to",
"look",
"for",
"non",
"public",
"methods",
"that",
"have",
"an",
"@Transactional",
"annotation",
"applied",
"to",
"it",
".",
"Spring",
"only",
"scans",
"public",
"methods",
"for",
"special",
"handling",
".",
"It",
"also",
... | train | https://github.com/mebigfatguy/fb-contrib/blob/3b5203196f627b399fbcea3c2ab2b1f4e56cc7b8/src/main/java/com/mebigfatguy/fbcontrib/detect/JPAIssues.java#L154-L178 |
igniterealtime/Smack | smack-experimental/src/main/java/org/jivesoftware/smackx/muclight/MultiUserChatLightManager.java | MultiUserChatLightManager.unblockUser | public void unblockUser(DomainBareJid mucLightService, Jid userJid)
throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
HashMap<Jid, Boolean> users = new HashMap<>();
users.put(userJid, true);
sendUnblockUsers(mucLightService, users);
} | java | public void unblockUser(DomainBareJid mucLightService, Jid userJid)
throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
HashMap<Jid, Boolean> users = new HashMap<>();
users.put(userJid, true);
sendUnblockUsers(mucLightService, users);
} | [
"public",
"void",
"unblockUser",
"(",
"DomainBareJid",
"mucLightService",
",",
"Jid",
"userJid",
")",
"throws",
"NoResponseException",
",",
"XMPPErrorException",
",",
"NotConnectedException",
",",
"InterruptedException",
"{",
"HashMap",
"<",
"Jid",
",",
"Boolean",
">"... | Unblock a user.
@param mucLightService
@param userJid
@throws NoResponseException
@throws XMPPErrorException
@throws NotConnectedException
@throws InterruptedException | [
"Unblock",
"a",
"user",
"."
] | train | https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-experimental/src/main/java/org/jivesoftware/smackx/muclight/MultiUserChatLightManager.java#L384-L389 |
atomix/copycat | client/src/main/java/io/atomix/copycat/client/util/AddressSelector.java | AddressSelector.matches | private boolean matches(Collection<Address> left, Collection<Address> right) {
if (left.size() != right.size())
return false;
for (Address address : left) {
if (!right.contains(address)) {
return false;
}
}
return true;
} | java | private boolean matches(Collection<Address> left, Collection<Address> right) {
if (left.size() != right.size())
return false;
for (Address address : left) {
if (!right.contains(address)) {
return false;
}
}
return true;
} | [
"private",
"boolean",
"matches",
"(",
"Collection",
"<",
"Address",
">",
"left",
",",
"Collection",
"<",
"Address",
">",
"right",
")",
"{",
"if",
"(",
"left",
".",
"size",
"(",
")",
"!=",
"right",
".",
"size",
"(",
")",
")",
"return",
"false",
";",
... | Returns a boolean value indicating whether the servers in the first list match the servers in the second list. | [
"Returns",
"a",
"boolean",
"value",
"indicating",
"whether",
"the",
"servers",
"in",
"the",
"first",
"list",
"match",
"the",
"servers",
"in",
"the",
"second",
"list",
"."
] | train | https://github.com/atomix/copycat/blob/c90b88ccd5c63d6ea0b49fb77c25e2f3272a7b10/client/src/main/java/io/atomix/copycat/client/util/AddressSelector.java#L150-L160 |
unbescape/unbescape | src/main/java/org/unbescape/html/HtmlEscape.java | HtmlEscape.unescapeHtml | public static void unescapeHtml(final String text, final Writer writer)
throws IOException {
if (writer == null) {
throw new IllegalArgumentException("Argument 'writer' cannot be null");
}
if (text == null) {
return;
}
if (text.indexOf('&') < 0) {
// Fail fast, avoid more complex (and less JIT-table) method to execute if not needed
writer.write(text);
return;
}
HtmlEscapeUtil.unescape(new InternalStringReader(text), writer);
} | java | public static void unescapeHtml(final String text, final Writer writer)
throws IOException {
if (writer == null) {
throw new IllegalArgumentException("Argument 'writer' cannot be null");
}
if (text == null) {
return;
}
if (text.indexOf('&') < 0) {
// Fail fast, avoid more complex (and less JIT-table) method to execute if not needed
writer.write(text);
return;
}
HtmlEscapeUtil.unescape(new InternalStringReader(text), writer);
} | [
"public",
"static",
"void",
"unescapeHtml",
"(",
"final",
"String",
"text",
",",
"final",
"Writer",
"writer",
")",
"throws",
"IOException",
"{",
"if",
"(",
"writer",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Argument 'writer' ca... | <p>
Perform an HTML <strong>unescape</strong> operation on a <tt>String</tt> input, writing results to
a <tt>Writer</tt>.
</p>
<p>
No additional configuration arguments are required. Unescape operations
will always perform <em>complete</em> unescape of NCRs (whole HTML5 set supported), decimal
and hexadecimal references.
</p>
<p>
This method is <strong>thread-safe</strong>.
</p>
@param text the <tt>String</tt> to be unescaped.
@param writer the <tt>java.io.Writer</tt> to which the unescaped result will be written. Nothing will
be written at all to this writer if input is <tt>null</tt>.
@throws IOException if an input/output exception occurs
@since 1.1.2 | [
"<p",
">",
"Perform",
"an",
"HTML",
"<strong",
">",
"unescape<",
"/",
"strong",
">",
"operation",
"on",
"a",
"<tt",
">",
"String<",
"/",
"tt",
">",
"input",
"writing",
"results",
"to",
"a",
"<tt",
">",
"Writer<",
"/",
"tt",
">",
".",
"<",
"/",
"p",... | train | https://github.com/unbescape/unbescape/blob/ec5435fb3508c2eed25d8165dc27ded2602cae13/src/main/java/org/unbescape/html/HtmlEscape.java#L1123-L1140 |
Azure/azure-sdk-for-java | logic/resource-manager/v2016_06_01/src/main/java/com/microsoft/azure/management/logic/v2016_06_01/implementation/IntegrationAccountsInner.java | IntegrationAccountsInner.getByResourceGroupAsync | public Observable<IntegrationAccountInner> getByResourceGroupAsync(String resourceGroupName, String integrationAccountName) {
return getByResourceGroupWithServiceResponseAsync(resourceGroupName, integrationAccountName).map(new Func1<ServiceResponse<IntegrationAccountInner>, IntegrationAccountInner>() {
@Override
public IntegrationAccountInner call(ServiceResponse<IntegrationAccountInner> response) {
return response.body();
}
});
} | java | public Observable<IntegrationAccountInner> getByResourceGroupAsync(String resourceGroupName, String integrationAccountName) {
return getByResourceGroupWithServiceResponseAsync(resourceGroupName, integrationAccountName).map(new Func1<ServiceResponse<IntegrationAccountInner>, IntegrationAccountInner>() {
@Override
public IntegrationAccountInner call(ServiceResponse<IntegrationAccountInner> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"IntegrationAccountInner",
">",
"getByResourceGroupAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"integrationAccountName",
")",
"{",
"return",
"getByResourceGroupWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"integrationAcco... | Gets an integration account.
@param resourceGroupName The resource group name.
@param integrationAccountName The integration account name.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the IntegrationAccountInner object | [
"Gets",
"an",
"integration",
"account",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/logic/resource-manager/v2016_06_01/src/main/java/com/microsoft/azure/management/logic/v2016_06_01/implementation/IntegrationAccountsInner.java#L601-L608 |
spring-projects/spring-android | spring-android-core/src/main/java/org/springframework/core/io/UrlResource.java | UrlResource.createRelative | @Override
public Resource createRelative(String relativePath) throws MalformedURLException {
if (relativePath.startsWith("/")) {
relativePath = relativePath.substring(1);
}
return new UrlResource(new URL(this.url, relativePath));
} | java | @Override
public Resource createRelative(String relativePath) throws MalformedURLException {
if (relativePath.startsWith("/")) {
relativePath = relativePath.substring(1);
}
return new UrlResource(new URL(this.url, relativePath));
} | [
"@",
"Override",
"public",
"Resource",
"createRelative",
"(",
"String",
"relativePath",
")",
"throws",
"MalformedURLException",
"{",
"if",
"(",
"relativePath",
".",
"startsWith",
"(",
"\"/\"",
")",
")",
"{",
"relativePath",
"=",
"relativePath",
".",
"substring",
... | This implementation creates a UrlResource, applying the given path
relative to the path of the underlying URL of this resource descriptor.
@see java.net.URL#URL(java.net.URL, String) | [
"This",
"implementation",
"creates",
"a",
"UrlResource",
"applying",
"the",
"given",
"path",
"relative",
"to",
"the",
"path",
"of",
"the",
"underlying",
"URL",
"of",
"this",
"resource",
"descriptor",
"."
] | train | https://github.com/spring-projects/spring-android/blob/941296e152d49a40e0745a3e81628a974f72b7e4/spring-android-core/src/main/java/org/springframework/core/io/UrlResource.java#L220-L226 |
hankcs/HanLP | src/main/java/com/hankcs/hanlp/HanLP.java | HanLP.getSummary | public static String getSummary(String document, int max_length, String sentence_separator)
{
// Parameter size in this method refers to the string length of the summary required;
// The actual length of the summary generated may be short than the required length, but never longer;
return TextRankSentence.getSummary(document, max_length, sentence_separator);
} | java | public static String getSummary(String document, int max_length, String sentence_separator)
{
// Parameter size in this method refers to the string length of the summary required;
// The actual length of the summary generated may be short than the required length, but never longer;
return TextRankSentence.getSummary(document, max_length, sentence_separator);
} | [
"public",
"static",
"String",
"getSummary",
"(",
"String",
"document",
",",
"int",
"max_length",
",",
"String",
"sentence_separator",
")",
"{",
"// Parameter size in this method refers to the string length of the summary required;",
"// The actual length of the summary generated may ... | 自动摘要
@param document 目标文档
@param max_length 需要摘要的长度
@param sentence_separator 分割目标文档时的句子分割符,正则格式, 如:[。??!!;;]
@return 摘要文本 | [
"自动摘要"
] | train | https://github.com/hankcs/HanLP/blob/a538d0722ab2e4980a9dcd9ea40324fc3ddba7ce/src/main/java/com/hankcs/hanlp/HanLP.java#L856-L861 |
MariaDB/mariadb-connector-j | src/main/java/org/mariadb/jdbc/internal/failover/FailoverProxy.java | FailoverProxy.handleFailOver | private Object handleFailOver(SQLException qe, Method method, Object[] args, Protocol protocol)
throws Throwable {
HostAddress failHostAddress = null;
boolean failIsMaster = true;
if (protocol != null) {
failHostAddress = protocol.getHostAddress();
failIsMaster = protocol.isMasterConnection();
}
HandleErrorResult handleErrorResult = listener.handleFailover(qe, method, args, protocol);
if (handleErrorResult.mustThrowError) {
listener
.throwFailoverMessage(failHostAddress, failIsMaster, qe, handleErrorResult.isReconnected);
}
return handleErrorResult.resultObject;
} | java | private Object handleFailOver(SQLException qe, Method method, Object[] args, Protocol protocol)
throws Throwable {
HostAddress failHostAddress = null;
boolean failIsMaster = true;
if (protocol != null) {
failHostAddress = protocol.getHostAddress();
failIsMaster = protocol.isMasterConnection();
}
HandleErrorResult handleErrorResult = listener.handleFailover(qe, method, args, protocol);
if (handleErrorResult.mustThrowError) {
listener
.throwFailoverMessage(failHostAddress, failIsMaster, qe, handleErrorResult.isReconnected);
}
return handleErrorResult.resultObject;
} | [
"private",
"Object",
"handleFailOver",
"(",
"SQLException",
"qe",
",",
"Method",
"method",
",",
"Object",
"[",
"]",
"args",
",",
"Protocol",
"protocol",
")",
"throws",
"Throwable",
"{",
"HostAddress",
"failHostAddress",
"=",
"null",
";",
"boolean",
"failIsMaster... | After a connection exception, launch failover.
@param qe the exception thrown
@param method the method to call if failover works well
@param args the arguments of the method
@return the object return from the method
@throws Throwable throwable | [
"After",
"a",
"connection",
"exception",
"launch",
"failover",
"."
] | train | https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/failover/FailoverProxy.java#L352-L367 |
Alluxio/alluxio | core/common/src/main/java/alluxio/util/ConfigurationUtils.java | ConfigurationUtils.loadPathConfiguration | private static PathConfiguration loadPathConfiguration(GetConfigurationPResponse response,
AlluxioConfiguration clusterConf) {
String clientVersion = clusterConf.get(PropertyKey.VERSION);
LOG.info("Alluxio client (version {}) is trying to load path level configurations",
clientVersion);
Map<String, AlluxioConfiguration> pathConfs = new HashMap<>();
response.getPathConfigsMap().forEach((path, conf) -> {
Properties props = loadClientProperties(conf.getPropertiesList(),
(key, value) -> String.format("Loading property: %s (%s) -> %s for path %s",
key, key.getScope(), value, path));
AlluxioProperties properties = new AlluxioProperties();
properties.merge(props, Source.PATH_DEFAULT);
pathConfs.put(path, new InstancedConfiguration(properties, true));
});
LOG.info("Alluxio client has loaded path level configurations");
return PathConfiguration.create(pathConfs);
} | java | private static PathConfiguration loadPathConfiguration(GetConfigurationPResponse response,
AlluxioConfiguration clusterConf) {
String clientVersion = clusterConf.get(PropertyKey.VERSION);
LOG.info("Alluxio client (version {}) is trying to load path level configurations",
clientVersion);
Map<String, AlluxioConfiguration> pathConfs = new HashMap<>();
response.getPathConfigsMap().forEach((path, conf) -> {
Properties props = loadClientProperties(conf.getPropertiesList(),
(key, value) -> String.format("Loading property: %s (%s) -> %s for path %s",
key, key.getScope(), value, path));
AlluxioProperties properties = new AlluxioProperties();
properties.merge(props, Source.PATH_DEFAULT);
pathConfs.put(path, new InstancedConfiguration(properties, true));
});
LOG.info("Alluxio client has loaded path level configurations");
return PathConfiguration.create(pathConfs);
} | [
"private",
"static",
"PathConfiguration",
"loadPathConfiguration",
"(",
"GetConfigurationPResponse",
"response",
",",
"AlluxioConfiguration",
"clusterConf",
")",
"{",
"String",
"clientVersion",
"=",
"clusterConf",
".",
"get",
"(",
"PropertyKey",
".",
"VERSION",
")",
";"... | Loads the path level configuration from the get configuration response.
Only client scope properties will be loaded.
@param response the get configuration RPC response
@param clusterConf cluster level configuration
@return the loaded path level configuration | [
"Loads",
"the",
"path",
"level",
"configuration",
"from",
"the",
"get",
"configuration",
"response",
"."
] | train | https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/common/src/main/java/alluxio/util/ConfigurationUtils.java#L569-L585 |
RestComm/media-core | stun/src/main/java/org/restcomm/media/core/stun/messages/attributes/StunAttributeFactory.java | StunAttributeFactory.createMessageIntegrityAttribute | public static MessageIntegrityAttribute createMessageIntegrityAttribute(String username, byte[] key) {
MessageIntegrityAttribute attribute = new MessageIntegrityAttribute();
attribute.setKey(key);
attribute.setUsername(username);
return attribute;
} | java | public static MessageIntegrityAttribute createMessageIntegrityAttribute(String username, byte[] key) {
MessageIntegrityAttribute attribute = new MessageIntegrityAttribute();
attribute.setKey(key);
attribute.setUsername(username);
return attribute;
} | [
"public",
"static",
"MessageIntegrityAttribute",
"createMessageIntegrityAttribute",
"(",
"String",
"username",
",",
"byte",
"[",
"]",
"key",
")",
"{",
"MessageIntegrityAttribute",
"attribute",
"=",
"new",
"MessageIntegrityAttribute",
"(",
")",
";",
"attribute",
".",
"... | Creates an empty <tt>MessageIntegrityAttribute</tt>. When included in a
message the stack would set the body of this attribute so that the the
HMAC-SHA1 (RFC 2104) would correspond to the actual message that's
transporting the attribute.
@param username
the username that we should use to obtain an encryption key
(password) that the {@link StunAttribute#encode()} method
should use when creating the content of this message.
@return the newly created address attribute. | [
"Creates",
"an",
"empty",
"<tt",
">",
"MessageIntegrityAttribute<",
"/",
"tt",
">",
".",
"When",
"included",
"in",
"a",
"message",
"the",
"stack",
"would",
"set",
"the",
"body",
"of",
"this",
"attribute",
"so",
"that",
"the",
"the",
"HMAC",
"-",
"SHA1",
... | train | https://github.com/RestComm/media-core/blob/07b8703343708599f60af66bae62aded77ee81b5/stun/src/main/java/org/restcomm/media/core/stun/messages/attributes/StunAttributeFactory.java#L374-L379 |
looly/hutool | hutool-core/src/main/java/cn/hutool/core/date/DateUtil.java | DateUtil.getBeginValue | public static int getBeginValue(Calendar calendar, int dateField) {
if(Calendar.DAY_OF_WEEK == dateField) {
return calendar.getFirstDayOfWeek();
}
return calendar.getActualMinimum(dateField);
} | java | public static int getBeginValue(Calendar calendar, int dateField) {
if(Calendar.DAY_OF_WEEK == dateField) {
return calendar.getFirstDayOfWeek();
}
return calendar.getActualMinimum(dateField);
} | [
"public",
"static",
"int",
"getBeginValue",
"(",
"Calendar",
"calendar",
",",
"int",
"dateField",
")",
"{",
"if",
"(",
"Calendar",
".",
"DAY_OF_WEEK",
"==",
"dateField",
")",
"{",
"return",
"calendar",
".",
"getFirstDayOfWeek",
"(",
")",
";",
"}",
"return",
... | 获取指定日期字段的最小值,例如分钟的最小值是0
@param calendar {@link Calendar}
@param dateField {@link DateField}
@return 字段最小值
@since 4.5.7
@see Calendar#getActualMinimum(int) | [
"获取指定日期字段的最小值,例如分钟的最小值是0"
] | train | https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/date/DateUtil.java#L1680-L1685 |
b3log/latke | latke-core/src/main/java/org/b3log/latke/util/Templates.java | Templates.hasExpression | private static boolean hasExpression(final Template template, final String expression, final TemplateElement templateElement) {
final String canonicalForm = templateElement.getCanonicalForm();
if (canonicalForm.startsWith(expression)) {
LOGGER.log(Level.TRACE, "Template has expression[nodeName={0}, expression={1}]",
new Object[]{templateElement.getNodeName(), expression});
return true;
}
final Enumeration<TemplateElement> children = templateElement.children();
while (children.hasMoreElements()) {
final TemplateElement nextElement = children.nextElement();
if (hasExpression(template, expression, nextElement)) {
return true;
}
}
return false;
} | java | private static boolean hasExpression(final Template template, final String expression, final TemplateElement templateElement) {
final String canonicalForm = templateElement.getCanonicalForm();
if (canonicalForm.startsWith(expression)) {
LOGGER.log(Level.TRACE, "Template has expression[nodeName={0}, expression={1}]",
new Object[]{templateElement.getNodeName(), expression});
return true;
}
final Enumeration<TemplateElement> children = templateElement.children();
while (children.hasMoreElements()) {
final TemplateElement nextElement = children.nextElement();
if (hasExpression(template, expression, nextElement)) {
return true;
}
}
return false;
} | [
"private",
"static",
"boolean",
"hasExpression",
"(",
"final",
"Template",
"template",
",",
"final",
"String",
"expression",
",",
"final",
"TemplateElement",
"templateElement",
")",
"{",
"final",
"String",
"canonicalForm",
"=",
"templateElement",
".",
"getCanonicalFor... | Determines whether the specified expression exists in the specified
element (includes its children) of the specified template.
@param template the specified template
@param expression the specified expression
@param templateElement the specified element
@return {@code true} if it exists, returns {@code false} otherwise | [
"Determines",
"whether",
"the",
"specified",
"expression",
"exists",
"in",
"the",
"specified",
"element",
"(",
"includes",
"its",
"children",
")",
"of",
"the",
"specified",
"template",
"."
] | train | https://github.com/b3log/latke/blob/f7e08a47eeecea5f7c94006382c24f353585de33/latke-core/src/main/java/org/b3log/latke/util/Templates.java#L68-L88 |
fuinorg/event-store-commons | spi/src/main/java/org/fuin/esc/spi/EscSpiUtils.java | EscSpiUtils.createEscMeta | public static EscMeta createEscMeta(@NotNull final SerializerRegistry registry, @NotNull final EnhancedMimeType targetContentType,
@Nullable final CommonEvent commonEvent) {
Contract.requireArgNotNull("registry", registry);
Contract.requireArgNotNull("targetContentType", targetContentType);
if (commonEvent == null) {
return null;
}
final String dataType = commonEvent.getDataType().asBaseType();
final Serializer dataSerializer = registry.getSerializer(new SerializedDataType(dataType));
final EnhancedMimeType dataContentType = contentType(dataSerializer.getMimeType(), targetContentType);
if (commonEvent.getMeta() == null) {
return new EscMeta(dataType, dataContentType);
}
final String metaType = commonEvent.getMetaType().asBaseType();
final SerializedDataType serDataType = new SerializedDataType(metaType);
final Serializer metaSerializer = registry.getSerializer(serDataType);
if (metaSerializer.getMimeType().matchEncoding(targetContentType)) {
return new EscMeta(dataType, dataContentType, metaType, metaSerializer.getMimeType(), commonEvent.getMeta());
}
final byte[] serMeta = metaSerializer.marshal(commonEvent.getMeta(), serDataType);
final EnhancedMimeType metaContentType = contentType(metaSerializer.getMimeType(), targetContentType);
return new EscMeta(dataType, dataContentType, metaType, metaContentType, new Base64Data(serMeta));
} | java | public static EscMeta createEscMeta(@NotNull final SerializerRegistry registry, @NotNull final EnhancedMimeType targetContentType,
@Nullable final CommonEvent commonEvent) {
Contract.requireArgNotNull("registry", registry);
Contract.requireArgNotNull("targetContentType", targetContentType);
if (commonEvent == null) {
return null;
}
final String dataType = commonEvent.getDataType().asBaseType();
final Serializer dataSerializer = registry.getSerializer(new SerializedDataType(dataType));
final EnhancedMimeType dataContentType = contentType(dataSerializer.getMimeType(), targetContentType);
if (commonEvent.getMeta() == null) {
return new EscMeta(dataType, dataContentType);
}
final String metaType = commonEvent.getMetaType().asBaseType();
final SerializedDataType serDataType = new SerializedDataType(metaType);
final Serializer metaSerializer = registry.getSerializer(serDataType);
if (metaSerializer.getMimeType().matchEncoding(targetContentType)) {
return new EscMeta(dataType, dataContentType, metaType, metaSerializer.getMimeType(), commonEvent.getMeta());
}
final byte[] serMeta = metaSerializer.marshal(commonEvent.getMeta(), serDataType);
final EnhancedMimeType metaContentType = contentType(metaSerializer.getMimeType(), targetContentType);
return new EscMeta(dataType, dataContentType, metaType, metaContentType, new Base64Data(serMeta));
} | [
"public",
"static",
"EscMeta",
"createEscMeta",
"(",
"@",
"NotNull",
"final",
"SerializerRegistry",
"registry",
",",
"@",
"NotNull",
"final",
"EnhancedMimeType",
"targetContentType",
",",
"@",
"Nullable",
"final",
"CommonEvent",
"commonEvent",
")",
"{",
"Contract",
... | Create meta information for a given a {@link CommonEvent}.
@param registry
Registry with serializers.
@param targetContentType
Content type that will later be used to serialize the created result.
@param commonEvent
Event to create meta information for.
@return New meta instance. | [
"Create",
"meta",
"information",
"for",
"a",
"given",
"a",
"{",
"@link",
"CommonEvent",
"}",
"."
] | train | https://github.com/fuinorg/event-store-commons/blob/ea175582d8cda2b5a6d2fe52bbb2f1c183eee77c/spi/src/main/java/org/fuin/esc/spi/EscSpiUtils.java#L197-L226 |
adessoAG/wicked-charts | highcharts-wrapper/src/main/java/de/adesso/wickedcharts/highcharts/jackson/JsonRenderer.java | JsonRenderer.addSerializer | public <T> void addSerializer(final Class<T> clazz, final JsonSerializer<T> serializer) {
this.jacksonModule.addSerializer(clazz, serializer);
} | java | public <T> void addSerializer(final Class<T> clazz, final JsonSerializer<T> serializer) {
this.jacksonModule.addSerializer(clazz, serializer);
} | [
"public",
"<",
"T",
">",
"void",
"addSerializer",
"(",
"final",
"Class",
"<",
"T",
">",
"clazz",
",",
"final",
"JsonSerializer",
"<",
"T",
">",
"serializer",
")",
"{",
"this",
".",
"jacksonModule",
".",
"addSerializer",
"(",
"clazz",
",",
"serializer",
"... | This method gives the opportunity to add a custom serializer to serializer
one of the highchart option classes. It may be neccessary to serialize
certain option classes differently for different web frameworks.
@param clazz the option class
@param serializer the serializer responsible for serializing objects of the option
class.
@param <T> the class we need a serializer for | [
"This",
"method",
"gives",
"the",
"opportunity",
"to",
"add",
"a",
"custom",
"serializer",
"to",
"serializer",
"one",
"of",
"the",
"highchart",
"option",
"classes",
".",
"It",
"may",
"be",
"neccessary",
"to",
"serialize",
"certain",
"option",
"classes",
"diffe... | train | https://github.com/adessoAG/wicked-charts/blob/498aceff025f612e22ba5135b26531afeabac03c/highcharts-wrapper/src/main/java/de/adesso/wickedcharts/highcharts/jackson/JsonRenderer.java#L65-L67 |
mgormley/pacaya | src/main/java/edu/jhu/pacaya/autodiff/StochasticGradientApproximation.java | StochasticGradientApproximation.getEpsilon | private static double getEpsilon(IntDoubleVector x, IntDoubleVector d) {
double machineEpsilon = 2.2204460492503131e-16;
double xInfNorm = DoubleArrays.infinityNorm(x.toNativeArray());
double dInfNorm = DoubleArrays.infinityNorm(d.toNativeArray());
return machineEpsilon * (1.0 + xInfNorm) / dInfNorm;
} | java | private static double getEpsilon(IntDoubleVector x, IntDoubleVector d) {
double machineEpsilon = 2.2204460492503131e-16;
double xInfNorm = DoubleArrays.infinityNorm(x.toNativeArray());
double dInfNorm = DoubleArrays.infinityNorm(d.toNativeArray());
return machineEpsilon * (1.0 + xInfNorm) / dInfNorm;
} | [
"private",
"static",
"double",
"getEpsilon",
"(",
"IntDoubleVector",
"x",
",",
"IntDoubleVector",
"d",
")",
"{",
"double",
"machineEpsilon",
"=",
"2.2204460492503131e-16",
";",
"double",
"xInfNorm",
"=",
"DoubleArrays",
".",
"infinityNorm",
"(",
"x",
".",
"toNativ... | Gets an epsilon constant as advised by Andrei (2009).
See also, http://timvieira.github.io/blog/post/2014/02/10/gradient-vector-product/. | [
"Gets",
"an",
"epsilon",
"constant",
"as",
"advised",
"by",
"Andrei",
"(",
"2009",
")",
".",
"See",
"also",
"http",
":",
"//",
"timvieira",
".",
"github",
".",
"io",
"/",
"blog",
"/",
"post",
"/",
"2014",
"/",
"02",
"/",
"10",
"/",
"gradient",
"-",... | train | https://github.com/mgormley/pacaya/blob/786294cbac7cc65dbc32210c10acc32ed0c69233/src/main/java/edu/jhu/pacaya/autodiff/StochasticGradientApproximation.java#L94-L99 |
facebookarchive/hadoop-20 | src/hdfs/org/apache/hadoop/hdfs/tools/offlineImageViewer/ImageLoaderCurrent.java | ImageLoaderCurrent.processLocalNameINodes | private void processLocalNameINodes(DataInputStream in, ImageVisitor v,
long numInodes, boolean skipBlocks) throws IOException {
// process root
processINode(in, v, skipBlocks, "");
numInodes--;
while (numInodes > 0) {
numInodes -= processDirectory(in, v, skipBlocks);
}
} | java | private void processLocalNameINodes(DataInputStream in, ImageVisitor v,
long numInodes, boolean skipBlocks) throws IOException {
// process root
processINode(in, v, skipBlocks, "");
numInodes--;
while (numInodes > 0) {
numInodes -= processDirectory(in, v, skipBlocks);
}
} | [
"private",
"void",
"processLocalNameINodes",
"(",
"DataInputStream",
"in",
",",
"ImageVisitor",
"v",
",",
"long",
"numInodes",
",",
"boolean",
"skipBlocks",
")",
"throws",
"IOException",
"{",
"// process root",
"processINode",
"(",
"in",
",",
"v",
",",
"skipBlocks... | Process image with full path name
@param in image stream
@param v visitor
@param numInodes number of indoes to read
@param skipBlocks skip blocks or not
@throws IOException if there is any error occurs | [
"Process",
"image",
"with",
"full",
"path",
"name"
] | train | https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/hdfs/org/apache/hadoop/hdfs/tools/offlineImageViewer/ImageLoaderCurrent.java#L346-L354 |
google/j2objc | xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xml/utils/DOMHelper.java | DOMHelper.locateAttrParent | private static Node locateAttrParent(Element elem, Node attr)
{
Node parent = null;
// This should only be called for Level 1 DOMs, so we don't have to
// worry about namespace issues. In later levels, it's possible
// for a DOM to have two Attrs with the same NodeName but
// different namespaces, and we'd need to get getAttributeNodeNS...
// but later levels also have Attr.getOwnerElement.
Attr check=elem.getAttributeNode(attr.getNodeName());
if(check==attr)
parent = elem;
if (null == parent)
{
for (Node node = elem.getFirstChild(); null != node;
node = node.getNextSibling())
{
if (Node.ELEMENT_NODE == node.getNodeType())
{
parent = locateAttrParent((Element) node, attr);
if (null != parent)
break;
}
}
}
return parent;
} | java | private static Node locateAttrParent(Element elem, Node attr)
{
Node parent = null;
// This should only be called for Level 1 DOMs, so we don't have to
// worry about namespace issues. In later levels, it's possible
// for a DOM to have two Attrs with the same NodeName but
// different namespaces, and we'd need to get getAttributeNodeNS...
// but later levels also have Attr.getOwnerElement.
Attr check=elem.getAttributeNode(attr.getNodeName());
if(check==attr)
parent = elem;
if (null == parent)
{
for (Node node = elem.getFirstChild(); null != node;
node = node.getNextSibling())
{
if (Node.ELEMENT_NODE == node.getNodeType())
{
parent = locateAttrParent((Element) node, attr);
if (null != parent)
break;
}
}
}
return parent;
} | [
"private",
"static",
"Node",
"locateAttrParent",
"(",
"Element",
"elem",
",",
"Node",
"attr",
")",
"{",
"Node",
"parent",
"=",
"null",
";",
"// This should only be called for Level 1 DOMs, so we don't have to",
"// worry about namespace issues. In later levels, it's possible",
... | Support for getParentOfNode; walks a DOM tree until it finds
the Element which owns the Attr. This is hugely expensive, and
if at all possible you should use the DOM Level 2 Attr.ownerElement()
method instead.
<p>
The DOM Level 1 developers expected that folks would keep track
of the last Element they'd seen and could recover the info from
that source. Obviously that doesn't work very well if the only
information you've been presented with is the Attr. The DOM Level 2
getOwnerElement() method fixes that, but only for Level 2 and
later DOMs.
@param elem Element whose subtree is to be searched for this Attr
@param attr Attr whose owner is to be located.
@return the first Element whose attribute list includes the provided
attr. In modern DOMs, this will also be the only such Element. (Early
DOMs had some hope that Attrs might be sharable, but this idea has
been abandoned.) | [
"Support",
"for",
"getParentOfNode",
";",
"walks",
"a",
"DOM",
"tree",
"until",
"it",
"finds",
"the",
"Element",
"which",
"owns",
"the",
"Attr",
".",
"This",
"is",
"hugely",
"expensive",
"and",
"if",
"at",
"all",
"possible",
"you",
"should",
"use",
"the",
... | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xml/utils/DOMHelper.java#L1194-L1224 |
smartsheet-platform/smartsheet-java-sdk | src/main/java/com/smartsheet/api/internal/http/DefaultHttpClient.java | DefaultHttpClient.calcBackoff | public long calcBackoff(int previousAttempts, long totalElapsedTimeMillis, Error error) {
long backoffMillis = (long)(Math.pow(2, previousAttempts) * 1000) + new Random().nextInt(1000);
if(totalElapsedTimeMillis + backoffMillis > maxRetryTimeMillis) {
logger.info("Elapsed time " + totalElapsedTimeMillis + " + backoff time " + backoffMillis +
" exceeds max retry time " + maxRetryTimeMillis + ", exiting retry loop");
return -1;
}
return backoffMillis;
} | java | public long calcBackoff(int previousAttempts, long totalElapsedTimeMillis, Error error) {
long backoffMillis = (long)(Math.pow(2, previousAttempts) * 1000) + new Random().nextInt(1000);
if(totalElapsedTimeMillis + backoffMillis > maxRetryTimeMillis) {
logger.info("Elapsed time " + totalElapsedTimeMillis + " + backoff time " + backoffMillis +
" exceeds max retry time " + maxRetryTimeMillis + ", exiting retry loop");
return -1;
}
return backoffMillis;
} | [
"public",
"long",
"calcBackoff",
"(",
"int",
"previousAttempts",
",",
"long",
"totalElapsedTimeMillis",
",",
"Error",
"error",
")",
"{",
"long",
"backoffMillis",
"=",
"(",
"long",
")",
"(",
"Math",
".",
"pow",
"(",
"2",
",",
"previousAttempts",
")",
"*",
"... | The backoff calculation routine. Uses exponential backoff. If the maximum elapsed time
has expired, this calculation returns -1 causing the caller to fall out of the retry loop.
@param previousAttempts
@param totalElapsedTimeMillis
@param error
@return -1 to fall out of retry loop, positive number indicates backoff time | [
"The",
"backoff",
"calculation",
"routine",
".",
"Uses",
"exponential",
"backoff",
".",
"If",
"the",
"maximum",
"elapsed",
"time",
"has",
"expired",
"this",
"calculation",
"returns",
"-",
"1",
"causing",
"the",
"caller",
"to",
"fall",
"out",
"of",
"the",
"re... | train | https://github.com/smartsheet-platform/smartsheet-java-sdk/blob/f60e264412076271f83b65889ef9b891fad83df8/src/main/java/com/smartsheet/api/internal/http/DefaultHttpClient.java#L419-L429 |
google/closure-templates | java/src/com/google/template/soy/jssrc/internal/NullSafeAccumulator.java | NullSafeAccumulator.bracketAccess | NullSafeAccumulator bracketAccess(Expression arg, boolean nullSafe) {
chain.add(new Bracket(arg, nullSafe));
// With a bracket access we no longer need to unpack the entire list, just a singular object.
accessType = AccessType.SINGULAR;
return this;
} | java | NullSafeAccumulator bracketAccess(Expression arg, boolean nullSafe) {
chain.add(new Bracket(arg, nullSafe));
// With a bracket access we no longer need to unpack the entire list, just a singular object.
accessType = AccessType.SINGULAR;
return this;
} | [
"NullSafeAccumulator",
"bracketAccess",
"(",
"Expression",
"arg",
",",
"boolean",
"nullSafe",
")",
"{",
"chain",
".",
"add",
"(",
"new",
"Bracket",
"(",
"arg",
",",
"nullSafe",
")",
")",
";",
"// With a bracket access we no longer need to unpack the entire list, just a ... | Extends the access chain with a bracket access to the given value.
@param nullSafe If true, code will be generated to ensure the chain is non-null before
dereferencing {@code arg}. | [
"Extends",
"the",
"access",
"chain",
"with",
"a",
"bracket",
"access",
"to",
"the",
"given",
"value",
"."
] | train | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jssrc/internal/NullSafeAccumulator.java#L113-L118 |
Azure/azure-sdk-for-java | batch/data-plane/src/main/java/com/microsoft/azure/batch/protocol/implementation/TasksImpl.java | TasksImpl.addAsync | public Observable<Void> addAsync(String jobId, TaskAddParameter task, TaskAddOptions taskAddOptions) {
return addWithServiceResponseAsync(jobId, task, taskAddOptions).map(new Func1<ServiceResponseWithHeaders<Void, TaskAddHeaders>, Void>() {
@Override
public Void call(ServiceResponseWithHeaders<Void, TaskAddHeaders> response) {
return response.body();
}
});
} | java | public Observable<Void> addAsync(String jobId, TaskAddParameter task, TaskAddOptions taskAddOptions) {
return addWithServiceResponseAsync(jobId, task, taskAddOptions).map(new Func1<ServiceResponseWithHeaders<Void, TaskAddHeaders>, Void>() {
@Override
public Void call(ServiceResponseWithHeaders<Void, TaskAddHeaders> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"Void",
">",
"addAsync",
"(",
"String",
"jobId",
",",
"TaskAddParameter",
"task",
",",
"TaskAddOptions",
"taskAddOptions",
")",
"{",
"return",
"addWithServiceResponseAsync",
"(",
"jobId",
",",
"task",
",",
"taskAddOptions",
")",
".",
... | Adds a task to the specified job.
The maximum lifetime of a task from addition to completion is 180 days. If a task has not completed within 180 days of being added it will be terminated by the Batch service and left in whatever state it was in at that time.
@param jobId The ID of the job to which the task is to be added.
@param task The task to be added.
@param taskAddOptions Additional parameters for the operation
@throws IllegalArgumentException thrown if parameters fail the validation
@return the {@link ServiceResponseWithHeaders} object if successful. | [
"Adds",
"a",
"task",
"to",
"the",
"specified",
"job",
".",
"The",
"maximum",
"lifetime",
"of",
"a",
"task",
"from",
"addition",
"to",
"completion",
"is",
"180",
"days",
".",
"If",
"a",
"task",
"has",
"not",
"completed",
"within",
"180",
"days",
"of",
"... | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/batch/data-plane/src/main/java/com/microsoft/azure/batch/protocol/implementation/TasksImpl.java#L268-L275 |
alkacon/opencms-core | src-gwt/org/opencms/gwt/client/ui/CmsListItemWidget.java | CmsListItemWidget.truncateAdditionalInfo | public void truncateAdditionalInfo(final String textMetricsPrefix, final int widgetWidth) {
for (Widget addInfo : m_additionalInfo) {
((AdditionalInfoItem)addInfo).truncate(textMetricsPrefix, widgetWidth - 10);
}
} | java | public void truncateAdditionalInfo(final String textMetricsPrefix, final int widgetWidth) {
for (Widget addInfo : m_additionalInfo) {
((AdditionalInfoItem)addInfo).truncate(textMetricsPrefix, widgetWidth - 10);
}
} | [
"public",
"void",
"truncateAdditionalInfo",
"(",
"final",
"String",
"textMetricsPrefix",
",",
"final",
"int",
"widgetWidth",
")",
"{",
"for",
"(",
"Widget",
"addInfo",
":",
"m_additionalInfo",
")",
"{",
"(",
"(",
"AdditionalInfoItem",
")",
"addInfo",
")",
".",
... | Truncates the additional info items.<p>
@param textMetricsPrefix the text metrics prefix
@param widgetWidth the width to truncate to | [
"Truncates",
"the",
"additional",
"info",
"items",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/gwt/client/ui/CmsListItemWidget.java#L985-L990 |
pinterest/secor | src/main/java/com/pinterest/secor/uploader/Uploader.java | Uploader.createReader | protected FileReader createReader(LogFilePath srcPath, CompressionCodec codec) throws Exception {
return ReflectionUtil.createFileReader(
mConfig.getFileReaderWriterFactory(),
srcPath,
codec,
mConfig
);
} | java | protected FileReader createReader(LogFilePath srcPath, CompressionCodec codec) throws Exception {
return ReflectionUtil.createFileReader(
mConfig.getFileReaderWriterFactory(),
srcPath,
codec,
mConfig
);
} | [
"protected",
"FileReader",
"createReader",
"(",
"LogFilePath",
"srcPath",
",",
"CompressionCodec",
"codec",
")",
"throws",
"Exception",
"{",
"return",
"ReflectionUtil",
".",
"createFileReader",
"(",
"mConfig",
".",
"getFileReaderWriterFactory",
"(",
")",
",",
"srcPath... | This method is intended to be overwritten in tests.
@param srcPath source Path
@param codec compression codec
@return FileReader created file reader
@throws Exception on error | [
"This",
"method",
"is",
"intended",
"to",
"be",
"overwritten",
"in",
"tests",
"."
] | train | https://github.com/pinterest/secor/blob/4099ff061db392f11044e57dedf46c1617895278/src/main/java/com/pinterest/secor/uploader/Uploader.java#L162-L169 |
HtmlUnit/htmlunit-cssparser | src/main/java/com/gargoylesoftware/css/parser/CSSOMParser.java | CSSOMParser.parseStyleSheet | public CSSStyleSheetImpl parseStyleSheet(final InputSource source, final String href) throws IOException {
final CSSOMHandler handler = new CSSOMHandler();
handler.setHref(href);
parser_.setDocumentHandler(handler);
parser_.parseStyleSheet(source);
final Object o = handler.getRoot();
if (o instanceof CSSStyleSheetImpl) {
return (CSSStyleSheetImpl) o;
}
return null;
} | java | public CSSStyleSheetImpl parseStyleSheet(final InputSource source, final String href) throws IOException {
final CSSOMHandler handler = new CSSOMHandler();
handler.setHref(href);
parser_.setDocumentHandler(handler);
parser_.parseStyleSheet(source);
final Object o = handler.getRoot();
if (o instanceof CSSStyleSheetImpl) {
return (CSSStyleSheetImpl) o;
}
return null;
} | [
"public",
"CSSStyleSheetImpl",
"parseStyleSheet",
"(",
"final",
"InputSource",
"source",
",",
"final",
"String",
"href",
")",
"throws",
"IOException",
"{",
"final",
"CSSOMHandler",
"handler",
"=",
"new",
"CSSOMHandler",
"(",
")",
";",
"handler",
".",
"setHref",
... | Parses a SAC input source into a CSSOM style sheet.
@param source the SAC input source
@param href the href
@return the CSSOM style sheet
@throws IOException if the underlying SAC parser throws an IOException | [
"Parses",
"a",
"SAC",
"input",
"source",
"into",
"a",
"CSSOM",
"style",
"sheet",
"."
] | train | https://github.com/HtmlUnit/htmlunit-cssparser/blob/384e4170737169b5b4c87c5766495d9b8a6d3866/src/main/java/com/gargoylesoftware/css/parser/CSSOMParser.java#L79-L89 |
aws/aws-sdk-java | aws-java-sdk-robomaker/src/main/java/com/amazonaws/services/robomaker/model/CreateDeploymentJobResult.java | CreateDeploymentJobResult.withTags | public CreateDeploymentJobResult withTags(java.util.Map<String, String> tags) {
setTags(tags);
return this;
} | java | public CreateDeploymentJobResult withTags(java.util.Map<String, String> tags) {
setTags(tags);
return this;
} | [
"public",
"CreateDeploymentJobResult",
"withTags",
"(",
"java",
".",
"util",
".",
"Map",
"<",
"String",
",",
"String",
">",
"tags",
")",
"{",
"setTags",
"(",
"tags",
")",
";",
"return",
"this",
";",
"}"
] | <p>
The list of all tags added to the deployment job.
</p>
@param tags
The list of all tags added to the deployment job.
@return Returns a reference to this object so that method calls can be chained together. | [
"<p",
">",
"The",
"list",
"of",
"all",
"tags",
"added",
"to",
"the",
"deployment",
"job",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-robomaker/src/main/java/com/amazonaws/services/robomaker/model/CreateDeploymentJobResult.java#L1206-L1209 |
grpc/grpc-java | netty/src/main/java/io/grpc/netty/WriteBufferingAndExceptionHandler.java | WriteBufferingAndExceptionHandler.close | @Override
public void close(ChannelHandlerContext ctx, ChannelPromise future) throws Exception {
Status status = Status.UNAVAILABLE.withDescription(
"Connection closing while performing protocol negotiation for " + ctx.pipeline().names());
failWrites(status.asRuntimeException());
super.close(ctx, future);
} | java | @Override
public void close(ChannelHandlerContext ctx, ChannelPromise future) throws Exception {
Status status = Status.UNAVAILABLE.withDescription(
"Connection closing while performing protocol negotiation for " + ctx.pipeline().names());
failWrites(status.asRuntimeException());
super.close(ctx, future);
} | [
"@",
"Override",
"public",
"void",
"close",
"(",
"ChannelHandlerContext",
"ctx",
",",
"ChannelPromise",
"future",
")",
"throws",
"Exception",
"{",
"Status",
"status",
"=",
"Status",
".",
"UNAVAILABLE",
".",
"withDescription",
"(",
"\"Connection closing while performin... | If we are still performing protocol negotiation, then this will propagate failures to all
buffered writes. | [
"If",
"we",
"are",
"still",
"performing",
"protocol",
"negotiation",
"then",
"this",
"will",
"propagate",
"failures",
"to",
"all",
"buffered",
"writes",
"."
] | train | https://github.com/grpc/grpc-java/blob/973885457f9609de232d2553b82c67f6c3ff57bf/netty/src/main/java/io/grpc/netty/WriteBufferingAndExceptionHandler.java#L160-L166 |
tvesalainen/util | util/src/main/java/org/vesalainen/navi/LocalLongitude.java | LocalLongitude.getInstance | public static LocalLongitude getInstance(double longitude, double latitude)
{
if (Math.abs(longitude) < 179)
{
return new LocalLongitude(latitude);
}
else
{
return new PacificLongitude(latitude);
}
} | java | public static LocalLongitude getInstance(double longitude, double latitude)
{
if (Math.abs(longitude) < 179)
{
return new LocalLongitude(latitude);
}
else
{
return new PacificLongitude(latitude);
}
} | [
"public",
"static",
"LocalLongitude",
"getInstance",
"(",
"double",
"longitude",
",",
"double",
"latitude",
")",
"{",
"if",
"(",
"Math",
".",
"abs",
"(",
"longitude",
")",
"<",
"179",
")",
"{",
"return",
"new",
"LocalLongitude",
"(",
"latitude",
")",
";",
... | Returns LocalLongitude instance which is usable about 60 NM around starting
point.
@param longitude
@param latitude
@return | [
"Returns",
"LocalLongitude",
"instance",
"which",
"is",
"usable",
"about",
"60",
"NM",
"around",
"starting",
"point",
"."
] | train | https://github.com/tvesalainen/util/blob/bba7a44689f638ffabc8be40a75bdc9a33676433/util/src/main/java/org/vesalainen/navi/LocalLongitude.java#L46-L56 |
wmdietl/jsr308-langtools | src/share/classes/com/sun/tools/doclets/internal/toolkit/util/ClassDocCatalog.java | ClassDocCatalog.addClass | private void addClass(ClassDoc classdoc, Map<String,Set<ClassDoc>> map) {
PackageDoc pkg = classdoc.containingPackage();
if (pkg.isIncluded() || (configuration.nodeprecated && Util.isDeprecated(pkg))) {
//No need to catalog this class if it's package is
//included on the command line or if -nodeprecated option is set
// and the containing package is marked as deprecated.
return;
}
String key = Util.getPackageName(pkg);
Set<ClassDoc> s = map.get(key);
if (s == null) {
packageSet.add(key);
s = new HashSet<ClassDoc>();
}
s.add(classdoc);
map.put(key, s);
} | java | private void addClass(ClassDoc classdoc, Map<String,Set<ClassDoc>> map) {
PackageDoc pkg = classdoc.containingPackage();
if (pkg.isIncluded() || (configuration.nodeprecated && Util.isDeprecated(pkg))) {
//No need to catalog this class if it's package is
//included on the command line or if -nodeprecated option is set
// and the containing package is marked as deprecated.
return;
}
String key = Util.getPackageName(pkg);
Set<ClassDoc> s = map.get(key);
if (s == null) {
packageSet.add(key);
s = new HashSet<ClassDoc>();
}
s.add(classdoc);
map.put(key, s);
} | [
"private",
"void",
"addClass",
"(",
"ClassDoc",
"classdoc",
",",
"Map",
"<",
"String",
",",
"Set",
"<",
"ClassDoc",
">",
">",
"map",
")",
"{",
"PackageDoc",
"pkg",
"=",
"classdoc",
".",
"containingPackage",
"(",
")",
";",
"if",
"(",
"pkg",
".",
"isIncl... | Add the given class to the given map.
@param classdoc the ClassDoc to add to the catelog.
@param map the Map to add the ClassDoc to. | [
"Add",
"the",
"given",
"class",
"to",
"the",
"given",
"map",
"."
] | train | https://github.com/wmdietl/jsr308-langtools/blob/8812d28c20f4de070a0dd6de1b45602431379834/src/share/classes/com/sun/tools/doclets/internal/toolkit/util/ClassDocCatalog.java#L156-L174 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.