repository_name stringlengths 7 58 | func_path_in_repository stringlengths 11 218 | func_name stringlengths 4 140 | whole_func_string stringlengths 153 5.32k | language stringclasses 1
value | func_code_string stringlengths 72 4k | func_code_tokens listlengths 20 832 | func_documentation_string stringlengths 61 2k | func_documentation_tokens listlengths 1 647 | split_name stringclasses 1
value | func_code_url stringlengths 102 339 |
|---|---|---|---|---|---|---|---|---|---|---|
Coveros/selenified | src/main/java/com/coveros/selenified/element/Element.java | Element.isScrolledTo | private void isScrolledTo(String action, String expected) {
"""
Determines if the element scrolled towards is now currently displayed on the
screen
@param action - what is the action occurring
@param expected - what is the expected outcome of said action
"""
WebElement webElement = getWebElement();
long elementPosition = webElement.getLocation().getY();
JavascriptExecutor js = (JavascriptExecutor) driver;
int scrollHeight = ((Number) js.executeScript("return document.documentElement.scrollTop || document.body.scrollTop;")).intValue();
int viewportHeight = ((Number) js.executeScript("return Math.max(document.documentElement.clientHeight, window.innerHeight || 0);")).intValue();
if (elementPosition < scrollHeight || elementPosition > viewportHeight + scrollHeight) {
reporter.fail(action, expected, prettyOutputStart() + " was scrolled to, but is not within the current viewport");
} else {
reporter.pass(action, expected, prettyOutputStart() + " is properly scrolled to and within the current viewport");
}
} | java | private void isScrolledTo(String action, String expected) {
WebElement webElement = getWebElement();
long elementPosition = webElement.getLocation().getY();
JavascriptExecutor js = (JavascriptExecutor) driver;
int scrollHeight = ((Number) js.executeScript("return document.documentElement.scrollTop || document.body.scrollTop;")).intValue();
int viewportHeight = ((Number) js.executeScript("return Math.max(document.documentElement.clientHeight, window.innerHeight || 0);")).intValue();
if (elementPosition < scrollHeight || elementPosition > viewportHeight + scrollHeight) {
reporter.fail(action, expected, prettyOutputStart() + " was scrolled to, but is not within the current viewport");
} else {
reporter.pass(action, expected, prettyOutputStart() + " is properly scrolled to and within the current viewport");
}
} | [
"private",
"void",
"isScrolledTo",
"(",
"String",
"action",
",",
"String",
"expected",
")",
"{",
"WebElement",
"webElement",
"=",
"getWebElement",
"(",
")",
";",
"long",
"elementPosition",
"=",
"webElement",
".",
"getLocation",
"(",
")",
".",
"getY",
"(",
")... | Determines if the element scrolled towards is now currently displayed on the
screen
@param action - what is the action occurring
@param expected - what is the expected outcome of said action | [
"Determines",
"if",
"the",
"element",
"scrolled",
"towards",
"is",
"now",
"currently",
"displayed",
"on",
"the",
"screen"
] | train | https://github.com/Coveros/selenified/blob/396cc1f010dd69eed33cc5061c41253de246a4cd/src/main/java/com/coveros/selenified/element/Element.java#L1112-L1124 |
lettuce-io/lettuce-core | src/main/java/io/lettuce/core/dynamic/ConversionService.java | ConversionService.addConverter | @SuppressWarnings("rawtypes")
public void addConverter(Function<?, ?> converter) {
"""
Register a converter {@link Function}.
@param converter the converter.
"""
LettuceAssert.notNull(converter, "Converter must not be null");
ClassTypeInformation<? extends Function> classTypeInformation = ClassTypeInformation.from(converter.getClass());
TypeInformation<?> typeInformation = classTypeInformation.getSuperTypeInformation(Function.class);
List<TypeInformation<?>> typeArguments = typeInformation.getTypeArguments();
ConvertiblePair pair = new ConvertiblePair(typeArguments.get(0).getType(), typeArguments.get(1).getType());
converterMap.put(pair, converter);
} | java | @SuppressWarnings("rawtypes")
public void addConverter(Function<?, ?> converter) {
LettuceAssert.notNull(converter, "Converter must not be null");
ClassTypeInformation<? extends Function> classTypeInformation = ClassTypeInformation.from(converter.getClass());
TypeInformation<?> typeInformation = classTypeInformation.getSuperTypeInformation(Function.class);
List<TypeInformation<?>> typeArguments = typeInformation.getTypeArguments();
ConvertiblePair pair = new ConvertiblePair(typeArguments.get(0).getType(), typeArguments.get(1).getType());
converterMap.put(pair, converter);
} | [
"@",
"SuppressWarnings",
"(",
"\"rawtypes\"",
")",
"public",
"void",
"addConverter",
"(",
"Function",
"<",
"?",
",",
"?",
">",
"converter",
")",
"{",
"LettuceAssert",
".",
"notNull",
"(",
"converter",
",",
"\"Converter must not be null\"",
")",
";",
"ClassTypeIn... | Register a converter {@link Function}.
@param converter the converter. | [
"Register",
"a",
"converter",
"{",
"@link",
"Function",
"}",
"."
] | train | https://github.com/lettuce-io/lettuce-core/blob/b6de74e384dea112e3656684ca3f50cdfd6c8e0d/src/main/java/io/lettuce/core/dynamic/ConversionService.java#L40-L51 |
landawn/AbacusUtil | src/com/landawn/abacus/util/Matth.java | Matth.saturatedSubtract | public static long saturatedSubtract(long a, long b) {
"""
Returns the difference of {@code a} and {@code b} unless it would overflow or underflow in
which case {@code Long.MAX_VALUE} or {@code Long.MIN_VALUE} is returned, respectively.
@since 20.0
"""
long naiveDifference = a - b;
if ((a ^ b) >= 0 | (a ^ naiveDifference) >= 0) {
// If a and b have the same signs or a has the same sign as the result then there was no
// overflow, return.
return naiveDifference;
}
// we did over/under flow
return Long.MAX_VALUE + ((naiveDifference >>> (Long.SIZE - 1)) ^ 1);
} | java | public static long saturatedSubtract(long a, long b) {
long naiveDifference = a - b;
if ((a ^ b) >= 0 | (a ^ naiveDifference) >= 0) {
// If a and b have the same signs or a has the same sign as the result then there was no
// overflow, return.
return naiveDifference;
}
// we did over/under flow
return Long.MAX_VALUE + ((naiveDifference >>> (Long.SIZE - 1)) ^ 1);
} | [
"public",
"static",
"long",
"saturatedSubtract",
"(",
"long",
"a",
",",
"long",
"b",
")",
"{",
"long",
"naiveDifference",
"=",
"a",
"-",
"b",
";",
"if",
"(",
"(",
"a",
"^",
"b",
")",
">=",
"0",
"|",
"(",
"a",
"^",
"naiveDifference",
")",
">=",
"0... | Returns the difference of {@code a} and {@code b} unless it would overflow or underflow in
which case {@code Long.MAX_VALUE} or {@code Long.MIN_VALUE} is returned, respectively.
@since 20.0 | [
"Returns",
"the",
"difference",
"of",
"{",
"@code",
"a",
"}",
"and",
"{",
"@code",
"b",
"}",
"unless",
"it",
"would",
"overflow",
"or",
"underflow",
"in",
"which",
"case",
"{",
"@code",
"Long",
".",
"MAX_VALUE",
"}",
"or",
"{",
"@code",
"Long",
".",
... | train | https://github.com/landawn/AbacusUtil/blob/544b7720175d15e9329f83dd22a8cc5fa4515e12/src/com/landawn/abacus/util/Matth.java#L1601-L1610 |
intuit/QuickBooks-V3-Java-SDK | oauth2-platform-api/src/main/java/com/intuit/oauth2/client/OAuth2PlatformClient.java | OAuth2PlatformClient.getUrlParameters | private List<NameValuePair> getUrlParameters(String action, String token, String redirectUri) {
"""
Method to build post parameters
@param action
@param token
@param redirectUri
@return
"""
List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
if (action == "revoke") {
urlParameters.add(new BasicNameValuePair("token", token));
} else if (action == "refresh") {
urlParameters.add(new BasicNameValuePair("refresh_token", token));
urlParameters.add(new BasicNameValuePair("grant_type", "refresh_token"));
} else {
urlParameters.add(new BasicNameValuePair("code", token));
urlParameters.add(new BasicNameValuePair("redirect_uri", redirectUri));
urlParameters.add(new BasicNameValuePair("grant_type", "authorization_code"));
}
return urlParameters;
} | java | private List<NameValuePair> getUrlParameters(String action, String token, String redirectUri) {
List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
if (action == "revoke") {
urlParameters.add(new BasicNameValuePair("token", token));
} else if (action == "refresh") {
urlParameters.add(new BasicNameValuePair("refresh_token", token));
urlParameters.add(new BasicNameValuePair("grant_type", "refresh_token"));
} else {
urlParameters.add(new BasicNameValuePair("code", token));
urlParameters.add(new BasicNameValuePair("redirect_uri", redirectUri));
urlParameters.add(new BasicNameValuePair("grant_type", "authorization_code"));
}
return urlParameters;
} | [
"private",
"List",
"<",
"NameValuePair",
">",
"getUrlParameters",
"(",
"String",
"action",
",",
"String",
"token",
",",
"String",
"redirectUri",
")",
"{",
"List",
"<",
"NameValuePair",
">",
"urlParameters",
"=",
"new",
"ArrayList",
"<",
"NameValuePair",
">",
"... | Method to build post parameters
@param action
@param token
@param redirectUri
@return | [
"Method",
"to",
"build",
"post",
"parameters"
] | train | https://github.com/intuit/QuickBooks-V3-Java-SDK/blob/59f988d0776d46620d0b34711c411b2b5b1da06b/oauth2-platform-api/src/main/java/com/intuit/oauth2/client/OAuth2PlatformClient.java#L163-L176 |
Waikato/moa | moa/src/main/java/moa/gui/visualization/GraphMultiCurve.java | GraphMultiCurve.setGraph | protected void setGraph(MeasureCollection[] measures, MeasureCollection[] measureStds, int[] processFrequencies, Color[] colors) {
"""
Updates the measure collection information and repaints the curves.
@param measures information about the curves
@param measureStds standard deviation of the measures
@param processFrequencies information about the process frequencies of
the curves
@param colors color encodings of the curves
"""
// this.processFrequencies = processFrequencies;
super.setGraph(measures, measureStds, colors);
} | java | protected void setGraph(MeasureCollection[] measures, MeasureCollection[] measureStds, int[] processFrequencies, Color[] colors){
// this.processFrequencies = processFrequencies;
super.setGraph(measures, measureStds, colors);
} | [
"protected",
"void",
"setGraph",
"(",
"MeasureCollection",
"[",
"]",
"measures",
",",
"MeasureCollection",
"[",
"]",
"measureStds",
",",
"int",
"[",
"]",
"processFrequencies",
",",
"Color",
"[",
"]",
"colors",
")",
"{",
"// \tthis.processFrequencies = processFreq... | Updates the measure collection information and repaints the curves.
@param measures information about the curves
@param measureStds standard deviation of the measures
@param processFrequencies information about the process frequencies of
the curves
@param colors color encodings of the curves | [
"Updates",
"the",
"measure",
"collection",
"information",
"and",
"repaints",
"the",
"curves",
"."
] | train | https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/gui/visualization/GraphMultiCurve.java#L49-L52 |
sarxos/v4l4j | src/main/java/au/edu/jcu/v4l4j/PushSource.java | PushSource.stopCapture | public final void stopCapture() {
"""
This method instructs this source to stop frame delivery
to the {@link CaptureCallback} object.
@throws StateException if the capture has already been stopped
"""
synchronized (this) {
// make sure we are running
if ((state == STATE_STOPPED) || (state == STATE_ABOUT_TO_STOP))
//throw new StateException("The capture is about to stop");
return;
// update our state
state = STATE_ABOUT_TO_STOP;
}
if (thread.isAlive()) {
thread.interrupt();
// wait for thread to exit if the push thread is not the one
// trying to join
if (! Thread.currentThread().equals(thread)) {
while (state == STATE_ABOUT_TO_STOP) {
try {
// wait for thread to exit
thread.join();
//thread = null;
} catch (InterruptedException e) {
// interrupted while waiting for the thread to join
// keep waiting
// System.err.println("interrupted while waiting for frame pusher thread to complete");
// e.printStackTrace();
// throw new StateException("interrupted while waiting for frame pusher thread to complete", e);
}
}
}
}
} | java | public final void stopCapture() {
synchronized (this) {
// make sure we are running
if ((state == STATE_STOPPED) || (state == STATE_ABOUT_TO_STOP))
//throw new StateException("The capture is about to stop");
return;
// update our state
state = STATE_ABOUT_TO_STOP;
}
if (thread.isAlive()) {
thread.interrupt();
// wait for thread to exit if the push thread is not the one
// trying to join
if (! Thread.currentThread().equals(thread)) {
while (state == STATE_ABOUT_TO_STOP) {
try {
// wait for thread to exit
thread.join();
//thread = null;
} catch (InterruptedException e) {
// interrupted while waiting for the thread to join
// keep waiting
// System.err.println("interrupted while waiting for frame pusher thread to complete");
// e.printStackTrace();
// throw new StateException("interrupted while waiting for frame pusher thread to complete", e);
}
}
}
}
} | [
"public",
"final",
"void",
"stopCapture",
"(",
")",
"{",
"synchronized",
"(",
"this",
")",
"{",
"// make sure we are running",
"if",
"(",
"(",
"state",
"==",
"STATE_STOPPED",
")",
"||",
"(",
"state",
"==",
"STATE_ABOUT_TO_STOP",
")",
")",
"//throw new StateExcep... | This method instructs this source to stop frame delivery
to the {@link CaptureCallback} object.
@throws StateException if the capture has already been stopped | [
"This",
"method",
"instructs",
"this",
"source",
"to",
"stop",
"frame",
"delivery",
"to",
"the",
"{"
] | train | https://github.com/sarxos/v4l4j/blob/4fc0eec2c3a1a4260593f6ac03b7a8013e3804c9/src/main/java/au/edu/jcu/v4l4j/PushSource.java#L89-L122 |
lessthanoptimal/ddogleg | src/org/ddogleg/clustering/kmeans/InitializePlusPlus.java | InitializePlusPlus.updateDistances | protected final void updateDistances( List<double[]> points , double []clusterNew ) {
"""
Updates the list of distances from a point to the closest cluster. Update list of total distances
"""
totalDistance = 0;
for (int i = 0; i < distance.size(); i++) {
double dOld = distance.get(i);
double dNew = StandardKMeans_F64.distanceSq(points.get(i),clusterNew);
if( dNew < dOld ) {
distance.data[i] = dNew;
totalDistance += dNew;
} else {
totalDistance += dOld;
}
}
} | java | protected final void updateDistances( List<double[]> points , double []clusterNew ) {
totalDistance = 0;
for (int i = 0; i < distance.size(); i++) {
double dOld = distance.get(i);
double dNew = StandardKMeans_F64.distanceSq(points.get(i),clusterNew);
if( dNew < dOld ) {
distance.data[i] = dNew;
totalDistance += dNew;
} else {
totalDistance += dOld;
}
}
} | [
"protected",
"final",
"void",
"updateDistances",
"(",
"List",
"<",
"double",
"[",
"]",
">",
"points",
",",
"double",
"[",
"]",
"clusterNew",
")",
"{",
"totalDistance",
"=",
"0",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"distance",
".",
... | Updates the list of distances from a point to the closest cluster. Update list of total distances | [
"Updates",
"the",
"list",
"of",
"distances",
"from",
"a",
"point",
"to",
"the",
"closest",
"cluster",
".",
"Update",
"list",
"of",
"total",
"distances"
] | train | https://github.com/lessthanoptimal/ddogleg/blob/3786bf448ba23d0e04962dd08c34fa68de276029/src/org/ddogleg/clustering/kmeans/InitializePlusPlus.java#L110-L122 |
apache/incubator-gobblin | gobblin-utility/src/main/java/org/apache/gobblin/broker/SharedResourcesBrokerImpl.java | SharedResourcesBrokerImpl.getConfigView | public <K extends SharedResourceKey> KeyedScopedConfigViewImpl<S, K> getConfigView(S scope, K key, String factoryName) {
"""
Get a {@link org.apache.gobblin.broker.iface.ConfigView} for the input scope, key, and factory.
"""
Config config = ConfigFactory.empty();
for (ScopedConfig<S> scopedConfig : this.scopedConfigs) {
if (scopedConfig.getScopeType().equals(scopedConfig.getScopeType().rootScope())) {
config = ConfigUtils.getConfigOrEmpty(scopedConfig.getConfig(), factoryName).withFallback(config);
} else if (scope != null && SharedResourcesBrokerUtils.isScopeTypeAncestor(scope, scopedConfig.getScopeType())) {
Config tmpConfig = ConfigUtils.getConfigOrEmpty(scopedConfig.getConfig(), factoryName);
tmpConfig = ConfigUtils.getConfigOrEmpty(tmpConfig, scope.name());
config = tmpConfig.atKey(scope.name()).withFallback(config);
}
}
return new KeyedScopedConfigViewImpl<>(scope, key, factoryName, config);
} | java | public <K extends SharedResourceKey> KeyedScopedConfigViewImpl<S, K> getConfigView(S scope, K key, String factoryName) {
Config config = ConfigFactory.empty();
for (ScopedConfig<S> scopedConfig : this.scopedConfigs) {
if (scopedConfig.getScopeType().equals(scopedConfig.getScopeType().rootScope())) {
config = ConfigUtils.getConfigOrEmpty(scopedConfig.getConfig(), factoryName).withFallback(config);
} else if (scope != null && SharedResourcesBrokerUtils.isScopeTypeAncestor(scope, scopedConfig.getScopeType())) {
Config tmpConfig = ConfigUtils.getConfigOrEmpty(scopedConfig.getConfig(), factoryName);
tmpConfig = ConfigUtils.getConfigOrEmpty(tmpConfig, scope.name());
config = tmpConfig.atKey(scope.name()).withFallback(config);
}
}
return new KeyedScopedConfigViewImpl<>(scope, key, factoryName, config);
} | [
"public",
"<",
"K",
"extends",
"SharedResourceKey",
">",
"KeyedScopedConfigViewImpl",
"<",
"S",
",",
"K",
">",
"getConfigView",
"(",
"S",
"scope",
",",
"K",
"key",
",",
"String",
"factoryName",
")",
"{",
"Config",
"config",
"=",
"ConfigFactory",
".",
"empty"... | Get a {@link org.apache.gobblin.broker.iface.ConfigView} for the input scope, key, and factory. | [
"Get",
"a",
"{"
] | train | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-utility/src/main/java/org/apache/gobblin/broker/SharedResourcesBrokerImpl.java#L118-L132 |
infinispan/infinispan | server/hotrod/src/main/java/org/infinispan/server/hotrod/TransactionRequestProcessor.java | TransactionRequestProcessor.checkExistingTxForPrepare | private boolean checkExistingTxForPrepare(HotRodHeader header, PrepareCoordinator txCoordinator) {
"""
Checks if the transaction was already prepared in another node
<p>
The client can send multiple requests to the server (in case of timeout or similar). This request is ignored when
(1) the originator is still alive; (2) the transaction is prepared or committed/rolled-back
<p>
If the transaction isn't prepared and the originator left the cluster, the previous transaction is rolled-back and
a new one is started.
"""
TxState txState = txCoordinator.getTxState();
if (txState == null) {
return false;
}
if (txCoordinator.isAlive(txState.getOriginator())) {
//transaction started on another node but the node is still in the topology. 2 possible scenarios:
// #1, the topology isn't updated
// #2, the client timed-out waiting for the reply
//in any case, we send a ignore reply and the client is free to retry (or rollback)
writeNotExecuted(header);
return true;
}
//originator is dead...
//First phase state machine
//success ACTIVE -> PREPARING -> PREPARED
//failed ACTIVE -> MARK_ROLLBACK -> ROLLED_BACK or ACTIVE -> PREPARING -> ROLLED_BACK
//1PC success ACTIVE -> PREPARING -> MARK_COMMIT -> COMMITTED
switch (txState.getStatus()) {
case ACTIVE:
case PREPARING:
//rollback existing transaction and retry with a new one
txCoordinator.rollbackRemoteTransaction(txState.getGlobalTransaction());
return false;
case PREPARED:
//2PC since 1PC never reaches this state
writeResponse(header, createTransactionResponse(header, XAResource.XA_OK));
return true;
case MARK_ROLLBACK:
//make sure it is rolled back and reply to the client
txCoordinator.rollbackRemoteTransaction(txState.getGlobalTransaction());
case ROLLED_BACK:
writeResponse(header, createTransactionResponse(header, XAException.XA_RBROLLBACK));
return true;
case MARK_COMMIT:
writeResponse(header, createTransactionResponse(header, txCoordinator.onePhaseCommitRemoteTransaction(txState.getGlobalTransaction(), txState.getModifications())));
return true;
case COMMITTED:
writeResponse(header, createTransactionResponse(header, XAResource.XA_OK));
return true;
default:
throw new IllegalStateException();
}
} | java | private boolean checkExistingTxForPrepare(HotRodHeader header, PrepareCoordinator txCoordinator) {
TxState txState = txCoordinator.getTxState();
if (txState == null) {
return false;
}
if (txCoordinator.isAlive(txState.getOriginator())) {
//transaction started on another node but the node is still in the topology. 2 possible scenarios:
// #1, the topology isn't updated
// #2, the client timed-out waiting for the reply
//in any case, we send a ignore reply and the client is free to retry (or rollback)
writeNotExecuted(header);
return true;
}
//originator is dead...
//First phase state machine
//success ACTIVE -> PREPARING -> PREPARED
//failed ACTIVE -> MARK_ROLLBACK -> ROLLED_BACK or ACTIVE -> PREPARING -> ROLLED_BACK
//1PC success ACTIVE -> PREPARING -> MARK_COMMIT -> COMMITTED
switch (txState.getStatus()) {
case ACTIVE:
case PREPARING:
//rollback existing transaction and retry with a new one
txCoordinator.rollbackRemoteTransaction(txState.getGlobalTransaction());
return false;
case PREPARED:
//2PC since 1PC never reaches this state
writeResponse(header, createTransactionResponse(header, XAResource.XA_OK));
return true;
case MARK_ROLLBACK:
//make sure it is rolled back and reply to the client
txCoordinator.rollbackRemoteTransaction(txState.getGlobalTransaction());
case ROLLED_BACK:
writeResponse(header, createTransactionResponse(header, XAException.XA_RBROLLBACK));
return true;
case MARK_COMMIT:
writeResponse(header, createTransactionResponse(header, txCoordinator.onePhaseCommitRemoteTransaction(txState.getGlobalTransaction(), txState.getModifications())));
return true;
case COMMITTED:
writeResponse(header, createTransactionResponse(header, XAResource.XA_OK));
return true;
default:
throw new IllegalStateException();
}
} | [
"private",
"boolean",
"checkExistingTxForPrepare",
"(",
"HotRodHeader",
"header",
",",
"PrepareCoordinator",
"txCoordinator",
")",
"{",
"TxState",
"txState",
"=",
"txCoordinator",
".",
"getTxState",
"(",
")",
";",
"if",
"(",
"txState",
"==",
"null",
")",
"{",
"r... | Checks if the transaction was already prepared in another node
<p>
The client can send multiple requests to the server (in case of timeout or similar). This request is ignored when
(1) the originator is still alive; (2) the transaction is prepared or committed/rolled-back
<p>
If the transaction isn't prepared and the originator left the cluster, the previous transaction is rolled-back and
a new one is started. | [
"Checks",
"if",
"the",
"transaction",
"was",
"already",
"prepared",
"in",
"another",
"node",
"<p",
">",
"The",
"client",
"can",
"send",
"multiple",
"requests",
"to",
"the",
"server",
"(",
"in",
"case",
"of",
"timeout",
"or",
"similar",
")",
".",
"This",
... | train | https://github.com/infinispan/infinispan/blob/7c62b94886c3febb4774ae8376acf2baa0265ab5/server/hotrod/src/main/java/org/infinispan/server/hotrod/TransactionRequestProcessor.java#L199-L243 |
alkacon/opencms-core | src/org/opencms/db/CmsSecurityManager.java | CmsSecurityManager.readOrganizationalUnit | public CmsOrganizationalUnit readOrganizationalUnit(CmsRequestContext context, String ouFqn) throws CmsException {
"""
Reads an organizational Unit based on its fully qualified name.<p>
@param context the current request context
@param ouFqn the fully qualified name of the organizational Unit to be read
@return the organizational Unit that with the provided fully qualified name
@throws CmsException if something goes wrong
"""
CmsDbContext dbc = m_dbContextFactory.getDbContext(context);
CmsOrganizationalUnit result = null;
try {
result = m_driverManager.readOrganizationalUnit(dbc, CmsOrganizationalUnit.removeLeadingSeparator(ouFqn));
} catch (Exception e) {
dbc.report(null, Messages.get().container(Messages.ERR_READ_ORGUNIT_1, ouFqn), e);
} finally {
dbc.clear();
}
return result;
} | java | public CmsOrganizationalUnit readOrganizationalUnit(CmsRequestContext context, String ouFqn) throws CmsException {
CmsDbContext dbc = m_dbContextFactory.getDbContext(context);
CmsOrganizationalUnit result = null;
try {
result = m_driverManager.readOrganizationalUnit(dbc, CmsOrganizationalUnit.removeLeadingSeparator(ouFqn));
} catch (Exception e) {
dbc.report(null, Messages.get().container(Messages.ERR_READ_ORGUNIT_1, ouFqn), e);
} finally {
dbc.clear();
}
return result;
} | [
"public",
"CmsOrganizationalUnit",
"readOrganizationalUnit",
"(",
"CmsRequestContext",
"context",
",",
"String",
"ouFqn",
")",
"throws",
"CmsException",
"{",
"CmsDbContext",
"dbc",
"=",
"m_dbContextFactory",
".",
"getDbContext",
"(",
"context",
")",
";",
"CmsOrganizatio... | Reads an organizational Unit based on its fully qualified name.<p>
@param context the current request context
@param ouFqn the fully qualified name of the organizational Unit to be read
@return the organizational Unit that with the provided fully qualified name
@throws CmsException if something goes wrong | [
"Reads",
"an",
"organizational",
"Unit",
"based",
"on",
"its",
"fully",
"qualified",
"name",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/db/CmsSecurityManager.java#L4578-L4590 |
Waikato/moa | moa/src/main/java/weka/core/MOAUtils.java | MOAUtils.fromCommandLine | public static MOAObject fromCommandLine(Class requiredType, String commandline) {
"""
Turns a commandline into an object (classname + optional options).
@param requiredType the required class
@param commandline the commandline to turn into an object
@return the generated oblect
"""
MOAObject result;
String[] tmpOptions;
String classname;
try {
tmpOptions = Utils.splitOptions(commandline);
classname = tmpOptions[0];
tmpOptions[0] = "";
try {
result = (MOAObject) Class.forName(classname).newInstance();
}
catch (Exception e) {
// try to prepend package name
result = (MOAObject) Class.forName(requiredType.getPackage().getName() + "." + classname).newInstance();
}
if (result instanceof AbstractOptionHandler) {
((AbstractOptionHandler) result).getOptions().setViaCLIString(Utils.joinOptions(tmpOptions));
((AbstractOptionHandler) result).prepareForUse();
}
}
catch (Exception e) {
e.printStackTrace();
result = null;
}
return result;
} | java | public static MOAObject fromCommandLine(Class requiredType, String commandline) {
MOAObject result;
String[] tmpOptions;
String classname;
try {
tmpOptions = Utils.splitOptions(commandline);
classname = tmpOptions[0];
tmpOptions[0] = "";
try {
result = (MOAObject) Class.forName(classname).newInstance();
}
catch (Exception e) {
// try to prepend package name
result = (MOAObject) Class.forName(requiredType.getPackage().getName() + "." + classname).newInstance();
}
if (result instanceof AbstractOptionHandler) {
((AbstractOptionHandler) result).getOptions().setViaCLIString(Utils.joinOptions(tmpOptions));
((AbstractOptionHandler) result).prepareForUse();
}
}
catch (Exception e) {
e.printStackTrace();
result = null;
}
return result;
} | [
"public",
"static",
"MOAObject",
"fromCommandLine",
"(",
"Class",
"requiredType",
",",
"String",
"commandline",
")",
"{",
"MOAObject",
"result",
";",
"String",
"[",
"]",
"tmpOptions",
";",
"String",
"classname",
";",
"try",
"{",
"tmpOptions",
"=",
"Utils",
"."... | Turns a commandline into an object (classname + optional options).
@param requiredType the required class
@param commandline the commandline to turn into an object
@return the generated oblect | [
"Turns",
"a",
"commandline",
"into",
"an",
"object",
"(",
"classname",
"+",
"optional",
"options",
")",
"."
] | train | https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/weka/core/MOAUtils.java#L54-L81 |
Jasig/resource-server | resource-server-utils/src/main/java/org/jasig/resourceserver/utils/aggr/ResourcesElementsProviderImpl.java | ResourcesElementsProviderImpl.resolveResourceContextPath | protected String resolveResourceContextPath(HttpServletRequest request, String resource) {
"""
If the resource serving servlet context is available and the resource
is available in the context, create a URL to the resource in that context.
If not, create a local URL for the requested resource.
"""
final String resourceContextPath = this.getResourceServerContextPath();
this.logger.debug("Attempting to locate resource serving webapp with context path: {}", resourceContextPath);
//Try to resolve the
final ServletContext resourceContext = this.servletContext.getContext(resourceContextPath);
if (resourceContext == null || !resourceContextPath.equals(resourceContext.getContextPath())) {
this.logger.warn("Could not find resource serving webapp under context path {} ensure the resource server is deployed and cross context dispatching is enable for this web application", resourceContextPath);
return request.getContextPath();
}
this.logger.debug("Found resource serving webapp at: {}", resourceContextPath);
URL url = null;
try {
url = resourceContext.getResource(resource);
}
catch (MalformedURLException e) {
//Ignore
}
if (url == null) {
this.logger.debug("Resource serving webapp {} doesn't contain resource {} Falling back to the local resource.", resourceContextPath, resource);
return request.getContextPath();
}
this.logger.debug("Resource serving webapp {} contains resource {} Using resource server.", resourceContextPath, resource);
return resourceContextPath;
} | java | protected String resolveResourceContextPath(HttpServletRequest request, String resource) {
final String resourceContextPath = this.getResourceServerContextPath();
this.logger.debug("Attempting to locate resource serving webapp with context path: {}", resourceContextPath);
//Try to resolve the
final ServletContext resourceContext = this.servletContext.getContext(resourceContextPath);
if (resourceContext == null || !resourceContextPath.equals(resourceContext.getContextPath())) {
this.logger.warn("Could not find resource serving webapp under context path {} ensure the resource server is deployed and cross context dispatching is enable for this web application", resourceContextPath);
return request.getContextPath();
}
this.logger.debug("Found resource serving webapp at: {}", resourceContextPath);
URL url = null;
try {
url = resourceContext.getResource(resource);
}
catch (MalformedURLException e) {
//Ignore
}
if (url == null) {
this.logger.debug("Resource serving webapp {} doesn't contain resource {} Falling back to the local resource.", resourceContextPath, resource);
return request.getContextPath();
}
this.logger.debug("Resource serving webapp {} contains resource {} Using resource server.", resourceContextPath, resource);
return resourceContextPath;
} | [
"protected",
"String",
"resolveResourceContextPath",
"(",
"HttpServletRequest",
"request",
",",
"String",
"resource",
")",
"{",
"final",
"String",
"resourceContextPath",
"=",
"this",
".",
"getResourceServerContextPath",
"(",
")",
";",
"this",
".",
"logger",
".",
"de... | If the resource serving servlet context is available and the resource
is available in the context, create a URL to the resource in that context.
If not, create a local URL for the requested resource. | [
"If",
"the",
"resource",
"serving",
"servlet",
"context",
"is",
"available",
"and",
"the",
"resource",
"is",
"available",
"in",
"the",
"context",
"create",
"a",
"URL",
"to",
"the",
"resource",
"in",
"that",
"context",
".",
"If",
"not",
"create",
"a",
"loca... | train | https://github.com/Jasig/resource-server/blob/13375f716777ec3c99ae9917f672881d4aa32df3/resource-server-utils/src/main/java/org/jasig/resourceserver/utils/aggr/ResourcesElementsProviderImpl.java#L383-L412 |
albfernandez/itext2 | src/main/java/com/lowagie/text/pdf/Type3Font.java | Type3Font.defineGlyph | public PdfContentByte defineGlyph(char c, float wx, float llx, float lly, float urx, float ury) {
"""
Defines a glyph. If the character was already defined it will return the same content
@param c the character to match this glyph.
@param wx the advance this character will have
@param llx the X lower left corner of the glyph bounding box. If the <CODE>colorize</CODE> option is
<CODE>true</CODE> the value is ignored
@param lly the Y lower left corner of the glyph bounding box. If the <CODE>colorize</CODE> option is
<CODE>true</CODE> the value is ignored
@param urx the X upper right corner of the glyph bounding box. If the <CODE>colorize</CODE> option is
<CODE>true</CODE> the value is ignored
@param ury the Y upper right corner of the glyph bounding box. If the <CODE>colorize</CODE> option is
<CODE>true</CODE> the value is ignored
@return a content where the glyph can be defined
"""
if (c == 0 || c > 255)
throw new IllegalArgumentException("The char " + (int)c + " doesn't belong in this Type3 font");
usedSlot[c] = true;
Integer ck = Integer.valueOf(c);
Type3Glyph glyph = (Type3Glyph)char2glyph.get(ck);
if (glyph != null)
return glyph;
widths3.put(c, (int)wx);
if (!colorized) {
if (Float.isNaN(this.llx)) {
this.llx = llx;
this.lly = lly;
this.urx = urx;
this.ury = ury;
}
else {
this.llx = Math.min(this.llx, llx);
this.lly = Math.min(this.lly, lly);
this.urx = Math.max(this.urx, urx);
this.ury = Math.max(this.ury, ury);
}
}
glyph = new Type3Glyph(writer, pageResources, wx, llx, lly, urx, ury, colorized);
char2glyph.put(ck, glyph);
return glyph;
} | java | public PdfContentByte defineGlyph(char c, float wx, float llx, float lly, float urx, float ury) {
if (c == 0 || c > 255)
throw new IllegalArgumentException("The char " + (int)c + " doesn't belong in this Type3 font");
usedSlot[c] = true;
Integer ck = Integer.valueOf(c);
Type3Glyph glyph = (Type3Glyph)char2glyph.get(ck);
if (glyph != null)
return glyph;
widths3.put(c, (int)wx);
if (!colorized) {
if (Float.isNaN(this.llx)) {
this.llx = llx;
this.lly = lly;
this.urx = urx;
this.ury = ury;
}
else {
this.llx = Math.min(this.llx, llx);
this.lly = Math.min(this.lly, lly);
this.urx = Math.max(this.urx, urx);
this.ury = Math.max(this.ury, ury);
}
}
glyph = new Type3Glyph(writer, pageResources, wx, llx, lly, urx, ury, colorized);
char2glyph.put(ck, glyph);
return glyph;
} | [
"public",
"PdfContentByte",
"defineGlyph",
"(",
"char",
"c",
",",
"float",
"wx",
",",
"float",
"llx",
",",
"float",
"lly",
",",
"float",
"urx",
",",
"float",
"ury",
")",
"{",
"if",
"(",
"c",
"==",
"0",
"||",
"c",
">",
"255",
")",
"throw",
"new",
... | Defines a glyph. If the character was already defined it will return the same content
@param c the character to match this glyph.
@param wx the advance this character will have
@param llx the X lower left corner of the glyph bounding box. If the <CODE>colorize</CODE> option is
<CODE>true</CODE> the value is ignored
@param lly the Y lower left corner of the glyph bounding box. If the <CODE>colorize</CODE> option is
<CODE>true</CODE> the value is ignored
@param urx the X upper right corner of the glyph bounding box. If the <CODE>colorize</CODE> option is
<CODE>true</CODE> the value is ignored
@param ury the Y upper right corner of the glyph bounding box. If the <CODE>colorize</CODE> option is
<CODE>true</CODE> the value is ignored
@return a content where the glyph can be defined | [
"Defines",
"a",
"glyph",
".",
"If",
"the",
"character",
"was",
"already",
"defined",
"it",
"will",
"return",
"the",
"same",
"content"
] | train | https://github.com/albfernandez/itext2/blob/438fc1899367fd13dfdfa8dfdca9a3c1a7783b84/src/main/java/com/lowagie/text/pdf/Type3Font.java#L126-L152 |
benjamin-bader/droptools | dropwizard-jooq/src/main/java/com/bendb/dropwizard/jooq/PostgresSupport.java | PostgresSupport.arrayAgg | @Support( {
"""
Applies the {@code array_agg} aggregate function on a field,
resulting in the input values being concatenated into an array.
@param field the field to be aggregated
@param <T> the type of the field
@return a {@link Field} representing the array aggregate.
@see <a href="http://www.postgresql.org/docs/9.3/static/functions-aggregate.html"/>
"""SQLDialect.POSTGRES})
public static <T> Field<T[]> arrayAgg(Field<T> field) {
return DSL.field("array_agg({0})", field.getDataType().getArrayDataType(), field);
} | java | @Support({SQLDialect.POSTGRES})
public static <T> Field<T[]> arrayAgg(Field<T> field) {
return DSL.field("array_agg({0})", field.getDataType().getArrayDataType(), field);
} | [
"@",
"Support",
"(",
"{",
"SQLDialect",
".",
"POSTGRES",
"}",
")",
"public",
"static",
"<",
"T",
">",
"Field",
"<",
"T",
"[",
"]",
">",
"arrayAgg",
"(",
"Field",
"<",
"T",
">",
"field",
")",
"{",
"return",
"DSL",
".",
"field",
"(",
"\"array_agg({0}... | Applies the {@code array_agg} aggregate function on a field,
resulting in the input values being concatenated into an array.
@param field the field to be aggregated
@param <T> the type of the field
@return a {@link Field} representing the array aggregate.
@see <a href="http://www.postgresql.org/docs/9.3/static/functions-aggregate.html"/> | [
"Applies",
"the",
"{",
"@code",
"array_agg",
"}",
"aggregate",
"function",
"on",
"a",
"field",
"resulting",
"in",
"the",
"input",
"values",
"being",
"concatenated",
"into",
"an",
"array",
"."
] | train | https://github.com/benjamin-bader/droptools/blob/f1964465d725dfb07a5b6eb16f7bbe794896d1e0/dropwizard-jooq/src/main/java/com/bendb/dropwizard/jooq/PostgresSupport.java#L26-L29 |
likethecolor/Alchemy-API | src/main/java/com/likethecolor/alchemy/api/parser/json/ConceptParser.java | ConceptParser.getConcept | private JSONObject getConcept(final JSONArray concepts, final int index) {
"""
Return a json object from the provided array. Return an empty object if
there is any problems fetching the concept data.
@param concepts array of concept data
@param index of the object to fetch
@return json object from the provided array
"""
JSONObject object = new JSONObject();
try {
object = (JSONObject) concepts.get(index);
}
catch(JSONException e) {
e.printStackTrace();
}
return object;
} | java | private JSONObject getConcept(final JSONArray concepts, final int index) {
JSONObject object = new JSONObject();
try {
object = (JSONObject) concepts.get(index);
}
catch(JSONException e) {
e.printStackTrace();
}
return object;
} | [
"private",
"JSONObject",
"getConcept",
"(",
"final",
"JSONArray",
"concepts",
",",
"final",
"int",
"index",
")",
"{",
"JSONObject",
"object",
"=",
"new",
"JSONObject",
"(",
")",
";",
"try",
"{",
"object",
"=",
"(",
"JSONObject",
")",
"concepts",
".",
"get"... | Return a json object from the provided array. Return an empty object if
there is any problems fetching the concept data.
@param concepts array of concept data
@param index of the object to fetch
@return json object from the provided array | [
"Return",
"a",
"json",
"object",
"from",
"the",
"provided",
"array",
".",
"Return",
"an",
"empty",
"object",
"if",
"there",
"is",
"any",
"problems",
"fetching",
"the",
"concept",
"data",
"."
] | train | https://github.com/likethecolor/Alchemy-API/blob/5208cfc92a878ceeaff052787af29da92d98db7e/src/main/java/com/likethecolor/alchemy/api/parser/json/ConceptParser.java#L77-L86 |
CloudSlang/cs-actions | cs-postgres/src/main/java/io/cloudslang/content/postgres/actions/UpdatePgHbaConfigAction.java | UpdatePgHbaConfigAction.execute | @Action(name = "Update pg_hba.config",
outputs = {
"""
Updates the Postgres config pg_hba.config
@param installationPath The full path to the PostgreSQL configuration file in the local machine to be updated.
@param allowedHosts A wildcard or a comma-separated list of hostnames or IPs (IPv4 or IPv6).
@param allowedUsers A comma-separated list of PostgreSQL users. If no value is specified for this input,
all users will have access to the server.
@return A map with strings as keys and strings as values that contains: outcome of the action (or failure message
and the exception if there is one), returnCode of the operation and the ID of the request
"""
@Output(RETURN_CODE),
@Output(RETURN_RESULT),
@Output(EXCEPTION),
@Output(STDERR)
},
responses = {
@Response(text = ResponseNames.SUCCESS, field = RETURN_CODE, value = SUCCESS,
matchType = MatchType.COMPARE_EQUAL,
responseType = ResponseType.RESOLVED),
@Response(text = ResponseNames.FAILURE, field = RETURN_CODE, value = FAILURE,
matchType = MatchType.COMPARE_EQUAL, responseType = ResponseType.ERROR, isOnFail = true)
})
public Map<String, String> execute(
@Param(value = FILE_PATH, required = true) String installationPath,
@Param(value = ALLOWED_HOSTS) String allowedHosts,
@Param(value = ALLOWED_USERS) String allowedUsers
) {
try {
if (allowedHosts == null && allowedUsers == null) {
return getSuccessResultsMap("No changes in pg_hba.conf");
}
if (allowedHosts == null || allowedHosts.trim().length() == 0) {
allowedHosts = "localhost";
}
allowedHosts = allowedHosts.replace("\'", "").trim();
if (allowedUsers == null || allowedUsers.trim().length() == 0) {
allowedUsers = "all";
} else {
allowedUsers = allowedUsers.replace("\'", "").trim();
}
ConfigService.changeProperty(installationPath, allowedHosts.split(";"), allowedUsers.split(";"));
return getSuccessResultsMap("Updated pg_hba.conf successfully");
} catch (Exception e) {
return getFailureResultsMap("Failed to update pg_hba.conf", e);
}
} | java | @Action(name = "Update pg_hba.config",
outputs = {
@Output(RETURN_CODE),
@Output(RETURN_RESULT),
@Output(EXCEPTION),
@Output(STDERR)
},
responses = {
@Response(text = ResponseNames.SUCCESS, field = RETURN_CODE, value = SUCCESS,
matchType = MatchType.COMPARE_EQUAL,
responseType = ResponseType.RESOLVED),
@Response(text = ResponseNames.FAILURE, field = RETURN_CODE, value = FAILURE,
matchType = MatchType.COMPARE_EQUAL, responseType = ResponseType.ERROR, isOnFail = true)
})
public Map<String, String> execute(
@Param(value = FILE_PATH, required = true) String installationPath,
@Param(value = ALLOWED_HOSTS) String allowedHosts,
@Param(value = ALLOWED_USERS) String allowedUsers
) {
try {
if (allowedHosts == null && allowedUsers == null) {
return getSuccessResultsMap("No changes in pg_hba.conf");
}
if (allowedHosts == null || allowedHosts.trim().length() == 0) {
allowedHosts = "localhost";
}
allowedHosts = allowedHosts.replace("\'", "").trim();
if (allowedUsers == null || allowedUsers.trim().length() == 0) {
allowedUsers = "all";
} else {
allowedUsers = allowedUsers.replace("\'", "").trim();
}
ConfigService.changeProperty(installationPath, allowedHosts.split(";"), allowedUsers.split(";"));
return getSuccessResultsMap("Updated pg_hba.conf successfully");
} catch (Exception e) {
return getFailureResultsMap("Failed to update pg_hba.conf", e);
}
} | [
"@",
"Action",
"(",
"name",
"=",
"\"Update pg_hba.config\"",
",",
"outputs",
"=",
"{",
"@",
"Output",
"(",
"RETURN_CODE",
")",
",",
"@",
"Output",
"(",
"RETURN_RESULT",
")",
",",
"@",
"Output",
"(",
"EXCEPTION",
")",
",",
"@",
"Output",
"(",
"STDERR",
... | Updates the Postgres config pg_hba.config
@param installationPath The full path to the PostgreSQL configuration file in the local machine to be updated.
@param allowedHosts A wildcard or a comma-separated list of hostnames or IPs (IPv4 or IPv6).
@param allowedUsers A comma-separated list of PostgreSQL users. If no value is specified for this input,
all users will have access to the server.
@return A map with strings as keys and strings as values that contains: outcome of the action (or failure message
and the exception if there is one), returnCode of the operation and the ID of the request | [
"Updates",
"the",
"Postgres",
"config",
"pg_hba",
".",
"config"
] | train | https://github.com/CloudSlang/cs-actions/blob/9a1be1e99ad88286a6c153d5f2275df6ae1a57a1/cs-postgres/src/main/java/io/cloudslang/content/postgres/actions/UpdatePgHbaConfigAction.java#L49-L91 |
jblas-project/jblas | src/main/java/org/jblas/Singular.java | Singular.fullSVD | public static DoubleMatrix[] fullSVD(DoubleMatrix A) {
"""
Compute a singular-value decomposition of A.
@return A DoubleMatrix[3] array of U, S, V such that A = U * diag(S) * V'
"""
int m = A.rows;
int n = A.columns;
DoubleMatrix U = new DoubleMatrix(m, m);
DoubleMatrix S = new DoubleMatrix(min(m, n));
DoubleMatrix V = new DoubleMatrix(n, n);
int info = NativeBlas.dgesvd('A', 'A', m, n, A.dup().data, 0, m, S.data, 0, U.data, 0, m, V.data, 0, n);
if (info > 0) {
throw new LapackConvergenceException("GESVD", info + " superdiagonals of an intermediate bidiagonal form failed to converge.");
}
return new DoubleMatrix[]{U, S, V.transpose()};
} | java | public static DoubleMatrix[] fullSVD(DoubleMatrix A) {
int m = A.rows;
int n = A.columns;
DoubleMatrix U = new DoubleMatrix(m, m);
DoubleMatrix S = new DoubleMatrix(min(m, n));
DoubleMatrix V = new DoubleMatrix(n, n);
int info = NativeBlas.dgesvd('A', 'A', m, n, A.dup().data, 0, m, S.data, 0, U.data, 0, m, V.data, 0, n);
if (info > 0) {
throw new LapackConvergenceException("GESVD", info + " superdiagonals of an intermediate bidiagonal form failed to converge.");
}
return new DoubleMatrix[]{U, S, V.transpose()};
} | [
"public",
"static",
"DoubleMatrix",
"[",
"]",
"fullSVD",
"(",
"DoubleMatrix",
"A",
")",
"{",
"int",
"m",
"=",
"A",
".",
"rows",
";",
"int",
"n",
"=",
"A",
".",
"columns",
";",
"DoubleMatrix",
"U",
"=",
"new",
"DoubleMatrix",
"(",
"m",
",",
"m",
")"... | Compute a singular-value decomposition of A.
@return A DoubleMatrix[3] array of U, S, V such that A = U * diag(S) * V' | [
"Compute",
"a",
"singular",
"-",
"value",
"decomposition",
"of",
"A",
"."
] | train | https://github.com/jblas-project/jblas/blob/2818f231228e655cda80dfd8e0b87709fdfd8a70/src/main/java/org/jblas/Singular.java#L21-L36 |
mapbox/mapbox-java | services-geojson/src/main/java/com/mapbox/geojson/GeometryCollection.java | GeometryCollection.fromGeometry | public static GeometryCollection fromGeometry(@NonNull Geometry geometry,
@Nullable BoundingBox bbox) {
"""
Create a new instance of this class by giving the collection a single GeoJSON {@link Geometry}.
@param geometry a non-null object of type geometry which makes up this collection
@param bbox optionally include a bbox definition as a double array
@return a new instance of this class defined by the values passed inside this static factory
method
@since 3.0.0
"""
List<Geometry> geometries = Arrays.asList(geometry);
return new GeometryCollection(TYPE, bbox, geometries);
} | java | public static GeometryCollection fromGeometry(@NonNull Geometry geometry,
@Nullable BoundingBox bbox) {
List<Geometry> geometries = Arrays.asList(geometry);
return new GeometryCollection(TYPE, bbox, geometries);
} | [
"public",
"static",
"GeometryCollection",
"fromGeometry",
"(",
"@",
"NonNull",
"Geometry",
"geometry",
",",
"@",
"Nullable",
"BoundingBox",
"bbox",
")",
"{",
"List",
"<",
"Geometry",
">",
"geometries",
"=",
"Arrays",
".",
"asList",
"(",
"geometry",
")",
";",
... | Create a new instance of this class by giving the collection a single GeoJSON {@link Geometry}.
@param geometry a non-null object of type geometry which makes up this collection
@param bbox optionally include a bbox definition as a double array
@return a new instance of this class defined by the values passed inside this static factory
method
@since 3.0.0 | [
"Create",
"a",
"new",
"instance",
"of",
"this",
"class",
"by",
"giving",
"the",
"collection",
"a",
"single",
"GeoJSON",
"{",
"@link",
"Geometry",
"}",
"."
] | train | https://github.com/mapbox/mapbox-java/blob/c0be138f462f91441388584c668f3760ba0e18e2/services-geojson/src/main/java/com/mapbox/geojson/GeometryCollection.java#L140-L144 |
JOML-CI/JOML | src/org/joml/Matrix3x2f.java | Matrix3x2f.rotateAbout | public Matrix3x2f rotateAbout(float ang, float x, float y, Matrix3x2f dest) {
"""
Apply a rotation transformation to this matrix by rotating the given amount of radians about
the specified rotation center <code>(x, y)</code> and store the result in <code>dest</code>.
<p>
This method is equivalent to calling: <code>translate(x, y, dest).rotate(ang).translate(-x, -y)</code>
<p>
If <code>M</code> is <code>this</code> matrix and <code>R</code> the rotation matrix,
then the new matrix will be <code>M * R</code>. So when transforming a
vector <code>v</code> with the new matrix by using <code>M * R * v</code>, the rotation will be applied first!
@see #translate(float, float, Matrix3x2f)
@see #rotate(float, Matrix3x2f)
@param ang
the angle in radians
@param x
the x component of the rotation center
@param y
the y component of the rotation center
@param dest
will hold the result
@return dest
"""
float tm20 = m00 * x + m10 * y + m20;
float tm21 = m01 * x + m11 * y + m21;
float cos = (float) Math.cos(ang);
float sin = (float) Math.sin(ang);
float nm00 = m00 * cos + m10 * sin;
float nm01 = m01 * cos + m11 * sin;
dest.m10 = m00 * -sin + m10 * cos;
dest.m11 = m01 * -sin + m11 * cos;
dest.m00 = nm00;
dest.m01 = nm01;
dest.m20 = dest.m00 * -x + dest.m10 * -y + tm20;
dest.m21 = dest.m01 * -x + dest.m11 * -y + tm21;
return dest;
} | java | public Matrix3x2f rotateAbout(float ang, float x, float y, Matrix3x2f dest) {
float tm20 = m00 * x + m10 * y + m20;
float tm21 = m01 * x + m11 * y + m21;
float cos = (float) Math.cos(ang);
float sin = (float) Math.sin(ang);
float nm00 = m00 * cos + m10 * sin;
float nm01 = m01 * cos + m11 * sin;
dest.m10 = m00 * -sin + m10 * cos;
dest.m11 = m01 * -sin + m11 * cos;
dest.m00 = nm00;
dest.m01 = nm01;
dest.m20 = dest.m00 * -x + dest.m10 * -y + tm20;
dest.m21 = dest.m01 * -x + dest.m11 * -y + tm21;
return dest;
} | [
"public",
"Matrix3x2f",
"rotateAbout",
"(",
"float",
"ang",
",",
"float",
"x",
",",
"float",
"y",
",",
"Matrix3x2f",
"dest",
")",
"{",
"float",
"tm20",
"=",
"m00",
"*",
"x",
"+",
"m10",
"*",
"y",
"+",
"m20",
";",
"float",
"tm21",
"=",
"m01",
"*",
... | Apply a rotation transformation to this matrix by rotating the given amount of radians about
the specified rotation center <code>(x, y)</code> and store the result in <code>dest</code>.
<p>
This method is equivalent to calling: <code>translate(x, y, dest).rotate(ang).translate(-x, -y)</code>
<p>
If <code>M</code> is <code>this</code> matrix and <code>R</code> the rotation matrix,
then the new matrix will be <code>M * R</code>. So when transforming a
vector <code>v</code> with the new matrix by using <code>M * R * v</code>, the rotation will be applied first!
@see #translate(float, float, Matrix3x2f)
@see #rotate(float, Matrix3x2f)
@param ang
the angle in radians
@param x
the x component of the rotation center
@param y
the y component of the rotation center
@param dest
will hold the result
@return dest | [
"Apply",
"a",
"rotation",
"transformation",
"to",
"this",
"matrix",
"by",
"rotating",
"the",
"given",
"amount",
"of",
"radians",
"about",
"the",
"specified",
"rotation",
"center",
"<code",
">",
"(",
"x",
"y",
")",
"<",
"/",
"code",
">",
"and",
"store",
"... | train | https://github.com/JOML-CI/JOML/blob/ce2652fc236b42bda3875c591f8e6645048a678f/src/org/joml/Matrix3x2f.java#L1982-L1996 |
cdk/cdk | legacy/src/main/java/org/openscience/cdk/geometry/GeometryTools.java | GeometryTools.scaleMolecule | public static void scaleMolecule(IAtomContainer atomCon, double scaleFactor) {
"""
Multiplies all the coordinates of the atoms of the given molecule with the
scalefactor.
See comment for center(IAtomContainer atomCon, Dimension areaDim, HashMap renderingCoordinates) for details on coordinate sets
@param atomCon The molecule to be scaled
@param scaleFactor Description of the Parameter
"""
for (int i = 0; i < atomCon.getAtomCount(); i++) {
if (atomCon.getAtom(i).getPoint2d() != null) {
atomCon.getAtom(i).getPoint2d().x *= scaleFactor;
atomCon.getAtom(i).getPoint2d().y *= scaleFactor;
}
}
} | java | public static void scaleMolecule(IAtomContainer atomCon, double scaleFactor) {
for (int i = 0; i < atomCon.getAtomCount(); i++) {
if (atomCon.getAtom(i).getPoint2d() != null) {
atomCon.getAtom(i).getPoint2d().x *= scaleFactor;
atomCon.getAtom(i).getPoint2d().y *= scaleFactor;
}
}
} | [
"public",
"static",
"void",
"scaleMolecule",
"(",
"IAtomContainer",
"atomCon",
",",
"double",
"scaleFactor",
")",
"{",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"atomCon",
".",
"getAtomCount",
"(",
")",
";",
"i",
"++",
")",
"{",
"if",
"(",
"at... | Multiplies all the coordinates of the atoms of the given molecule with the
scalefactor.
See comment for center(IAtomContainer atomCon, Dimension areaDim, HashMap renderingCoordinates) for details on coordinate sets
@param atomCon The molecule to be scaled
@param scaleFactor Description of the Parameter | [
"Multiplies",
"all",
"the",
"coordinates",
"of",
"the",
"atoms",
"of",
"the",
"given",
"molecule",
"with",
"the",
"scalefactor",
".",
"See",
"comment",
"for",
"center",
"(",
"IAtomContainer",
"atomCon",
"Dimension",
"areaDim",
"HashMap",
"renderingCoordinates",
")... | train | https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/legacy/src/main/java/org/openscience/cdk/geometry/GeometryTools.java#L167-L174 |
Alluxio/alluxio | core/server/master/src/main/java/alluxio/master/block/meta/MasterWorkerInfo.java | MasterWorkerInfo.updateCapacityBytes | public void updateCapacityBytes(Map<String, Long> capacityBytesOnTiers) {
"""
Sets the capacity of the worker in bytes.
@param capacityBytesOnTiers used bytes on each storage tier
"""
mCapacityBytes = 0;
mTotalBytesOnTiers = capacityBytesOnTiers;
for (long t : mTotalBytesOnTiers.values()) {
mCapacityBytes += t;
}
} | java | public void updateCapacityBytes(Map<String, Long> capacityBytesOnTiers) {
mCapacityBytes = 0;
mTotalBytesOnTiers = capacityBytesOnTiers;
for (long t : mTotalBytesOnTiers.values()) {
mCapacityBytes += t;
}
} | [
"public",
"void",
"updateCapacityBytes",
"(",
"Map",
"<",
"String",
",",
"Long",
">",
"capacityBytesOnTiers",
")",
"{",
"mCapacityBytes",
"=",
"0",
";",
"mTotalBytesOnTiers",
"=",
"capacityBytesOnTiers",
";",
"for",
"(",
"long",
"t",
":",
"mTotalBytesOnTiers",
"... | Sets the capacity of the worker in bytes.
@param capacityBytesOnTiers used bytes on each storage tier | [
"Sets",
"the",
"capacity",
"of",
"the",
"worker",
"in",
"bytes",
"."
] | train | https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/server/master/src/main/java/alluxio/master/block/meta/MasterWorkerInfo.java#L412-L418 |
spring-projects/spring-mobile | spring-mobile-device/src/main/java/org/springframework/mobile/device/switcher/SiteSwitcherRequestFilter.java | SiteSwitcherRequestFilter.dotMobi | private void dotMobi() throws ServletException {
"""
Configures a site switcher that redirects to a <code>.mobi</code> domain for normal site requests that either
originate from a mobile device or indicate a mobile site preference.
Will strip off the trailing domain name when building the mobile domain
e.g. "app.com" will become "app.mobi" (the .com will be stripped).
Uses a {@link CookieSitePreferenceRepository} that saves a cookie that is shared between the two domains.
"""
if (serverName == null) {
throw new ServletException("serverName init parameter not found");
}
int lastDot = serverName.lastIndexOf('.');
this.siteSwitcherHandler = new StandardSiteSwitcherHandler(new StandardSiteUrlFactory(serverName),
new StandardSiteUrlFactory(serverName.substring(0, lastDot) + ".mobi"), null,
new StandardSitePreferenceHandler(new CookieSitePreferenceRepository("." + serverName)), tabletIsMobile);
} | java | private void dotMobi() throws ServletException {
if (serverName == null) {
throw new ServletException("serverName init parameter not found");
}
int lastDot = serverName.lastIndexOf('.');
this.siteSwitcherHandler = new StandardSiteSwitcherHandler(new StandardSiteUrlFactory(serverName),
new StandardSiteUrlFactory(serverName.substring(0, lastDot) + ".mobi"), null,
new StandardSitePreferenceHandler(new CookieSitePreferenceRepository("." + serverName)), tabletIsMobile);
} | [
"private",
"void",
"dotMobi",
"(",
")",
"throws",
"ServletException",
"{",
"if",
"(",
"serverName",
"==",
"null",
")",
"{",
"throw",
"new",
"ServletException",
"(",
"\"serverName init parameter not found\"",
")",
";",
"}",
"int",
"lastDot",
"=",
"serverName",
".... | Configures a site switcher that redirects to a <code>.mobi</code> domain for normal site requests that either
originate from a mobile device or indicate a mobile site preference.
Will strip off the trailing domain name when building the mobile domain
e.g. "app.com" will become "app.mobi" (the .com will be stripped).
Uses a {@link CookieSitePreferenceRepository} that saves a cookie that is shared between the two domains. | [
"Configures",
"a",
"site",
"switcher",
"that",
"redirects",
"to",
"a",
"<code",
">",
".",
"mobi<",
"/",
"code",
">",
"domain",
"for",
"normal",
"site",
"requests",
"that",
"either",
"originate",
"from",
"a",
"mobile",
"device",
"or",
"indicate",
"a",
"mobi... | train | https://github.com/spring-projects/spring-mobile/blob/a402cbcaf208e24288b957f44c9984bd6e8bf064/spring-mobile-device/src/main/java/org/springframework/mobile/device/switcher/SiteSwitcherRequestFilter.java#L268-L276 |
Stratio/bdt | src/main/java/com/stratio/qa/specs/DcosSpec.java | DcosSpec.setGoSecSSOCookie | @Given("^I( do not)? set sso token using host '(.+?)' with user '(.+?)' and password '(.+?)'( and tenant '(.+?)')?$")
public void setGoSecSSOCookie(String set, String ssoHost, String userName, String passWord, String foo, String tenant) throws Exception {
"""
Generate token to authenticate in gosec SSO
@param ssoHost current sso host
@param userName username
@param passWord password
@throws Exception exception
"""
if (set == null) {
HashMap<String, String> ssoCookies = new GosecSSOUtils(ssoHost, userName, passWord, tenant).ssoTokenGenerator();
String[] tokenList = {"user", "dcos-acs-auth-cookie"};
List<com.ning.http.client.cookie.Cookie> cookiesAtributes = addSsoToken(ssoCookies, tokenList);
commonspec.setCookies(cookiesAtributes);
}
} | java | @Given("^I( do not)? set sso token using host '(.+?)' with user '(.+?)' and password '(.+?)'( and tenant '(.+?)')?$")
public void setGoSecSSOCookie(String set, String ssoHost, String userName, String passWord, String foo, String tenant) throws Exception {
if (set == null) {
HashMap<String, String> ssoCookies = new GosecSSOUtils(ssoHost, userName, passWord, tenant).ssoTokenGenerator();
String[] tokenList = {"user", "dcos-acs-auth-cookie"};
List<com.ning.http.client.cookie.Cookie> cookiesAtributes = addSsoToken(ssoCookies, tokenList);
commonspec.setCookies(cookiesAtributes);
}
} | [
"@",
"Given",
"(",
"\"^I( do not)? set sso token using host '(.+?)' with user '(.+?)' and password '(.+?)'( and tenant '(.+?)')?$\"",
")",
"public",
"void",
"setGoSecSSOCookie",
"(",
"String",
"set",
",",
"String",
"ssoHost",
",",
"String",
"userName",
",",
"String",
"passWord"... | Generate token to authenticate in gosec SSO
@param ssoHost current sso host
@param userName username
@param passWord password
@throws Exception exception | [
"Generate",
"token",
"to",
"authenticate",
"in",
"gosec",
"SSO"
] | train | https://github.com/Stratio/bdt/blob/55324d19e7497764ad3dd7139923e13eb9841d75/src/main/java/com/stratio/qa/specs/DcosSpec.java#L96-L105 |
zackpollard/JavaTelegramBot-API | core/src/main/java/pro/zackpollard/telegrambot/api/TelegramBot.java | TelegramBot.editMessageText | public Message editMessageText(Message oldMessage, String text, ParseMode parseMode, boolean disableWebPagePreview, InlineReplyMarkup inlineReplyMarkup) {
"""
This allows you to edit the text of a message you have already sent previously
@param oldMessage The Message object that represents the message you want to edit
@param text The new text you want to display
@param parseMode The ParseMode that should be used with this new text
@param disableWebPagePreview Whether any URLs should be displayed with a preview of their content
@param inlineReplyMarkup Any InlineReplyMarkup object you want to edit into the message
@return A new Message object representing the edited message
"""
return this.editMessageText(oldMessage.getChat().getId(), oldMessage.getMessageId(), text, parseMode, disableWebPagePreview, inlineReplyMarkup);
} | java | public Message editMessageText(Message oldMessage, String text, ParseMode parseMode, boolean disableWebPagePreview, InlineReplyMarkup inlineReplyMarkup) {
return this.editMessageText(oldMessage.getChat().getId(), oldMessage.getMessageId(), text, parseMode, disableWebPagePreview, inlineReplyMarkup);
} | [
"public",
"Message",
"editMessageText",
"(",
"Message",
"oldMessage",
",",
"String",
"text",
",",
"ParseMode",
"parseMode",
",",
"boolean",
"disableWebPagePreview",
",",
"InlineReplyMarkup",
"inlineReplyMarkup",
")",
"{",
"return",
"this",
".",
"editMessageText",
"(",... | This allows you to edit the text of a message you have already sent previously
@param oldMessage The Message object that represents the message you want to edit
@param text The new text you want to display
@param parseMode The ParseMode that should be used with this new text
@param disableWebPagePreview Whether any URLs should be displayed with a preview of their content
@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",
"text",
"of",
"a",
"message",
"you",
"have",
"already",
"sent",
"previously"
] | train | https://github.com/zackpollard/JavaTelegramBot-API/blob/9d100f351824042ca5fc0ea735d1fa376a13e81d/core/src/main/java/pro/zackpollard/telegrambot/api/TelegramBot.java#L668-L671 |
OpenFeign/feign | core/src/main/java/feign/template/UriUtils.java | UriUtils.pathEncode | public static String pathEncode(String path, Charset charset) {
"""
Uri Encode a Path Fragment.
@param path containing the path fragment.
@param charset to use.
@return the encoded path fragment.
"""
return encodeReserved(path, FragmentType.PATH_SEGMENT, charset);
/*
* path encoding is not equivalent to query encoding, there are few differences, namely dealing
* with spaces, !, ', (, ), and ~ characters. we will need to manually process those values.
*/
// return encoded.replaceAll("\\+", "%20");
} | java | public static String pathEncode(String path, Charset charset) {
return encodeReserved(path, FragmentType.PATH_SEGMENT, charset);
/*
* path encoding is not equivalent to query encoding, there are few differences, namely dealing
* with spaces, !, ', (, ), and ~ characters. we will need to manually process those values.
*/
// return encoded.replaceAll("\\+", "%20");
} | [
"public",
"static",
"String",
"pathEncode",
"(",
"String",
"path",
",",
"Charset",
"charset",
")",
"{",
"return",
"encodeReserved",
"(",
"path",
",",
"FragmentType",
".",
"PATH_SEGMENT",
",",
"charset",
")",
";",
"/*\n * path encoding is not equivalent to query en... | Uri Encode a Path Fragment.
@param path containing the path fragment.
@param charset to use.
@return the encoded path fragment. | [
"Uri",
"Encode",
"a",
"Path",
"Fragment",
"."
] | train | https://github.com/OpenFeign/feign/blob/318fb0e955b8cfcf64f70d6aeea0ba5795f8a7eb/core/src/main/java/feign/template/UriUtils.java#L86-L94 |
JRebirth/JRebirth | org.jrebirth.af/core/src/main/java/org/jrebirth/af/core/service/AbstractService.java | AbstractService.bindTitle | private void bindTitle(final ServiceTask<?> task, final StringProperty titleProperty) {
"""
Bind a task to a string property that will display the task title.
@param task the service task that we need to follow the progression
@param titleProperty the title presenter
"""
// Perform this binding into the JAT to respect widget and task API
JRebirth.runIntoJAT("Bind Title for " + task.getServiceHandlerName(),
// Bind the task title
() -> titleProperty.bind(task.titleProperty()));
} | java | private void bindTitle(final ServiceTask<?> task, final StringProperty titleProperty) {
// Perform this binding into the JAT to respect widget and task API
JRebirth.runIntoJAT("Bind Title for " + task.getServiceHandlerName(),
// Bind the task title
() -> titleProperty.bind(task.titleProperty()));
} | [
"private",
"void",
"bindTitle",
"(",
"final",
"ServiceTask",
"<",
"?",
">",
"task",
",",
"final",
"StringProperty",
"titleProperty",
")",
"{",
"// Perform this binding into the JAT to respect widget and task API",
"JRebirth",
".",
"runIntoJAT",
"(",
"\"Bind Title for \"",
... | Bind a task to a string property that will display the task title.
@param task the service task that we need to follow the progression
@param titleProperty the title presenter | [
"Bind",
"a",
"task",
"to",
"a",
"string",
"property",
"that",
"will",
"display",
"the",
"task",
"title",
"."
] | train | https://github.com/JRebirth/JRebirth/blob/93f4fc087b83c73db540333b9686e97b4cec694d/org.jrebirth.af/core/src/main/java/org/jrebirth/af/core/service/AbstractService.java#L224-L230 |
apereo/cas | support/cas-server-support-saml-idp-web/src/main/java/org/apereo/cas/support/saml/web/idp/profile/sso/SSOSamlProfileCallbackHandlerController.java | SSOSamlProfileCallbackHandlerController.handleCallbackProfileRequest | @GetMapping(path = SamlIdPConstants.ENDPOINT_SAML2_SSO_PROFILE_POST_CALLBACK)
protected void handleCallbackProfileRequest(final HttpServletResponse response, final HttpServletRequest request) throws Exception {
"""
Handle callback profile request.
@param response the response
@param request the request
@throws Exception the exception
"""
LOGGER.info("Received SAML callback profile request [{}]", request.getRequestURI());
val authnRequest = retrieveSamlAuthenticationRequestFromHttpRequest(request);
if (authnRequest == null) {
LOGGER.error("Can not validate the request because the original Authn request can not be found.");
response.setStatus(HttpServletResponse.SC_FORBIDDEN);
return;
}
val ticket = CommonUtils.safeGetParameter(request, CasProtocolConstants.PARAMETER_TICKET);
if (StringUtils.isBlank(ticket)) {
LOGGER.error("Can not validate the request because no [{}] is provided via the request", CasProtocolConstants.PARAMETER_TICKET);
response.setStatus(HttpServletResponse.SC_FORBIDDEN);
return;
}
val authenticationContext = buildAuthenticationContextPair(request, authnRequest);
val assertion = validateRequestAndBuildCasAssertion(response, request, authenticationContext);
val binding = determineProfileBinding(authenticationContext, assertion);
buildSamlResponse(response, request, authenticationContext, assertion, binding);
} | java | @GetMapping(path = SamlIdPConstants.ENDPOINT_SAML2_SSO_PROFILE_POST_CALLBACK)
protected void handleCallbackProfileRequest(final HttpServletResponse response, final HttpServletRequest request) throws Exception {
LOGGER.info("Received SAML callback profile request [{}]", request.getRequestURI());
val authnRequest = retrieveSamlAuthenticationRequestFromHttpRequest(request);
if (authnRequest == null) {
LOGGER.error("Can not validate the request because the original Authn request can not be found.");
response.setStatus(HttpServletResponse.SC_FORBIDDEN);
return;
}
val ticket = CommonUtils.safeGetParameter(request, CasProtocolConstants.PARAMETER_TICKET);
if (StringUtils.isBlank(ticket)) {
LOGGER.error("Can not validate the request because no [{}] is provided via the request", CasProtocolConstants.PARAMETER_TICKET);
response.setStatus(HttpServletResponse.SC_FORBIDDEN);
return;
}
val authenticationContext = buildAuthenticationContextPair(request, authnRequest);
val assertion = validateRequestAndBuildCasAssertion(response, request, authenticationContext);
val binding = determineProfileBinding(authenticationContext, assertion);
buildSamlResponse(response, request, authenticationContext, assertion, binding);
} | [
"@",
"GetMapping",
"(",
"path",
"=",
"SamlIdPConstants",
".",
"ENDPOINT_SAML2_SSO_PROFILE_POST_CALLBACK",
")",
"protected",
"void",
"handleCallbackProfileRequest",
"(",
"final",
"HttpServletResponse",
"response",
",",
"final",
"HttpServletRequest",
"request",
")",
"throws",... | Handle callback profile request.
@param response the response
@param request the request
@throws Exception the exception | [
"Handle",
"callback",
"profile",
"request",
"."
] | train | https://github.com/apereo/cas/blob/b4b306433a8782cef803a39bea5b1f96740e0e9b/support/cas-server-support-saml-idp-web/src/main/java/org/apereo/cas/support/saml/web/idp/profile/sso/SSOSamlProfileCallbackHandlerController.java#L67-L88 |
ddf-project/DDF | core/src/main/java/io/ddf/content/AMetaDataHandler.java | AMetaDataHandler.copyFactor | public void copyFactor(DDF ddf, List<String> columns) throws DDFException {
"""
Transfer factor information from ddf to this DDF
@param ddf
@param columns Columns to re-compute factors
@throws DDFException
"""
// if there is no columns to recompute factor info
if (columns == null) {
columns = new ArrayList<String>();
}
for (Schema.Column col : ddf.getSchema().getColumns()) {
if (this.getDDF().getColumn(col.getName()) != null && col.getColumnClass() == Schema.ColumnClass.FACTOR) {
// Set corresponding column as factor
this.getDDF().getSchemaHandler().setAsFactor(col.getName());
// if not in list of columns to re-compute factors
// then we just copy existing factor info to the new ones
if (!columns.contains(col.getName())) {
// copy existing factor column info
this.getDDF().getSchemaHandler().setFactorLevels(col.getName(), col.getOptionalFactor());
}
}
}
this.getDDF().getSchemaHandler().computeFactorLevelsAndLevelCounts();
} | java | public void copyFactor(DDF ddf, List<String> columns) throws DDFException {
// if there is no columns to recompute factor info
if (columns == null) {
columns = new ArrayList<String>();
}
for (Schema.Column col : ddf.getSchema().getColumns()) {
if (this.getDDF().getColumn(col.getName()) != null && col.getColumnClass() == Schema.ColumnClass.FACTOR) {
// Set corresponding column as factor
this.getDDF().getSchemaHandler().setAsFactor(col.getName());
// if not in list of columns to re-compute factors
// then we just copy existing factor info to the new ones
if (!columns.contains(col.getName())) {
// copy existing factor column info
this.getDDF().getSchemaHandler().setFactorLevels(col.getName(), col.getOptionalFactor());
}
}
}
this.getDDF().getSchemaHandler().computeFactorLevelsAndLevelCounts();
} | [
"public",
"void",
"copyFactor",
"(",
"DDF",
"ddf",
",",
"List",
"<",
"String",
">",
"columns",
")",
"throws",
"DDFException",
"{",
"// if there is no columns to recompute factor info",
"if",
"(",
"columns",
"==",
"null",
")",
"{",
"columns",
"=",
"new",
"ArrayLi... | Transfer factor information from ddf to this DDF
@param ddf
@param columns Columns to re-compute factors
@throws DDFException | [
"Transfer",
"factor",
"information",
"from",
"ddf",
"to",
"this",
"DDF"
] | train | https://github.com/ddf-project/DDF/blob/e4e68315dcec1ed8b287bf1ee73baa88e7e41eba/core/src/main/java/io/ddf/content/AMetaDataHandler.java#L115-L135 |
Azure/azure-sdk-for-java | batch/data-plane/src/main/java/com/microsoft/azure/batch/protocol/implementation/FilesImpl.java | FilesImpl.listFromTaskAsync | public ServiceFuture<List<NodeFile>> listFromTaskAsync(final String jobId, final String taskId, final ListOperationCallback<NodeFile> serviceCallback) {
"""
Lists the files in a task's directory on its compute node.
@param jobId The ID of the job that contains the task.
@param taskId The ID of the task whose files you want to list.
@param serviceCallback the async ServiceCallback to handle successful and failed responses.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the {@link ServiceFuture} object
"""
return AzureServiceFuture.fromHeaderPageResponse(
listFromTaskSinglePageAsync(jobId, taskId),
new Func1<String, Observable<ServiceResponseWithHeaders<Page<NodeFile>, FileListFromTaskHeaders>>>() {
@Override
public Observable<ServiceResponseWithHeaders<Page<NodeFile>, FileListFromTaskHeaders>> call(String nextPageLink) {
return listFromTaskNextSinglePageAsync(nextPageLink, null);
}
},
serviceCallback);
} | java | public ServiceFuture<List<NodeFile>> listFromTaskAsync(final String jobId, final String taskId, final ListOperationCallback<NodeFile> serviceCallback) {
return AzureServiceFuture.fromHeaderPageResponse(
listFromTaskSinglePageAsync(jobId, taskId),
new Func1<String, Observable<ServiceResponseWithHeaders<Page<NodeFile>, FileListFromTaskHeaders>>>() {
@Override
public Observable<ServiceResponseWithHeaders<Page<NodeFile>, FileListFromTaskHeaders>> call(String nextPageLink) {
return listFromTaskNextSinglePageAsync(nextPageLink, null);
}
},
serviceCallback);
} | [
"public",
"ServiceFuture",
"<",
"List",
"<",
"NodeFile",
">",
">",
"listFromTaskAsync",
"(",
"final",
"String",
"jobId",
",",
"final",
"String",
"taskId",
",",
"final",
"ListOperationCallback",
"<",
"NodeFile",
">",
"serviceCallback",
")",
"{",
"return",
"AzureS... | Lists the files in a task's directory on its compute node.
@param jobId The ID of the job that contains the task.
@param taskId The ID of the task whose files you want to list.
@param serviceCallback the async ServiceCallback to handle successful and failed responses.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the {@link ServiceFuture} object | [
"Lists",
"the",
"files",
"in",
"a",
"task",
"s",
"directory",
"on",
"its",
"compute",
"node",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/batch/data-plane/src/main/java/com/microsoft/azure/batch/protocol/implementation/FilesImpl.java#L1624-L1634 |
cloudant/java-cloudant | cloudant-client/src/main/java/com/cloudant/client/org/lightcouch/CouchDbClient.java | CouchDbClient.deleteDB | @Deprecated
public void deleteDB(String dbName, String confirm) {
"""
Requests CouchDB deletes a database.
@param dbName The database name
@param confirm A confirmation string with the value: <tt>delete database</tt>
@Deprecated Use {@link CouchDbClient#deleteDB(String)}
"""
if (!"delete database".equals(confirm)) {
throw new IllegalArgumentException("Invalid confirm!");
}
deleteDB(dbName);
} | java | @Deprecated
public void deleteDB(String dbName, String confirm) {
if (!"delete database".equals(confirm)) {
throw new IllegalArgumentException("Invalid confirm!");
}
deleteDB(dbName);
} | [
"@",
"Deprecated",
"public",
"void",
"deleteDB",
"(",
"String",
"dbName",
",",
"String",
"confirm",
")",
"{",
"if",
"(",
"!",
"\"delete database\"",
".",
"equals",
"(",
"confirm",
")",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Invalid confi... | Requests CouchDB deletes a database.
@param dbName The database name
@param confirm A confirmation string with the value: <tt>delete database</tt>
@Deprecated Use {@link CouchDbClient#deleteDB(String)} | [
"Requests",
"CouchDB",
"deletes",
"a",
"database",
"."
] | train | https://github.com/cloudant/java-cloudant/blob/42c438654945361bded2cc0827afc046d535b31b/cloudant-client/src/main/java/com/cloudant/client/org/lightcouch/CouchDbClient.java#L189-L195 |
lessthanoptimal/ejml | main/ejml-ddense/src/org/ejml/dense/row/factory/DecompositionFactory_DDRM.java | DecompositionFactory_DDRM.decomposeSafe | public static <T extends DMatrix> boolean decomposeSafe(DecompositionInterface<T> decomp, T M ) {
"""
A simple convinience function that decomposes the matrix but automatically checks the input ti make
sure is not being modified.
@param decomp Decomposition which is being wrapped
@param M THe matrix being decomposed.
@param <T> Matrix type.
@return If the decomposition was successful or not.
"""
if( decomp.inputModified() ) {
return decomp.decompose(M.<T>copy());
} else {
return decomp.decompose(M);
}
} | java | public static <T extends DMatrix> boolean decomposeSafe(DecompositionInterface<T> decomp, T M ) {
if( decomp.inputModified() ) {
return decomp.decompose(M.<T>copy());
} else {
return decomp.decompose(M);
}
} | [
"public",
"static",
"<",
"T",
"extends",
"DMatrix",
">",
"boolean",
"decomposeSafe",
"(",
"DecompositionInterface",
"<",
"T",
">",
"decomp",
",",
"T",
"M",
")",
"{",
"if",
"(",
"decomp",
".",
"inputModified",
"(",
")",
")",
"{",
"return",
"decomp",
".",
... | A simple convinience function that decomposes the matrix but automatically checks the input ti make
sure is not being modified.
@param decomp Decomposition which is being wrapped
@param M THe matrix being decomposed.
@param <T> Matrix type.
@return If the decomposition was successful or not. | [
"A",
"simple",
"convinience",
"function",
"that",
"decomposes",
"the",
"matrix",
"but",
"automatically",
"checks",
"the",
"input",
"ti",
"make",
"sure",
"is",
"not",
"being",
"modified",
"."
] | train | https://github.com/lessthanoptimal/ejml/blob/1444680cc487af5e866730e62f48f5f9636850d9/main/ejml-ddense/src/org/ejml/dense/row/factory/DecompositionFactory_DDRM.java#L331-L337 |
airlift/slice | src/main/java/io/airlift/slice/SliceUtf8.java | SliceUtf8.firstNonMatchPosition | private static int firstNonMatchPosition(Slice utf8, int[] codePointsToMatch) {
"""
This function is an exact duplicate of firstNonWhitespacePosition(Slice) except for one line.
"""
int length = utf8.length();
int position = 0;
while (position < length) {
int codePoint = tryGetCodePointAt(utf8, position);
if (codePoint < 0) {
break;
}
if (!matches(codePoint, codePointsToMatch)) {
break;
}
position += lengthOfCodePoint(codePoint);
}
return position;
} | java | private static int firstNonMatchPosition(Slice utf8, int[] codePointsToMatch)
{
int length = utf8.length();
int position = 0;
while (position < length) {
int codePoint = tryGetCodePointAt(utf8, position);
if (codePoint < 0) {
break;
}
if (!matches(codePoint, codePointsToMatch)) {
break;
}
position += lengthOfCodePoint(codePoint);
}
return position;
} | [
"private",
"static",
"int",
"firstNonMatchPosition",
"(",
"Slice",
"utf8",
",",
"int",
"[",
"]",
"codePointsToMatch",
")",
"{",
"int",
"length",
"=",
"utf8",
".",
"length",
"(",
")",
";",
"int",
"position",
"=",
"0",
";",
"while",
"(",
"position",
"<",
... | This function is an exact duplicate of firstNonWhitespacePosition(Slice) except for one line. | [
"This",
"function",
"is",
"an",
"exact",
"duplicate",
"of",
"firstNonWhitespacePosition",
"(",
"Slice",
")",
"except",
"for",
"one",
"line",
"."
] | train | https://github.com/airlift/slice/blob/7166cb0319e3655f8ba15f5a7ccf3d2f721c1242/src/main/java/io/airlift/slice/SliceUtf8.java#L417-L433 |
Harium/keel | src/main/java/com/harium/keel/catalano/math/Tools.java | Tools.Clamp | public static int Clamp(int x, IntRange range) {
"""
Clamp values.
@param x Value.
@param range Range.
@return Value.
"""
return Clamp(x, range.getMin(), range.getMax());
} | java | public static int Clamp(int x, IntRange range) {
return Clamp(x, range.getMin(), range.getMax());
} | [
"public",
"static",
"int",
"Clamp",
"(",
"int",
"x",
",",
"IntRange",
"range",
")",
"{",
"return",
"Clamp",
"(",
"x",
",",
"range",
".",
"getMin",
"(",
")",
",",
"range",
".",
"getMax",
"(",
")",
")",
";",
"}"
] | Clamp values.
@param x Value.
@param range Range.
@return Value. | [
"Clamp",
"values",
"."
] | train | https://github.com/Harium/keel/blob/0369ae674f9e664bccc5f9e161ae7e7a3b949a1e/src/main/java/com/harium/keel/catalano/math/Tools.java#L134-L136 |
looly/hutool | hutool-core/src/main/java/cn/hutool/core/util/NumberUtil.java | NumberUtil.isLess | public static boolean isLess(BigDecimal bigNum1, BigDecimal bigNum2) {
"""
比较大小,参数1 < 参数2 返回true
@param bigNum1 数字1
@param bigNum2 数字2
@return 是否小于
@since 3,0.9
"""
Assert.notNull(bigNum1);
Assert.notNull(bigNum2);
return bigNum1.compareTo(bigNum2) < 0;
} | java | public static boolean isLess(BigDecimal bigNum1, BigDecimal bigNum2) {
Assert.notNull(bigNum1);
Assert.notNull(bigNum2);
return bigNum1.compareTo(bigNum2) < 0;
} | [
"public",
"static",
"boolean",
"isLess",
"(",
"BigDecimal",
"bigNum1",
",",
"BigDecimal",
"bigNum2",
")",
"{",
"Assert",
".",
"notNull",
"(",
"bigNum1",
")",
";",
"Assert",
".",
"notNull",
"(",
"bigNum2",
")",
";",
"return",
"bigNum1",
".",
"compareTo",
"(... | 比较大小,参数1 < 参数2 返回true
@param bigNum1 数字1
@param bigNum2 数字2
@return 是否小于
@since 3,0.9 | [
"比较大小,参数1",
"<",
";",
"参数2",
"返回true"
] | train | https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/util/NumberUtil.java#L1650-L1654 |
jamesagnew/hapi-fhir | hapi-fhir-jaxrsserver-base/src/main/java/ca/uhn/fhir/jaxrs/server/AbstractJaxRsProvider.java | AbstractJaxRsProvider.getRequest | public Builder getRequest(final RequestTypeEnum requestType, final RestOperationTypeEnum restOperation) {
"""
Return the requestbuilder for the server
@param requestType
the type of the request
@param restOperation
the rest operation type
@return the requestbuilder
"""
return getRequest(requestType, restOperation, null);
} | java | public Builder getRequest(final RequestTypeEnum requestType, final RestOperationTypeEnum restOperation) {
return getRequest(requestType, restOperation, null);
} | [
"public",
"Builder",
"getRequest",
"(",
"final",
"RequestTypeEnum",
"requestType",
",",
"final",
"RestOperationTypeEnum",
"restOperation",
")",
"{",
"return",
"getRequest",
"(",
"requestType",
",",
"restOperation",
",",
"null",
")",
";",
"}"
] | Return the requestbuilder for the server
@param requestType
the type of the request
@param restOperation
the rest operation type
@return the requestbuilder | [
"Return",
"the",
"requestbuilder",
"for",
"the",
"server"
] | train | https://github.com/jamesagnew/hapi-fhir/blob/150a84d52fe691b7f48fcb28247c4bddb7aec352/hapi-fhir-jaxrsserver-base/src/main/java/ca/uhn/fhir/jaxrs/server/AbstractJaxRsProvider.java#L192-L194 |
osmdroid/osmdroid | osmdroid-android/src/main/java/org/osmdroid/tileprovider/cachemanager/CacheManager.java | CacheManager.getTilesRect | public static Rect getTilesRect(final BoundingBox pBB,
final int pZoomLevel) {
"""
Retrieve upper left and lower right points(exclusive) corresponding to the tiles coverage for
the selected zoom level.
@param pBB the given bounding box
@param pZoomLevel the given zoom level
@return the {@link Rect} reflecting the tiles coverage
"""
final int mapTileUpperBound = 1 << pZoomLevel;
final int right = MapView.getTileSystem().getTileXFromLongitude(pBB.getLonEast(), pZoomLevel);
final int bottom = MapView.getTileSystem().getTileYFromLatitude(pBB.getLatSouth(), pZoomLevel);
final int left = MapView.getTileSystem().getTileXFromLongitude(pBB.getLonWest(), pZoomLevel);
final int top = MapView.getTileSystem().getTileYFromLatitude(pBB.getLatNorth(), pZoomLevel);
int width = right - left + 1; // handling the modulo
if (width <= 0) {
width += mapTileUpperBound;
}
int height = bottom - top + 1; // handling the modulo
if (height <= 0) {
height += mapTileUpperBound;
}
return new Rect(left, top, left + width - 1, top + height - 1);
} | java | public static Rect getTilesRect(final BoundingBox pBB,
final int pZoomLevel){
final int mapTileUpperBound = 1 << pZoomLevel;
final int right = MapView.getTileSystem().getTileXFromLongitude(pBB.getLonEast(), pZoomLevel);
final int bottom = MapView.getTileSystem().getTileYFromLatitude(pBB.getLatSouth(), pZoomLevel);
final int left = MapView.getTileSystem().getTileXFromLongitude(pBB.getLonWest(), pZoomLevel);
final int top = MapView.getTileSystem().getTileYFromLatitude(pBB.getLatNorth(), pZoomLevel);
int width = right - left + 1; // handling the modulo
if (width <= 0) {
width += mapTileUpperBound;
}
int height = bottom - top + 1; // handling the modulo
if (height <= 0) {
height += mapTileUpperBound;
}
return new Rect(left, top, left + width - 1, top + height - 1);
} | [
"public",
"static",
"Rect",
"getTilesRect",
"(",
"final",
"BoundingBox",
"pBB",
",",
"final",
"int",
"pZoomLevel",
")",
"{",
"final",
"int",
"mapTileUpperBound",
"=",
"1",
"<<",
"pZoomLevel",
";",
"final",
"int",
"right",
"=",
"MapView",
".",
"getTileSystem",
... | Retrieve upper left and lower right points(exclusive) corresponding to the tiles coverage for
the selected zoom level.
@param pBB the given bounding box
@param pZoomLevel the given zoom level
@return the {@link Rect} reflecting the tiles coverage | [
"Retrieve",
"upper",
"left",
"and",
"lower",
"right",
"points",
"(",
"exclusive",
")",
"corresponding",
"to",
"the",
"tiles",
"coverage",
"for",
"the",
"selected",
"zoom",
"level",
"."
] | train | https://github.com/osmdroid/osmdroid/blob/3b178b2f078497dd88c137110e87aafe45ad2b16/osmdroid-android/src/main/java/org/osmdroid/tileprovider/cachemanager/CacheManager.java#L246-L262 |
Azure/azure-sdk-for-java | network/resource-manager/v2018_06_01/src/main/java/com/microsoft/azure/management/network/v2018_06_01/implementation/RoutesInner.java | RoutesInner.createOrUpdateAsync | public Observable<RouteInner> createOrUpdateAsync(String resourceGroupName, String routeTableName, String routeName, RouteInner routeParameters) {
"""
Creates or updates a route in the specified route table.
@param resourceGroupName The name of the resource group.
@param routeTableName The name of the route table.
@param routeName The name of the route.
@param routeParameters Parameters supplied to the create or update route operation.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable for the request
"""
return createOrUpdateWithServiceResponseAsync(resourceGroupName, routeTableName, routeName, routeParameters).map(new Func1<ServiceResponse<RouteInner>, RouteInner>() {
@Override
public RouteInner call(ServiceResponse<RouteInner> response) {
return response.body();
}
});
} | java | public Observable<RouteInner> createOrUpdateAsync(String resourceGroupName, String routeTableName, String routeName, RouteInner routeParameters) {
return createOrUpdateWithServiceResponseAsync(resourceGroupName, routeTableName, routeName, routeParameters).map(new Func1<ServiceResponse<RouteInner>, RouteInner>() {
@Override
public RouteInner call(ServiceResponse<RouteInner> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"RouteInner",
">",
"createOrUpdateAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"routeTableName",
",",
"String",
"routeName",
",",
"RouteInner",
"routeParameters",
")",
"{",
"return",
"createOrUpdateWithServiceResponseAsync",
"(",... | Creates or updates a route in the specified route table.
@param resourceGroupName The name of the resource group.
@param routeTableName The name of the route table.
@param routeName The name of the route.
@param routeParameters Parameters supplied to the create or update route operation.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable for the request | [
"Creates",
"or",
"updates",
"a",
"route",
"in",
"the",
"specified",
"route",
"table",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2018_06_01/src/main/java/com/microsoft/azure/management/network/v2018_06_01/implementation/RoutesInner.java#L391-L398 |
sebastiangraf/treetank | interfacemodules/jax-rx/src/main/java/org/jaxrx/resource/JaxRxResource.java | JaxRxResource.getResource | @Path(JaxRxConstants.JAXRXPATH)
@GET
public Response getResource(@PathParam(JaxRxConstants.SYSTEM) final String system,
@Context final UriInfo uri, @Context final HttpHeaders headers) {
"""
This method returns a collection of available resources. An available
resource can be either a particular XML resource or a collection containing
further XML resources.
@param system
The associated system with this request.
@param uri
The context information due to the requested URI.
@param headers
HTTP header attributes.
@return The available resources resources according to the URL path.
"""
return getResource(system, uri, "", headers);
} | java | @Path(JaxRxConstants.JAXRXPATH)
@GET
public Response getResource(@PathParam(JaxRxConstants.SYSTEM) final String system,
@Context final UriInfo uri, @Context final HttpHeaders headers) {
return getResource(system, uri, "", headers);
} | [
"@",
"Path",
"(",
"JaxRxConstants",
".",
"JAXRXPATH",
")",
"@",
"GET",
"public",
"Response",
"getResource",
"(",
"@",
"PathParam",
"(",
"JaxRxConstants",
".",
"SYSTEM",
")",
"final",
"String",
"system",
",",
"@",
"Context",
"final",
"UriInfo",
"uri",
",",
... | This method returns a collection of available resources. An available
resource can be either a particular XML resource or a collection containing
further XML resources.
@param system
The associated system with this request.
@param uri
The context information due to the requested URI.
@param headers
HTTP header attributes.
@return The available resources resources according to the URL path. | [
"This",
"method",
"returns",
"a",
"collection",
"of",
"available",
"resources",
".",
"An",
"available",
"resource",
"can",
"be",
"either",
"a",
"particular",
"XML",
"resource",
"or",
"a",
"collection",
"containing",
"further",
"XML",
"resources",
"."
] | train | https://github.com/sebastiangraf/treetank/blob/9b96d631b6c2a8502a0cc958dcb02bd6a6fd8b60/interfacemodules/jax-rx/src/main/java/org/jaxrx/resource/JaxRxResource.java#L111-L116 |
apptik/jus | android/jus-android/src/main/java/io/apptik/comm/jus/util/BitmapLruPool.java | BitmapLruPool.getBitmap | public synchronized Bitmap getBitmap(BitmapFactory.Options options) {
"""
Returns a bitmap from the pool if one is available in the requested size, or allocates a new
one if a pooled one is not available.
@param options the options required to reuse the bitmap. The returned bitmap
may be larger.
@return Bitmap or null if not found.
"""
Bitmap bitmap = null;
synchronized (bitmapsBySize) {
final Iterator<Bitmap> iterator = bitmapsBySize.iterator();
Bitmap item;
while (iterator.hasNext()) {
item = iterator.next();
if (null != item && canBePooled(item)) {
// Check to see it the item can be used for inBitmap
if (BitmapLruPool.canUseForInBitmap(item, options)) {
bitmap = item;
currentSize -= getBitmapSize(bitmap);
// Remove from reusable set so it can't be used again
iterator.remove();
bitmapsByLastUse.remove(bitmap);
break;
}
} else {
currentSize -= getBitmapSize(item);
// Remove from the set if the reference has been cleared.
iterator.remove();
bitmapsByLastUse.remove(item);
}
}
}
return bitmap;
} | java | public synchronized Bitmap getBitmap(BitmapFactory.Options options) {
Bitmap bitmap = null;
synchronized (bitmapsBySize) {
final Iterator<Bitmap> iterator = bitmapsBySize.iterator();
Bitmap item;
while (iterator.hasNext()) {
item = iterator.next();
if (null != item && canBePooled(item)) {
// Check to see it the item can be used for inBitmap
if (BitmapLruPool.canUseForInBitmap(item, options)) {
bitmap = item;
currentSize -= getBitmapSize(bitmap);
// Remove from reusable set so it can't be used again
iterator.remove();
bitmapsByLastUse.remove(bitmap);
break;
}
} else {
currentSize -= getBitmapSize(item);
// Remove from the set if the reference has been cleared.
iterator.remove();
bitmapsByLastUse.remove(item);
}
}
}
return bitmap;
} | [
"public",
"synchronized",
"Bitmap",
"getBitmap",
"(",
"BitmapFactory",
".",
"Options",
"options",
")",
"{",
"Bitmap",
"bitmap",
"=",
"null",
";",
"synchronized",
"(",
"bitmapsBySize",
")",
"{",
"final",
"Iterator",
"<",
"Bitmap",
">",
"iterator",
"=",
"bitmaps... | Returns a bitmap from the pool if one is available in the requested size, or allocates a new
one if a pooled one is not available.
@param options the options required to reuse the bitmap. The returned bitmap
may be larger.
@return Bitmap or null if not found. | [
"Returns",
"a",
"bitmap",
"from",
"the",
"pool",
"if",
"one",
"is",
"available",
"in",
"the",
"requested",
"size",
"or",
"allocates",
"a",
"new",
"one",
"if",
"a",
"pooled",
"one",
"is",
"not",
"available",
"."
] | train | https://github.com/apptik/jus/blob/8a37a21b41f897d68eaeaab07368ec22a1e5a60e/android/jus-android/src/main/java/io/apptik/comm/jus/util/BitmapLruPool.java#L100-L130 |
michael-rapp/AndroidUtil | library/src/main/java/de/mrapp/android/util/ElevationUtil.java | ElevationUtil.getHorizontalShadowColor | private static int getHorizontalShadowColor(final int elevation,
@NonNull final Orientation orientation,
final boolean parallelLight) {
"""
Returns the color of a shadow, which is located next to a corner of an elevated view in
horizontal direction.
@param elevation
The elevation, which should be emulated, in dp as an {@link Integer} value. The
elevation must be at least 0 and at maximum the value of the constant
<code>MAX_ELEVATION</code>
@param orientation
The orientation of the shadow in relation to the elevated view as a value of the enum
{@link Orientation}. The orientation may either be <code>TOP_LEFT</code>,
<code>TOP_RIGHT</code>, <code>BOTTOM_LEFT</code> or <code>BOTTOM_RIGHT</code>
@param parallelLight
True, if parallel light should be emulated, false otherwise
@return The color of the shadow as an {@link Integer} value
"""
switch (orientation) {
case TOP_LEFT:
case TOP_RIGHT:
return getShadowColor(elevation, Orientation.TOP, parallelLight);
case BOTTOM_LEFT:
case BOTTOM_RIGHT:
return getShadowColor(elevation, Orientation.BOTTOM, parallelLight);
default:
throw new IllegalArgumentException("Invalid orientation: " + orientation);
}
} | java | private static int getHorizontalShadowColor(final int elevation,
@NonNull final Orientation orientation,
final boolean parallelLight) {
switch (orientation) {
case TOP_LEFT:
case TOP_RIGHT:
return getShadowColor(elevation, Orientation.TOP, parallelLight);
case BOTTOM_LEFT:
case BOTTOM_RIGHT:
return getShadowColor(elevation, Orientation.BOTTOM, parallelLight);
default:
throw new IllegalArgumentException("Invalid orientation: " + orientation);
}
} | [
"private",
"static",
"int",
"getHorizontalShadowColor",
"(",
"final",
"int",
"elevation",
",",
"@",
"NonNull",
"final",
"Orientation",
"orientation",
",",
"final",
"boolean",
"parallelLight",
")",
"{",
"switch",
"(",
"orientation",
")",
"{",
"case",
"TOP_LEFT",
... | Returns the color of a shadow, which is located next to a corner of an elevated view in
horizontal direction.
@param elevation
The elevation, which should be emulated, in dp as an {@link Integer} value. The
elevation must be at least 0 and at maximum the value of the constant
<code>MAX_ELEVATION</code>
@param orientation
The orientation of the shadow in relation to the elevated view as a value of the enum
{@link Orientation}. The orientation may either be <code>TOP_LEFT</code>,
<code>TOP_RIGHT</code>, <code>BOTTOM_LEFT</code> or <code>BOTTOM_RIGHT</code>
@param parallelLight
True, if parallel light should be emulated, false otherwise
@return The color of the shadow as an {@link Integer} value | [
"Returns",
"the",
"color",
"of",
"a",
"shadow",
"which",
"is",
"located",
"next",
"to",
"a",
"corner",
"of",
"an",
"elevated",
"view",
"in",
"horizontal",
"direction",
"."
] | train | https://github.com/michael-rapp/AndroidUtil/blob/67ec0e5732344eeb4d946dd1f96d782939e449f4/library/src/main/java/de/mrapp/android/util/ElevationUtil.java#L536-L549 |
rundeck/rundeck | core/src/main/java/com/dtolabs/rundeck/core/authorization/providers/PoliciesCache.java | PoliciesCache.fromDir | public static PoliciesCache fromDir(File rootDir, final Set<Attribute> forcedContext) {
"""
Create a cache from a directory source
@param rootDir base director
@return cache
"""
return fromSourceProvider(YamlProvider.getDirProvider(rootDir),forcedContext);
} | java | public static PoliciesCache fromDir(File rootDir, final Set<Attribute> forcedContext) {
return fromSourceProvider(YamlProvider.getDirProvider(rootDir),forcedContext);
} | [
"public",
"static",
"PoliciesCache",
"fromDir",
"(",
"File",
"rootDir",
",",
"final",
"Set",
"<",
"Attribute",
">",
"forcedContext",
")",
"{",
"return",
"fromSourceProvider",
"(",
"YamlProvider",
".",
"getDirProvider",
"(",
"rootDir",
")",
",",
"forcedContext",
... | Create a cache from a directory source
@param rootDir base director
@return cache | [
"Create",
"a",
"cache",
"from",
"a",
"directory",
"source"
] | train | https://github.com/rundeck/rundeck/blob/8070f774f55bffaa1118ff0c03aea319d40a9668/core/src/main/java/com/dtolabs/rundeck/core/authorization/providers/PoliciesCache.java#L197-L199 |
alkacon/opencms-core | src/org/opencms/gwt/shared/CmsTemplateContextInfo.java | CmsTemplateContextInfo.setClientVariant | public void setClientVariant(String context, String variant, CmsClientVariantInfo info) {
"""
Adds a client variant.<p>
@param context a context name
@param variant the variant name
@param info the bean with the variant information
"""
if (!m_clientVariantInfo.containsKey(context)) {
Map<String, CmsClientVariantInfo> variants = new LinkedHashMap<String, CmsClientVariantInfo>();
m_clientVariantInfo.put(context, variants);
}
m_clientVariantInfo.get(context).put(variant, info);
} | java | public void setClientVariant(String context, String variant, CmsClientVariantInfo info) {
if (!m_clientVariantInfo.containsKey(context)) {
Map<String, CmsClientVariantInfo> variants = new LinkedHashMap<String, CmsClientVariantInfo>();
m_clientVariantInfo.put(context, variants);
}
m_clientVariantInfo.get(context).put(variant, info);
} | [
"public",
"void",
"setClientVariant",
"(",
"String",
"context",
",",
"String",
"variant",
",",
"CmsClientVariantInfo",
"info",
")",
"{",
"if",
"(",
"!",
"m_clientVariantInfo",
".",
"containsKey",
"(",
"context",
")",
")",
"{",
"Map",
"<",
"String",
",",
"Cms... | Adds a client variant.<p>
@param context a context name
@param variant the variant name
@param info the bean with the variant information | [
"Adds",
"a",
"client",
"variant",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/gwt/shared/CmsTemplateContextInfo.java#L195-L202 |
TheHortonMachine/hortonmachine | gears/src/main/java/org/hortonmachine/gears/spatialite/SpatialDbsImportUtils.java | SpatialDbsImportUtils.importShapefile | public static boolean importShapefile( ASpatialDb db, File shapeFile, String tableName, int limit, IHMProgressMonitor pm )
throws Exception {
"""
Import a shapefile into a table.
@param db the database to use.
@param shapeFile the shapefile to import.
@param tableName the name of the table to import to.
@param limit if > 0, a limit to the imported features is applied.
@param pm the progress monitor.
@return <code>false</code>, is an error occurred.
@throws Exception
"""
FileDataStore store = FileDataStoreFinder.getDataStore(shapeFile);
SimpleFeatureSource featureSource = store.getFeatureSource();
SimpleFeatureCollection features = featureSource.getFeatures();
return importFeatureCollection(db, features, tableName, limit, pm);
} | java | public static boolean importShapefile( ASpatialDb db, File shapeFile, String tableName, int limit, IHMProgressMonitor pm )
throws Exception {
FileDataStore store = FileDataStoreFinder.getDataStore(shapeFile);
SimpleFeatureSource featureSource = store.getFeatureSource();
SimpleFeatureCollection features = featureSource.getFeatures();
return importFeatureCollection(db, features, tableName, limit, pm);
} | [
"public",
"static",
"boolean",
"importShapefile",
"(",
"ASpatialDb",
"db",
",",
"File",
"shapeFile",
",",
"String",
"tableName",
",",
"int",
"limit",
",",
"IHMProgressMonitor",
"pm",
")",
"throws",
"Exception",
"{",
"FileDataStore",
"store",
"=",
"FileDataStoreFin... | Import a shapefile into a table.
@param db the database to use.
@param shapeFile the shapefile to import.
@param tableName the name of the table to import to.
@param limit if > 0, a limit to the imported features is applied.
@param pm the progress monitor.
@return <code>false</code>, is an error occurred.
@throws Exception | [
"Import",
"a",
"shapefile",
"into",
"a",
"table",
"."
] | train | https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/org/hortonmachine/gears/spatialite/SpatialDbsImportUtils.java#L199-L207 |
google/j2objc | xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xalan/transformer/TransformerImpl.java | TransformerImpl.transformToGlobalRTF | public int transformToGlobalRTF(ElemTemplateElement templateParent)
throws TransformerException {
"""
Given a stylesheet element, create a result tree fragment from it's
contents. The fragment will also use the shared DTM system, but will
obtain its space from the global variable pool rather than the dynamic
variable stack. This allows late binding of XUnresolvedVariables without
the risk that their content will be discarded when the variable stack
is popped.
@param templateParent The template element that holds the fragment.
@return the NodeHandle for the root node of the resulting RTF.
@throws TransformerException
@xsl.usage advanced
"""
// Retrieve a DTM to contain the RTF. At this writing, this may be a
// multi-document DTM (SAX2RTFDTM).
DTM dtmFrag = m_xcontext.getGlobalRTFDTM();
return transformToRTF(templateParent,dtmFrag);
} | java | public int transformToGlobalRTF(ElemTemplateElement templateParent)
throws TransformerException
{
// Retrieve a DTM to contain the RTF. At this writing, this may be a
// multi-document DTM (SAX2RTFDTM).
DTM dtmFrag = m_xcontext.getGlobalRTFDTM();
return transformToRTF(templateParent,dtmFrag);
} | [
"public",
"int",
"transformToGlobalRTF",
"(",
"ElemTemplateElement",
"templateParent",
")",
"throws",
"TransformerException",
"{",
"// Retrieve a DTM to contain the RTF. At this writing, this may be a",
"// multi-document DTM (SAX2RTFDTM).",
"DTM",
"dtmFrag",
"=",
"m_xcontext",
".",
... | Given a stylesheet element, create a result tree fragment from it's
contents. The fragment will also use the shared DTM system, but will
obtain its space from the global variable pool rather than the dynamic
variable stack. This allows late binding of XUnresolvedVariables without
the risk that their content will be discarded when the variable stack
is popped.
@param templateParent The template element that holds the fragment.
@return the NodeHandle for the root node of the resulting RTF.
@throws TransformerException
@xsl.usage advanced | [
"Given",
"a",
"stylesheet",
"element",
"create",
"a",
"result",
"tree",
"fragment",
"from",
"it",
"s",
"contents",
".",
"The",
"fragment",
"will",
"also",
"use",
"the",
"shared",
"DTM",
"system",
"but",
"will",
"obtain",
"its",
"space",
"from",
"the",
"glo... | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xalan/transformer/TransformerImpl.java#L1771-L1778 |
apache/incubator-gobblin | gobblin-core/src/main/java/org/apache/gobblin/converter/avro/JsonElementConversionFactory.java | JsonElementConversionFactory.getConvertor | public static JsonElementConverter getConvertor(String fieldName, String fieldType, JsonObject schemaNode,
WorkUnitState state, boolean nullable)
throws UnsupportedDateTypeException {
"""
Backward Compatible form of {@link JsonElementConverter#getConvertor(JsonSchema, String, WorkUnitState)}
@param fieldName
@param fieldType
@param schemaNode
@param state
@param nullable
@return
@throws UnsupportedDateTypeException
"""
if (!schemaNode.has(COLUMN_NAME_KEY)) {
schemaNode.addProperty(COLUMN_NAME_KEY, fieldName);
}
if (!schemaNode.has(DATA_TYPE_KEY)) {
schemaNode.add(DATA_TYPE_KEY, new JsonObject());
}
JsonObject dataType = schemaNode.get(DATA_TYPE_KEY).getAsJsonObject();
if (!dataType.has(TYPE_KEY)) {
dataType.addProperty(TYPE_KEY, fieldType);
}
if (!schemaNode.has(IS_NULLABLE_KEY)) {
schemaNode.addProperty(IS_NULLABLE_KEY, nullable);
}
JsonSchema schema = new JsonSchema(schemaNode);
return getConvertor(schema, null, state);
} | java | public static JsonElementConverter getConvertor(String fieldName, String fieldType, JsonObject schemaNode,
WorkUnitState state, boolean nullable)
throws UnsupportedDateTypeException {
if (!schemaNode.has(COLUMN_NAME_KEY)) {
schemaNode.addProperty(COLUMN_NAME_KEY, fieldName);
}
if (!schemaNode.has(DATA_TYPE_KEY)) {
schemaNode.add(DATA_TYPE_KEY, new JsonObject());
}
JsonObject dataType = schemaNode.get(DATA_TYPE_KEY).getAsJsonObject();
if (!dataType.has(TYPE_KEY)) {
dataType.addProperty(TYPE_KEY, fieldType);
}
if (!schemaNode.has(IS_NULLABLE_KEY)) {
schemaNode.addProperty(IS_NULLABLE_KEY, nullable);
}
JsonSchema schema = new JsonSchema(schemaNode);
return getConvertor(schema, null, state);
} | [
"public",
"static",
"JsonElementConverter",
"getConvertor",
"(",
"String",
"fieldName",
",",
"String",
"fieldType",
",",
"JsonObject",
"schemaNode",
",",
"WorkUnitState",
"state",
",",
"boolean",
"nullable",
")",
"throws",
"UnsupportedDateTypeException",
"{",
"if",
"(... | Backward Compatible form of {@link JsonElementConverter#getConvertor(JsonSchema, String, WorkUnitState)}
@param fieldName
@param fieldType
@param schemaNode
@param state
@param nullable
@return
@throws UnsupportedDateTypeException | [
"Backward",
"Compatible",
"form",
"of",
"{"
] | train | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-core/src/main/java/org/apache/gobblin/converter/avro/JsonElementConversionFactory.java#L177-L195 |
Azure/azure-sdk-for-java | keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/implementation/KeyVaultClientBaseImpl.java | KeyVaultClientBaseImpl.updateCertificateAsync | public ServiceFuture<CertificateBundle> updateCertificateAsync(String vaultBaseUrl, String certificateName, String certificateVersion, final ServiceCallback<CertificateBundle> serviceCallback) {
"""
Updates the specified attributes associated with the given certificate.
The UpdateCertificate operation applies the specified update on the given certificate; the only elements updated are the certificate's attributes. This operation requires the certificates/update permission.
@param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net.
@param certificateName The name of the certificate in the given key vault.
@param certificateVersion The version of the certificate.
@param serviceCallback the async ServiceCallback to handle successful and failed responses.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the {@link ServiceFuture} object
"""
return ServiceFuture.fromResponse(updateCertificateWithServiceResponseAsync(vaultBaseUrl, certificateName, certificateVersion), serviceCallback);
} | java | public ServiceFuture<CertificateBundle> updateCertificateAsync(String vaultBaseUrl, String certificateName, String certificateVersion, final ServiceCallback<CertificateBundle> serviceCallback) {
return ServiceFuture.fromResponse(updateCertificateWithServiceResponseAsync(vaultBaseUrl, certificateName, certificateVersion), serviceCallback);
} | [
"public",
"ServiceFuture",
"<",
"CertificateBundle",
">",
"updateCertificateAsync",
"(",
"String",
"vaultBaseUrl",
",",
"String",
"certificateName",
",",
"String",
"certificateVersion",
",",
"final",
"ServiceCallback",
"<",
"CertificateBundle",
">",
"serviceCallback",
")"... | Updates the specified attributes associated with the given certificate.
The UpdateCertificate operation applies the specified update on the given certificate; the only elements updated are the certificate's attributes. This operation requires the certificates/update permission.
@param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net.
@param certificateName The name of the certificate in the given key vault.
@param certificateVersion The version of the certificate.
@param serviceCallback the async ServiceCallback to handle successful and failed responses.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the {@link ServiceFuture} object | [
"Updates",
"the",
"specified",
"attributes",
"associated",
"with",
"the",
"given",
"certificate",
".",
"The",
"UpdateCertificate",
"operation",
"applies",
"the",
"specified",
"update",
"on",
"the",
"given",
"certificate",
";",
"the",
"only",
"elements",
"updated",
... | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/implementation/KeyVaultClientBaseImpl.java#L7352-L7354 |
lucee/Lucee | core/src/main/java/lucee/runtime/type/util/ComponentUtil.java | ComponentUtil.getClientComponentPropertiesClass | public static Class getClientComponentPropertiesClass(PageContext pc, String className, ASMProperty[] properties, Class extendsClass) throws PageException {
"""
/*
includes the application context javasettings
@param pc
@param className
@param properties
@return
@throws PageException
"""
try {
return _getComponentPropertiesClass(pc, pc.getConfig(), className, properties, extendsClass);
}
catch (Exception e) {
throw Caster.toPageException(e);
}
} | java | public static Class getClientComponentPropertiesClass(PageContext pc, String className, ASMProperty[] properties, Class extendsClass) throws PageException {
try {
return _getComponentPropertiesClass(pc, pc.getConfig(), className, properties, extendsClass);
}
catch (Exception e) {
throw Caster.toPageException(e);
}
} | [
"public",
"static",
"Class",
"getClientComponentPropertiesClass",
"(",
"PageContext",
"pc",
",",
"String",
"className",
",",
"ASMProperty",
"[",
"]",
"properties",
",",
"Class",
"extendsClass",
")",
"throws",
"PageException",
"{",
"try",
"{",
"return",
"_getComponen... | /*
includes the application context javasettings
@param pc
@param className
@param properties
@return
@throws PageException | [
"/",
"*",
"includes",
"the",
"application",
"context",
"javasettings"
] | train | https://github.com/lucee/Lucee/blob/29b153fc4e126e5edb97da937f2ee2e231b87593/core/src/main/java/lucee/runtime/type/util/ComponentUtil.java#L357-L364 |
katjahahn/PortEx | src/main/java/com/github/katjahahn/tools/visualizer/Visualizer.java | Visualizer.getColorForEntropy | private Color getColorForEntropy(double entropy) {
"""
Creates a color instance based on a given entropy.
@param entropy
value between 0 and 1
@return Color for given entropy
"""
assert entropy <= 1;
assert entropy >= 0;
Color entropyColor = colorMap.get(ENTROPY);
float[] hsbvals = new float[3];
Color.RGBtoHSB(entropyColor.getRed(), entropyColor.getGreen(),
entropyColor.getBlue(), hsbvals);
float entropyHue = hsbvals[0];
float saturation = hsbvals[1];
float brightness = (float) entropy;
return Color.getHSBColor(entropyHue, saturation, brightness);
// int col = (int) (entropy * 255);
// return new Color(col, col, col);
} | java | private Color getColorForEntropy(double entropy) {
assert entropy <= 1;
assert entropy >= 0;
Color entropyColor = colorMap.get(ENTROPY);
float[] hsbvals = new float[3];
Color.RGBtoHSB(entropyColor.getRed(), entropyColor.getGreen(),
entropyColor.getBlue(), hsbvals);
float entropyHue = hsbvals[0];
float saturation = hsbvals[1];
float brightness = (float) entropy;
return Color.getHSBColor(entropyHue, saturation, brightness);
// int col = (int) (entropy * 255);
// return new Color(col, col, col);
} | [
"private",
"Color",
"getColorForEntropy",
"(",
"double",
"entropy",
")",
"{",
"assert",
"entropy",
"<=",
"1",
";",
"assert",
"entropy",
">=",
"0",
";",
"Color",
"entropyColor",
"=",
"colorMap",
".",
"get",
"(",
"ENTROPY",
")",
";",
"float",
"[",
"]",
"hs... | Creates a color instance based on a given entropy.
@param entropy
value between 0 and 1
@return Color for given entropy | [
"Creates",
"a",
"color",
"instance",
"based",
"on",
"a",
"given",
"entropy",
"."
] | train | https://github.com/katjahahn/PortEx/blob/319f08560aa58e3d5d7abe346ffdf623d6dc6990/src/main/java/com/github/katjahahn/tools/visualizer/Visualizer.java#L283-L296 |
google/error-prone | check_api/src/main/java/com/google/errorprone/matchers/Matchers.java | Matchers.hasAnnotationOnAnyOverriddenMethod | public static Matcher<MethodTree> hasAnnotationOnAnyOverriddenMethod(
final String annotationClass) {
"""
Matches if a method or any method it overrides has an annotation of the given type. JUnit 4's
{@code @Test}, {@code @Before}, and {@code @After} annotations behave this way.
@param annotationClass the binary class name of the annotation (e.g.
"javax.annotation.Nullable", or "some.package.OuterClassName$InnerClassName")
"""
return new Matcher<MethodTree>() {
@Override
public boolean matches(MethodTree tree, VisitorState state) {
MethodSymbol methodSym = ASTHelpers.getSymbol(tree);
if (methodSym == null) {
return false;
}
if (ASTHelpers.hasAnnotation(methodSym, annotationClass, state)) {
return true;
}
for (MethodSymbol method : ASTHelpers.findSuperMethods(methodSym, state.getTypes())) {
if (ASTHelpers.hasAnnotation(method, annotationClass, state)) {
return true;
}
}
return false;
}
};
} | java | public static Matcher<MethodTree> hasAnnotationOnAnyOverriddenMethod(
final String annotationClass) {
return new Matcher<MethodTree>() {
@Override
public boolean matches(MethodTree tree, VisitorState state) {
MethodSymbol methodSym = ASTHelpers.getSymbol(tree);
if (methodSym == null) {
return false;
}
if (ASTHelpers.hasAnnotation(methodSym, annotationClass, state)) {
return true;
}
for (MethodSymbol method : ASTHelpers.findSuperMethods(methodSym, state.getTypes())) {
if (ASTHelpers.hasAnnotation(method, annotationClass, state)) {
return true;
}
}
return false;
}
};
} | [
"public",
"static",
"Matcher",
"<",
"MethodTree",
">",
"hasAnnotationOnAnyOverriddenMethod",
"(",
"final",
"String",
"annotationClass",
")",
"{",
"return",
"new",
"Matcher",
"<",
"MethodTree",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"boolean",
"matches",
... | Matches if a method or any method it overrides has an annotation of the given type. JUnit 4's
{@code @Test}, {@code @Before}, and {@code @After} annotations behave this way.
@param annotationClass the binary class name of the annotation (e.g.
"javax.annotation.Nullable", or "some.package.OuterClassName$InnerClassName") | [
"Matches",
"if",
"a",
"method",
"or",
"any",
"method",
"it",
"overrides",
"has",
"an",
"annotation",
"of",
"the",
"given",
"type",
".",
"JUnit",
"4",
"s",
"{",
"@code",
"@Test",
"}",
"{",
"@code",
"@Before",
"}",
"and",
"{",
"@code",
"@After",
"}",
"... | train | https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/check_api/src/main/java/com/google/errorprone/matchers/Matchers.java#L859-L879 |
itfsw/QueryBuilder | src/main/java/com/itfsw/query/builder/support/utils/spring/Assert.java | Assert.isInstanceOf | public static void isInstanceOf(Class<?> type, Object obj, String message) {
"""
Assert that the provided object is an instance of the provided class.
<pre class="code">Assert.instanceOf(Foo.class, foo, "Foo expected");</pre>
@param type the type to check against
@param obj the object to check
@param message a message which will be prepended to provide further context.
If it is empty or ends in ":" or ";" or "," or ".", a full exception message
will be appended. If it ends in a space, the name of the offending object's
type will be appended. In any other case, a ":" with a space and the name
of the offending object's type will be appended.
@throws IllegalArgumentException if the object is not an instance of type
"""
notNull(type, "Type to check against must not be null");
if (!type.isInstance(obj)) {
instanceCheckFailed(type, obj, message);
}
} | java | public static void isInstanceOf(Class<?> type, Object obj, String message) {
notNull(type, "Type to check against must not be null");
if (!type.isInstance(obj)) {
instanceCheckFailed(type, obj, message);
}
} | [
"public",
"static",
"void",
"isInstanceOf",
"(",
"Class",
"<",
"?",
">",
"type",
",",
"Object",
"obj",
",",
"String",
"message",
")",
"{",
"notNull",
"(",
"type",
",",
"\"Type to check against must not be null\"",
")",
";",
"if",
"(",
"!",
"type",
".",
"is... | Assert that the provided object is an instance of the provided class.
<pre class="code">Assert.instanceOf(Foo.class, foo, "Foo expected");</pre>
@param type the type to check against
@param obj the object to check
@param message a message which will be prepended to provide further context.
If it is empty or ends in ":" or ";" or "," or ".", a full exception message
will be appended. If it ends in a space, the name of the offending object's
type will be appended. In any other case, a ":" with a space and the name
of the offending object's type will be appended.
@throws IllegalArgumentException if the object is not an instance of type | [
"Assert",
"that",
"the",
"provided",
"object",
"is",
"an",
"instance",
"of",
"the",
"provided",
"class",
".",
"<pre",
"class",
"=",
"code",
">",
"Assert",
".",
"instanceOf",
"(",
"Foo",
".",
"class",
"foo",
"Foo",
"expected",
")",
";",
"<",
"/",
"pre",... | train | https://github.com/itfsw/QueryBuilder/blob/231dc9a334d54cf98755cfcb236202201ddee162/src/main/java/com/itfsw/query/builder/support/utils/spring/Assert.java#L324-L329 |
outbrain/ob1k | ob1k-concurrent/src/main/java/com/outbrain/ob1k/concurrent/ComposableFutures.java | ComposableFutures.submit | public static <T> ComposableFuture<T> submit(final Callable<T> task) {
"""
sends a callable task to the default thread pool and returns a ComposableFuture that represent the result.
@param task the task to run.
@param <T> the future type
@return a future representing the result.
"""
return submit(false, task);
} | java | public static <T> ComposableFuture<T> submit(final Callable<T> task) {
return submit(false, task);
} | [
"public",
"static",
"<",
"T",
">",
"ComposableFuture",
"<",
"T",
">",
"submit",
"(",
"final",
"Callable",
"<",
"T",
">",
"task",
")",
"{",
"return",
"submit",
"(",
"false",
",",
"task",
")",
";",
"}"
] | sends a callable task to the default thread pool and returns a ComposableFuture that represent the result.
@param task the task to run.
@param <T> the future type
@return a future representing the result. | [
"sends",
"a",
"callable",
"task",
"to",
"the",
"default",
"thread",
"pool",
"and",
"returns",
"a",
"ComposableFuture",
"that",
"represent",
"the",
"result",
"."
] | train | https://github.com/outbrain/ob1k/blob/9e43ab39230c5787065053da0f766d822d0fe4e7/ob1k-concurrent/src/main/java/com/outbrain/ob1k/concurrent/ComposableFutures.java#L415-L417 |
Wadpam/guja | guja-contact/src/main/java/com/wadpam/guja/dao/GeneratedDContactDaoImpl.java | GeneratedDContactDaoImpl.queryByAddress2 | public Iterable<DContact> queryByAddress2(Object parent, java.lang.String address2) {
"""
query-by method for field address2
@param address2 the specified attribute
@return an Iterable of DContacts for the specified address2
"""
return queryByField(parent, DContactMapper.Field.ADDRESS2.getFieldName(), address2);
} | java | public Iterable<DContact> queryByAddress2(Object parent, java.lang.String address2) {
return queryByField(parent, DContactMapper.Field.ADDRESS2.getFieldName(), address2);
} | [
"public",
"Iterable",
"<",
"DContact",
">",
"queryByAddress2",
"(",
"Object",
"parent",
",",
"java",
".",
"lang",
".",
"String",
"address2",
")",
"{",
"return",
"queryByField",
"(",
"parent",
",",
"DContactMapper",
".",
"Field",
".",
"ADDRESS2",
".",
"getFie... | query-by method for field address2
@param address2 the specified attribute
@return an Iterable of DContacts for the specified address2 | [
"query",
"-",
"by",
"method",
"for",
"field",
"address2"
] | train | https://github.com/Wadpam/guja/blob/eb8ba8e6794a96ea0dd9744cada4f9ad9618f114/guja-contact/src/main/java/com/wadpam/guja/dao/GeneratedDContactDaoImpl.java#L79-L81 |
LearnLib/automatalib | commons/util/src/main/java/net/automatalib/commons/util/process/ProcessUtil.java | ProcessUtil.invokeProcess | public static int invokeProcess(String[] commandLine, Reader input) throws IOException, InterruptedException {
"""
Runs the given set of command line arguments as a system process and returns the exit value of the spawned
process. Additionally allows to supply an input stream to the invoked program. Discards any output of the
process.
@param commandLine
the list of command line arguments to run
@param input
the input passed to the program
@return the exit code of the process
@throws IOException
if an exception occurred while reading the process' outputs, or writing the process' inputs
@throws InterruptedException
if an exception occurred during process exception
"""
return invokeProcess(commandLine, input, new NOPConsumer());
} | java | public static int invokeProcess(String[] commandLine, Reader input) throws IOException, InterruptedException {
return invokeProcess(commandLine, input, new NOPConsumer());
} | [
"public",
"static",
"int",
"invokeProcess",
"(",
"String",
"[",
"]",
"commandLine",
",",
"Reader",
"input",
")",
"throws",
"IOException",
",",
"InterruptedException",
"{",
"return",
"invokeProcess",
"(",
"commandLine",
",",
"input",
",",
"new",
"NOPConsumer",
"(... | Runs the given set of command line arguments as a system process and returns the exit value of the spawned
process. Additionally allows to supply an input stream to the invoked program. Discards any output of the
process.
@param commandLine
the list of command line arguments to run
@param input
the input passed to the program
@return the exit code of the process
@throws IOException
if an exception occurred while reading the process' outputs, or writing the process' inputs
@throws InterruptedException
if an exception occurred during process exception | [
"Runs",
"the",
"given",
"set",
"of",
"command",
"line",
"arguments",
"as",
"a",
"system",
"process",
"and",
"returns",
"the",
"exit",
"value",
"of",
"the",
"spawned",
"process",
".",
"Additionally",
"allows",
"to",
"supply",
"an",
"input",
"stream",
"to",
... | train | https://github.com/LearnLib/automatalib/blob/8a462ec52f6eaab9f8996e344f2163a72cb8aa6e/commons/util/src/main/java/net/automatalib/commons/util/process/ProcessUtil.java#L78-L80 |
Stratio/bdt | src/main/java/com/stratio/qa/specs/DatabaseSpec.java | DatabaseSpec.sendQueryOfType | @When("^I execute a query '(.+?)' of type '(json|string)' in mongo '(.+?)' database using collection '(.+?)' with:$")
public void sendQueryOfType(String query, String type, String database, String collection, DataTable modifications) throws Exception {
"""
Execute a query on (mongo) database
@param query path to query
@param type type of data in query (string or json)
@param collection collection in database
@param modifications modifications to perform in query
"""
try {
commonspec.setResultsType("mongo");
String retrievedData = commonspec.retrieveData(query, type);
String modifiedData = commonspec.modifyData(retrievedData, type, modifications);
commonspec.getMongoDBClient().connectToMongoDBDataBase(database);
DBCollection dbCollection = commonspec.getMongoDBClient().getMongoDBCollection(collection);
DBObject dbObject = (DBObject) JSON.parse(modifiedData);
DBCursor cursor = dbCollection.find(dbObject);
commonspec.setMongoResults(cursor);
} catch (Exception e) {
commonspec.getExceptions().add(e);
}
} | java | @When("^I execute a query '(.+?)' of type '(json|string)' in mongo '(.+?)' database using collection '(.+?)' with:$")
public void sendQueryOfType(String query, String type, String database, String collection, DataTable modifications) throws Exception {
try {
commonspec.setResultsType("mongo");
String retrievedData = commonspec.retrieveData(query, type);
String modifiedData = commonspec.modifyData(retrievedData, type, modifications);
commonspec.getMongoDBClient().connectToMongoDBDataBase(database);
DBCollection dbCollection = commonspec.getMongoDBClient().getMongoDBCollection(collection);
DBObject dbObject = (DBObject) JSON.parse(modifiedData);
DBCursor cursor = dbCollection.find(dbObject);
commonspec.setMongoResults(cursor);
} catch (Exception e) {
commonspec.getExceptions().add(e);
}
} | [
"@",
"When",
"(",
"\"^I execute a query '(.+?)' of type '(json|string)' in mongo '(.+?)' database using collection '(.+?)' with:$\"",
")",
"public",
"void",
"sendQueryOfType",
"(",
"String",
"query",
",",
"String",
"type",
",",
"String",
"database",
",",
"String",
"collection",... | Execute a query on (mongo) database
@param query path to query
@param type type of data in query (string or json)
@param collection collection in database
@param modifications modifications to perform in query | [
"Execute",
"a",
"query",
"on",
"(",
"mongo",
")",
"database"
] | train | https://github.com/Stratio/bdt/blob/55324d19e7497764ad3dd7139923e13eb9841d75/src/main/java/com/stratio/qa/specs/DatabaseSpec.java#L434-L448 |
roboconf/roboconf-platform | core/roboconf-plugin-script/src/main/java/net/roboconf/plugin/script/internal/templating/InstanceTemplateHelper.java | InstanceTemplateHelper.injectInstanceImports | public static void injectInstanceImports(Instance instance, File templateFile, Writer writer)
throws IOException {
"""
Reads the import values of the instances and injects them into the template file.
<p>
See test resources to see the associated way to write templates
</p>
@param instance the instance whose imports must be injected
@param templateFile the template file
@param writer a writer
@throws IOException if something went wrong
"""
MustacheFactory mf = new DefaultMustacheFactory( templateFile.getParentFile());
Mustache mustache = mf.compile( templateFile.getName());
mustache.execute(writer, new InstanceBean( instance )).flush();
} | java | public static void injectInstanceImports(Instance instance, File templateFile, Writer writer)
throws IOException {
MustacheFactory mf = new DefaultMustacheFactory( templateFile.getParentFile());
Mustache mustache = mf.compile( templateFile.getName());
mustache.execute(writer, new InstanceBean( instance )).flush();
} | [
"public",
"static",
"void",
"injectInstanceImports",
"(",
"Instance",
"instance",
",",
"File",
"templateFile",
",",
"Writer",
"writer",
")",
"throws",
"IOException",
"{",
"MustacheFactory",
"mf",
"=",
"new",
"DefaultMustacheFactory",
"(",
"templateFile",
".",
"getPa... | Reads the import values of the instances and injects them into the template file.
<p>
See test resources to see the associated way to write templates
</p>
@param instance the instance whose imports must be injected
@param templateFile the template file
@param writer a writer
@throws IOException if something went wrong | [
"Reads",
"the",
"import",
"values",
"of",
"the",
"instances",
"and",
"injects",
"them",
"into",
"the",
"template",
"file",
".",
"<p",
">",
"See",
"test",
"resources",
"to",
"see",
"the",
"associated",
"way",
"to",
"write",
"templates",
"<",
"/",
"p",
">"... | train | https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/core/roboconf-plugin-script/src/main/java/net/roboconf/plugin/script/internal/templating/InstanceTemplateHelper.java#L68-L74 |
Erudika/para | para-core/src/main/java/com/erudika/para/core/User.java | User.isValidEmailConfirmationToken | public final boolean isValidEmailConfirmationToken(String token) {
"""
Validates a token sent for email confirmation.
@param token a token
@return true if valid
"""
Sysprop s = CoreUtils.getInstance().getDao().read(getAppid(), identifier);
return isValidToken(s, Config._EMAIL_TOKEN, token);
} | java | public final boolean isValidEmailConfirmationToken(String token) {
Sysprop s = CoreUtils.getInstance().getDao().read(getAppid(), identifier);
return isValidToken(s, Config._EMAIL_TOKEN, token);
} | [
"public",
"final",
"boolean",
"isValidEmailConfirmationToken",
"(",
"String",
"token",
")",
"{",
"Sysprop",
"s",
"=",
"CoreUtils",
".",
"getInstance",
"(",
")",
".",
"getDao",
"(",
")",
".",
"read",
"(",
"getAppid",
"(",
")",
",",
"identifier",
")",
";",
... | Validates a token sent for email confirmation.
@param token a token
@return true if valid | [
"Validates",
"a",
"token",
"sent",
"for",
"email",
"confirmation",
"."
] | train | https://github.com/Erudika/para/blob/5ba096c477042ea7b18e9a0e8b5b1ee0f5bd6ce9/para-core/src/main/java/com/erudika/para/core/User.java#L728-L731 |
mygreen/xlsmapper | src/main/java/com/gh/mygreen/xlsmapper/xml/XmlIO.java | XmlIO.save | public static void save(final AnnotationMappingInfo xmlInfo, final OutputStream out) throws XmlOperateException {
"""
XMLをファイルに保存する。
@since 1.1
@param xmlInfo XML情報。
@param out
@throws XmlOperateException XMLの書き込みに失敗した場合。
@throws IllegalArgumentException xmlInfo is null.
@throws IllegalArgumentException writer is null.
"""
ArgUtils.notNull(xmlInfo, "xmlInfo");
ArgUtils.notNull(out, "out");
try {
JAXB.marshal(xmlInfo, out);
} catch (DataBindingException e) {
throw new XmlOperateException("fail save xml with JAXB.", e);
}
} | java | public static void save(final AnnotationMappingInfo xmlInfo, final OutputStream out) throws XmlOperateException {
ArgUtils.notNull(xmlInfo, "xmlInfo");
ArgUtils.notNull(out, "out");
try {
JAXB.marshal(xmlInfo, out);
} catch (DataBindingException e) {
throw new XmlOperateException("fail save xml with JAXB.", e);
}
} | [
"public",
"static",
"void",
"save",
"(",
"final",
"AnnotationMappingInfo",
"xmlInfo",
",",
"final",
"OutputStream",
"out",
")",
"throws",
"XmlOperateException",
"{",
"ArgUtils",
".",
"notNull",
"(",
"xmlInfo",
",",
"\"xmlInfo\"",
")",
";",
"ArgUtils",
".",
"notN... | XMLをファイルに保存する。
@since 1.1
@param xmlInfo XML情報。
@param out
@throws XmlOperateException XMLの書き込みに失敗した場合。
@throws IllegalArgumentException xmlInfo is null.
@throws IllegalArgumentException writer is null. | [
"XMLをファイルに保存する。"
] | train | https://github.com/mygreen/xlsmapper/blob/a0c6b25c622e5f3a50b199ef685d2ee46ad5483c/src/main/java/com/gh/mygreen/xlsmapper/xml/XmlIO.java#L109-L120 |
adorsys/hbci4java-adorsys | src/main/java/org/kapott/hbci/protocol/SyntaxElement.java | SyntaxElement.enumerateSegs | public int enumerateSegs(int startValue, boolean allowOverwrite) {
"""
loop through all child-elements; the segments found there
will be sequentially enumerated starting with num startValue;
if startValue is zero, the segments will not be enumerated,
but all given the number 0
@param startValue value to be used for the first segment found
@return next sequence number usable for enumeration
"""
int idx = startValue;
for (MultipleSyntaxElements s : getChildContainers()) {
if (s != null)
idx = s.enumerateSegs(idx, allowOverwrite);
}
return idx;
} | java | public int enumerateSegs(int startValue, boolean allowOverwrite) {
int idx = startValue;
for (MultipleSyntaxElements s : getChildContainers()) {
if (s != null)
idx = s.enumerateSegs(idx, allowOverwrite);
}
return idx;
} | [
"public",
"int",
"enumerateSegs",
"(",
"int",
"startValue",
",",
"boolean",
"allowOverwrite",
")",
"{",
"int",
"idx",
"=",
"startValue",
";",
"for",
"(",
"MultipleSyntaxElements",
"s",
":",
"getChildContainers",
"(",
")",
")",
"{",
"if",
"(",
"s",
"!=",
"n... | loop through all child-elements; the segments found there
will be sequentially enumerated starting with num startValue;
if startValue is zero, the segments will not be enumerated,
but all given the number 0
@param startValue value to be used for the first segment found
@return next sequence number usable for enumeration | [
"loop",
"through",
"all",
"child",
"-",
"elements",
";",
"the",
"segments",
"found",
"there",
"will",
"be",
"sequentially",
"enumerated",
"starting",
"with",
"num",
"startValue",
";",
"if",
"startValue",
"is",
"zero",
"the",
"segments",
"will",
"not",
"be",
... | train | https://github.com/adorsys/hbci4java-adorsys/blob/5e24f7e429d6b555e1d993196b4cf1adda6433cf/src/main/java/org/kapott/hbci/protocol/SyntaxElement.java#L315-L324 |
Azure/azure-sdk-for-java | compute/resource-manager/v2017_03_30/src/main/java/com/microsoft/azure/management/compute/v2017_03_30/implementation/VirtualMachineScaleSetExtensionsInner.java | VirtualMachineScaleSetExtensionsInner.getAsync | public Observable<VirtualMachineScaleSetExtensionInner> getAsync(String resourceGroupName, String vmScaleSetName, String vmssExtensionName, String expand) {
"""
The operation to get the extension.
@param resourceGroupName The name of the resource group.
@param vmScaleSetName The name of the VM scale set containing the extension.
@param vmssExtensionName The name of the VM scale set extension.
@param expand The expand expression to apply on the operation.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the VirtualMachineScaleSetExtensionInner object
"""
return getWithServiceResponseAsync(resourceGroupName, vmScaleSetName, vmssExtensionName, expand).map(new Func1<ServiceResponse<VirtualMachineScaleSetExtensionInner>, VirtualMachineScaleSetExtensionInner>() {
@Override
public VirtualMachineScaleSetExtensionInner call(ServiceResponse<VirtualMachineScaleSetExtensionInner> response) {
return response.body();
}
});
} | java | public Observable<VirtualMachineScaleSetExtensionInner> getAsync(String resourceGroupName, String vmScaleSetName, String vmssExtensionName, String expand) {
return getWithServiceResponseAsync(resourceGroupName, vmScaleSetName, vmssExtensionName, expand).map(new Func1<ServiceResponse<VirtualMachineScaleSetExtensionInner>, VirtualMachineScaleSetExtensionInner>() {
@Override
public VirtualMachineScaleSetExtensionInner call(ServiceResponse<VirtualMachineScaleSetExtensionInner> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"VirtualMachineScaleSetExtensionInner",
">",
"getAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"vmScaleSetName",
",",
"String",
"vmssExtensionName",
",",
"String",
"expand",
")",
"{",
"return",
"getWithServiceResponseAsync",
"(",
... | The operation to get the extension.
@param resourceGroupName The name of the resource group.
@param vmScaleSetName The name of the VM scale set containing the extension.
@param vmssExtensionName The name of the VM scale set extension.
@param expand The expand expression to apply on the operation.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the VirtualMachineScaleSetExtensionInner object | [
"The",
"operation",
"to",
"get",
"the",
"extension",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/compute/resource-manager/v2017_03_30/src/main/java/com/microsoft/azure/management/compute/v2017_03_30/implementation/VirtualMachineScaleSetExtensionsInner.java#L579-L586 |
infinispan/infinispan | query/src/main/java/org/infinispan/query/impl/LifecycleManager.java | LifecycleManager.registerQueryMBeans | private void registerQueryMBeans(ComponentRegistry cr, Configuration cfg, SearchIntegrator searchIntegrator) {
"""
Register query statistics and mass-indexer MBeans for a cache.
"""
AdvancedCache<?, ?> cache = cr.getComponent(Cache.class).getAdvancedCache();
// Resolve MBean server instance
GlobalJmxStatisticsConfiguration jmxConfig = cr.getGlobalComponentRegistry().getGlobalConfiguration().globalJmxStatistics();
if (!jmxConfig.enabled())
return;
if (mbeanServer == null) {
mbeanServer = JmxUtil.lookupMBeanServer(jmxConfig.mbeanServerLookup(), jmxConfig.properties());
}
// Resolve jmx domain to use for query MBeans
String queryGroupName = getQueryGroupName(jmxConfig.cacheManagerName(), cache.getName());
String jmxDomain = JmxUtil.buildJmxDomain(jmxConfig.domain(), mbeanServer, queryGroupName);
// Register query statistics MBean, but only enable it if Infinispan config says so
try {
ObjectName statsObjName = new ObjectName(jmxDomain + ":" + queryGroupName + ",component=Statistics");
InfinispanQueryStatisticsInfo stats = new InfinispanQueryStatisticsInfo(searchIntegrator, statsObjName);
stats.setStatisticsEnabled(cfg.jmxStatistics().enabled());
JmxUtil.registerMBean(stats, statsObjName, mbeanServer);
cr.registerComponent(stats, InfinispanQueryStatisticsInfo.class);
} catch (Exception e) {
throw new CacheException("Unable to register query statistics MBean", e);
}
// Register mass indexer MBean, picking metadata from repo
ManageableComponentMetadata massIndexerCompMetadata = cr.getGlobalComponentRegistry().getComponentMetadataRepo()
.findComponentMetadata(MassIndexer.class)
.toManageableComponentMetadata();
try {
KeyTransformationHandler keyTransformationHandler = ComponentRegistryUtils.getKeyTransformationHandler(cache);
TimeService timeService = ComponentRegistryUtils.getTimeService(cache);
// TODO: MassIndexer should be some kind of query cache component?
DistributedExecutorMassIndexer massIndexer = new DistributedExecutorMassIndexer(cache, searchIntegrator, keyTransformationHandler, timeService);
ResourceDMBean mbean = new ResourceDMBean(massIndexer, massIndexerCompMetadata);
ObjectName massIndexerObjName = new ObjectName(jmxDomain + ":"
+ queryGroupName + ",component=" + massIndexerCompMetadata.getJmxObjectName());
JmxUtil.registerMBean(mbean, massIndexerObjName, mbeanServer);
} catch (Exception e) {
throw new CacheException("Unable to create MassIndexer MBean", e);
}
} | java | private void registerQueryMBeans(ComponentRegistry cr, Configuration cfg, SearchIntegrator searchIntegrator) {
AdvancedCache<?, ?> cache = cr.getComponent(Cache.class).getAdvancedCache();
// Resolve MBean server instance
GlobalJmxStatisticsConfiguration jmxConfig = cr.getGlobalComponentRegistry().getGlobalConfiguration().globalJmxStatistics();
if (!jmxConfig.enabled())
return;
if (mbeanServer == null) {
mbeanServer = JmxUtil.lookupMBeanServer(jmxConfig.mbeanServerLookup(), jmxConfig.properties());
}
// Resolve jmx domain to use for query MBeans
String queryGroupName = getQueryGroupName(jmxConfig.cacheManagerName(), cache.getName());
String jmxDomain = JmxUtil.buildJmxDomain(jmxConfig.domain(), mbeanServer, queryGroupName);
// Register query statistics MBean, but only enable it if Infinispan config says so
try {
ObjectName statsObjName = new ObjectName(jmxDomain + ":" + queryGroupName + ",component=Statistics");
InfinispanQueryStatisticsInfo stats = new InfinispanQueryStatisticsInfo(searchIntegrator, statsObjName);
stats.setStatisticsEnabled(cfg.jmxStatistics().enabled());
JmxUtil.registerMBean(stats, statsObjName, mbeanServer);
cr.registerComponent(stats, InfinispanQueryStatisticsInfo.class);
} catch (Exception e) {
throw new CacheException("Unable to register query statistics MBean", e);
}
// Register mass indexer MBean, picking metadata from repo
ManageableComponentMetadata massIndexerCompMetadata = cr.getGlobalComponentRegistry().getComponentMetadataRepo()
.findComponentMetadata(MassIndexer.class)
.toManageableComponentMetadata();
try {
KeyTransformationHandler keyTransformationHandler = ComponentRegistryUtils.getKeyTransformationHandler(cache);
TimeService timeService = ComponentRegistryUtils.getTimeService(cache);
// TODO: MassIndexer should be some kind of query cache component?
DistributedExecutorMassIndexer massIndexer = new DistributedExecutorMassIndexer(cache, searchIntegrator, keyTransformationHandler, timeService);
ResourceDMBean mbean = new ResourceDMBean(massIndexer, massIndexerCompMetadata);
ObjectName massIndexerObjName = new ObjectName(jmxDomain + ":"
+ queryGroupName + ",component=" + massIndexerCompMetadata.getJmxObjectName());
JmxUtil.registerMBean(mbean, massIndexerObjName, mbeanServer);
} catch (Exception e) {
throw new CacheException("Unable to create MassIndexer MBean", e);
}
} | [
"private",
"void",
"registerQueryMBeans",
"(",
"ComponentRegistry",
"cr",
",",
"Configuration",
"cfg",
",",
"SearchIntegrator",
"searchIntegrator",
")",
"{",
"AdvancedCache",
"<",
"?",
",",
"?",
">",
"cache",
"=",
"cr",
".",
"getComponent",
"(",
"Cache",
".",
... | Register query statistics and mass-indexer MBeans for a cache. | [
"Register",
"query",
"statistics",
"and",
"mass",
"-",
"indexer",
"MBeans",
"for",
"a",
"cache",
"."
] | train | https://github.com/infinispan/infinispan/blob/7c62b94886c3febb4774ae8376acf2baa0265ab5/query/src/main/java/org/infinispan/query/impl/LifecycleManager.java#L280-L324 |
geomajas/geomajas-project-server | impl/src/main/java/org/geomajas/internal/layer/vector/GetFeaturesEachStep.java | GetFeaturesEachStep.findStyleFilter | private StyleFilter findStyleFilter(Object feature, List<StyleFilter> styles) {
"""
Find the style filter that must be applied to this feature.
@param feature
feature to find the style for
@param styles
style filters to select from
@return a style filter
"""
for (StyleFilter styleFilter : styles) {
if (styleFilter.getFilter().evaluate(feature)) {
return styleFilter;
}
}
return new StyleFilterImpl();
} | java | private StyleFilter findStyleFilter(Object feature, List<StyleFilter> styles) {
for (StyleFilter styleFilter : styles) {
if (styleFilter.getFilter().evaluate(feature)) {
return styleFilter;
}
}
return new StyleFilterImpl();
} | [
"private",
"StyleFilter",
"findStyleFilter",
"(",
"Object",
"feature",
",",
"List",
"<",
"StyleFilter",
">",
"styles",
")",
"{",
"for",
"(",
"StyleFilter",
"styleFilter",
":",
"styles",
")",
"{",
"if",
"(",
"styleFilter",
".",
"getFilter",
"(",
")",
".",
"... | Find the style filter that must be applied to this feature.
@param feature
feature to find the style for
@param styles
style filters to select from
@return a style filter | [
"Find",
"the",
"style",
"filter",
"that",
"must",
"be",
"applied",
"to",
"this",
"feature",
"."
] | train | https://github.com/geomajas/geomajas-project-server/blob/904b7d7deed1350d28955589098dd1e0a786d76e/impl/src/main/java/org/geomajas/internal/layer/vector/GetFeaturesEachStep.java#L228-L235 |
ngageoint/geopackage-java | src/main/java/mil/nga/geopackage/tiles/features/FeatureTiles.java | FeatureTiles.getStylePaint | private Paint getStylePaint(StyleRow style, FeatureDrawType drawType) {
"""
Get the style paint from cache, or create and cache it
@param style
style row
@param drawType
draw type
@return paint
"""
Paint paint = featurePaintCache.getPaint(style, drawType);
if (paint == null) {
mil.nga.geopackage.style.Color color = null;
Float strokeWidth = null;
switch (drawType) {
case CIRCLE:
color = style.getColorOrDefault();
break;
case STROKE:
color = style.getColorOrDefault();
strokeWidth = this.scale * (float) style.getWidthOrDefault();
break;
case FILL:
color = style.getFillColor();
strokeWidth = this.scale * (float) style.getWidthOrDefault();
break;
default:
throw new GeoPackageException("Unsupported Draw Type: "
+ drawType);
}
Paint stylePaint = new Paint();
stylePaint.setColor(new Color(color.getColorWithAlpha(), true));
if (strokeWidth != null) {
stylePaint.setStrokeWidth(strokeWidth);
}
synchronized (featurePaintCache) {
paint = featurePaintCache.getPaint(style, drawType);
if (paint == null) {
featurePaintCache.setPaint(style, drawType, stylePaint);
paint = stylePaint;
}
}
}
return paint;
} | java | private Paint getStylePaint(StyleRow style, FeatureDrawType drawType) {
Paint paint = featurePaintCache.getPaint(style, drawType);
if (paint == null) {
mil.nga.geopackage.style.Color color = null;
Float strokeWidth = null;
switch (drawType) {
case CIRCLE:
color = style.getColorOrDefault();
break;
case STROKE:
color = style.getColorOrDefault();
strokeWidth = this.scale * (float) style.getWidthOrDefault();
break;
case FILL:
color = style.getFillColor();
strokeWidth = this.scale * (float) style.getWidthOrDefault();
break;
default:
throw new GeoPackageException("Unsupported Draw Type: "
+ drawType);
}
Paint stylePaint = new Paint();
stylePaint.setColor(new Color(color.getColorWithAlpha(), true));
if (strokeWidth != null) {
stylePaint.setStrokeWidth(strokeWidth);
}
synchronized (featurePaintCache) {
paint = featurePaintCache.getPaint(style, drawType);
if (paint == null) {
featurePaintCache.setPaint(style, drawType, stylePaint);
paint = stylePaint;
}
}
}
return paint;
} | [
"private",
"Paint",
"getStylePaint",
"(",
"StyleRow",
"style",
",",
"FeatureDrawType",
"drawType",
")",
"{",
"Paint",
"paint",
"=",
"featurePaintCache",
".",
"getPaint",
"(",
"style",
",",
"drawType",
")",
";",
"if",
"(",
"paint",
"==",
"null",
")",
"{",
"... | Get the style paint from cache, or create and cache it
@param style
style row
@param drawType
draw type
@return paint | [
"Get",
"the",
"style",
"paint",
"from",
"cache",
"or",
"create",
"and",
"cache",
"it"
] | train | https://github.com/ngageoint/geopackage-java/blob/889bffb5d18330a3f4bd89443acf7959ebe3a376/src/main/java/mil/nga/geopackage/tiles/features/FeatureTiles.java#L1480-L1525 |
infinispan/infinispan | lucene/lucene-directory/src/main/java/org/infinispan/lucene/cacheloader/LuceneCacheLoader.java | LuceneCacheLoader.getDirectory | private DirectoryLoaderAdaptor getDirectory(final String indexName) {
"""
Looks up the Directory adapter if it's already known, or attempts to initialize indexes.
"""
DirectoryLoaderAdaptor adapter = openDirectories.get(indexName);
if (adapter == null) {
synchronized (openDirectories) {
adapter = openDirectories.get(indexName);
if (adapter == null) {
final File path = new File(this.rootDirectory, indexName);
final FSDirectory directory = openLuceneDirectory(path);
adapter = new DirectoryLoaderAdaptor(directory, indexName, autoChunkSize, affinitySegmentId);
openDirectories.put(indexName, adapter);
}
}
}
return adapter;
} | java | private DirectoryLoaderAdaptor getDirectory(final String indexName) {
DirectoryLoaderAdaptor adapter = openDirectories.get(indexName);
if (adapter == null) {
synchronized (openDirectories) {
adapter = openDirectories.get(indexName);
if (adapter == null) {
final File path = new File(this.rootDirectory, indexName);
final FSDirectory directory = openLuceneDirectory(path);
adapter = new DirectoryLoaderAdaptor(directory, indexName, autoChunkSize, affinitySegmentId);
openDirectories.put(indexName, adapter);
}
}
}
return adapter;
} | [
"private",
"DirectoryLoaderAdaptor",
"getDirectory",
"(",
"final",
"String",
"indexName",
")",
"{",
"DirectoryLoaderAdaptor",
"adapter",
"=",
"openDirectories",
".",
"get",
"(",
"indexName",
")",
";",
"if",
"(",
"adapter",
"==",
"null",
")",
"{",
"synchronized",
... | Looks up the Directory adapter if it's already known, or attempts to initialize indexes. | [
"Looks",
"up",
"the",
"Directory",
"adapter",
"if",
"it",
"s",
"already",
"known",
"or",
"attempts",
"to",
"initialize",
"indexes",
"."
] | train | https://github.com/infinispan/infinispan/blob/7c62b94886c3febb4774ae8376acf2baa0265ab5/lucene/lucene-directory/src/main/java/org/infinispan/lucene/cacheloader/LuceneCacheLoader.java#L172-L186 |
ModeShape/modeshape | modeshape-jcr/src/main/java/org/modeshape/jcr/clustering/ClusteringService.java | ClusteringService.sendMessage | public boolean sendMessage( Serializable payload ) {
"""
Sends a message of a given type across a cluster.
@param payload the main body of the message; must not be {@code null}
@return {@code true} if the send operation was successful, {@code false} otherwise
"""
if (!isOpen() || !multipleMembersInCluster()) {
return false;
}
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("{0} SENDING {1} ", toString(), payload);
}
try {
byte[] messageData = toByteArray(payload);
Message jgMessage = new Message(null, channel.getAddress(), messageData);
channel.send(jgMessage);
return true;
} catch (Exception e) {
// Something went wrong here
throw new SystemFailureException(ClusteringI18n.errorSendingMessage.text(clusterName()), e);
}
} | java | public boolean sendMessage( Serializable payload ) {
if (!isOpen() || !multipleMembersInCluster()) {
return false;
}
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("{0} SENDING {1} ", toString(), payload);
}
try {
byte[] messageData = toByteArray(payload);
Message jgMessage = new Message(null, channel.getAddress(), messageData);
channel.send(jgMessage);
return true;
} catch (Exception e) {
// Something went wrong here
throw new SystemFailureException(ClusteringI18n.errorSendingMessage.text(clusterName()), e);
}
} | [
"public",
"boolean",
"sendMessage",
"(",
"Serializable",
"payload",
")",
"{",
"if",
"(",
"!",
"isOpen",
"(",
")",
"||",
"!",
"multipleMembersInCluster",
"(",
")",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"LOGGER",
".",
"isDebugEnabled",
"(",
")"... | Sends a message of a given type across a cluster.
@param payload the main body of the message; must not be {@code null}
@return {@code true} if the send operation was successful, {@code false} otherwise | [
"Sends",
"a",
"message",
"of",
"a",
"given",
"type",
"across",
"a",
"cluster",
"."
] | train | https://github.com/ModeShape/modeshape/blob/794cfdabb67a90f24629c4fff0424a6125f8f95b/modeshape-jcr/src/main/java/org/modeshape/jcr/clustering/ClusteringService.java#L227-L244 |
HadoopGenomics/Hadoop-BAM | src/main/java/org/seqdoop/hadoop_bam/SequencedFragment.java | SequencedFragment.verifyQuality | public static int verifyQuality(Text quality, BaseQualityEncoding encoding) {
"""
Verify that the given quality bytes are within the range allowed for the specified encoding.
In theory, the Sanger encoding uses the entire
range of characters from ASCII 33 to 126, giving a value range of [0,93]. However, values over 60 are
unlikely in practice, and are more likely to be caused by mistaking a file that uses Illumina encoding
for Sanger. So, we'll enforce the same range supported by Illumina encoding ([0,62]) for Sanger.
@return -1 if quality is ok.
@return If an out-of-range value is found the index of the value is returned.
"""
// set allowed quality range
int max, min;
if (encoding == BaseQualityEncoding.Illumina)
{
max = FormatConstants.ILLUMINA_OFFSET + FormatConstants.ILLUMINA_MAX;
min = FormatConstants.ILLUMINA_OFFSET;
}
else if (encoding == BaseQualityEncoding.Sanger)
{
max = FormatConstants.SANGER_OFFSET + FormatConstants.SANGER_MAX;
min = FormatConstants.SANGER_OFFSET;
}
else
throw new IllegalArgumentException("Unsupported base encoding quality " + encoding);
// verify
final byte[] bytes = quality.getBytes();
final int len = quality.getLength();
for (int i = 0; i < len; ++i)
{
if (bytes[i] < min || bytes[i] > max)
return i;
}
return -1;
} | java | public static int verifyQuality(Text quality, BaseQualityEncoding encoding)
{
// set allowed quality range
int max, min;
if (encoding == BaseQualityEncoding.Illumina)
{
max = FormatConstants.ILLUMINA_OFFSET + FormatConstants.ILLUMINA_MAX;
min = FormatConstants.ILLUMINA_OFFSET;
}
else if (encoding == BaseQualityEncoding.Sanger)
{
max = FormatConstants.SANGER_OFFSET + FormatConstants.SANGER_MAX;
min = FormatConstants.SANGER_OFFSET;
}
else
throw new IllegalArgumentException("Unsupported base encoding quality " + encoding);
// verify
final byte[] bytes = quality.getBytes();
final int len = quality.getLength();
for (int i = 0; i < len; ++i)
{
if (bytes[i] < min || bytes[i] > max)
return i;
}
return -1;
} | [
"public",
"static",
"int",
"verifyQuality",
"(",
"Text",
"quality",
",",
"BaseQualityEncoding",
"encoding",
")",
"{",
"// set allowed quality range",
"int",
"max",
",",
"min",
";",
"if",
"(",
"encoding",
"==",
"BaseQualityEncoding",
".",
"Illumina",
")",
"{",
"m... | Verify that the given quality bytes are within the range allowed for the specified encoding.
In theory, the Sanger encoding uses the entire
range of characters from ASCII 33 to 126, giving a value range of [0,93]. However, values over 60 are
unlikely in practice, and are more likely to be caused by mistaking a file that uses Illumina encoding
for Sanger. So, we'll enforce the same range supported by Illumina encoding ([0,62]) for Sanger.
@return -1 if quality is ok.
@return If an out-of-range value is found the index of the value is returned. | [
"Verify",
"that",
"the",
"given",
"quality",
"bytes",
"are",
"within",
"the",
"range",
"allowed",
"for",
"the",
"specified",
"encoding",
"."
] | train | https://github.com/HadoopGenomics/Hadoop-BAM/blob/9f974cf635a8d72f69604021cc3d5f3469d38d2f/src/main/java/org/seqdoop/hadoop_bam/SequencedFragment.java#L281-L309 |
looly/hutool | hutool-core/src/main/java/cn/hutool/core/img/ImgUtil.java | ImgUtil.convert | public static void convert(InputStream srcStream, String formatName, OutputStream destStream) {
"""
图像类型转换:GIF=》JPG、GIF=》PNG、PNG=》JPG、PNG=》GIF(X)、BMP=》PNG<br>
此方法并不关闭流
@param srcStream 源图像流
@param formatName 包含格式非正式名称的 String:如JPG、JPEG、GIF等
@param destStream 目标图像输出流
@since 3.0.9
"""
write(read(srcStream), formatName, getImageOutputStream(destStream));
} | java | public static void convert(InputStream srcStream, String formatName, OutputStream destStream) {
write(read(srcStream), formatName, getImageOutputStream(destStream));
} | [
"public",
"static",
"void",
"convert",
"(",
"InputStream",
"srcStream",
",",
"String",
"formatName",
",",
"OutputStream",
"destStream",
")",
"{",
"write",
"(",
"read",
"(",
"srcStream",
")",
",",
"formatName",
",",
"getImageOutputStream",
"(",
"destStream",
")",... | 图像类型转换:GIF=》JPG、GIF=》PNG、PNG=》JPG、PNG=》GIF(X)、BMP=》PNG<br>
此方法并不关闭流
@param srcStream 源图像流
@param formatName 包含格式非正式名称的 String:如JPG、JPEG、GIF等
@param destStream 目标图像输出流
@since 3.0.9 | [
"图像类型转换:GIF",
"=",
"》JPG、GIF",
"=",
"》PNG、PNG",
"=",
"》JPG、PNG",
"=",
"》GIF",
"(",
"X",
")",
"、BMP",
"=",
"》PNG<br",
">",
"此方法并不关闭流"
] | train | https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/img/ImgUtil.java#L521-L523 |
mgormley/pacaya | src/main/java/edu/jhu/pacaya/parse/cky/chart/Chart.java | Chart.getViterbiTree | private BinaryTree getViterbiTree(int start, int end, int rootSymbol) {
"""
Gets the highest probability tree with the span (start, end) and the root symbol rootSymbol.
@param start The start of the span of the requested tree.
@param end The end of the span of the requested tree.
@param rootSymbol The symbol of the root of the requested tree.
@return The highest probability tree or null if no parse exists.
"""
ChartCell cell = chart[start][end];
BackPointer bp = cell.getBp(rootSymbol);
if (bp == null) {
return null;
}
BinaryTree leftChild;
BinaryTree rightChild;
if (bp.r.isLexical()) {
String lcSymbolStr = grammar.getLexAlphabet().lookupObject(bp.r.getLeftChild());
leftChild = new BinaryTree(lcSymbolStr, start, end, null, null, true);
rightChild = null;
} else if (bp.r.isUnary()) {
leftChild = getViterbiTree(start, bp.mid, bp.r.getLeftChild());
rightChild = null;
} else {
leftChild = getViterbiTree(start, bp.mid, bp.r.getLeftChild());
rightChild = getViterbiTree(bp.mid, end, bp.r.getRightChild());
}
String rootSymbolStr = grammar.getNtAlphabet().lookupObject(rootSymbol);
return new BinaryTree(rootSymbolStr, start, end, leftChild, rightChild, false);
} | java | private BinaryTree getViterbiTree(int start, int end, int rootSymbol) {
ChartCell cell = chart[start][end];
BackPointer bp = cell.getBp(rootSymbol);
if (bp == null) {
return null;
}
BinaryTree leftChild;
BinaryTree rightChild;
if (bp.r.isLexical()) {
String lcSymbolStr = grammar.getLexAlphabet().lookupObject(bp.r.getLeftChild());
leftChild = new BinaryTree(lcSymbolStr, start, end, null, null, true);
rightChild = null;
} else if (bp.r.isUnary()) {
leftChild = getViterbiTree(start, bp.mid, bp.r.getLeftChild());
rightChild = null;
} else {
leftChild = getViterbiTree(start, bp.mid, bp.r.getLeftChild());
rightChild = getViterbiTree(bp.mid, end, bp.r.getRightChild());
}
String rootSymbolStr = grammar.getNtAlphabet().lookupObject(rootSymbol);
return new BinaryTree(rootSymbolStr, start, end, leftChild, rightChild, false);
} | [
"private",
"BinaryTree",
"getViterbiTree",
"(",
"int",
"start",
",",
"int",
"end",
",",
"int",
"rootSymbol",
")",
"{",
"ChartCell",
"cell",
"=",
"chart",
"[",
"start",
"]",
"[",
"end",
"]",
";",
"BackPointer",
"bp",
"=",
"cell",
".",
"getBp",
"(",
"roo... | Gets the highest probability tree with the span (start, end) and the root symbol rootSymbol.
@param start The start of the span of the requested tree.
@param end The end of the span of the requested tree.
@param rootSymbol The symbol of the root of the requested tree.
@return The highest probability tree or null if no parse exists. | [
"Gets",
"the",
"highest",
"probability",
"tree",
"with",
"the",
"span",
"(",
"start",
"end",
")",
"and",
"the",
"root",
"symbol",
"rootSymbol",
"."
] | train | https://github.com/mgormley/pacaya/blob/786294cbac7cc65dbc32210c10acc32ed0c69233/src/main/java/edu/jhu/pacaya/parse/cky/chart/Chart.java#L147-L170 |
DV8FromTheWorld/JDA | src/main/java/net/dv8tion/jda/core/utils/PermissionUtil.java | PermissionUtil.canInteract | public static boolean canInteract(User issuer, Emote emote, MessageChannel channel, boolean botOverride) {
"""
Checks whether the specified {@link net.dv8tion.jda.core.entities.Emote Emote} can be used by the provided
{@link net.dv8tion.jda.core.entities.User User} in the {@link net.dv8tion.jda.core.entities.MessageChannel MessageChannel}.
@param issuer
The user that tries to interact with the Emote
@param emote
The emote that is the target interaction
@param channel
The MessageChannel this emote should be interacted within
@param botOverride
Whether bots can use non-managed emotes in other guilds
@throws IllegalArgumentException
if any of the provided parameters is {@code null}
or the provided entities are not from the same guild
@return True, if the issuer can interact with the emote within the specified MessageChannel
"""
Checks.notNull(issuer, "Issuer Member");
Checks.notNull(emote, "Target Emote");
Checks.notNull(channel, "Target Channel");
if (emote.getGuild() == null || !emote.getGuild().isMember(issuer))
return false; // cannot use an emote if you're not in its guild
Member member = emote.getGuild().getMemberById(issuer.getIdLong());
if (!canInteract(member, emote))
return false;
// external means it is available outside of its own guild - works for bots or if its managed
// currently we cannot check whether other users have nitro, we assume no here
final boolean external = emote.isManaged() || (issuer.isBot() && botOverride) || isNitro(issuer);
switch (channel.getType())
{
case TEXT:
TextChannel text = (TextChannel) channel;
member = text.getGuild().getMemberById(issuer.getIdLong());
return emote.getGuild().equals(text.getGuild()) // within the same guild
|| (external && member.hasPermission(text, Permission.MESSAGE_EXT_EMOJI)); // in different guild
default:
return external; // In Group or Private it only needs to be external
}
} | java | public static boolean canInteract(User issuer, Emote emote, MessageChannel channel, boolean botOverride)
{
Checks.notNull(issuer, "Issuer Member");
Checks.notNull(emote, "Target Emote");
Checks.notNull(channel, "Target Channel");
if (emote.getGuild() == null || !emote.getGuild().isMember(issuer))
return false; // cannot use an emote if you're not in its guild
Member member = emote.getGuild().getMemberById(issuer.getIdLong());
if (!canInteract(member, emote))
return false;
// external means it is available outside of its own guild - works for bots or if its managed
// currently we cannot check whether other users have nitro, we assume no here
final boolean external = emote.isManaged() || (issuer.isBot() && botOverride) || isNitro(issuer);
switch (channel.getType())
{
case TEXT:
TextChannel text = (TextChannel) channel;
member = text.getGuild().getMemberById(issuer.getIdLong());
return emote.getGuild().equals(text.getGuild()) // within the same guild
|| (external && member.hasPermission(text, Permission.MESSAGE_EXT_EMOJI)); // in different guild
default:
return external; // In Group or Private it only needs to be external
}
} | [
"public",
"static",
"boolean",
"canInteract",
"(",
"User",
"issuer",
",",
"Emote",
"emote",
",",
"MessageChannel",
"channel",
",",
"boolean",
"botOverride",
")",
"{",
"Checks",
".",
"notNull",
"(",
"issuer",
",",
"\"Issuer Member\"",
")",
";",
"Checks",
".",
... | Checks whether the specified {@link net.dv8tion.jda.core.entities.Emote Emote} can be used by the provided
{@link net.dv8tion.jda.core.entities.User User} in the {@link net.dv8tion.jda.core.entities.MessageChannel MessageChannel}.
@param issuer
The user that tries to interact with the Emote
@param emote
The emote that is the target interaction
@param channel
The MessageChannel this emote should be interacted within
@param botOverride
Whether bots can use non-managed emotes in other guilds
@throws IllegalArgumentException
if any of the provided parameters is {@code null}
or the provided entities are not from the same guild
@return True, if the issuer can interact with the emote within the specified MessageChannel | [
"Checks",
"whether",
"the",
"specified",
"{",
"@link",
"net",
".",
"dv8tion",
".",
"jda",
".",
"core",
".",
"entities",
".",
"Emote",
"Emote",
"}",
"can",
"be",
"used",
"by",
"the",
"provided",
"{",
"@link",
"net",
".",
"dv8tion",
".",
"jda",
".",
"c... | train | https://github.com/DV8FromTheWorld/JDA/blob/8ecbbe354d03f6bf448411bba573d0d4c268b560/src/main/java/net/dv8tion/jda/core/utils/PermissionUtil.java#L186-L210 |
Azure/azure-sdk-for-java | appservice/resource-manager/v2016_09_01/src/main/java/com/microsoft/azure/management/appservice/v2016_09_01/implementation/AppServicePlansInner.java | AppServicePlansInner.deleteHybridConnection | public void deleteHybridConnection(String resourceGroupName, String name, String namespaceName, String relayName) {
"""
Delete a Hybrid Connection in use in an App Service plan.
Delete a Hybrid Connection in use in an App Service plan.
@param resourceGroupName Name of the resource group to which the resource belongs.
@param name Name of the App Service plan.
@param namespaceName Name of the Service Bus namespace.
@param relayName Name of the Service Bus relay.
@throws IllegalArgumentException thrown if parameters fail the validation
@throws CloudException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
"""
deleteHybridConnectionWithServiceResponseAsync(resourceGroupName, name, namespaceName, relayName).toBlocking().single().body();
} | java | public void deleteHybridConnection(String resourceGroupName, String name, String namespaceName, String relayName) {
deleteHybridConnectionWithServiceResponseAsync(resourceGroupName, name, namespaceName, relayName).toBlocking().single().body();
} | [
"public",
"void",
"deleteHybridConnection",
"(",
"String",
"resourceGroupName",
",",
"String",
"name",
",",
"String",
"namespaceName",
",",
"String",
"relayName",
")",
"{",
"deleteHybridConnectionWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"name",
",",
"na... | Delete a Hybrid Connection in use in an App Service plan.
Delete a Hybrid Connection in use in an App Service plan.
@param resourceGroupName Name of the resource group to which the resource belongs.
@param name Name of the App Service plan.
@param namespaceName Name of the Service Bus namespace.
@param relayName Name of the Service Bus relay.
@throws IllegalArgumentException thrown if parameters fail the validation
@throws CloudException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent | [
"Delete",
"a",
"Hybrid",
"Connection",
"in",
"use",
"in",
"an",
"App",
"Service",
"plan",
".",
"Delete",
"a",
"Hybrid",
"Connection",
"in",
"use",
"in",
"an",
"App",
"Service",
"plan",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/appservice/resource-manager/v2016_09_01/src/main/java/com/microsoft/azure/management/appservice/v2016_09_01/implementation/AppServicePlansInner.java#L1238-L1240 |
raydac/java-binary-block-parser | jbbp/src/main/java/com/igormaznitsa/jbbp/utils/JBBPTextWriter.java | JBBPTextWriter.Long | public JBBPTextWriter Long(final long[] values, int off, int len) throws IOException {
"""
print values from long array.
@param values array to be printed, must not be null
@param off offset to the first element to print
@param len number of elements to be printed
@return the context
@throws IOException it will be thrown for transport errors
"""
while (len-- > 0) {
this.Long(values[off++]);
}
return this;
} | java | public JBBPTextWriter Long(final long[] values, int off, int len) throws IOException {
while (len-- > 0) {
this.Long(values[off++]);
}
return this;
} | [
"public",
"JBBPTextWriter",
"Long",
"(",
"final",
"long",
"[",
"]",
"values",
",",
"int",
"off",
",",
"int",
"len",
")",
"throws",
"IOException",
"{",
"while",
"(",
"len",
"--",
">",
"0",
")",
"{",
"this",
".",
"Long",
"(",
"values",
"[",
"off",
"+... | print values from long array.
@param values array to be printed, must not be null
@param off offset to the first element to print
@param len number of elements to be printed
@return the context
@throws IOException it will be thrown for transport errors | [
"print",
"values",
"from",
"long",
"array",
"."
] | train | https://github.com/raydac/java-binary-block-parser/blob/6d98abcab01e0c72d525ebcc9e7b694f9ce49f5b/jbbp/src/main/java/com/igormaznitsa/jbbp/utils/JBBPTextWriter.java#L1161-L1166 |
shrinkwrap/shrinkwrap | impl-base/src/main/java/org/jboss/shrinkwrap/impl/base/container/ContainerBase.java | ContainerBase.addNestedJarFileResource | private T addNestedJarFileResource(final File resource, final ArchivePath target, final ArchivePath base)
throws IllegalArgumentException {
"""
Adds the specified {@link File} resource (a nested JAR File form) to the current archive, returning the archive
itself
@param resource
@param target
@return
@throws IllegalArgumentException
"""
final Iterable<ClassLoader> classLoaders = ((Configurable) this.getArchive()).getConfiguration()
.getClassLoaders();
for (final ClassLoader classLoader : classLoaders) {
final InputStream in = classLoader.getResourceAsStream(resourceAdjustedPath(resource));
if (in != null) {
final Asset asset = new ByteArrayAsset(in);
return add(asset, base, target.get());
}
}
throw new IllegalArgumentException(resource.getPath() + " was not found in any available ClassLoaders");
} | java | private T addNestedJarFileResource(final File resource, final ArchivePath target, final ArchivePath base)
throws IllegalArgumentException {
final Iterable<ClassLoader> classLoaders = ((Configurable) this.getArchive()).getConfiguration()
.getClassLoaders();
for (final ClassLoader classLoader : classLoaders) {
final InputStream in = classLoader.getResourceAsStream(resourceAdjustedPath(resource));
if (in != null) {
final Asset asset = new ByteArrayAsset(in);
return add(asset, base, target.get());
}
}
throw new IllegalArgumentException(resource.getPath() + " was not found in any available ClassLoaders");
} | [
"private",
"T",
"addNestedJarFileResource",
"(",
"final",
"File",
"resource",
",",
"final",
"ArchivePath",
"target",
",",
"final",
"ArchivePath",
"base",
")",
"throws",
"IllegalArgumentException",
"{",
"final",
"Iterable",
"<",
"ClassLoader",
">",
"classLoaders",
"=... | Adds the specified {@link File} resource (a nested JAR File form) to the current archive, returning the archive
itself
@param resource
@param target
@return
@throws IllegalArgumentException | [
"Adds",
"the",
"specified",
"{",
"@link",
"File",
"}",
"resource",
"(",
"a",
"nested",
"JAR",
"File",
"form",
")",
"to",
"the",
"current",
"archive",
"returning",
"the",
"archive",
"itself"
] | train | https://github.com/shrinkwrap/shrinkwrap/blob/3f8a1a6d344651428c709a63ebb52d35343c5387/impl-base/src/main/java/org/jboss/shrinkwrap/impl/base/container/ContainerBase.java#L799-L812 |
apereo/person-directory | person-directory-impl/src/main/java/org/apereo/services/persondir/support/MultivaluedPersonAttributeUtils.java | MultivaluedPersonAttributeUtils.addResult | @SuppressWarnings("unchecked")
public static <K, V> void addResult(final Map<K, List<V>> results, final K key, final Object value) {
"""
Adds a key/value pair to the specified {@link Map}, creating multi-valued
values when appropriate.
<br>
Since multi-valued attributes end up with a value of type
{@link List}, passing in a {@link List} of any type will
cause its contents to be added to the <code>results</code>
{@link Map} directly under the specified <code>key</code>
@param <K> Key type (extends Object)
@param <V> Value type (extends Object)
@param results The {@link Map} to modify.
@param key The key to add the value for.
@param value The value to add for the key.
@throws IllegalArgumentException if any argument is null
"""
Validate.notNull(results, "Cannot add a result to a null map.");
Validate.notNull(key, "Cannot add a result with a null key.");
// don't put null values into the Map.
if (value == null) {
return;
}
List<V> currentValue = results.get(key);
if (currentValue == null) {
currentValue = new LinkedList<>();
results.put(key, currentValue);
}
if (value instanceof List) {
currentValue.addAll((List<V>) value);
} else {
currentValue.add((V) value);
}
} | java | @SuppressWarnings("unchecked")
public static <K, V> void addResult(final Map<K, List<V>> results, final K key, final Object value) {
Validate.notNull(results, "Cannot add a result to a null map.");
Validate.notNull(key, "Cannot add a result with a null key.");
// don't put null values into the Map.
if (value == null) {
return;
}
List<V> currentValue = results.get(key);
if (currentValue == null) {
currentValue = new LinkedList<>();
results.put(key, currentValue);
}
if (value instanceof List) {
currentValue.addAll((List<V>) value);
} else {
currentValue.add((V) value);
}
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"public",
"static",
"<",
"K",
",",
"V",
">",
"void",
"addResult",
"(",
"final",
"Map",
"<",
"K",
",",
"List",
"<",
"V",
">",
">",
"results",
",",
"final",
"K",
"key",
",",
"final",
"Object",
"value"... | Adds a key/value pair to the specified {@link Map}, creating multi-valued
values when appropriate.
<br>
Since multi-valued attributes end up with a value of type
{@link List}, passing in a {@link List} of any type will
cause its contents to be added to the <code>results</code>
{@link Map} directly under the specified <code>key</code>
@param <K> Key type (extends Object)
@param <V> Value type (extends Object)
@param results The {@link Map} to modify.
@param key The key to add the value for.
@param value The value to add for the key.
@throws IllegalArgumentException if any argument is null | [
"Adds",
"a",
"key",
"/",
"value",
"pair",
"to",
"the",
"specified",
"{",
"@link",
"Map",
"}",
"creating",
"multi",
"-",
"valued",
"values",
"when",
"appropriate",
".",
"<br",
">",
"Since",
"multi",
"-",
"valued",
"attributes",
"end",
"up",
"with",
"a",
... | train | https://github.com/apereo/person-directory/blob/331200c0878aec202b8aff12a732402d6ba7681f/person-directory-impl/src/main/java/org/apereo/services/persondir/support/MultivaluedPersonAttributeUtils.java#L136-L157 |
VoltDB/voltdb | src/hsqldb19b3/org/hsqldb_voltpatches/jdbc/JDBCResultSet.java | JDBCResultSet.updateFloat | public void updateFloat(int columnIndex, float x) throws SQLException {
"""
<!-- start generic documentation -->
Updates the designated column with a <code>float</code> value.
The updater methods are used to update column values in the
current row or the insert row. The updater methods do not
update the underlying database; instead the <code>updateRow</code> or
<code>insertRow</code> methods are called to update the database.
<!-- end generic documentation -->
<!-- start release-specific documentation -->
<div class="ReleaseSpecificDocumentation">
<h3>HSQLDB-Specific Information:</h3> <p>
HSQLDB supports this feature. <p>
</div>
<!-- end release-specific documentation -->
@param columnIndex the first column is 1, the second is 2, ...
@param x the new column value
@exception SQLException if a database access error occurs,
the result set concurrency is <code>CONCUR_READ_ONLY</code>
or this method is called on a closed result set
@exception SQLFeatureNotSupportedException if the JDBC driver does not support
this method
@since JDK 1.2 (JDK 1.1.x developers: read the overview for
JDBCResultSet)
"""
Double value = new Double(x);
startUpdate(columnIndex);
preparedStatement.setParameter(columnIndex, value);
} | java | public void updateFloat(int columnIndex, float x) throws SQLException {
Double value = new Double(x);
startUpdate(columnIndex);
preparedStatement.setParameter(columnIndex, value);
} | [
"public",
"void",
"updateFloat",
"(",
"int",
"columnIndex",
",",
"float",
"x",
")",
"throws",
"SQLException",
"{",
"Double",
"value",
"=",
"new",
"Double",
"(",
"x",
")",
";",
"startUpdate",
"(",
"columnIndex",
")",
";",
"preparedStatement",
".",
"setParamet... | <!-- start generic documentation -->
Updates the designated column with a <code>float</code> value.
The updater methods are used to update column values in the
current row or the insert row. The updater methods do not
update the underlying database; instead the <code>updateRow</code> or
<code>insertRow</code> methods are called to update the database.
<!-- end generic documentation -->
<!-- start release-specific documentation -->
<div class="ReleaseSpecificDocumentation">
<h3>HSQLDB-Specific Information:</h3> <p>
HSQLDB supports this feature. <p>
</div>
<!-- end release-specific documentation -->
@param columnIndex the first column is 1, the second is 2, ...
@param x the new column value
@exception SQLException if a database access error occurs,
the result set concurrency is <code>CONCUR_READ_ONLY</code>
or this method is called on a closed result set
@exception SQLFeatureNotSupportedException if the JDBC driver does not support
this method
@since JDK 1.2 (JDK 1.1.x developers: read the overview for
JDBCResultSet) | [
"<!",
"--",
"start",
"generic",
"documentation",
"--",
">",
"Updates",
"the",
"designated",
"column",
"with",
"a",
"<code",
">",
"float<",
"/",
"code",
">",
"value",
".",
"The",
"updater",
"methods",
"are",
"used",
"to",
"update",
"column",
"values",
"in",... | train | https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/hsqldb19b3/org/hsqldb_voltpatches/jdbc/JDBCResultSet.java#L2813-L2819 |
apache/flink | flink-streaming-java/src/main/java/org/apache/flink/streaming/api/datastream/DataStream.java | DataStream.keyBy | public KeyedStream<T, Tuple> keyBy(String... fields) {
"""
Partitions the operator state of a {@link DataStream} using field expressions.
A field expression is either the name of a public field or a getter method with parentheses
of the {@link DataStream}'s underlying type. A dot can be used to drill
down into objects, as in {@code "field1.getInnerField2()" }.
@param fields
One or more field expressions on which the state of the {@link DataStream} operators will be
partitioned.
@return The {@link DataStream} with partitioned state (i.e. KeyedStream)
"""
return keyBy(new Keys.ExpressionKeys<>(fields, getType()));
} | java | public KeyedStream<T, Tuple> keyBy(String... fields) {
return keyBy(new Keys.ExpressionKeys<>(fields, getType()));
} | [
"public",
"KeyedStream",
"<",
"T",
",",
"Tuple",
">",
"keyBy",
"(",
"String",
"...",
"fields",
")",
"{",
"return",
"keyBy",
"(",
"new",
"Keys",
".",
"ExpressionKeys",
"<>",
"(",
"fields",
",",
"getType",
"(",
")",
")",
")",
";",
"}"
] | Partitions the operator state of a {@link DataStream} using field expressions.
A field expression is either the name of a public field or a getter method with parentheses
of the {@link DataStream}'s underlying type. A dot can be used to drill
down into objects, as in {@code "field1.getInnerField2()" }.
@param fields
One or more field expressions on which the state of the {@link DataStream} operators will be
partitioned.
@return The {@link DataStream} with partitioned state (i.e. KeyedStream) | [
"Partitions",
"the",
"operator",
"state",
"of",
"a",
"{",
"@link",
"DataStream",
"}",
"using",
"field",
"expressions",
".",
"A",
"field",
"expression",
"is",
"either",
"the",
"name",
"of",
"a",
"public",
"field",
"or",
"a",
"getter",
"method",
"with",
"par... | train | https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-streaming-java/src/main/java/org/apache/flink/streaming/api/datastream/DataStream.java#L336-L338 |
sundrio/sundrio | core/src/main/java/io/sundr/builder/BaseFluent.java | BaseFluent.hasCompatibleVisitMethod | private static <V,F> Boolean hasCompatibleVisitMethod(V visitor, F fluent) {
"""
Checks if the specified visitor has a visit method compatible with the specified fluent.
@param visitor
@param fluent
@param <V>
@param <F>
@return
"""
for (Method method : visitor.getClass().getMethods()) {
if (!method.getName().equals(VISIT) || method.getParameterTypes().length != 1) {
continue;
}
Class visitorType = method.getParameterTypes()[0];
if (visitorType.isAssignableFrom(fluent.getClass())) {
return true;
} else {
return false;
}
}
return false;
} | java | private static <V,F> Boolean hasCompatibleVisitMethod(V visitor, F fluent) {
for (Method method : visitor.getClass().getMethods()) {
if (!method.getName().equals(VISIT) || method.getParameterTypes().length != 1) {
continue;
}
Class visitorType = method.getParameterTypes()[0];
if (visitorType.isAssignableFrom(fluent.getClass())) {
return true;
} else {
return false;
}
}
return false;
} | [
"private",
"static",
"<",
"V",
",",
"F",
">",
"Boolean",
"hasCompatibleVisitMethod",
"(",
"V",
"visitor",
",",
"F",
"fluent",
")",
"{",
"for",
"(",
"Method",
"method",
":",
"visitor",
".",
"getClass",
"(",
")",
".",
"getMethods",
"(",
")",
")",
"{",
... | Checks if the specified visitor has a visit method compatible with the specified fluent.
@param visitor
@param fluent
@param <V>
@param <F>
@return | [
"Checks",
"if",
"the",
"specified",
"visitor",
"has",
"a",
"visit",
"method",
"compatible",
"with",
"the",
"specified",
"fluent",
"."
] | train | https://github.com/sundrio/sundrio/blob/4e38368f4db0d950f7c41a8c75e15b0baff1f69a/core/src/main/java/io/sundr/builder/BaseFluent.java#L120-L133 |
messagebird/java-rest-api | api/src/main/java/com/messagebird/MessageBirdClient.java | MessageBirdClient.getRequestHlr | public Hlr getRequestHlr(final BigInteger msisdn, final String reference) throws GeneralException, UnauthorizedException {
"""
MessageBird provides an API to send Network Queries to any mobile number across the world.
An HLR allows you to view which mobile number (MSISDN) belongs to what operator in real time and see whether the number is active.
@param msisdn The telephone number.
@param reference A client reference
@return Hlr Object
@throws UnauthorizedException if client is unauthorized
@throws GeneralException general exception
"""
if (msisdn == null) {
throw new IllegalArgumentException("msisdn must be specified.");
}
if (reference == null) {
throw new IllegalArgumentException("Reference must be specified.");
}
final Map<String, Object> payload = new LinkedHashMap<String, Object>();
payload.put("msisdn", msisdn);
payload.put("reference", reference);
return messageBirdService.sendPayLoad(HLRPATH, payload, Hlr.class);
} | java | public Hlr getRequestHlr(final BigInteger msisdn, final String reference) throws GeneralException, UnauthorizedException {
if (msisdn == null) {
throw new IllegalArgumentException("msisdn must be specified.");
}
if (reference == null) {
throw new IllegalArgumentException("Reference must be specified.");
}
final Map<String, Object> payload = new LinkedHashMap<String, Object>();
payload.put("msisdn", msisdn);
payload.put("reference", reference);
return messageBirdService.sendPayLoad(HLRPATH, payload, Hlr.class);
} | [
"public",
"Hlr",
"getRequestHlr",
"(",
"final",
"BigInteger",
"msisdn",
",",
"final",
"String",
"reference",
")",
"throws",
"GeneralException",
",",
"UnauthorizedException",
"{",
"if",
"(",
"msisdn",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalArgumentExceptio... | MessageBird provides an API to send Network Queries to any mobile number across the world.
An HLR allows you to view which mobile number (MSISDN) belongs to what operator in real time and see whether the number is active.
@param msisdn The telephone number.
@param reference A client reference
@return Hlr Object
@throws UnauthorizedException if client is unauthorized
@throws GeneralException general exception | [
"MessageBird",
"provides",
"an",
"API",
"to",
"send",
"Network",
"Queries",
"to",
"any",
"mobile",
"number",
"across",
"the",
"world",
".",
"An",
"HLR",
"allows",
"you",
"to",
"view",
"which",
"mobile",
"number",
"(",
"MSISDN",
")",
"belongs",
"to",
"what"... | train | https://github.com/messagebird/java-rest-api/blob/f92cd93afff413e6dc12aa6e41e69f26cbae8941/api/src/main/java/com/messagebird/MessageBirdClient.java#L100-L111 |
Azure/azure-sdk-for-java | recoveryservices/resource-manager/v2016_06_01/src/main/java/com/microsoft/azure/management/recoveryservices/v2016_06_01/implementation/VaultCertificatesInner.java | VaultCertificatesInner.create | public VaultCertificateResponseInner create(String resourceGroupName, String vaultName, String certificateName, RawCertificateData properties) {
"""
Uploads a certificate for a resource.
@param resourceGroupName The name of the resource group where the recovery services vault is present.
@param vaultName The name of the recovery services vault.
@param certificateName Certificate friendly name.
@param properties the RawCertificateData value
@throws IllegalArgumentException thrown if parameters fail the validation
@throws CloudException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the VaultCertificateResponseInner object if successful.
"""
return createWithServiceResponseAsync(resourceGroupName, vaultName, certificateName, properties).toBlocking().single().body();
} | java | public VaultCertificateResponseInner create(String resourceGroupName, String vaultName, String certificateName, RawCertificateData properties) {
return createWithServiceResponseAsync(resourceGroupName, vaultName, certificateName, properties).toBlocking().single().body();
} | [
"public",
"VaultCertificateResponseInner",
"create",
"(",
"String",
"resourceGroupName",
",",
"String",
"vaultName",
",",
"String",
"certificateName",
",",
"RawCertificateData",
"properties",
")",
"{",
"return",
"createWithServiceResponseAsync",
"(",
"resourceGroupName",
",... | Uploads a certificate for a resource.
@param resourceGroupName The name of the resource group where the recovery services vault is present.
@param vaultName The name of the recovery services vault.
@param certificateName Certificate friendly name.
@param properties the RawCertificateData value
@throws IllegalArgumentException thrown if parameters fail the validation
@throws CloudException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the VaultCertificateResponseInner object if successful. | [
"Uploads",
"a",
"certificate",
"for",
"a",
"resource",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/recoveryservices/resource-manager/v2016_06_01/src/main/java/com/microsoft/azure/management/recoveryservices/v2016_06_01/implementation/VaultCertificatesInner.java#L165-L167 |
cybazeitalia/emaze-dysfunctional | src/main/java/net/emaze/dysfunctional/Spies.java | Spies.spy1st | public static <T1, T2, R> BiFunction<T1, T2, R> spy1st(BiFunction<T1, T2, R> function, Box<T1> param1) {
"""
Proxies a binary function spying for first parameter.
@param <T1> the function first parameter type
@param <T2> the function second parameter type
@param <R> the function result type
@param function the function that will be spied
@param param1 a box that will be containing the first spied parameter
@return the proxied function
"""
return spy(function, Box.<R>empty(), param1, Box.<T2>empty());
} | java | public static <T1, T2, R> BiFunction<T1, T2, R> spy1st(BiFunction<T1, T2, R> function, Box<T1> param1) {
return spy(function, Box.<R>empty(), param1, Box.<T2>empty());
} | [
"public",
"static",
"<",
"T1",
",",
"T2",
",",
"R",
">",
"BiFunction",
"<",
"T1",
",",
"T2",
",",
"R",
">",
"spy1st",
"(",
"BiFunction",
"<",
"T1",
",",
"T2",
",",
"R",
">",
"function",
",",
"Box",
"<",
"T1",
">",
"param1",
")",
"{",
"return",
... | Proxies a binary function spying for first parameter.
@param <T1> the function first parameter type
@param <T2> the function second parameter type
@param <R> the function result type
@param function the function that will be spied
@param param1 a box that will be containing the first spied parameter
@return the proxied function | [
"Proxies",
"a",
"binary",
"function",
"spying",
"for",
"first",
"parameter",
"."
] | train | https://github.com/cybazeitalia/emaze-dysfunctional/blob/98115a436e35335c5e8831f9fdc12f6d93d524be/src/main/java/net/emaze/dysfunctional/Spies.java#L267-L269 |
jglobus/JGlobus | ssl-proxies/src/main/java/org/globus/gsi/trustmanager/X509ProxyCertPathValidator.java | X509ProxyCertPathValidator.getCertificateCheckers | protected List<CertificateChecker> getCertificateCheckers() {
"""
COMMENT enable the checkers again when ProxyPathValidator starts working!
"""
List<CertificateChecker> checkers = new ArrayList<CertificateChecker>();
checkers.add(new DateValidityChecker());
checkers.add(new UnsupportedCriticalExtensionChecker());
checkers.add(new IdentityChecker(this));
// NOTE: the (possible) refresh of the CRLs happens when we call getDefault.
// Hence, we must recreate crlsList for each call to checkCertificate
// Sadly, this also means that the amount of work necessary for checkCertificate
// can be arbitrarily large (if the CRL is indeed refreshed).
//
// Note we DO NOT use this.certStore by default! TODO: This differs from the unit test
CertificateRevocationLists crlsList = CertificateRevocationLists.getDefaultCertificateRevocationLists();
checkers.add(new CRLChecker(crlsList, this.keyStore, true));
checkers.add(new SigningPolicyChecker(this.policyStore));
return checkers;
} | java | protected List<CertificateChecker> getCertificateCheckers() {
List<CertificateChecker> checkers = new ArrayList<CertificateChecker>();
checkers.add(new DateValidityChecker());
checkers.add(new UnsupportedCriticalExtensionChecker());
checkers.add(new IdentityChecker(this));
// NOTE: the (possible) refresh of the CRLs happens when we call getDefault.
// Hence, we must recreate crlsList for each call to checkCertificate
// Sadly, this also means that the amount of work necessary for checkCertificate
// can be arbitrarily large (if the CRL is indeed refreshed).
//
// Note we DO NOT use this.certStore by default! TODO: This differs from the unit test
CertificateRevocationLists crlsList = CertificateRevocationLists.getDefaultCertificateRevocationLists();
checkers.add(new CRLChecker(crlsList, this.keyStore, true));
checkers.add(new SigningPolicyChecker(this.policyStore));
return checkers;
} | [
"protected",
"List",
"<",
"CertificateChecker",
">",
"getCertificateCheckers",
"(",
")",
"{",
"List",
"<",
"CertificateChecker",
">",
"checkers",
"=",
"new",
"ArrayList",
"<",
"CertificateChecker",
">",
"(",
")",
";",
"checkers",
".",
"add",
"(",
"new",
"DateV... | COMMENT enable the checkers again when ProxyPathValidator starts working! | [
"COMMENT",
"enable",
"the",
"checkers",
"again",
"when",
"ProxyPathValidator",
"starts",
"working!"
] | train | https://github.com/jglobus/JGlobus/blob/e14f6f6636544fd84298f9cec749d626ea971930/ssl-proxies/src/main/java/org/globus/gsi/trustmanager/X509ProxyCertPathValidator.java#L451-L466 |
yatechorg/jedis-utils | src/main/java/org/yatech/jedis/utils/lua/LuaScriptBuilder.java | LuaScriptBuilder.endPreparedScript | public LuaPreparedScript endPreparedScript(LuaScriptConfig config) {
"""
End building the prepared script
@param config the configuration for the script to build
@return the new {@link LuaPreparedScript} instance
"""
if (!endsWithReturnStatement()) {
add(new LuaAstReturnStatement());
}
String scriptText = buildScriptText();
ArrayList<LuaKeyArgument> keyList = new ArrayList<>(keyArg2AstArg.keySet());
ArrayList<LuaValueArgument> argvList = new ArrayList<>(valueArg2AstArg.keySet());
if (config.isThreadSafe()) {
return new ThreadSafeLuaPreparedScript(scriptText, keyList, argvList, config);
} else {
return new BasicLuaPreparedScript(scriptText, keyList, argvList, config);
}
} | java | public LuaPreparedScript endPreparedScript(LuaScriptConfig config) {
if (!endsWithReturnStatement()) {
add(new LuaAstReturnStatement());
}
String scriptText = buildScriptText();
ArrayList<LuaKeyArgument> keyList = new ArrayList<>(keyArg2AstArg.keySet());
ArrayList<LuaValueArgument> argvList = new ArrayList<>(valueArg2AstArg.keySet());
if (config.isThreadSafe()) {
return new ThreadSafeLuaPreparedScript(scriptText, keyList, argvList, config);
} else {
return new BasicLuaPreparedScript(scriptText, keyList, argvList, config);
}
} | [
"public",
"LuaPreparedScript",
"endPreparedScript",
"(",
"LuaScriptConfig",
"config",
")",
"{",
"if",
"(",
"!",
"endsWithReturnStatement",
"(",
")",
")",
"{",
"add",
"(",
"new",
"LuaAstReturnStatement",
"(",
")",
")",
";",
"}",
"String",
"scriptText",
"=",
"bu... | End building the prepared script
@param config the configuration for the script to build
@return the new {@link LuaPreparedScript} instance | [
"End",
"building",
"the",
"prepared",
"script"
] | train | https://github.com/yatechorg/jedis-utils/blob/1951609fa6697df4f69be76e7d66b9284924bd97/src/main/java/org/yatech/jedis/utils/lua/LuaScriptBuilder.java#L125-L137 |
HanSolo/SteelSeries-Swing | src/main/java/eu/hansolo/steelseries/tools/Model.java | Model.setMinValue | public void setMinValue(final double MIN_VALUE) {
"""
Sets the minium value that will be used for the calculation
of the nice minimum value for the scale.
@param MIN_VALUE
"""
// check min-max values
if (Double.compare(MIN_VALUE, maxValue) == 0) {
throw new IllegalArgumentException("Min value cannot be equal to max value");
}
if (Double.compare(MIN_VALUE, maxValue) > 0) {
minValue = maxValue;
maxValue = MIN_VALUE;
} else {
minValue = MIN_VALUE;
}
calculate();
validate();
calcAngleStep();
fireStateChanged();
} | java | public void setMinValue(final double MIN_VALUE) {
// check min-max values
if (Double.compare(MIN_VALUE, maxValue) == 0) {
throw new IllegalArgumentException("Min value cannot be equal to max value");
}
if (Double.compare(MIN_VALUE, maxValue) > 0) {
minValue = maxValue;
maxValue = MIN_VALUE;
} else {
minValue = MIN_VALUE;
}
calculate();
validate();
calcAngleStep();
fireStateChanged();
} | [
"public",
"void",
"setMinValue",
"(",
"final",
"double",
"MIN_VALUE",
")",
"{",
"// check min-max values",
"if",
"(",
"Double",
".",
"compare",
"(",
"MIN_VALUE",
",",
"maxValue",
")",
"==",
"0",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Min... | Sets the minium value that will be used for the calculation
of the nice minimum value for the scale.
@param MIN_VALUE | [
"Sets",
"the",
"minium",
"value",
"that",
"will",
"be",
"used",
"for",
"the",
"calculation",
"of",
"the",
"nice",
"minimum",
"value",
"for",
"the",
"scale",
"."
] | train | https://github.com/HanSolo/SteelSeries-Swing/blob/c2f7b45a477757ef21bbb6a1174ddedb2250ae57/src/main/java/eu/hansolo/steelseries/tools/Model.java#L355-L371 |
mygreen/xlsmapper | src/main/java/com/gh/mygreen/xlsmapper/cellconverter/CellFormulaHandler.java | CellFormulaHandler.handleFormula | public void handleFormula(final FieldAccessor field, final Configuration config, final Cell cell, final Object targetBean) {
"""
セルに数式を設定する
@param field フィールド情報
@param config システム情報
@param cell セル情報
@param targetBean 処理対象のフィールドが定義されているクラスのインスタンス。
@throws ConversionException 数式の解析に失敗した場合。
"""
ArgUtils.notNull(field, "field");
ArgUtils.notNull(config, "config");
ArgUtils.notNull(cell, "cell");
final String evaluatedFormula = createFormulaValue(config, cell, targetBean);
if(Utils.isEmpty(evaluatedFormula)) {
cell.setCellType(CellType.BLANK);
return;
}
try {
cell.setCellFormula(evaluatedFormula);
cell.setCellType(CellType.FORMULA);
} catch(FormulaParseException e) {
// 数式の解析に失敗した場合
String message = MessageBuilder.create("cell.failParseFormula")
.var("property", field.getNameWithClass())
.var("cellAddress", CellPosition.of(cell).toString())
.var("formula", evaluatedFormula)
.format();
throw new ConversionException(message, e, field.getType());
}
} | java | public void handleFormula(final FieldAccessor field, final Configuration config, final Cell cell, final Object targetBean) {
ArgUtils.notNull(field, "field");
ArgUtils.notNull(config, "config");
ArgUtils.notNull(cell, "cell");
final String evaluatedFormula = createFormulaValue(config, cell, targetBean);
if(Utils.isEmpty(evaluatedFormula)) {
cell.setCellType(CellType.BLANK);
return;
}
try {
cell.setCellFormula(evaluatedFormula);
cell.setCellType(CellType.FORMULA);
} catch(FormulaParseException e) {
// 数式の解析に失敗した場合
String message = MessageBuilder.create("cell.failParseFormula")
.var("property", field.getNameWithClass())
.var("cellAddress", CellPosition.of(cell).toString())
.var("formula", evaluatedFormula)
.format();
throw new ConversionException(message, e, field.getType());
}
} | [
"public",
"void",
"handleFormula",
"(",
"final",
"FieldAccessor",
"field",
",",
"final",
"Configuration",
"config",
",",
"final",
"Cell",
"cell",
",",
"final",
"Object",
"targetBean",
")",
"{",
"ArgUtils",
".",
"notNull",
"(",
"field",
",",
"\"field\"",
")",
... | セルに数式を設定する
@param field フィールド情報
@param config システム情報
@param cell セル情報
@param targetBean 処理対象のフィールドが定義されているクラスのインスタンス。
@throws ConversionException 数式の解析に失敗した場合。 | [
"セルに数式を設定する"
] | train | https://github.com/mygreen/xlsmapper/blob/a0c6b25c622e5f3a50b199ef685d2ee46ad5483c/src/main/java/com/gh/mygreen/xlsmapper/cellconverter/CellFormulaHandler.java#L80-L107 |
lievendoclo/Valkyrie-RCP | valkyrie-rcp-core/src/main/java/org/valkyriercp/binding/value/support/AbstractValueModel.java | AbstractValueModel.fireValueChange | protected final void fireValueChange(boolean oldValue, boolean newValue) {
"""
Notifies all listeners that have registered interest for
notification on this event type. The event instance
is lazily created using the parameters passed into
the fire method.
@param oldValue the boolean value before the change
@param newValue the boolean value after the change
"""
fireValueChange(Boolean.valueOf(oldValue), Boolean.valueOf(newValue));
} | java | protected final void fireValueChange(boolean oldValue, boolean newValue) {
fireValueChange(Boolean.valueOf(oldValue), Boolean.valueOf(newValue));
} | [
"protected",
"final",
"void",
"fireValueChange",
"(",
"boolean",
"oldValue",
",",
"boolean",
"newValue",
")",
"{",
"fireValueChange",
"(",
"Boolean",
".",
"valueOf",
"(",
"oldValue",
")",
",",
"Boolean",
".",
"valueOf",
"(",
"newValue",
")",
")",
";",
"}"
] | Notifies all listeners that have registered interest for
notification on this event type. The event instance
is lazily created using the parameters passed into
the fire method.
@param oldValue the boolean value before the change
@param newValue the boolean value after the change | [
"Notifies",
"all",
"listeners",
"that",
"have",
"registered",
"interest",
"for",
"notification",
"on",
"this",
"event",
"type",
".",
"The",
"event",
"instance",
"is",
"lazily",
"created",
"using",
"the",
"parameters",
"passed",
"into",
"the",
"fire",
"method",
... | train | https://github.com/lievendoclo/Valkyrie-RCP/blob/6aad6e640b348cda8f3b0841f6e42025233f1eb8/valkyrie-rcp-core/src/main/java/org/valkyriercp/binding/value/support/AbstractValueModel.java#L91-L93 |
fuinorg/utils4j | src/main/java/org/fuin/utils4j/Utils4J.java | Utils4J.replaceVars | public static String replaceVars(final String str, final Map<String, String> vars) {
"""
Replaces all variables inside a string with values from a map.
@param str
Text with variables (Format: ${key} ) - May be <code>null</code> or empty.
@param vars
Map with key/values (both of type <code>String</code> - May be <code>null</code>.
@return String with replaced variables. Unknown variables will remain unchanged.
"""
if ((str == null) || (str.length() == 0) || (vars == null) || (vars.size() == 0)) {
return str;
}
final StringBuilder sb = new StringBuilder();
int end = -1;
int from = 0;
int start = -1;
while ((start = str.indexOf("${", from)) > -1) {
sb.append(str.substring(end + 1, start));
end = str.indexOf('}', start + 1);
if (end == -1) {
// No closing bracket found...
sb.append(str.substring(start));
from = str.length();
} else {
final String key = str.substring(start + 2, end);
final String value = (String) vars.get(key);
if (value == null) {
sb.append("${");
sb.append(key);
sb.append("}");
} else {
sb.append(value);
}
from = end + 1;
}
}
sb.append(str.substring(from));
return sb.toString();
} | java | public static String replaceVars(final String str, final Map<String, String> vars) {
if ((str == null) || (str.length() == 0) || (vars == null) || (vars.size() == 0)) {
return str;
}
final StringBuilder sb = new StringBuilder();
int end = -1;
int from = 0;
int start = -1;
while ((start = str.indexOf("${", from)) > -1) {
sb.append(str.substring(end + 1, start));
end = str.indexOf('}', start + 1);
if (end == -1) {
// No closing bracket found...
sb.append(str.substring(start));
from = str.length();
} else {
final String key = str.substring(start + 2, end);
final String value = (String) vars.get(key);
if (value == null) {
sb.append("${");
sb.append(key);
sb.append("}");
} else {
sb.append(value);
}
from = end + 1;
}
}
sb.append(str.substring(from));
return sb.toString();
} | [
"public",
"static",
"String",
"replaceVars",
"(",
"final",
"String",
"str",
",",
"final",
"Map",
"<",
"String",
",",
"String",
">",
"vars",
")",
"{",
"if",
"(",
"(",
"str",
"==",
"null",
")",
"||",
"(",
"str",
".",
"length",
"(",
")",
"==",
"0",
... | Replaces all variables inside a string with values from a map.
@param str
Text with variables (Format: ${key} ) - May be <code>null</code> or empty.
@param vars
Map with key/values (both of type <code>String</code> - May be <code>null</code>.
@return String with replaced variables. Unknown variables will remain unchanged. | [
"Replaces",
"all",
"variables",
"inside",
"a",
"string",
"with",
"values",
"from",
"a",
"map",
"."
] | train | https://github.com/fuinorg/utils4j/blob/71cf88e0a8d8ed67bbac513bf3cab165cd7e3280/src/main/java/org/fuin/utils4j/Utils4J.java#L929-L964 |
alkacon/opencms-core | src/org/opencms/xml/containerpage/CmsADECache.java | CmsADECache.removeCachedContent | private <CONTENT extends CmsXmlContent> void removeCachedContent(CmsResource resource, Map<String, CONTENT> cache) {
"""
Removes a cached XML content from the cache if it matches a given resource.<p>
@param resource the resource for which the cached XML content should be removed
@param cache the cache from which to remove the XML content
"""
Iterator<Map.Entry<String, CONTENT>> iterator = cache.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, CONTENT> entry = iterator.next();
CONTENT content = entry.getValue();
CmsResource contentFile = content.getFile();
if (contentFile.getStructureId().equals(resource.getStructureId())
|| contentFile.getResourceId().equals(resource.getResourceId())) {
iterator.remove();
}
}
} | java | private <CONTENT extends CmsXmlContent> void removeCachedContent(CmsResource resource, Map<String, CONTENT> cache) {
Iterator<Map.Entry<String, CONTENT>> iterator = cache.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, CONTENT> entry = iterator.next();
CONTENT content = entry.getValue();
CmsResource contentFile = content.getFile();
if (contentFile.getStructureId().equals(resource.getStructureId())
|| contentFile.getResourceId().equals(resource.getResourceId())) {
iterator.remove();
}
}
} | [
"private",
"<",
"CONTENT",
"extends",
"CmsXmlContent",
">",
"void",
"removeCachedContent",
"(",
"CmsResource",
"resource",
",",
"Map",
"<",
"String",
",",
"CONTENT",
">",
"cache",
")",
"{",
"Iterator",
"<",
"Map",
".",
"Entry",
"<",
"String",
",",
"CONTENT",... | Removes a cached XML content from the cache if it matches a given resource.<p>
@param resource the resource for which the cached XML content should be removed
@param cache the cache from which to remove the XML content | [
"Removes",
"a",
"cached",
"XML",
"content",
"from",
"the",
"cache",
"if",
"it",
"matches",
"a",
"given",
"resource",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/xml/containerpage/CmsADECache.java#L420-L433 |
jbundle/jbundle | app/program/db/src/main/java/org/jbundle/app/program/db/IncludeScopeField.java | IncludeScopeField.setupDefaultView | public ScreenComponent setupDefaultView(ScreenLoc itsLocation, ComponentParent targetScreen, Convert converter, int iDisplayFieldDesc, Map<String, Object> properties) {
"""
Set up the default screen control for this field.
@param itsLocation Location of this component on screen (ie., GridBagConstraint).
@param targetScreen Where to place this component (ie., Parent screen or GridBagLayout).
@param converter The converter to set the screenfield to.
@param iDisplayFieldDesc Display the label? (optional).
@param properties Extra properties
@return Return the component or ScreenField that is created for this field.
"""
ScreenComponent screenField = null;
createScreenComponent(ScreenModel.STATIC_STRING, itsLocation, targetScreen, converter, iDisplayFieldDesc, properties);
String strDisplay = converter.getFieldDesc();
if ((strDisplay != null) && (strDisplay.length() > 0))
{
ScreenLoc descLocation = targetScreen.getNextLocation(ScreenConstants.FIELD_DESC, ScreenConstants.DONT_SET_ANCHOR);
Map<String, Object> descProps = new HashMap<String, Object>();
descProps.put(ScreenModel.DISPLAY_STRING, strDisplay);
createScreenComponent(ScreenModel.STATIC_STRING, descLocation, targetScreen, null, 0, properties);
}
Converter dayConverter = (Converter)converter;
dayConverter = new FieldDescConverter(dayConverter, "Thick");
dayConverter = new BitConverter(dayConverter, 0, true, true);
itsLocation = targetScreen.getNextLocation(ScreenConstants.RIGHT_OF_LAST_CHECKBOX, ScreenConstants.DONT_SET_ANCHOR);
screenField = dayConverter.setupDefaultView(itsLocation, targetScreen, iDisplayFieldDesc);
dayConverter = new FieldDescConverter(dayConverter, "Thin");
dayConverter = new BitConverter(dayConverter, 1, true, true);
itsLocation = targetScreen.getNextLocation(ScreenConstants.RIGHT_OF_LAST_CHECKBOX, ScreenConstants.DONT_SET_ANCHOR);
screenField = dayConverter.setupDefaultView(itsLocation, targetScreen, iDisplayFieldDesc);
dayConverter = new FieldDescConverter(dayConverter, "Interface");
dayConverter = new BitConverter(dayConverter, 2, true, true);
itsLocation = targetScreen.getNextLocation(ScreenConstants.RIGHT_OF_LAST_CHECKBOX, ScreenConstants.DONT_SET_ANCHOR);
screenField = dayConverter.setupDefaultView(itsLocation, targetScreen, iDisplayFieldDesc);
return screenField;
} | java | public ScreenComponent setupDefaultView(ScreenLoc itsLocation, ComponentParent targetScreen, Convert converter, int iDisplayFieldDesc, Map<String, Object> properties)
{
ScreenComponent screenField = null;
createScreenComponent(ScreenModel.STATIC_STRING, itsLocation, targetScreen, converter, iDisplayFieldDesc, properties);
String strDisplay = converter.getFieldDesc();
if ((strDisplay != null) && (strDisplay.length() > 0))
{
ScreenLoc descLocation = targetScreen.getNextLocation(ScreenConstants.FIELD_DESC, ScreenConstants.DONT_SET_ANCHOR);
Map<String, Object> descProps = new HashMap<String, Object>();
descProps.put(ScreenModel.DISPLAY_STRING, strDisplay);
createScreenComponent(ScreenModel.STATIC_STRING, descLocation, targetScreen, null, 0, properties);
}
Converter dayConverter = (Converter)converter;
dayConverter = new FieldDescConverter(dayConverter, "Thick");
dayConverter = new BitConverter(dayConverter, 0, true, true);
itsLocation = targetScreen.getNextLocation(ScreenConstants.RIGHT_OF_LAST_CHECKBOX, ScreenConstants.DONT_SET_ANCHOR);
screenField = dayConverter.setupDefaultView(itsLocation, targetScreen, iDisplayFieldDesc);
dayConverter = new FieldDescConverter(dayConverter, "Thin");
dayConverter = new BitConverter(dayConverter, 1, true, true);
itsLocation = targetScreen.getNextLocation(ScreenConstants.RIGHT_OF_LAST_CHECKBOX, ScreenConstants.DONT_SET_ANCHOR);
screenField = dayConverter.setupDefaultView(itsLocation, targetScreen, iDisplayFieldDesc);
dayConverter = new FieldDescConverter(dayConverter, "Interface");
dayConverter = new BitConverter(dayConverter, 2, true, true);
itsLocation = targetScreen.getNextLocation(ScreenConstants.RIGHT_OF_LAST_CHECKBOX, ScreenConstants.DONT_SET_ANCHOR);
screenField = dayConverter.setupDefaultView(itsLocation, targetScreen, iDisplayFieldDesc);
return screenField;
} | [
"public",
"ScreenComponent",
"setupDefaultView",
"(",
"ScreenLoc",
"itsLocation",
",",
"ComponentParent",
"targetScreen",
",",
"Convert",
"converter",
",",
"int",
"iDisplayFieldDesc",
",",
"Map",
"<",
"String",
",",
"Object",
">",
"properties",
")",
"{",
"ScreenComp... | Set up the default screen control for this field.
@param itsLocation Location of this component on screen (ie., GridBagConstraint).
@param targetScreen Where to place this component (ie., Parent screen or GridBagLayout).
@param converter The converter to set the screenfield to.
@param iDisplayFieldDesc Display the label? (optional).
@param properties Extra properties
@return Return the component or ScreenField that is created for this field. | [
"Set",
"up",
"the",
"default",
"screen",
"control",
"for",
"this",
"field",
"."
] | train | https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/app/program/db/src/main/java/org/jbundle/app/program/db/IncludeScopeField.java#L66-L96 |
twilio/twilio-java | src/main/java/com/twilio/converter/Promoter.java | Promoter.enumFromString | public static <T extends Enum<?>> T enumFromString(final String value, final T[] values) {
"""
Convert a string to a enum type.
@param value string value
@param values enum values
@param <T> enum type
@return converted enum if able to convert; null otherwise
"""
if (value == null) {
return null;
}
for (T v : values) {
if (v.toString().equalsIgnoreCase(value)) {
return v;
}
}
return null;
} | java | public static <T extends Enum<?>> T enumFromString(final String value, final T[] values) {
if (value == null) {
return null;
}
for (T v : values) {
if (v.toString().equalsIgnoreCase(value)) {
return v;
}
}
return null;
} | [
"public",
"static",
"<",
"T",
"extends",
"Enum",
"<",
"?",
">",
">",
"T",
"enumFromString",
"(",
"final",
"String",
"value",
",",
"final",
"T",
"[",
"]",
"values",
")",
"{",
"if",
"(",
"value",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
... | Convert a string to a enum type.
@param value string value
@param values enum values
@param <T> enum type
@return converted enum if able to convert; null otherwise | [
"Convert",
"a",
"string",
"to",
"a",
"enum",
"type",
"."
] | train | https://github.com/twilio/twilio-java/blob/0318974c0a6a152994af167d430255684d5e9b9f/src/main/java/com/twilio/converter/Promoter.java#L57-L69 |
jenkinsci/java-client-api | jenkins-client/src/main/java/com/offbytwo/jenkins/JenkinsServer.java | JenkinsServer.renameJob | public JenkinsServer renameJob(FolderJob folder, String oldJobName, String newJobName) throws IOException {
"""
Rename a job
@param folder {@link FolderJob}
@param oldJobName existing job name.
@param newJobName The new job name.
@throws IOException In case of a failure.
"""
return renameJob(folder, oldJobName, newJobName, false);
} | java | public JenkinsServer renameJob(FolderJob folder, String oldJobName, String newJobName) throws IOException {
return renameJob(folder, oldJobName, newJobName, false);
} | [
"public",
"JenkinsServer",
"renameJob",
"(",
"FolderJob",
"folder",
",",
"String",
"oldJobName",
",",
"String",
"newJobName",
")",
"throws",
"IOException",
"{",
"return",
"renameJob",
"(",
"folder",
",",
"oldJobName",
",",
"newJobName",
",",
"false",
")",
";",
... | Rename a job
@param folder {@link FolderJob}
@param oldJobName existing job name.
@param newJobName The new job name.
@throws IOException In case of a failure. | [
"Rename",
"a",
"job"
] | train | https://github.com/jenkinsci/java-client-api/blob/c4f5953d3d4dda92cd946ad3bf2b811524c32da9/jenkins-client/src/main/java/com/offbytwo/jenkins/JenkinsServer.java#L887-L889 |
albfernandez/itext2 | src/main/java/com/lowagie/text/FontFactoryImp.java | FontFactoryImp.getFont | public Font getFont(String fontname, String encoding, boolean embedded, float size, int style, Color color) {
"""
Constructs a <CODE>Font</CODE>-object.
@param fontname the name of the font
@param encoding the encoding of the font
@param embedded true if the font is to be embedded in the PDF
@param size the size of this font
@param style the style of this font
@param color the <CODE>Color</CODE> of this font.
@return the Font constructed based on the parameters
"""
return getFont(fontname, encoding, embedded, size, style, color, true);
} | java | public Font getFont(String fontname, String encoding, boolean embedded, float size, int style, Color color) {
return getFont(fontname, encoding, embedded, size, style, color, true);
} | [
"public",
"Font",
"getFont",
"(",
"String",
"fontname",
",",
"String",
"encoding",
",",
"boolean",
"embedded",
",",
"float",
"size",
",",
"int",
"style",
",",
"Color",
"color",
")",
"{",
"return",
"getFont",
"(",
"fontname",
",",
"encoding",
",",
"embedded... | Constructs a <CODE>Font</CODE>-object.
@param fontname the name of the font
@param encoding the encoding of the font
@param embedded true if the font is to be embedded in the PDF
@param size the size of this font
@param style the style of this font
@param color the <CODE>Color</CODE> of this font.
@return the Font constructed based on the parameters | [
"Constructs",
"a",
"<CODE",
">",
"Font<",
"/",
"CODE",
">",
"-",
"object",
"."
] | train | https://github.com/albfernandez/itext2/blob/438fc1899367fd13dfdfa8dfdca9a3c1a7783b84/src/main/java/com/lowagie/text/FontFactoryImp.java#L150-L152 |
lessthanoptimal/BoofCV | main/boofcv-ip/src/main/java/boofcv/alg/filter/binary/BinaryImageOps.java | BinaryImageOps.labelToBinary | public static GrayU8 labelToBinary(GrayS32 labelImage , GrayU8 binaryImage ) {
"""
Converts a labeled image into a binary image by setting any non-zero value to one.
@param labelImage Input image. Not modified.
@param binaryImage Output image. Modified.
@return The binary image.
"""
binaryImage = InputSanityCheck.checkDeclare(labelImage, binaryImage, GrayU8.class);
if( BoofConcurrency.USE_CONCURRENT ) {
ImplBinaryImageOps_MT.labelToBinary(labelImage, binaryImage);
} else {
ImplBinaryImageOps.labelToBinary(labelImage, binaryImage);
}
return binaryImage;
} | java | public static GrayU8 labelToBinary(GrayS32 labelImage , GrayU8 binaryImage ) {
binaryImage = InputSanityCheck.checkDeclare(labelImage, binaryImage, GrayU8.class);
if( BoofConcurrency.USE_CONCURRENT ) {
ImplBinaryImageOps_MT.labelToBinary(labelImage, binaryImage);
} else {
ImplBinaryImageOps.labelToBinary(labelImage, binaryImage);
}
return binaryImage;
} | [
"public",
"static",
"GrayU8",
"labelToBinary",
"(",
"GrayS32",
"labelImage",
",",
"GrayU8",
"binaryImage",
")",
"{",
"binaryImage",
"=",
"InputSanityCheck",
".",
"checkDeclare",
"(",
"labelImage",
",",
"binaryImage",
",",
"GrayU8",
".",
"class",
")",
";",
"if",
... | Converts a labeled image into a binary image by setting any non-zero value to one.
@param labelImage Input image. Not modified.
@param binaryImage Output image. Modified.
@return The binary image. | [
"Converts",
"a",
"labeled",
"image",
"into",
"a",
"binary",
"image",
"by",
"setting",
"any",
"non",
"-",
"zero",
"value",
"to",
"one",
"."
] | train | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-ip/src/main/java/boofcv/alg/filter/binary/BinaryImageOps.java#L524-L534 |
knowm/XChange | xchange-bitso/src/main/java/org/knowm/xchange/bitso/BitsoAdapters.java | BitsoAdapters.adaptTrades | public static Trades adaptTrades(BitsoTransaction[] transactions, CurrencyPair currencyPair) {
"""
Adapts a Transaction[] to a Trades Object
@param transactions The Bitso transactions
@param currencyPair (e.g. BTC/MXN)
@return The XChange Trades
"""
List<Trade> trades = new ArrayList<>();
long lastTradeId = 0;
for (BitsoTransaction tx : transactions) {
Order.OrderType type;
switch (tx.getSide()) {
case "buy":
type = Order.OrderType.ASK;
break;
case "sell":
type = Order.OrderType.BID;
break;
default:
type = null;
}
final long tradeId = tx.getTid();
if (tradeId > lastTradeId) {
lastTradeId = tradeId;
}
trades.add(
new Trade(
type,
tx.getAmount(),
currencyPair,
tx.getPrice(),
DateUtils.fromMillisUtc(tx.getDate() * 1000L),
String.valueOf(tradeId)));
}
return new Trades(trades, lastTradeId, TradeSortType.SortByID);
} | java | public static Trades adaptTrades(BitsoTransaction[] transactions, CurrencyPair currencyPair) {
List<Trade> trades = new ArrayList<>();
long lastTradeId = 0;
for (BitsoTransaction tx : transactions) {
Order.OrderType type;
switch (tx.getSide()) {
case "buy":
type = Order.OrderType.ASK;
break;
case "sell":
type = Order.OrderType.BID;
break;
default:
type = null;
}
final long tradeId = tx.getTid();
if (tradeId > lastTradeId) {
lastTradeId = tradeId;
}
trades.add(
new Trade(
type,
tx.getAmount(),
currencyPair,
tx.getPrice(),
DateUtils.fromMillisUtc(tx.getDate() * 1000L),
String.valueOf(tradeId)));
}
return new Trades(trades, lastTradeId, TradeSortType.SortByID);
} | [
"public",
"static",
"Trades",
"adaptTrades",
"(",
"BitsoTransaction",
"[",
"]",
"transactions",
",",
"CurrencyPair",
"currencyPair",
")",
"{",
"List",
"<",
"Trade",
">",
"trades",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"long",
"lastTradeId",
"=",
"0",... | Adapts a Transaction[] to a Trades Object
@param transactions The Bitso transactions
@param currencyPair (e.g. BTC/MXN)
@return The XChange Trades | [
"Adapts",
"a",
"Transaction",
"[]",
"to",
"a",
"Trades",
"Object"
] | train | https://github.com/knowm/XChange/blob/e45f437ac8e0b89cd66cdcb3258bdb1bf3d88186/xchange-bitso/src/main/java/org/knowm/xchange/bitso/BitsoAdapters.java#L105-L136 |
apache/groovy | src/main/java/org/codehaus/groovy/runtime/DefaultGroovyMethods.java | DefaultGroovyMethods.toSorted | public static <T> Iterator<T> toSorted(Iterator<T> self) {
"""
Sorts the Iterator. Assumes that the Iterator elements are
comparable and uses a {@link NumberAwareComparator} to determine the resulting order.
{@code NumberAwareComparator} has special treatment for numbers but otherwise uses the
natural ordering of the Iterator elements.
A new iterator is produced that traverses the items in sorted order.
@param self the Iterator to be sorted
@return the sorted items as an Iterator
@see #toSorted(Iterator, Comparator)
@since 2.4.0
"""
return toSorted(self, new NumberAwareComparator<T>());
} | java | public static <T> Iterator<T> toSorted(Iterator<T> self) {
return toSorted(self, new NumberAwareComparator<T>());
} | [
"public",
"static",
"<",
"T",
">",
"Iterator",
"<",
"T",
">",
"toSorted",
"(",
"Iterator",
"<",
"T",
">",
"self",
")",
"{",
"return",
"toSorted",
"(",
"self",
",",
"new",
"NumberAwareComparator",
"<",
"T",
">",
"(",
")",
")",
";",
"}"
] | Sorts the Iterator. Assumes that the Iterator elements are
comparable and uses a {@link NumberAwareComparator} to determine the resulting order.
{@code NumberAwareComparator} has special treatment for numbers but otherwise uses the
natural ordering of the Iterator elements.
A new iterator is produced that traverses the items in sorted order.
@param self the Iterator to be sorted
@return the sorted items as an Iterator
@see #toSorted(Iterator, Comparator)
@since 2.4.0 | [
"Sorts",
"the",
"Iterator",
".",
"Assumes",
"that",
"the",
"Iterator",
"elements",
"are",
"comparable",
"and",
"uses",
"a",
"{",
"@link",
"NumberAwareComparator",
"}",
"to",
"determine",
"the",
"resulting",
"order",
".",
"{",
"@code",
"NumberAwareComparator",
"}... | train | https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/codehaus/groovy/runtime/DefaultGroovyMethods.java#L9455-L9457 |
milaboratory/milib | src/main/java/com/milaboratory/core/Range.java | Range.without | @SuppressWarnings("unchecked")
public List<Range> without(Range range) {
"""
Subtract provided range and return list of ranges contained in current range and not intersecting with other
range.
@param range range to subtract
@return list of ranges contained in current range and not intersecting with other range
"""
if (!intersectsWith(range))
return Collections.singletonList(this);
if (upper <= range.upper)
return range.lower <= lower ? Collections.EMPTY_LIST : Collections.singletonList(new Range(lower, range.lower, reversed));
if (range.lower <= lower)
return Collections.singletonList(new Range(range.upper, upper, reversed));
return Arrays.asList(new Range(lower, range.lower, reversed), new Range(range.upper, upper, reversed));
} | java | @SuppressWarnings("unchecked")
public List<Range> without(Range range) {
if (!intersectsWith(range))
return Collections.singletonList(this);
if (upper <= range.upper)
return range.lower <= lower ? Collections.EMPTY_LIST : Collections.singletonList(new Range(lower, range.lower, reversed));
if (range.lower <= lower)
return Collections.singletonList(new Range(range.upper, upper, reversed));
return Arrays.asList(new Range(lower, range.lower, reversed), new Range(range.upper, upper, reversed));
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"public",
"List",
"<",
"Range",
">",
"without",
"(",
"Range",
"range",
")",
"{",
"if",
"(",
"!",
"intersectsWith",
"(",
"range",
")",
")",
"return",
"Collections",
".",
"singletonList",
"(",
"this",
")",
... | Subtract provided range and return list of ranges contained in current range and not intersecting with other
range.
@param range range to subtract
@return list of ranges contained in current range and not intersecting with other range | [
"Subtract",
"provided",
"range",
"and",
"return",
"list",
"of",
"ranges",
"contained",
"in",
"current",
"range",
"and",
"not",
"intersecting",
"with",
"other",
"range",
"."
] | train | https://github.com/milaboratory/milib/blob/2349b3dccdd3c7948643760e570238d6e30d5a34/src/main/java/com/milaboratory/core/Range.java#L317-L329 |
xebialabs/overcast | src/main/java/com/xebialabs/overcast/support/libvirt/DomainWrapper.java | DomainWrapper.cloneWithBackingStore | public DomainWrapper cloneWithBackingStore(String cloneName, List<Filesystem> mappings) {
"""
Clone the domain. All disks are cloned using the original disk as backing store. The names of the disks are
created by suffixing the original disk name with a number.
"""
logger.info("Creating clone from {}", getName());
try {
// duplicate definition of base
Document cloneXmlDocument = domainXml.clone();
setDomainName(cloneXmlDocument, cloneName);
prepareForCloning(cloneXmlDocument);
// keep track of who we are a clone from...
updateCloneMetadata(cloneXmlDocument, getName(), new Date());
cloneDisks(cloneXmlDocument, cloneName);
updateFilesystemMappings(cloneXmlDocument, mappings);
String cloneXml = documentToString(cloneXmlDocument);
logger.debug("Clone xml={}", cloneXml);
// Domain cloneDomain = domain.getConnect().domainCreateXML(cloneXml, 0);
Domain cloneDomain = domain.getConnect().domainDefineXML(cloneXml);
String createdCloneXml = cloneDomain.getXMLDesc(0);
logger.debug("Created clone xml: {}", createdCloneXml);
cloneDomain.create();
logger.debug("Starting clone: '{}'", cloneDomain.getName());
return newWrapper(cloneDomain);
} catch (IOException | LibvirtException e) {
throw new LibvirtRuntimeException("Unable to clone domain", e);
}
} | java | public DomainWrapper cloneWithBackingStore(String cloneName, List<Filesystem> mappings) {
logger.info("Creating clone from {}", getName());
try {
// duplicate definition of base
Document cloneXmlDocument = domainXml.clone();
setDomainName(cloneXmlDocument, cloneName);
prepareForCloning(cloneXmlDocument);
// keep track of who we are a clone from...
updateCloneMetadata(cloneXmlDocument, getName(), new Date());
cloneDisks(cloneXmlDocument, cloneName);
updateFilesystemMappings(cloneXmlDocument, mappings);
String cloneXml = documentToString(cloneXmlDocument);
logger.debug("Clone xml={}", cloneXml);
// Domain cloneDomain = domain.getConnect().domainCreateXML(cloneXml, 0);
Domain cloneDomain = domain.getConnect().domainDefineXML(cloneXml);
String createdCloneXml = cloneDomain.getXMLDesc(0);
logger.debug("Created clone xml: {}", createdCloneXml);
cloneDomain.create();
logger.debug("Starting clone: '{}'", cloneDomain.getName());
return newWrapper(cloneDomain);
} catch (IOException | LibvirtException e) {
throw new LibvirtRuntimeException("Unable to clone domain", e);
}
} | [
"public",
"DomainWrapper",
"cloneWithBackingStore",
"(",
"String",
"cloneName",
",",
"List",
"<",
"Filesystem",
">",
"mappings",
")",
"{",
"logger",
".",
"info",
"(",
"\"Creating clone from {}\"",
",",
"getName",
"(",
")",
")",
";",
"try",
"{",
"// duplicate def... | Clone the domain. All disks are cloned using the original disk as backing store. The names of the disks are
created by suffixing the original disk name with a number. | [
"Clone",
"the",
"domain",
".",
"All",
"disks",
"are",
"cloned",
"using",
"the",
"original",
"disk",
"as",
"backing",
"store",
".",
"The",
"names",
"of",
"the",
"disks",
"are",
"created",
"by",
"suffixing",
"the",
"original",
"disk",
"name",
"with",
"a",
... | train | https://github.com/xebialabs/overcast/blob/716e57b66870c9afe51edc3b6045863a34fb0061/src/main/java/com/xebialabs/overcast/support/libvirt/DomainWrapper.java#L108-L139 |
jcuda/jcusparse | JCusparseJava/src/main/java/jcuda/jcusparse/JCusparse.java | JCusparse.cusparseSnnz_compress | public static int cusparseSnnz_compress(
cusparseHandle handle,
int m,
cusparseMatDescr descr,
Pointer csrSortedValA,
Pointer csrSortedRowPtrA,
Pointer nnzPerRow,
Pointer nnzC,
float tol) {
"""
Description: This routine finds the total number of non-zero elements and
the number of non-zero elements per row in a noncompressed csr matrix A.
"""
return checkResult(cusparseSnnz_compressNative(handle, m, descr, csrSortedValA, csrSortedRowPtrA, nnzPerRow, nnzC, tol));
} | java | public static int cusparseSnnz_compress(
cusparseHandle handle,
int m,
cusparseMatDescr descr,
Pointer csrSortedValA,
Pointer csrSortedRowPtrA,
Pointer nnzPerRow,
Pointer nnzC,
float tol)
{
return checkResult(cusparseSnnz_compressNative(handle, m, descr, csrSortedValA, csrSortedRowPtrA, nnzPerRow, nnzC, tol));
} | [
"public",
"static",
"int",
"cusparseSnnz_compress",
"(",
"cusparseHandle",
"handle",
",",
"int",
"m",
",",
"cusparseMatDescr",
"descr",
",",
"Pointer",
"csrSortedValA",
",",
"Pointer",
"csrSortedRowPtrA",
",",
"Pointer",
"nnzPerRow",
",",
"Pointer",
"nnzC",
",",
"... | Description: This routine finds the total number of non-zero elements and
the number of non-zero elements per row in a noncompressed csr matrix A. | [
"Description",
":",
"This",
"routine",
"finds",
"the",
"total",
"number",
"of",
"non",
"-",
"zero",
"elements",
"and",
"the",
"number",
"of",
"non",
"-",
"zero",
"elements",
"per",
"row",
"in",
"a",
"noncompressed",
"csr",
"matrix",
"A",
"."
] | train | https://github.com/jcuda/jcusparse/blob/7687a62a4ef6b76cb91cf7da93d4cf5ade96a791/JCusparseJava/src/main/java/jcuda/jcusparse/JCusparse.java#L10946-L10957 |
OpenLiberty/open-liberty | dev/com.ibm.ws.kernel.boot.core/src/com/ibm/ws/kernel/boot/BootstrapConfig.java | BootstrapConfig.assertDirectory | protected File assertDirectory(String dirName, String locName) {
"""
Ensure that the given directory either does not yet exists,
or exists as a directory.
@param dirName
Name/path to directory
@param locName
Symbol/location associated with directory
@return File for directory location
@throws LocationException
if dirName references an existing File (isFile).
"""
File d = new File(dirName);
if (d.isFile())
throw new LocationException("Path must reference a directory", MessageFormat.format(BootstrapConstants.messages.getString("error.specifiedLocation"), locName,
d.getAbsolutePath()));
return d;
} | java | protected File assertDirectory(String dirName, String locName) {
File d = new File(dirName);
if (d.isFile())
throw new LocationException("Path must reference a directory", MessageFormat.format(BootstrapConstants.messages.getString("error.specifiedLocation"), locName,
d.getAbsolutePath()));
return d;
} | [
"protected",
"File",
"assertDirectory",
"(",
"String",
"dirName",
",",
"String",
"locName",
")",
"{",
"File",
"d",
"=",
"new",
"File",
"(",
"dirName",
")",
";",
"if",
"(",
"d",
".",
"isFile",
"(",
")",
")",
"throw",
"new",
"LocationException",
"(",
"\"... | Ensure that the given directory either does not yet exists,
or exists as a directory.
@param dirName
Name/path to directory
@param locName
Symbol/location associated with directory
@return File for directory location
@throws LocationException
if dirName references an existing File (isFile). | [
"Ensure",
"that",
"the",
"given",
"directory",
"either",
"does",
"not",
"yet",
"exists",
"or",
"exists",
"as",
"a",
"directory",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.kernel.boot.core/src/com/ibm/ws/kernel/boot/BootstrapConfig.java#L372-L378 |
asterisk-java/asterisk-java | src/main/java/org/asteriskjava/live/internal/AsteriskQueueImpl.java | AsteriskQueueImpl.createNewEntry | void createNewEntry(AsteriskChannelImpl channel, int reportedPosition, Date dateReceived) {
"""
Creates a new AsteriskQueueEntry, adds it to this queue.<p>
Fires:
<ul>
<li>PCE on channel</li>
<li>NewEntry on this queue</li>
<li>PCE on other queue entries if shifted (never happens)</li>
<li>NewQueueEntry on server</li>
</ul>
@param channel the channel that joined the queue
@param reportedPosition the position as given by Asterisk (currently not used)
@param dateReceived the date the hannel joined the queue
"""
AsteriskQueueEntryImpl qe = new AsteriskQueueEntryImpl(server, this, channel, reportedPosition, dateReceived);
long delay = serviceLevel * 1000L;
if (delay > 0)
{
ServiceLevelTimerTask timerTask = new ServiceLevelTimerTask(qe);
timer.schedule(timerTask, delay);
synchronized (serviceLevelTimerTasks)
{
serviceLevelTimerTasks.put(qe, timerTask);
}
}
synchronized (entries)
{
entries.add(qe); // at the end of the list
// Keep the lock !
// This will fire PCE on the newly created queue entry
// but hopefully this one has no listeners yet
shift();
}
// Set the channel property ony here as queue entries and channels
// maintain a reciprocal reference.
// That way property change on channel and new entry event on queue will be
// lanched when BOTH channel and queue are correctly set.
channel.setQueueEntry(qe);
fireNewEntry(qe);
server.fireNewQueueEntry(qe);
} | java | void createNewEntry(AsteriskChannelImpl channel, int reportedPosition, Date dateReceived)
{
AsteriskQueueEntryImpl qe = new AsteriskQueueEntryImpl(server, this, channel, reportedPosition, dateReceived);
long delay = serviceLevel * 1000L;
if (delay > 0)
{
ServiceLevelTimerTask timerTask = new ServiceLevelTimerTask(qe);
timer.schedule(timerTask, delay);
synchronized (serviceLevelTimerTasks)
{
serviceLevelTimerTasks.put(qe, timerTask);
}
}
synchronized (entries)
{
entries.add(qe); // at the end of the list
// Keep the lock !
// This will fire PCE on the newly created queue entry
// but hopefully this one has no listeners yet
shift();
}
// Set the channel property ony here as queue entries and channels
// maintain a reciprocal reference.
// That way property change on channel and new entry event on queue will be
// lanched when BOTH channel and queue are correctly set.
channel.setQueueEntry(qe);
fireNewEntry(qe);
server.fireNewQueueEntry(qe);
} | [
"void",
"createNewEntry",
"(",
"AsteriskChannelImpl",
"channel",
",",
"int",
"reportedPosition",
",",
"Date",
"dateReceived",
")",
"{",
"AsteriskQueueEntryImpl",
"qe",
"=",
"new",
"AsteriskQueueEntryImpl",
"(",
"server",
",",
"this",
",",
"channel",
",",
"reportedPo... | Creates a new AsteriskQueueEntry, adds it to this queue.<p>
Fires:
<ul>
<li>PCE on channel</li>
<li>NewEntry on this queue</li>
<li>PCE on other queue entries if shifted (never happens)</li>
<li>NewQueueEntry on server</li>
</ul>
@param channel the channel that joined the queue
@param reportedPosition the position as given by Asterisk (currently not used)
@param dateReceived the date the hannel joined the queue | [
"Creates",
"a",
"new",
"AsteriskQueueEntry",
"adds",
"it",
"to",
"this",
"queue",
".",
"<p",
">",
"Fires",
":",
"<ul",
">",
"<li",
">",
"PCE",
"on",
"channel<",
"/",
"li",
">",
"<li",
">",
"NewEntry",
"on",
"this",
"queue<",
"/",
"li",
">",
"<li",
... | train | https://github.com/asterisk-java/asterisk-java/blob/cdc9849270d97ef75afa447a02c5194ed29121eb/src/main/java/org/asteriskjava/live/internal/AsteriskQueueImpl.java#L353-L385 |
zeroturnaround/zt-zip | src/main/java/org/zeroturnaround/zip/extra/ZipLong.java | ZipLong.getValue | public static long getValue(byte[] bytes, int offset) {
"""
Helper method to get the value as a Java long from four bytes starting at given array offset
@param bytes the array of bytes
@param offset the offset to start
@return the corresponding Java long value
"""
long value = (bytes[offset + BYTE_3] << BYTE_3_SHIFT) & BYTE_3_MASK;
value += (bytes[offset + BYTE_2] << BYTE_2_SHIFT) & BYTE_2_MASK;
value += (bytes[offset + BYTE_1] << BYTE_1_SHIFT) & BYTE_1_MASK;
value += (bytes[offset] & BYTE_MASK);
return value;
} | java | public static long getValue(byte[] bytes, int offset) {
long value = (bytes[offset + BYTE_3] << BYTE_3_SHIFT) & BYTE_3_MASK;
value += (bytes[offset + BYTE_2] << BYTE_2_SHIFT) & BYTE_2_MASK;
value += (bytes[offset + BYTE_1] << BYTE_1_SHIFT) & BYTE_1_MASK;
value += (bytes[offset] & BYTE_MASK);
return value;
} | [
"public",
"static",
"long",
"getValue",
"(",
"byte",
"[",
"]",
"bytes",
",",
"int",
"offset",
")",
"{",
"long",
"value",
"=",
"(",
"bytes",
"[",
"offset",
"+",
"BYTE_3",
"]",
"<<",
"BYTE_3_SHIFT",
")",
"&",
"BYTE_3_MASK",
";",
"value",
"+=",
"(",
"by... | Helper method to get the value as a Java long from four bytes starting at given array offset
@param bytes the array of bytes
@param offset the offset to start
@return the corresponding Java long value | [
"Helper",
"method",
"to",
"get",
"the",
"value",
"as",
"a",
"Java",
"long",
"from",
"four",
"bytes",
"starting",
"at",
"given",
"array",
"offset"
] | train | https://github.com/zeroturnaround/zt-zip/blob/abb4dc43583e4d19339c0c021035019798970a13/src/main/java/org/zeroturnaround/zip/extra/ZipLong.java#L141-L147 |
facebookarchive/hadoop-20 | src/hdfs/org/apache/hadoop/hdfs/server/namenode/EditLogFileOutputStream.java | EditLogFileOutputStream.writeRaw | @Override
public void writeRaw(byte[] bytes, int offset, int length) throws IOException {
"""
Write a transaction to the stream. The serialization format is:
<ul>
<li>the opcode (byte)</li>
<li>the transaction id (long)</li>
<li>the actual Writables for the transaction</li>
</ul>
"""
doubleBuf.writeRaw(bytes, offset, length);
} | java | @Override
public void writeRaw(byte[] bytes, int offset, int length) throws IOException {
doubleBuf.writeRaw(bytes, offset, length);
} | [
"@",
"Override",
"public",
"void",
"writeRaw",
"(",
"byte",
"[",
"]",
"bytes",
",",
"int",
"offset",
",",
"int",
"length",
")",
"throws",
"IOException",
"{",
"doubleBuf",
".",
"writeRaw",
"(",
"bytes",
",",
"offset",
",",
"length",
")",
";",
"}"
] | Write a transaction to the stream. The serialization format is:
<ul>
<li>the opcode (byte)</li>
<li>the transaction id (long)</li>
<li>the actual Writables for the transaction</li>
</ul> | [
"Write",
"a",
"transaction",
"to",
"the",
"stream",
".",
"The",
"serialization",
"format",
"is",
":",
"<ul",
">",
"<li",
">",
"the",
"opcode",
"(",
"byte",
")",
"<",
"/",
"li",
">",
"<li",
">",
"the",
"transaction",
"id",
"(",
"long",
")",
"<",
"/"... | train | https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/hdfs/org/apache/hadoop/hdfs/server/namenode/EditLogFileOutputStream.java#L113-L116 |
loldevs/riotapi | rtmp/src/main/java/net/boreeas/riotapi/rtmp/RtmpClient.java | RtmpClient.sendRpcToDefault | public InvokeCallback sendRpcToDefault(String service, String method, Object... args) {
"""
<p>
Send a remote procedure call.
</p>
@param service The service handling the call
@param method The method to call
@param args Optional arguments to the call
@return The callback getting called once the rpc returns a result
"""
return sendRpcWithEndpoint("my-rtmps", service, method, args);
} | java | public InvokeCallback sendRpcToDefault(String service, String method, Object... args) {
return sendRpcWithEndpoint("my-rtmps", service, method, args);
} | [
"public",
"InvokeCallback",
"sendRpcToDefault",
"(",
"String",
"service",
",",
"String",
"method",
",",
"Object",
"...",
"args",
")",
"{",
"return",
"sendRpcWithEndpoint",
"(",
"\"my-rtmps\"",
",",
"service",
",",
"method",
",",
"args",
")",
";",
"}"
] | <p>
Send a remote procedure call.
</p>
@param service The service handling the call
@param method The method to call
@param args Optional arguments to the call
@return The callback getting called once the rpc returns a result | [
"<p",
">",
"Send",
"a",
"remote",
"procedure",
"call",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/loldevs/riotapi/blob/0b8aac407aa5289845f249024f9732332855544f/rtmp/src/main/java/net/boreeas/riotapi/rtmp/RtmpClient.java#L598-L600 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.