repository_name stringlengths 7 58 | func_path_in_repository stringlengths 11 204 | func_name stringlengths 5 103 | whole_func_string stringlengths 87 3.44k | language stringclasses 1
value | func_code_string stringlengths 87 3.44k | func_code_tokens listlengths 21 714 | func_documentation_string stringlengths 61 1.95k | func_documentation_tokens listlengths 1 482 | split_name stringclasses 1
value | func_code_url stringlengths 102 309 |
|---|---|---|---|---|---|---|---|---|---|---|
zafarkhaja/jsemver | src/main/java/com/github/zafarkhaja/semver/expr/ExpressionParser.java | ExpressionParser.parseWildcardRange | private CompositeExpression parseWildcardRange() {
if (tokens.positiveLookahead(WILDCARD)) {
tokens.consume();
return gte(versionFor(0, 0, 0));
}
int major = intOf(consumeNextToken(NUMERIC).lexeme);
consumeNextToken(DOT);
if (tokens.positiveLookahead(WILDCARD)) {
tokens.consume();
return gte(versionFor(major)).and(lt(versionFor(major + 1)));
}
int minor = intOf(consumeNextToken(NUMERIC).lexeme);
consumeNextToken(DOT);
consumeNextToken(WILDCARD);
return gte(versionFor(major, minor)).and(lt(versionFor(major, minor + 1)));
} | java | private CompositeExpression parseWildcardRange() {
if (tokens.positiveLookahead(WILDCARD)) {
tokens.consume();
return gte(versionFor(0, 0, 0));
}
int major = intOf(consumeNextToken(NUMERIC).lexeme);
consumeNextToken(DOT);
if (tokens.positiveLookahead(WILDCARD)) {
tokens.consume();
return gte(versionFor(major)).and(lt(versionFor(major + 1)));
}
int minor = intOf(consumeNextToken(NUMERIC).lexeme);
consumeNextToken(DOT);
consumeNextToken(WILDCARD);
return gte(versionFor(major, minor)).and(lt(versionFor(major, minor + 1)));
} | [
"private",
"CompositeExpression",
"parseWildcardRange",
"(",
")",
"{",
"if",
"(",
"tokens",
".",
"positiveLookahead",
"(",
"WILDCARD",
")",
")",
"{",
"tokens",
".",
"consume",
"(",
")",
";",
"return",
"gte",
"(",
"versionFor",
"(",
"0",
",",
"0",
",",
"0... | Parses the {@literal <wildcard-range>} non-terminal.
<pre>
{@literal
<wildcard-range> ::= <wildcard>
| <major> "." <wildcard>
| <major> "." <minor> "." <wildcard>
<wildcard> ::= "*" | "x" | "X"
}
</pre>
@return the expression AST | [
"Parses",
"the",
"{",
"@literal",
"<wildcard",
"-",
"range",
">",
"}",
"non",
"-",
"terminal",
"."
] | train | https://github.com/zafarkhaja/jsemver/blob/1f4996ea3dab06193c378fd66fd4f8fdc8334cc6/src/main/java/com/github/zafarkhaja/semver/expr/ExpressionParser.java#L314-L331 |
spotify/crtauth-java | src/main/java/com/spotify/crtauth/CrtAuthServer.java | CrtAuthServer.createFakeFingerprint | private Fingerprint createFakeFingerprint(String userName) {
byte[] usernameHmac = CrtAuthCodec.getAuthenticationCode(
this.secret, userName.getBytes(Charsets.UTF_8));
return new Fingerprint(Arrays.copyOfRange(usernameHmac, 0, 6));
} | java | private Fingerprint createFakeFingerprint(String userName) {
byte[] usernameHmac = CrtAuthCodec.getAuthenticationCode(
this.secret, userName.getBytes(Charsets.UTF_8));
return new Fingerprint(Arrays.copyOfRange(usernameHmac, 0, 6));
} | [
"private",
"Fingerprint",
"createFakeFingerprint",
"(",
"String",
"userName",
")",
"{",
"byte",
"[",
"]",
"usernameHmac",
"=",
"CrtAuthCodec",
".",
"getAuthenticationCode",
"(",
"this",
".",
"secret",
",",
"userName",
".",
"getBytes",
"(",
"Charsets",
".",
"UTF_... | Generate a fake real looking fingerprint for a non-existent user.
@param userName the username to seed the transform with
@return a Fingerprint with bytes that are a function of username and secret | [
"Generate",
"a",
"fake",
"real",
"looking",
"fingerprint",
"for",
"a",
"non",
"-",
"existent",
"user",
"."
] | train | https://github.com/spotify/crtauth-java/blob/90f3b40323848740c915b195ad1b547fbeb41700/src/main/java/com/spotify/crtauth/CrtAuthServer.java#L248-L252 |
looly/hutool | hutool-extra/src/main/java/cn/hutool/extra/mail/MailUtil.java | MailUtil.sendText | public static void sendText(String to, String subject, String content, File... files) {
send(to, subject, content, false, files);
} | java | public static void sendText(String to, String subject, String content, File... files) {
send(to, subject, content, false, files);
} | [
"public",
"static",
"void",
"sendText",
"(",
"String",
"to",
",",
"String",
"subject",
",",
"String",
"content",
",",
"File",
"...",
"files",
")",
"{",
"send",
"(",
"to",
",",
"subject",
",",
"content",
",",
"false",
",",
"files",
")",
";",
"}"
] | 使用配置文件中设置的账户发送文本邮件,发送给单个或多个收件人<br>
多个收件人可以使用逗号“,”分隔,也可以通过分号“;”分隔
@param to 收件人
@param subject 标题
@param content 正文
@param files 附件列表
@since 3.2.0 | [
"使用配置文件中设置的账户发送文本邮件,发送给单个或多个收件人<br",
">",
"多个收件人可以使用逗号“",
"”分隔,也可以通过分号“",
";",
"”分隔"
] | train | https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-extra/src/main/java/cn/hutool/extra/mail/MailUtil.java#L28-L30 |
fabric8io/kubernetes-client | kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/RollingUpdater.java | RollingUpdater.waitUntilDeleted | private void waitUntilDeleted(final String namespace, final String name) {
final CountDownLatch countDownLatch = new CountDownLatch(1);
final Runnable waitTillDeletedPoller = () -> {
try {
T res = resources().inNamespace(namespace).withName(name).get();
if (res == null) {
countDownLatch.countDown();
}
} catch (KubernetesClientException e) {
if (e.getCode() == 404) {
countDownLatch.countDown();
}
}
};
ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
ScheduledFuture poller = executor.scheduleWithFixedDelay(waitTillDeletedPoller, 0, 5, TimeUnit.SECONDS);
ScheduledFuture logger = executor.scheduleWithFixedDelay(() -> LOG.debug("Found resource {}/{} not yet deleted on server, so waiting...", namespace, name), 0, loggingIntervalMillis, TimeUnit.MILLISECONDS);
try {
countDownLatch.await(DEFAULT_SERVER_GC_WAIT_TIMEOUT, TimeUnit.MILLISECONDS);
executor.shutdown();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
poller.cancel(true);
logger.cancel(true);
executor.shutdown();
LOG.warn("Still found deleted resource {} in namespace: {} after waiting for {} seconds so giving up",
name, namespace, TimeUnit.MILLISECONDS.toSeconds(DEFAULT_SERVER_GC_WAIT_TIMEOUT));
}
} | java | private void waitUntilDeleted(final String namespace, final String name) {
final CountDownLatch countDownLatch = new CountDownLatch(1);
final Runnable waitTillDeletedPoller = () -> {
try {
T res = resources().inNamespace(namespace).withName(name).get();
if (res == null) {
countDownLatch.countDown();
}
} catch (KubernetesClientException e) {
if (e.getCode() == 404) {
countDownLatch.countDown();
}
}
};
ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
ScheduledFuture poller = executor.scheduleWithFixedDelay(waitTillDeletedPoller, 0, 5, TimeUnit.SECONDS);
ScheduledFuture logger = executor.scheduleWithFixedDelay(() -> LOG.debug("Found resource {}/{} not yet deleted on server, so waiting...", namespace, name), 0, loggingIntervalMillis, TimeUnit.MILLISECONDS);
try {
countDownLatch.await(DEFAULT_SERVER_GC_WAIT_TIMEOUT, TimeUnit.MILLISECONDS);
executor.shutdown();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
poller.cancel(true);
logger.cancel(true);
executor.shutdown();
LOG.warn("Still found deleted resource {} in namespace: {} after waiting for {} seconds so giving up",
name, namespace, TimeUnit.MILLISECONDS.toSeconds(DEFAULT_SERVER_GC_WAIT_TIMEOUT));
}
} | [
"private",
"void",
"waitUntilDeleted",
"(",
"final",
"String",
"namespace",
",",
"final",
"String",
"name",
")",
"{",
"final",
"CountDownLatch",
"countDownLatch",
"=",
"new",
"CountDownLatch",
"(",
"1",
")",
";",
"final",
"Runnable",
"waitTillDeletedPoller",
"=",
... | Since k8s v1.4.x, rc/rs deletes are asynchronous.
Lets wait until the resource is actually deleted in the server | [
"Since",
"k8s",
"v1",
".",
"4",
".",
"x",
"rc",
"/",
"rs",
"deletes",
"are",
"asynchronous",
".",
"Lets",
"wait",
"until",
"the",
"resource",
"is",
"actually",
"deleted",
"in",
"the",
"server"
] | train | https://github.com/fabric8io/kubernetes-client/blob/141668a882ed8e902c045a5cd0a80f14bd17d132/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/RollingUpdater.java#L218-L248 |
lessthanoptimal/BoofCV | main/boofcv-recognition/src/main/java/boofcv/alg/scene/ClassifierKNearestNeighborsBow.java | ClassifierKNearestNeighborsBow.setClassificationData | public void setClassificationData(List<HistogramScene> memory , int numScenes ) {
nn.setPoints(memory, false);
scenes = new double[ numScenes ];
} | java | public void setClassificationData(List<HistogramScene> memory , int numScenes ) {
nn.setPoints(memory, false);
scenes = new double[ numScenes ];
} | [
"public",
"void",
"setClassificationData",
"(",
"List",
"<",
"HistogramScene",
">",
"memory",
",",
"int",
"numScenes",
")",
"{",
"nn",
".",
"setPoints",
"(",
"memory",
",",
"false",
")",
";",
"scenes",
"=",
"new",
"double",
"[",
"numScenes",
"]",
";",
"}... | Provides a set of labeled word histograms to use to classify a new image
@param memory labeled histograms | [
"Provides",
"a",
"set",
"of",
"labeled",
"word",
"histograms",
"to",
"use",
"to",
"classify",
"a",
"new",
"image"
] | train | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-recognition/src/main/java/boofcv/alg/scene/ClassifierKNearestNeighborsBow.java#L98-L103 |
kmi/iserve | iserve-discovery-api/src/main/java/uk/ac/open/kmi/iserve/discovery/api/impl/AbstractMatcher.java | AbstractMatcher.listMatchesAtMostOfType | @Override
public Table<URI, URI, MatchResult> listMatchesAtMostOfType(Set<URI> origins, MatchType maxType) {
return listMatchesWithinRange(origins, this.matchTypesSupported.getLowest(), maxType);
} | java | @Override
public Table<URI, URI, MatchResult> listMatchesAtMostOfType(Set<URI> origins, MatchType maxType) {
return listMatchesWithinRange(origins, this.matchTypesSupported.getLowest(), maxType);
} | [
"@",
"Override",
"public",
"Table",
"<",
"URI",
",",
"URI",
",",
"MatchResult",
">",
"listMatchesAtMostOfType",
"(",
"Set",
"<",
"URI",
">",
"origins",
",",
"MatchType",
"maxType",
")",
"{",
"return",
"listMatchesWithinRange",
"(",
"origins",
",",
"this",
".... | Obtain all the matching resources that have a MatchTyoe with the URIs of {@code origin} of the type provided (inclusive) or less.
@param origins URIs to match
@param maxType the maximum MatchType we want to obtain
@return a {@link com.google.common.collect.Table} with the result of the matching indexed by origin URI and then destination URI. | [
"Obtain",
"all",
"the",
"matching",
"resources",
"that",
"have",
"a",
"MatchTyoe",
"with",
"the",
"URIs",
"of",
"{",
"@code",
"origin",
"}",
"of",
"the",
"type",
"provided",
"(",
"inclusive",
")",
"or",
"less",
"."
] | train | https://github.com/kmi/iserve/blob/13e7016e64c1d5a539b838c6debf1a5cc4aefcb7/iserve-discovery-api/src/main/java/uk/ac/open/kmi/iserve/discovery/api/impl/AbstractMatcher.java#L135-L138 |
alkacon/opencms-core | src/org/opencms/security/CmsPrincipal.java | CmsPrincipal.getDisplayName | public String getDisplayName(CmsObject cms, Locale locale, I_CmsGroupNameTranslation translation)
throws CmsException {
if (!isGroup() || (translation == null)) {
return getDisplayName(cms, locale);
}
return Messages.get().getBundle(locale).key(
Messages.GUI_PRINCIPAL_DISPLAY_NAME_2,
translation.translateGroupName(getName(), false),
OpenCms.getOrgUnitManager().readOrganizationalUnit(cms, getOuFqn()).getDisplayName(locale));
} | java | public String getDisplayName(CmsObject cms, Locale locale, I_CmsGroupNameTranslation translation)
throws CmsException {
if (!isGroup() || (translation == null)) {
return getDisplayName(cms, locale);
}
return Messages.get().getBundle(locale).key(
Messages.GUI_PRINCIPAL_DISPLAY_NAME_2,
translation.translateGroupName(getName(), false),
OpenCms.getOrgUnitManager().readOrganizationalUnit(cms, getOuFqn()).getDisplayName(locale));
} | [
"public",
"String",
"getDisplayName",
"(",
"CmsObject",
"cms",
",",
"Locale",
"locale",
",",
"I_CmsGroupNameTranslation",
"translation",
")",
"throws",
"CmsException",
"{",
"if",
"(",
"!",
"isGroup",
"(",
")",
"||",
"(",
"translation",
"==",
"null",
")",
")",
... | Returns the translated display name of this principal if it is a group and the display name otherwise.<p>
@param cms the current CMS context
@param locale the locale
@param translation the group name translation to use
@return the translated display name
@throws CmsException if something goes wrong | [
"Returns",
"the",
"translated",
"display",
"name",
"of",
"this",
"principal",
"if",
"it",
"is",
"a",
"group",
"and",
"the",
"display",
"name",
"otherwise",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/security/CmsPrincipal.java#L427-L437 |
knowm/XChange | xchange-ripple/src/main/java/org/knowm/xchange/ripple/RippleAdapters.java | RippleAdapters.adaptOpenOrders | public static OpenOrders adaptOpenOrders(
final RippleAccountOrders rippleOrders, final int scale) {
final List<LimitOrder> list = new ArrayList<>(rippleOrders.getOrders().size());
for (final RippleAccountOrdersBody order : rippleOrders.getOrders()) {
final OrderType orderType;
final RippleAmount baseAmount;
final RippleAmount counterAmount;
if (order.getType().equals("buy")) {
// buying: we receive base and pay with counter, taker receives counter and pays with base
counterAmount = order.getTakerGets();
baseAmount = order.getTakerPays();
orderType = OrderType.BID;
} else {
// selling: we receive counter and pay with base, taker receives base and pays with counter
baseAmount = order.getTakerGets();
counterAmount = order.getTakerPays();
orderType = OrderType.ASK;
}
final String baseSymbol = baseAmount.getCurrency();
final String counterSymbol = counterAmount.getCurrency();
// need to provide rounding scale to prevent ArithmeticException
final BigDecimal price =
counterAmount
.getValue()
.divide(baseAmount.getValue(), scale, RoundingMode.HALF_UP)
.stripTrailingZeros();
final CurrencyPair pair = new CurrencyPair(baseSymbol, counterSymbol);
final RippleLimitOrder xchangeOrder =
(RippleLimitOrder)
new RippleLimitOrder.Builder(orderType, pair)
.baseCounterparty(baseAmount.getCounterparty())
.counterCounterparty(counterAmount.getCounterparty())
.id(Long.toString(order.getSequence()))
.limitPrice(price)
.timestamp(null)
.originalAmount(baseAmount.getValue())
.build();
list.add(xchangeOrder);
}
return new OpenOrders(list);
} | java | public static OpenOrders adaptOpenOrders(
final RippleAccountOrders rippleOrders, final int scale) {
final List<LimitOrder> list = new ArrayList<>(rippleOrders.getOrders().size());
for (final RippleAccountOrdersBody order : rippleOrders.getOrders()) {
final OrderType orderType;
final RippleAmount baseAmount;
final RippleAmount counterAmount;
if (order.getType().equals("buy")) {
// buying: we receive base and pay with counter, taker receives counter and pays with base
counterAmount = order.getTakerGets();
baseAmount = order.getTakerPays();
orderType = OrderType.BID;
} else {
// selling: we receive counter and pay with base, taker receives base and pays with counter
baseAmount = order.getTakerGets();
counterAmount = order.getTakerPays();
orderType = OrderType.ASK;
}
final String baseSymbol = baseAmount.getCurrency();
final String counterSymbol = counterAmount.getCurrency();
// need to provide rounding scale to prevent ArithmeticException
final BigDecimal price =
counterAmount
.getValue()
.divide(baseAmount.getValue(), scale, RoundingMode.HALF_UP)
.stripTrailingZeros();
final CurrencyPair pair = new CurrencyPair(baseSymbol, counterSymbol);
final RippleLimitOrder xchangeOrder =
(RippleLimitOrder)
new RippleLimitOrder.Builder(orderType, pair)
.baseCounterparty(baseAmount.getCounterparty())
.counterCounterparty(counterAmount.getCounterparty())
.id(Long.toString(order.getSequence()))
.limitPrice(price)
.timestamp(null)
.originalAmount(baseAmount.getValue())
.build();
list.add(xchangeOrder);
}
return new OpenOrders(list);
} | [
"public",
"static",
"OpenOrders",
"adaptOpenOrders",
"(",
"final",
"RippleAccountOrders",
"rippleOrders",
",",
"final",
"int",
"scale",
")",
"{",
"final",
"List",
"<",
"LimitOrder",
">",
"list",
"=",
"new",
"ArrayList",
"<>",
"(",
"rippleOrders",
".",
"getOrders... | Adapts a Ripple Account Orders object to an XChange OpenOrders object Counterparties set in
additional data since there is no other way of the application receiving this information. | [
"Adapts",
"a",
"Ripple",
"Account",
"Orders",
"object",
"to",
"an",
"XChange",
"OpenOrders",
"object",
"Counterparties",
"set",
"in",
"additional",
"data",
"since",
"there",
"is",
"no",
"other",
"way",
"of",
"the",
"application",
"receiving",
"this",
"informatio... | train | https://github.com/knowm/XChange/blob/e45f437ac8e0b89cd66cdcb3258bdb1bf3d88186/xchange-ripple/src/main/java/org/knowm/xchange/ripple/RippleAdapters.java#L203-L249 |
cubedtear/aritzh | aritzh-core/src/main/java/io/github/aritzhack/aritzh/util/ARGBColorUtil.java | ARGBColorUtil.getColor | public static int getColor(final int alpha, final int red, final int green, final int blue) {
return (alpha << ALPHA_SHIFT) | (red << RED_SHIFT) | (green << GREEN_SHIFT) | blue;
} | java | public static int getColor(final int alpha, final int red, final int green, final int blue) {
return (alpha << ALPHA_SHIFT) | (red << RED_SHIFT) | (green << GREEN_SHIFT) | blue;
} | [
"public",
"static",
"int",
"getColor",
"(",
"final",
"int",
"alpha",
",",
"final",
"int",
"red",
",",
"final",
"int",
"green",
",",
"final",
"int",
"blue",
")",
"{",
"return",
"(",
"alpha",
"<<",
"ALPHA_SHIFT",
")",
"|",
"(",
"red",
"<<",
"RED_SHIFT",
... | Gets a color composed of the specified channels. All values must be between 0 and 255, both inclusive
@param alpha The alpha channel [0-255]
@param red The red channel [0-255]
@param green The green channel [0-255]
@param blue The blue channel [0-255]
@return The color composed of the specified channels | [
"Gets",
"a",
"color",
"composed",
"of",
"the",
"specified",
"channels",
".",
"All",
"values",
"must",
"be",
"between",
"0",
"and",
"255",
"both",
"inclusive"
] | train | https://github.com/cubedtear/aritzh/blob/bc7493447a1a6088c4a7306ca4d0f0c20278364f/aritzh-core/src/main/java/io/github/aritzhack/aritzh/util/ARGBColorUtil.java#L114-L116 |
VoltDB/voltdb | third_party/java/src/org/HdrHistogram_voltpatches/Histogram.java | Histogram.decodeFromCompressedByteBuffer | public static Histogram decodeFromCompressedByteBuffer(final ByteBuffer buffer,
final long minBarForHighestTrackableValue) throws DataFormatException {
return decodeFromCompressedByteBuffer(buffer, Histogram.class, minBarForHighestTrackableValue);
} | java | public static Histogram decodeFromCompressedByteBuffer(final ByteBuffer buffer,
final long minBarForHighestTrackableValue) throws DataFormatException {
return decodeFromCompressedByteBuffer(buffer, Histogram.class, minBarForHighestTrackableValue);
} | [
"public",
"static",
"Histogram",
"decodeFromCompressedByteBuffer",
"(",
"final",
"ByteBuffer",
"buffer",
",",
"final",
"long",
"minBarForHighestTrackableValue",
")",
"throws",
"DataFormatException",
"{",
"return",
"decodeFromCompressedByteBuffer",
"(",
"buffer",
",",
"Histo... | Construct a new histogram by decoding it from a compressed form in a ByteBuffer.
@param buffer The buffer to decode from
@param minBarForHighestTrackableValue Force highestTrackableValue to be set at least this high
@return The newly constructed histogram
@throws DataFormatException on error parsing/decompressing the buffer | [
"Construct",
"a",
"new",
"histogram",
"by",
"decoding",
"it",
"from",
"a",
"compressed",
"form",
"in",
"a",
"ByteBuffer",
"."
] | train | https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/third_party/java/src/org/HdrHistogram_voltpatches/Histogram.java#L251-L254 |
fozziethebeat/S-Space | opt/src/main/java/edu/ucla/sspace/lra/LatentRelationalAnalysis.java | LatentRelationalAnalysis.indexDirectory | private static void indexDirectory(IndexWriter writer, File dir)
throws IOException {
File[] files = dir.listFiles();
for (int i = 0; i < files.length; i++) {
File f = files[i];
if (f.isDirectory()) {
indexDirectory(writer, f);
} else if (f.getName().endsWith(".txt")) {
indexFile(writer, f);
}
}
} | java | private static void indexDirectory(IndexWriter writer, File dir)
throws IOException {
File[] files = dir.listFiles();
for (int i = 0; i < files.length; i++) {
File f = files[i];
if (f.isDirectory()) {
indexDirectory(writer, f);
} else if (f.getName().endsWith(".txt")) {
indexFile(writer, f);
}
}
} | [
"private",
"static",
"void",
"indexDirectory",
"(",
"IndexWriter",
"writer",
",",
"File",
"dir",
")",
"throws",
"IOException",
"{",
"File",
"[",
"]",
"files",
"=",
"dir",
".",
"listFiles",
"(",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<... | recursive method that calls itself when it finds a directory, or indexes if
it is at a file ending in ".txt" | [
"recursive",
"method",
"that",
"calls",
"itself",
"when",
"it",
"finds",
"a",
"directory",
"or",
"indexes",
"if",
"it",
"is",
"at",
"a",
"file",
"ending",
"in",
".",
"txt"
] | train | https://github.com/fozziethebeat/S-Space/blob/a608102737dfd3d59038a9ead33fe60356bc6029/opt/src/main/java/edu/ucla/sspace/lra/LatentRelationalAnalysis.java#L377-L390 |
Azure/azure-sdk-for-java | cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/ModelsImpl.java | ModelsImpl.getIntentSuggestionsWithServiceResponseAsync | public Observable<ServiceResponse<List<IntentsSuggestionExample>>> getIntentSuggestionsWithServiceResponseAsync(UUID appId, String versionId, UUID intentId, GetIntentSuggestionsOptionalParameter getIntentSuggestionsOptionalParameter) {
if (this.client.endpoint() == null) {
throw new IllegalArgumentException("Parameter this.client.endpoint() is required and cannot be null.");
}
if (appId == null) {
throw new IllegalArgumentException("Parameter appId is required and cannot be null.");
}
if (versionId == null) {
throw new IllegalArgumentException("Parameter versionId is required and cannot be null.");
}
if (intentId == null) {
throw new IllegalArgumentException("Parameter intentId is required and cannot be null.");
}
final Integer take = getIntentSuggestionsOptionalParameter != null ? getIntentSuggestionsOptionalParameter.take() : null;
return getIntentSuggestionsWithServiceResponseAsync(appId, versionId, intentId, take);
} | java | public Observable<ServiceResponse<List<IntentsSuggestionExample>>> getIntentSuggestionsWithServiceResponseAsync(UUID appId, String versionId, UUID intentId, GetIntentSuggestionsOptionalParameter getIntentSuggestionsOptionalParameter) {
if (this.client.endpoint() == null) {
throw new IllegalArgumentException("Parameter this.client.endpoint() is required and cannot be null.");
}
if (appId == null) {
throw new IllegalArgumentException("Parameter appId is required and cannot be null.");
}
if (versionId == null) {
throw new IllegalArgumentException("Parameter versionId is required and cannot be null.");
}
if (intentId == null) {
throw new IllegalArgumentException("Parameter intentId is required and cannot be null.");
}
final Integer take = getIntentSuggestionsOptionalParameter != null ? getIntentSuggestionsOptionalParameter.take() : null;
return getIntentSuggestionsWithServiceResponseAsync(appId, versionId, intentId, take);
} | [
"public",
"Observable",
"<",
"ServiceResponse",
"<",
"List",
"<",
"IntentsSuggestionExample",
">",
">",
">",
"getIntentSuggestionsWithServiceResponseAsync",
"(",
"UUID",
"appId",
",",
"String",
"versionId",
",",
"UUID",
"intentId",
",",
"GetIntentSuggestionsOptionalParame... | Suggests examples that would improve the accuracy of the intent model.
@param appId The application ID.
@param versionId The version ID.
@param intentId The intent classifier ID.
@param getIntentSuggestionsOptionalParameter the object representing the optional parameters to be set before calling this API
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the List<IntentsSuggestionExample> object | [
"Suggests",
"examples",
"that",
"would",
"improve",
"the",
"accuracy",
"of",
"the",
"intent",
"model",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/ModelsImpl.java#L5119-L5135 |
citrusframework/citrus | modules/citrus-java-dsl/src/main/java/com/consol/citrus/dsl/builder/SoapServerActionBuilder.java | SoapServerActionBuilder.sendFault | public SoapServerFaultResponseActionBuilder sendFault() {
SoapServerFaultResponseActionBuilder soapServerResponseActionBuilder = new SoapServerFaultResponseActionBuilder(action, soapServer)
.withApplicationContext(applicationContext);
return soapServerResponseActionBuilder;
} | java | public SoapServerFaultResponseActionBuilder sendFault() {
SoapServerFaultResponseActionBuilder soapServerResponseActionBuilder = new SoapServerFaultResponseActionBuilder(action, soapServer)
.withApplicationContext(applicationContext);
return soapServerResponseActionBuilder;
} | [
"public",
"SoapServerFaultResponseActionBuilder",
"sendFault",
"(",
")",
"{",
"SoapServerFaultResponseActionBuilder",
"soapServerResponseActionBuilder",
"=",
"new",
"SoapServerFaultResponseActionBuilder",
"(",
"action",
",",
"soapServer",
")",
".",
"withApplicationContext",
"(",
... | Generic response builder for sending SOAP fault messages to client.
@return | [
"Generic",
"response",
"builder",
"for",
"sending",
"SOAP",
"fault",
"messages",
"to",
"client",
"."
] | train | https://github.com/citrusframework/citrus/blob/55c58ef74c01d511615e43646ca25c1b2301c56d/modules/citrus-java-dsl/src/main/java/com/consol/citrus/dsl/builder/SoapServerActionBuilder.java#L70-L74 |
Javacord/Javacord | javacord-api/src/main/java/org/javacord/api/entity/message/embed/EmbedBuilder.java | EmbedBuilder.setImage | public EmbedBuilder setImage(BufferedImage image, String fileType) {
delegate.setImage(image, fileType);
return this;
} | java | public EmbedBuilder setImage(BufferedImage image, String fileType) {
delegate.setImage(image, fileType);
return this;
} | [
"public",
"EmbedBuilder",
"setImage",
"(",
"BufferedImage",
"image",
",",
"String",
"fileType",
")",
"{",
"delegate",
".",
"setImage",
"(",
"image",
",",
"fileType",
")",
";",
"return",
"this",
";",
"}"
] | Sets the image of the embed.
@param image The image.
@param fileType The type of the file, e.g. "png" or "gif".
@return The current instance in order to chain call methods. | [
"Sets",
"the",
"image",
"of",
"the",
"embed",
"."
] | train | https://github.com/Javacord/Javacord/blob/915aad084dc5e863284267529d0dccd625fc6886/javacord-api/src/main/java/org/javacord/api/entity/message/embed/EmbedBuilder.java#L326-L329 |
alkacon/opencms-core | src/org/opencms/jlan/CmsJlanRepository.java | CmsJlanRepository.createLoggingProxy | public static DiskInterface createLoggingProxy(final DiskInterface impl) {
return (DiskInterface)Proxy.newProxyInstance(
Thread.currentThread().getContextClassLoader(),
new Class[] {DiskInterface.class},
new InvocationHandler() {
@SuppressWarnings("synthetic-access")
public Object invoke(Object target, Method method, Object[] params) throws Throwable {
// Just to be on the safe side performance-wise, we only log the parameters/result
// if the info channel is enabled
if (LOG.isInfoEnabled()) {
List<String> paramStrings = new ArrayList<String>();
for (Object param : params) {
paramStrings.add("" + param);
}
String paramsAsString = CmsStringUtil.listAsString(paramStrings, ", ");
LOG.info("Call: " + method.getName() + " " + paramsAsString);
}
try {
Object result = method.invoke(impl, params);
if (LOG.isInfoEnabled()) {
LOG.info("Returned from " + method.getName() + ": " + result);
}
return result;
} catch (InvocationTargetException e) {
Throwable cause = e.getCause();
if ((cause != null) && (cause instanceof CmsSilentWrapperException)) {
// not really an error
LOG.info(cause.getCause().getLocalizedMessage(), cause.getCause());
} else {
LOG.error(e.getLocalizedMessage(), e);
}
throw e.getCause();
}
}
});
} | java | public static DiskInterface createLoggingProxy(final DiskInterface impl) {
return (DiskInterface)Proxy.newProxyInstance(
Thread.currentThread().getContextClassLoader(),
new Class[] {DiskInterface.class},
new InvocationHandler() {
@SuppressWarnings("synthetic-access")
public Object invoke(Object target, Method method, Object[] params) throws Throwable {
// Just to be on the safe side performance-wise, we only log the parameters/result
// if the info channel is enabled
if (LOG.isInfoEnabled()) {
List<String> paramStrings = new ArrayList<String>();
for (Object param : params) {
paramStrings.add("" + param);
}
String paramsAsString = CmsStringUtil.listAsString(paramStrings, ", ");
LOG.info("Call: " + method.getName() + " " + paramsAsString);
}
try {
Object result = method.invoke(impl, params);
if (LOG.isInfoEnabled()) {
LOG.info("Returned from " + method.getName() + ": " + result);
}
return result;
} catch (InvocationTargetException e) {
Throwable cause = e.getCause();
if ((cause != null) && (cause instanceof CmsSilentWrapperException)) {
// not really an error
LOG.info(cause.getCause().getLocalizedMessage(), cause.getCause());
} else {
LOG.error(e.getLocalizedMessage(), e);
}
throw e.getCause();
}
}
});
} | [
"public",
"static",
"DiskInterface",
"createLoggingProxy",
"(",
"final",
"DiskInterface",
"impl",
")",
"{",
"return",
"(",
"DiskInterface",
")",
"Proxy",
".",
"newProxyInstance",
"(",
"Thread",
".",
"currentThread",
"(",
")",
".",
"getContextClassLoader",
"(",
")"... | Creates a dynamic proxy for a disk interface which logs the method calls and their results.<p>
@param impl the disk interface for which a logging proxy should be created
@return the dynamic proxy which logs methods calls | [
"Creates",
"a",
"dynamic",
"proxy",
"for",
"a",
"disk",
"interface",
"which",
"logs",
"the",
"method",
"calls",
"and",
"their",
"results",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/jlan/CmsJlanRepository.java#L141-L179 |
cloudendpoints/endpoints-management-java | endpoints-control/src/main/java/com/google/api/control/model/Distributions.java | Distributions.createLinear | public static Distribution createLinear(int numFiniteBuckets, double width, double offset) {
if (numFiniteBuckets <= 0) {
throw new IllegalArgumentException(MSG_BAD_NUM_FINITE_BUCKETS);
}
if (width <= 0.0) {
throw new IllegalArgumentException(String.format(MSG_DOUBLE_TOO_LOW, "width", 0.0));
}
LinearBuckets buckets = LinearBuckets.newBuilder().setOffset(offset).setWidth(width)
.setNumFiniteBuckets(numFiniteBuckets).build();
Builder builder = Distribution.newBuilder().setLinearBuckets(buckets);
for (int i = 0; i < numFiniteBuckets + 2; i++) {
builder.addBucketCounts(0L);
}
return builder.build();
} | java | public static Distribution createLinear(int numFiniteBuckets, double width, double offset) {
if (numFiniteBuckets <= 0) {
throw new IllegalArgumentException(MSG_BAD_NUM_FINITE_BUCKETS);
}
if (width <= 0.0) {
throw new IllegalArgumentException(String.format(MSG_DOUBLE_TOO_LOW, "width", 0.0));
}
LinearBuckets buckets = LinearBuckets.newBuilder().setOffset(offset).setWidth(width)
.setNumFiniteBuckets(numFiniteBuckets).build();
Builder builder = Distribution.newBuilder().setLinearBuckets(buckets);
for (int i = 0; i < numFiniteBuckets + 2; i++) {
builder.addBucketCounts(0L);
}
return builder.build();
} | [
"public",
"static",
"Distribution",
"createLinear",
"(",
"int",
"numFiniteBuckets",
",",
"double",
"width",
",",
"double",
"offset",
")",
"{",
"if",
"(",
"numFiniteBuckets",
"<=",
"0",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"MSG_BAD_NUM_FINITE_... | Creates a {@code Distribution} with {@code LinearBuckets}.
@param numFiniteBuckets initializes the number of finite buckets
@param width initializes the width of each bucket
@param offset initializes the offset of the start bucket
@return a {@code Distribution} with {@code LinearBuckets}
@throws IllegalArgumentException if a bad input prevents creation. | [
"Creates",
"a",
"{",
"@code",
"Distribution",
"}",
"with",
"{",
"@code",
"LinearBuckets",
"}",
"."
] | train | https://github.com/cloudendpoints/endpoints-management-java/blob/5bbf20ddadbbd51b890049e3c338c28abe2c9f94/endpoints-control/src/main/java/com/google/api/control/model/Distributions.java#L89-L103 |
groupon/odo | client/src/main/java/com/groupon/odo/client/Client.java | Client.addMethodToResponseOverride | public boolean addMethodToResponseOverride(String pathName, String methodName) {
// need to find out the ID for the method
// TODO: change api for adding methods to take the name instead of ID
try {
Integer overrideId = getOverrideIdForMethodName(methodName);
// now post to path api to add this is a selected override
BasicNameValuePair[] params = {
new BasicNameValuePair("addOverride", overrideId.toString()),
new BasicNameValuePair("profileIdentifier", this._profileName)
};
JSONObject response = new JSONObject(doPost(BASE_PATH + uriEncode(pathName), params));
// check enabled endpoints array to see if this overrideID exists
JSONArray enabled = response.getJSONArray("enabledEndpoints");
for (int x = 0; x < enabled.length(); x++) {
if (enabled.getJSONObject(x).getInt("overrideId") == overrideId) {
return true;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return false;
} | java | public boolean addMethodToResponseOverride(String pathName, String methodName) {
// need to find out the ID for the method
// TODO: change api for adding methods to take the name instead of ID
try {
Integer overrideId = getOverrideIdForMethodName(methodName);
// now post to path api to add this is a selected override
BasicNameValuePair[] params = {
new BasicNameValuePair("addOverride", overrideId.toString()),
new BasicNameValuePair("profileIdentifier", this._profileName)
};
JSONObject response = new JSONObject(doPost(BASE_PATH + uriEncode(pathName), params));
// check enabled endpoints array to see if this overrideID exists
JSONArray enabled = response.getJSONArray("enabledEndpoints");
for (int x = 0; x < enabled.length(); x++) {
if (enabled.getJSONObject(x).getInt("overrideId") == overrideId) {
return true;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return false;
} | [
"public",
"boolean",
"addMethodToResponseOverride",
"(",
"String",
"pathName",
",",
"String",
"methodName",
")",
"{",
"// need to find out the ID for the method",
"// TODO: change api for adding methods to take the name instead of ID",
"try",
"{",
"Integer",
"overrideId",
"=",
"g... | Add a method to the enabled response overrides for a path
@param pathName name of path
@param methodName name of method
@return true if success, false otherwise | [
"Add",
"a",
"method",
"to",
"the",
"enabled",
"response",
"overrides",
"for",
"a",
"path"
] | train | https://github.com/groupon/odo/blob/3bae43d5eca8ace036775e5b2d3ed9af1a9ff9b1/client/src/main/java/com/groupon/odo/client/Client.java#L617-L641 |
ehcache/ehcache3 | impl/src/main/java/org/ehcache/impl/internal/resilience/RobustResilienceStrategy.java | RobustResilienceStrategy.removeAllFailure | @Override
public void removeAllFailure(Iterable<? extends K> keys, StoreAccessException e) {
cleanup(keys, e);
} | java | @Override
public void removeAllFailure(Iterable<? extends K> keys, StoreAccessException e) {
cleanup(keys, e);
} | [
"@",
"Override",
"public",
"void",
"removeAllFailure",
"(",
"Iterable",
"<",
"?",
"extends",
"K",
">",
"keys",
",",
"StoreAccessException",
"e",
")",
"{",
"cleanup",
"(",
"keys",
",",
"e",
")",
";",
"}"
] | Do nothing.
@param keys the keys being removed
@param e the triggered failure | [
"Do",
"nothing",
"."
] | train | https://github.com/ehcache/ehcache3/blob/3cceda57185e522f8d241ddb75146d67ee2af898/impl/src/main/java/org/ehcache/impl/internal/resilience/RobustResilienceStrategy.java#L198-L201 |
wisdom-framework/wisdom | extensions/wisdom-npm-runner-maven-plugin/src/main/java/org/wisdom/mojo/npm/NpmRunnerMojo.java | NpmRunnerMojo.fileCreated | @Override
public boolean fileCreated(File file) throws WatchingException {
try {
execute();
} catch (MojoExecutionException e) {
throw new WatchingException("Cannot execute the NPM '" + name + "'", e);
}
return true;
} | java | @Override
public boolean fileCreated(File file) throws WatchingException {
try {
execute();
} catch (MojoExecutionException e) {
throw new WatchingException("Cannot execute the NPM '" + name + "'", e);
}
return true;
} | [
"@",
"Override",
"public",
"boolean",
"fileCreated",
"(",
"File",
"file",
")",
"throws",
"WatchingException",
"{",
"try",
"{",
"execute",
"(",
")",
";",
"}",
"catch",
"(",
"MojoExecutionException",
"e",
")",
"{",
"throw",
"new",
"WatchingException",
"(",
"\"... | An accepted file was created - executes the NPM.
@param file is the file.
@return {@code true}
@throws org.wisdom.maven.WatchingException if the execution fails. | [
"An",
"accepted",
"file",
"was",
"created",
"-",
"executes",
"the",
"NPM",
"."
] | train | https://github.com/wisdom-framework/wisdom/blob/a35b6431200fec56b178c0ff60837ed73fd7874d/extensions/wisdom-npm-runner-maven-plugin/src/main/java/org/wisdom/mojo/npm/NpmRunnerMojo.java#L107-L115 |
fhoeben/hsac-fitnesse-fixtures | src/main/java/nl/hsac/fitnesse/fixture/util/MapHelper.java | MapHelper.setValuesForIn | public void setValuesForIn(String values, String name, Map<String, Object> map) {
String cleanName = htmlCleaner.cleanupValue(name);
String[] valueArrays = values.split("\\s*,\\s*");
List<Object> valueObjects = new ArrayList<Object>(valueArrays.length);
for (int i = 0; i < valueArrays.length; i++) {
Object cleanValue = getCleanValue(valueArrays[i]);
valueObjects.add(cleanValue);
}
setValueForIn(valueObjects, cleanName, map);
} | java | public void setValuesForIn(String values, String name, Map<String, Object> map) {
String cleanName = htmlCleaner.cleanupValue(name);
String[] valueArrays = values.split("\\s*,\\s*");
List<Object> valueObjects = new ArrayList<Object>(valueArrays.length);
for (int i = 0; i < valueArrays.length; i++) {
Object cleanValue = getCleanValue(valueArrays[i]);
valueObjects.add(cleanValue);
}
setValueForIn(valueObjects, cleanName, map);
} | [
"public",
"void",
"setValuesForIn",
"(",
"String",
"values",
",",
"String",
"name",
",",
"Map",
"<",
"String",
",",
"Object",
">",
"map",
")",
"{",
"String",
"cleanName",
"=",
"htmlCleaner",
".",
"cleanupValue",
"(",
"name",
")",
";",
"String",
"[",
"]",... | Stores list of values in map.
@param values comma separated list of values.
@param name name to use this list for.
@param map map to store values in. | [
"Stores",
"list",
"of",
"values",
"in",
"map",
"."
] | train | https://github.com/fhoeben/hsac-fitnesse-fixtures/blob/4e9018d7386a9aa65bfcbf07eb28ae064edd1732/src/main/java/nl/hsac/fitnesse/fixture/util/MapHelper.java#L134-L143 |
raydac/java-binary-block-parser | jbbp-plugins/jbbp-plugin-common/src/main/java/com/igormaznitsa/jbbp/plugin/common/utils/CommonUtils.java | CommonUtils.scriptFileToJavaFile | @Nonnull
public static File scriptFileToJavaFile(@Nullable final File targetDir, @Nullable final String classPackage, @Nonnull final File scriptFile) {
final String rawFileName = FilenameUtils.getBaseName(scriptFile.getName());
final String className = CommonUtils.extractClassName(rawFileName);
final String packageName = classPackage == null ? CommonUtils.extractPackageName(rawFileName) : classPackage;
String fullClassName = packageName.isEmpty() ? className : packageName + '.' + className;
fullClassName = fullClassName.replace('.', File.separatorChar) + ".java";
return new File(targetDir, fullClassName);
} | java | @Nonnull
public static File scriptFileToJavaFile(@Nullable final File targetDir, @Nullable final String classPackage, @Nonnull final File scriptFile) {
final String rawFileName = FilenameUtils.getBaseName(scriptFile.getName());
final String className = CommonUtils.extractClassName(rawFileName);
final String packageName = classPackage == null ? CommonUtils.extractPackageName(rawFileName) : classPackage;
String fullClassName = packageName.isEmpty() ? className : packageName + '.' + className;
fullClassName = fullClassName.replace('.', File.separatorChar) + ".java";
return new File(targetDir, fullClassName);
} | [
"@",
"Nonnull",
"public",
"static",
"File",
"scriptFileToJavaFile",
"(",
"@",
"Nullable",
"final",
"File",
"targetDir",
",",
"@",
"Nullable",
"final",
"String",
"classPackage",
",",
"@",
"Nonnull",
"final",
"File",
"scriptFile",
")",
"{",
"final",
"String",
"r... | Convert script file into path to Java class file.
@param targetDir the target dir for generated sources, it can be null
@param classPackage class package to override extracted one from script name, it can be null
@param scriptFile the script file, must not be null
@return java source file for the script file | [
"Convert",
"script",
"file",
"into",
"path",
"to",
"Java",
"class",
"file",
"."
] | train | https://github.com/raydac/java-binary-block-parser/blob/6d98abcab01e0c72d525ebcc9e7b694f9ce49f5b/jbbp-plugins/jbbp-plugin-common/src/main/java/com/igormaznitsa/jbbp/plugin/common/utils/CommonUtils.java#L91-L101 |
qiujiayu/AutoLoadCache | src/main/java/com/jarvis/cache/script/AbstractScriptParser.java | AbstractScriptParser.isCanDelete | public boolean isCanDelete(CacheDeleteKey cacheDeleteKey, Object[] arguments, Object retVal) throws Exception {
boolean rv = true;
if (null != arguments && arguments.length > 0 && null != cacheDeleteKey.condition()
&& cacheDeleteKey.condition().length() > 0) {
rv = this.getElValue(cacheDeleteKey.condition(), null, arguments, retVal, true, Boolean.class);
}
return rv;
} | java | public boolean isCanDelete(CacheDeleteKey cacheDeleteKey, Object[] arguments, Object retVal) throws Exception {
boolean rv = true;
if (null != arguments && arguments.length > 0 && null != cacheDeleteKey.condition()
&& cacheDeleteKey.condition().length() > 0) {
rv = this.getElValue(cacheDeleteKey.condition(), null, arguments, retVal, true, Boolean.class);
}
return rv;
} | [
"public",
"boolean",
"isCanDelete",
"(",
"CacheDeleteKey",
"cacheDeleteKey",
",",
"Object",
"[",
"]",
"arguments",
",",
"Object",
"retVal",
")",
"throws",
"Exception",
"{",
"boolean",
"rv",
"=",
"true",
";",
"if",
"(",
"null",
"!=",
"arguments",
"&&",
"argum... | 是否可以删除缓存
@param cacheDeleteKey CacheDeleteKey注解
@param arguments 参数
@param retVal 结果值
@return Can Delete
@throws Exception 异常 | [
"是否可以删除缓存"
] | train | https://github.com/qiujiayu/AutoLoadCache/blob/8121c146f1a420fa6d6832e849acadb547c13622/src/main/java/com/jarvis/cache/script/AbstractScriptParser.java#L169-L176 |
xiancloud/xian | xian-message/src/main/java/info/xiancloud/message/short_msg/yunpian/JavaSmsApi.java | JavaSmsApi.tplSendSms | public static Single<String> tplSendSms(String apikey, long tpl_id, String tpl_value, String mobile) {
Map<String, String> params = new HashMap<>();
params.put("apikey", apikey);
params.put("tpl_id", String.valueOf(tpl_id));
params.put("tpl_value", tpl_value);
params.put("mobile", mobile);
return post(URI_TPL_SEND_SMS, params);
} | java | public static Single<String> tplSendSms(String apikey, long tpl_id, String tpl_value, String mobile) {
Map<String, String> params = new HashMap<>();
params.put("apikey", apikey);
params.put("tpl_id", String.valueOf(tpl_id));
params.put("tpl_value", tpl_value);
params.put("mobile", mobile);
return post(URI_TPL_SEND_SMS, params);
} | [
"public",
"static",
"Single",
"<",
"String",
">",
"tplSendSms",
"(",
"String",
"apikey",
",",
"long",
"tpl_id",
",",
"String",
"tpl_value",
",",
"String",
"mobile",
")",
"{",
"Map",
"<",
"String",
",",
"String",
">",
"params",
"=",
"new",
"HashMap",
"<>"... | 通过模板发送短信(不推荐)
@param apikey apikey
@param tpl_id 模板id
@param tpl_value 模板变量值
@param mobile 接受的手机号
@return json格式字符串 | [
"通过模板发送短信",
"(",
"不推荐",
")"
] | train | https://github.com/xiancloud/xian/blob/1948e088545553d2745b2c86d8b5a64988bb850e/xian-message/src/main/java/info/xiancloud/message/short_msg/yunpian/JavaSmsApi.java#L108-L115 |
Azure/azure-sdk-for-java | sql/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sql/v2017_03_01_preview/implementation/JobExecutionsInner.java | JobExecutionsInner.listByAgentWithServiceResponseAsync | public Observable<ServiceResponse<Page<JobExecutionInner>>> listByAgentWithServiceResponseAsync(final String resourceGroupName, final String serverName, final String jobAgentName, final DateTime createTimeMin, final DateTime createTimeMax, final DateTime endTimeMin, final DateTime endTimeMax, final Boolean isActive, final Integer skip, final Integer top) {
return listByAgentSinglePageAsync(resourceGroupName, serverName, jobAgentName, createTimeMin, createTimeMax, endTimeMin, endTimeMax, isActive, skip, top)
.concatMap(new Func1<ServiceResponse<Page<JobExecutionInner>>, Observable<ServiceResponse<Page<JobExecutionInner>>>>() {
@Override
public Observable<ServiceResponse<Page<JobExecutionInner>>> call(ServiceResponse<Page<JobExecutionInner>> page) {
String nextPageLink = page.body().nextPageLink();
if (nextPageLink == null) {
return Observable.just(page);
}
return Observable.just(page).concatWith(listByAgentNextWithServiceResponseAsync(nextPageLink));
}
});
} | java | public Observable<ServiceResponse<Page<JobExecutionInner>>> listByAgentWithServiceResponseAsync(final String resourceGroupName, final String serverName, final String jobAgentName, final DateTime createTimeMin, final DateTime createTimeMax, final DateTime endTimeMin, final DateTime endTimeMax, final Boolean isActive, final Integer skip, final Integer top) {
return listByAgentSinglePageAsync(resourceGroupName, serverName, jobAgentName, createTimeMin, createTimeMax, endTimeMin, endTimeMax, isActive, skip, top)
.concatMap(new Func1<ServiceResponse<Page<JobExecutionInner>>, Observable<ServiceResponse<Page<JobExecutionInner>>>>() {
@Override
public Observable<ServiceResponse<Page<JobExecutionInner>>> call(ServiceResponse<Page<JobExecutionInner>> page) {
String nextPageLink = page.body().nextPageLink();
if (nextPageLink == null) {
return Observable.just(page);
}
return Observable.just(page).concatWith(listByAgentNextWithServiceResponseAsync(nextPageLink));
}
});
} | [
"public",
"Observable",
"<",
"ServiceResponse",
"<",
"Page",
"<",
"JobExecutionInner",
">",
">",
">",
"listByAgentWithServiceResponseAsync",
"(",
"final",
"String",
"resourceGroupName",
",",
"final",
"String",
"serverName",
",",
"final",
"String",
"jobAgentName",
",",... | Lists all executions in a job agent.
@param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal.
@param serverName The name of the server.
@param jobAgentName The name of the job agent.
@param createTimeMin If specified, only job executions created at or after the specified time are included.
@param createTimeMax If specified, only job executions created before the specified time are included.
@param endTimeMin If specified, only job executions completed at or after the specified time are included.
@param endTimeMax If specified, only job executions completed before the specified time are included.
@param isActive If specified, only active or only completed job executions are included.
@param skip The number of elements in the collection to skip.
@param top The number of elements to return from the collection.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the PagedList<JobExecutionInner> object | [
"Lists",
"all",
"executions",
"in",
"a",
"job",
"agent",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/sql/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sql/v2017_03_01_preview/implementation/JobExecutionsInner.java#L336-L348 |
netty/netty | codec-http2/src/main/java/io/netty/handler/codec/http2/Http2ConnectionHandler.java | Http2ConnectionHandler.goAway | private ChannelFuture goAway(ChannelHandlerContext ctx, Http2Exception cause, ChannelPromise promise) {
long errorCode = cause != null ? cause.error().code() : NO_ERROR.code();
int lastKnownStream = connection().remote().lastStreamCreated();
return goAway(ctx, lastKnownStream, errorCode, Http2CodecUtil.toByteBuf(ctx, cause), promise);
} | java | private ChannelFuture goAway(ChannelHandlerContext ctx, Http2Exception cause, ChannelPromise promise) {
long errorCode = cause != null ? cause.error().code() : NO_ERROR.code();
int lastKnownStream = connection().remote().lastStreamCreated();
return goAway(ctx, lastKnownStream, errorCode, Http2CodecUtil.toByteBuf(ctx, cause), promise);
} | [
"private",
"ChannelFuture",
"goAway",
"(",
"ChannelHandlerContext",
"ctx",
",",
"Http2Exception",
"cause",
",",
"ChannelPromise",
"promise",
")",
"{",
"long",
"errorCode",
"=",
"cause",
"!=",
"null",
"?",
"cause",
".",
"error",
"(",
")",
".",
"code",
"(",
")... | Close the remote endpoint with with a {@code GO_AWAY} frame. Does <strong>not</strong> flush
immediately, this is the responsibility of the caller. | [
"Close",
"the",
"remote",
"endpoint",
"with",
"with",
"a",
"{"
] | train | https://github.com/netty/netty/blob/ba06eafa1c1824bd154f1a380019e7ea2edf3c4c/codec-http2/src/main/java/io/netty/handler/codec/http2/Http2ConnectionHandler.java#L873-L877 |
h2oai/h2o-3 | h2o-parsers/h2o-parquet-parser/src/main/java/water/parser/parquet/ParquetParser.java | ParquetParser.correctTypeConversions | public static byte[] correctTypeConversions(ByteVec vec, byte[] requestedTypes) {
byte[] metadataBytes = VecParquetReader.readFooterAsBytes(vec);
ParquetMetadata metadata = VecParquetReader.readFooter(metadataBytes, ParquetMetadataConverter.NO_FILTER);
byte[] roughTypes = roughGuessTypes(metadata.getFileMetaData().getSchema());
return correctTypeConversions(roughTypes, requestedTypes);
} | java | public static byte[] correctTypeConversions(ByteVec vec, byte[] requestedTypes) {
byte[] metadataBytes = VecParquetReader.readFooterAsBytes(vec);
ParquetMetadata metadata = VecParquetReader.readFooter(metadataBytes, ParquetMetadataConverter.NO_FILTER);
byte[] roughTypes = roughGuessTypes(metadata.getFileMetaData().getSchema());
return correctTypeConversions(roughTypes, requestedTypes);
} | [
"public",
"static",
"byte",
"[",
"]",
"correctTypeConversions",
"(",
"ByteVec",
"vec",
",",
"byte",
"[",
"]",
"requestedTypes",
")",
"{",
"byte",
"[",
"]",
"metadataBytes",
"=",
"VecParquetReader",
".",
"readFooterAsBytes",
"(",
"vec",
")",
";",
"ParquetMetada... | Overrides unsupported type conversions/mappings specified by the user.
@param vec byte vec holding bin\ary parquet data
@param requestedTypes user-specified target types
@return corrected types | [
"Overrides",
"unsupported",
"type",
"conversions",
"/",
"mappings",
"specified",
"by",
"the",
"user",
"."
] | train | https://github.com/h2oai/h2o-3/blob/845eb49dfeaadf638b6e2f779d82fac996391fad/h2o-parsers/h2o-parquet-parser/src/main/java/water/parser/parquet/ParquetParser.java#L145-L150 |
UrielCh/ovh-java-sdk | ovh-java-sdk-cloud/src/main/java/net/minidev/ovh/api/ApiOvhCloud.java | ApiOvhCloud.project_serviceName_quota_GET | public ArrayList<OvhQuotas> project_serviceName_quota_GET(String serviceName) throws IOException {
String qPath = "/cloud/project/{serviceName}/quota";
StringBuilder sb = path(qPath, serviceName);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, t16);
} | java | public ArrayList<OvhQuotas> project_serviceName_quota_GET(String serviceName) throws IOException {
String qPath = "/cloud/project/{serviceName}/quota";
StringBuilder sb = path(qPath, serviceName);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, t16);
} | [
"public",
"ArrayList",
"<",
"OvhQuotas",
">",
"project_serviceName_quota_GET",
"(",
"String",
"serviceName",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/cloud/project/{serviceName}/quota\"",
";",
"StringBuilder",
"sb",
"=",
"path",
"(",
"qPath",
","... | Get project quotas
REST: GET /cloud/project/{serviceName}/quota
@param serviceName [required] Project id | [
"Get",
"project",
"quotas"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-cloud/src/main/java/net/minidev/ovh/api/ApiOvhCloud.java#L1411-L1416 |
pippo-java/pippo | pippo-core/src/main/java/ro/pippo/core/PippoSettings.java | PippoSettings.overrideSetting | public void overrideSetting(String name, char value) {
overrides.put(name, Character.toString(value));
} | java | public void overrideSetting(String name, char value) {
overrides.put(name, Character.toString(value));
} | [
"public",
"void",
"overrideSetting",
"(",
"String",
"name",
",",
"char",
"value",
")",
"{",
"overrides",
".",
"put",
"(",
"name",
",",
"Character",
".",
"toString",
"(",
"value",
")",
")",
";",
"}"
] | Override the setting at runtime with the specified value.
This change does not persist.
@param name
@param value | [
"Override",
"the",
"setting",
"at",
"runtime",
"with",
"the",
"specified",
"value",
".",
"This",
"change",
"does",
"not",
"persist",
"."
] | train | https://github.com/pippo-java/pippo/blob/cb5ccb453bffcc3cf386adc660674812d10b9726/pippo-core/src/main/java/ro/pippo/core/PippoSettings.java#L1034-L1036 |
elki-project/elki | elki/src/main/java/de/lmu/ifi/dbs/elki/persistent/PersistentPageFile.java | PersistentPageFile.writePage | @Override
public void writePage(int pageID, P page) {
try {
countWrite();
byte[] array = pageToByteArray(page);
long offset = ((long) (header.getReservedPages() + pageID)) * (long) pageSize;
assert offset >= 0 : header.getReservedPages() + " " + pageID + " " + pageSize + " " + offset;
file.seek(offset);
file.write(array);
page.setDirty(false);
}
catch(IOException e) {
throw new RuntimeException("Error writing to page file.", e);
}
} | java | @Override
public void writePage(int pageID, P page) {
try {
countWrite();
byte[] array = pageToByteArray(page);
long offset = ((long) (header.getReservedPages() + pageID)) * (long) pageSize;
assert offset >= 0 : header.getReservedPages() + " " + pageID + " " + pageSize + " " + offset;
file.seek(offset);
file.write(array);
page.setDirty(false);
}
catch(IOException e) {
throw new RuntimeException("Error writing to page file.", e);
}
} | [
"@",
"Override",
"public",
"void",
"writePage",
"(",
"int",
"pageID",
",",
"P",
"page",
")",
"{",
"try",
"{",
"countWrite",
"(",
")",
";",
"byte",
"[",
"]",
"array",
"=",
"pageToByteArray",
"(",
"page",
")",
";",
"long",
"offset",
"=",
"(",
"(",
"l... | This method is called by the cache if the <code>page</code> is not longer
stored in the cache and has to be written to disk.
@param page the page which has to be written to disk | [
"This",
"method",
"is",
"called",
"by",
"the",
"cache",
"if",
"the",
"<code",
">",
"page<",
"/",
"code",
">",
"is",
"not",
"longer",
"stored",
"in",
"the",
"cache",
"and",
"has",
"to",
"be",
"written",
"to",
"disk",
"."
] | train | https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki/src/main/java/de/lmu/ifi/dbs/elki/persistent/PersistentPageFile.java#L156-L170 |
lessthanoptimal/BoofCV | main/boofcv-ip/src/main/java/boofcv/factory/filter/kernel/FactoryKernel.java | FactoryKernel.random2D_F64 | public static Kernel2D_F64 random2D_F64(int width , int offset, double min, double max, Random rand) {
Kernel2D_F64 ret = new Kernel2D_F64(width,offset);
double range = max - min;
for (int i = 0; i < ret.data.length; i++) {
ret.data[i] = rand.nextDouble() * range + min;
}
return ret;
} | java | public static Kernel2D_F64 random2D_F64(int width , int offset, double min, double max, Random rand) {
Kernel2D_F64 ret = new Kernel2D_F64(width,offset);
double range = max - min;
for (int i = 0; i < ret.data.length; i++) {
ret.data[i] = rand.nextDouble() * range + min;
}
return ret;
} | [
"public",
"static",
"Kernel2D_F64",
"random2D_F64",
"(",
"int",
"width",
",",
"int",
"offset",
",",
"double",
"min",
",",
"double",
"max",
",",
"Random",
"rand",
")",
"{",
"Kernel2D_F64",
"ret",
"=",
"new",
"Kernel2D_F64",
"(",
"width",
",",
"offset",
")",... | Creates a random 2D kernel drawn from a uniform distribution.
@param width Kernel's width.
@param offset Offset for element zero in the kernel
@param min minimum value.
@param max maximum value.
@param rand Random number generator.
@return Randomized kernel. | [
"Creates",
"a",
"random",
"2D",
"kernel",
"drawn",
"from",
"a",
"uniform",
"distribution",
"."
] | train | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-ip/src/main/java/boofcv/factory/filter/kernel/FactoryKernel.java#L319-L328 |
stratosphere/stratosphere | stratosphere-runtime/src/main/java/eu/stratosphere/nephele/jobgraph/AbstractJobVertex.java | AbstractJobVertex.connectTo | public void connectTo(final AbstractJobVertex vertex, final int indexOfOutputGate, final int indexOfInputGate)
throws JobGraphDefinitionException {
this.connectTo(vertex, null, indexOfOutputGate, indexOfInputGate, DistributionPattern.BIPARTITE);
} | java | public void connectTo(final AbstractJobVertex vertex, final int indexOfOutputGate, final int indexOfInputGate)
throws JobGraphDefinitionException {
this.connectTo(vertex, null, indexOfOutputGate, indexOfInputGate, DistributionPattern.BIPARTITE);
} | [
"public",
"void",
"connectTo",
"(",
"final",
"AbstractJobVertex",
"vertex",
",",
"final",
"int",
"indexOfOutputGate",
",",
"final",
"int",
"indexOfInputGate",
")",
"throws",
"JobGraphDefinitionException",
"{",
"this",
".",
"connectTo",
"(",
"vertex",
",",
"null",
... | Connects the job vertex to the specified job vertex.
@param vertex
the vertex this vertex should connect to
@param indexOfOutputGate
index of the producing task's output gate to be used, <code>-1</code> will determine the next free index
number
@param indexOfInputGate
index of the consuming task's input gate to be used, <code>-1</code> will determine the next free index
number
@throws JobGraphDefinitionException
thrown if the given vertex cannot be connected to <code>vertex</code> in the requested manner | [
"Connects",
"the",
"job",
"vertex",
"to",
"the",
"specified",
"job",
"vertex",
"."
] | train | https://github.com/stratosphere/stratosphere/blob/c543a08f9676c5b2b0a7088123bd6e795a8ae0c8/stratosphere-runtime/src/main/java/eu/stratosphere/nephele/jobgraph/AbstractJobVertex.java#L141-L144 |
googleapis/google-cloud-java | google-cloud-clients/google-cloud-compute/src/main/java/com/google/cloud/compute/deprecated/DiskId.java | DiskId.of | public static DiskId of(ZoneId zoneId, String disk) {
return new DiskId(zoneId.getProject(), zoneId.getZone(), disk);
} | java | public static DiskId of(ZoneId zoneId, String disk) {
return new DiskId(zoneId.getProject(), zoneId.getZone(), disk);
} | [
"public",
"static",
"DiskId",
"of",
"(",
"ZoneId",
"zoneId",
",",
"String",
"disk",
")",
"{",
"return",
"new",
"DiskId",
"(",
"zoneId",
".",
"getProject",
"(",
")",
",",
"zoneId",
".",
"getZone",
"(",
")",
",",
"disk",
")",
";",
"}"
] | Returns a disk identity given the zone identity and the disk name. The disk name must be 1-63
characters long and comply with RFC1035. Specifically, the name must match the regular
expression {@code [a-z]([-a-z0-9]*[a-z0-9])?} which means the first character must be a
lowercase letter, and all following characters must be a dash, lowercase letter, or digit,
except the last character, which cannot be a dash.
@see <a href="https://www.ietf.org/rfc/rfc1035.txt">RFC1035</a> | [
"Returns",
"a",
"disk",
"identity",
"given",
"the",
"zone",
"identity",
"and",
"the",
"disk",
"name",
".",
"The",
"disk",
"name",
"must",
"be",
"1",
"-",
"63",
"characters",
"long",
"and",
"comply",
"with",
"RFC1035",
".",
"Specifically",
"the",
"name",
... | train | https://github.com/googleapis/google-cloud-java/blob/d2f0bc64a53049040fe9c9d338b12fab3dd1ad6a/google-cloud-clients/google-cloud-compute/src/main/java/com/google/cloud/compute/deprecated/DiskId.java#L110-L112 |
ironjacamar/ironjacamar | codegenerator/src/main/java/org/ironjacamar/codegenerator/code/CciConnCodeGen.java | CciConnCodeGen.writeClassBody | @Override
public void writeClassBody(Definition def, Writer out) throws IOException
{
out.write("public class " + getClassName(def) + " implements Connection");
writeLeftCurlyBracket(out, 0);
int indent = 1;
writeDefaultConstructor(def, out, indent);
//constructor
writeWithIndent(out, indent, "/**\n");
writeWithIndent(out, indent, " * Default constructor\n");
writeWithIndent(out, indent, " * @param connSpec ConnectionSpec\n");
writeWithIndent(out, indent, " */\n");
writeWithIndent(out, indent, "public " + getClassName(def) + "(ConnectionSpec connSpec)");
writeLeftCurlyBracket(out, indent);
writeRightCurlyBracket(out, indent);
writeEol(out);
writeClose(def, out, indent);
writeInteraction(def, out, indent);
writeLocalTransaction(def, out, indent);
writeMetaData(def, out, indent);
writeResultSetInfo(def, out, indent);
writeEol(out);
writeWithIndent(out, indent, "/**\n");
writeWithIndent(out, indent, " * Set ManagedConnection\n");
writeWithIndent(out, indent, " */\n");
writeWithIndent(out, indent,
"void setManagedConnection(" + def.getMcfDefs().get(getNumOfMcf()).getMcClass() + " mc)");
writeLeftCurlyBracket(out, indent);
writeRightCurlyBracket(out, indent);
writeRightCurlyBracket(out, 0);
} | java | @Override
public void writeClassBody(Definition def, Writer out) throws IOException
{
out.write("public class " + getClassName(def) + " implements Connection");
writeLeftCurlyBracket(out, 0);
int indent = 1;
writeDefaultConstructor(def, out, indent);
//constructor
writeWithIndent(out, indent, "/**\n");
writeWithIndent(out, indent, " * Default constructor\n");
writeWithIndent(out, indent, " * @param connSpec ConnectionSpec\n");
writeWithIndent(out, indent, " */\n");
writeWithIndent(out, indent, "public " + getClassName(def) + "(ConnectionSpec connSpec)");
writeLeftCurlyBracket(out, indent);
writeRightCurlyBracket(out, indent);
writeEol(out);
writeClose(def, out, indent);
writeInteraction(def, out, indent);
writeLocalTransaction(def, out, indent);
writeMetaData(def, out, indent);
writeResultSetInfo(def, out, indent);
writeEol(out);
writeWithIndent(out, indent, "/**\n");
writeWithIndent(out, indent, " * Set ManagedConnection\n");
writeWithIndent(out, indent, " */\n");
writeWithIndent(out, indent,
"void setManagedConnection(" + def.getMcfDefs().get(getNumOfMcf()).getMcClass() + " mc)");
writeLeftCurlyBracket(out, indent);
writeRightCurlyBracket(out, indent);
writeRightCurlyBracket(out, 0);
} | [
"@",
"Override",
"public",
"void",
"writeClassBody",
"(",
"Definition",
"def",
",",
"Writer",
"out",
")",
"throws",
"IOException",
"{",
"out",
".",
"write",
"(",
"\"public class \"",
"+",
"getClassName",
"(",
"def",
")",
"+",
"\" implements Connection\"",
")",
... | Output ResourceAdapater class
@param def definition
@param out Writer
@throws IOException ioException | [
"Output",
"ResourceAdapater",
"class"
] | train | https://github.com/ironjacamar/ironjacamar/blob/f0389ee7e62aa8b40ba09b251edad76d220ea796/codegenerator/src/main/java/org/ironjacamar/codegenerator/code/CciConnCodeGen.java#L43-L80 |
google/closure-compiler | src/com/google/javascript/jscomp/RewriteAsyncIteration.java | RewriteAsyncIteration.convertAwaitOfAsyncGenerator | private void convertAwaitOfAsyncGenerator(NodeTraversal t, LexicalContext ctx, Node awaitNode) {
checkNotNull(awaitNode);
checkState(awaitNode.isAwait());
checkState(ctx != null && ctx.function != null);
checkState(ctx.function.isAsyncGeneratorFunction());
Node expression = awaitNode.removeFirstChild();
checkNotNull(expression, "await needs an expression");
Node newActionRecord =
astFactory.createNewNode(
astFactory.createQName(t.getScope(), ACTION_RECORD_NAME),
astFactory.createQName(t.getScope(), ACTION_ENUM_AWAIT),
expression);
newActionRecord.useSourceInfoIfMissingFromForTree(awaitNode);
awaitNode.addChildToFront(newActionRecord);
awaitNode.setToken(Token.YIELD);
} | java | private void convertAwaitOfAsyncGenerator(NodeTraversal t, LexicalContext ctx, Node awaitNode) {
checkNotNull(awaitNode);
checkState(awaitNode.isAwait());
checkState(ctx != null && ctx.function != null);
checkState(ctx.function.isAsyncGeneratorFunction());
Node expression = awaitNode.removeFirstChild();
checkNotNull(expression, "await needs an expression");
Node newActionRecord =
astFactory.createNewNode(
astFactory.createQName(t.getScope(), ACTION_RECORD_NAME),
astFactory.createQName(t.getScope(), ACTION_ENUM_AWAIT),
expression);
newActionRecord.useSourceInfoIfMissingFromForTree(awaitNode);
awaitNode.addChildToFront(newActionRecord);
awaitNode.setToken(Token.YIELD);
} | [
"private",
"void",
"convertAwaitOfAsyncGenerator",
"(",
"NodeTraversal",
"t",
",",
"LexicalContext",
"ctx",
",",
"Node",
"awaitNode",
")",
"{",
"checkNotNull",
"(",
"awaitNode",
")",
";",
"checkState",
"(",
"awaitNode",
".",
"isAwait",
"(",
")",
")",
";",
"che... | Converts an await into a yield of an ActionRecord to perform "AWAIT".
<pre>{@code await myPromise}</pre>
<p>becomes
<pre>{@code yield new ActionRecord(ActionEnum.AWAIT_VALUE, myPromise)}</pre>
@param awaitNode the original await Node to be converted | [
"Converts",
"an",
"await",
"into",
"a",
"yield",
"of",
"an",
"ActionRecord",
"to",
"perform",
"AWAIT",
"."
] | train | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/RewriteAsyncIteration.java#L411-L427 |
apache/flink | flink-optimizer/src/main/java/org/apache/flink/optimizer/DataStatistics.java | DataStatistics.cacheBaseStatistics | public void cacheBaseStatistics(BaseStatistics statistics, String identifier) {
synchronized (this.baseStatisticsCache) {
this.baseStatisticsCache.put(identifier, statistics);
}
} | java | public void cacheBaseStatistics(BaseStatistics statistics, String identifier) {
synchronized (this.baseStatisticsCache) {
this.baseStatisticsCache.put(identifier, statistics);
}
} | [
"public",
"void",
"cacheBaseStatistics",
"(",
"BaseStatistics",
"statistics",
",",
"String",
"identifier",
")",
"{",
"synchronized",
"(",
"this",
".",
"baseStatisticsCache",
")",
"{",
"this",
".",
"baseStatisticsCache",
".",
"put",
"(",
"identifier",
",",
"statist... | Caches the given statistics. They are later retrievable under the given identifier.
@param statistics The statistics to cache.
@param identifier The identifier which may be later used to retrieve the statistics. | [
"Caches",
"the",
"given",
"statistics",
".",
"They",
"are",
"later",
"retrievable",
"under",
"the",
"given",
"identifier",
"."
] | train | https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-optimizer/src/main/java/org/apache/flink/optimizer/DataStatistics.java#L64-L68 |
mapbox/mapbox-navigation-android | libandroid-navigation/src/main/java/com/mapbox/services/android/navigation/v5/navigation/MapboxOfflineRouter.java | MapboxOfflineRouter.downloadTiles | public void downloadTiles(OfflineTiles offlineTiles, RouteTileDownloadListener listener) {
new RouteTileDownloader(offlineNavigator, tilePath, listener).startDownload(offlineTiles);
} | java | public void downloadTiles(OfflineTiles offlineTiles, RouteTileDownloadListener listener) {
new RouteTileDownloader(offlineNavigator, tilePath, listener).startDownload(offlineTiles);
} | [
"public",
"void",
"downloadTiles",
"(",
"OfflineTiles",
"offlineTiles",
",",
"RouteTileDownloadListener",
"listener",
")",
"{",
"new",
"RouteTileDownloader",
"(",
"offlineNavigator",
",",
"tilePath",
",",
"listener",
")",
".",
"startDownload",
"(",
"offlineTiles",
")"... | Starts the download of tiles specified by the provided {@link OfflineTiles} object.
@param offlineTiles object specifying parameters for the tile request
@param listener which is updated on error, on progress update and on completion | [
"Starts",
"the",
"download",
"of",
"tiles",
"specified",
"by",
"the",
"provided",
"{",
"@link",
"OfflineTiles",
"}",
"object",
"."
] | train | https://github.com/mapbox/mapbox-navigation-android/blob/375a89c017d360b9defc2c90d0c03468165162ec/libandroid-navigation/src/main/java/com/mapbox/services/android/navigation/v5/navigation/MapboxOfflineRouter.java#L77-L79 |
mangstadt/biweekly | src/main/java/biweekly/util/Google2445Utils.java | Google2445Utils.createRecurrenceIterable | public static RecurrenceIterable createRecurrenceIterable(Recurrence recurrence, ICalDate start, TimeZone timezone) {
DateValue startValue = convert(start, timezone);
return RecurrenceIteratorFactory.createRecurrenceIterable(recurrence, startValue, timezone);
} | java | public static RecurrenceIterable createRecurrenceIterable(Recurrence recurrence, ICalDate start, TimeZone timezone) {
DateValue startValue = convert(start, timezone);
return RecurrenceIteratorFactory.createRecurrenceIterable(recurrence, startValue, timezone);
} | [
"public",
"static",
"RecurrenceIterable",
"createRecurrenceIterable",
"(",
"Recurrence",
"recurrence",
",",
"ICalDate",
"start",
",",
"TimeZone",
"timezone",
")",
"{",
"DateValue",
"startValue",
"=",
"convert",
"(",
"start",
",",
"timezone",
")",
";",
"return",
"R... | Creates a recurrence iterator based on the given recurrence rule.
@param recurrence the recurrence rule
@param start the start date
@param timezone the timezone to iterate in. This is needed in order to
account for when the iterator passes over a daylight savings boundary.
@return the recurrence iterator | [
"Creates",
"a",
"recurrence",
"iterator",
"based",
"on",
"the",
"given",
"recurrence",
"rule",
"."
] | train | https://github.com/mangstadt/biweekly/blob/2e21350f85c13dfff52fdef98fdbebe2976fcf61/src/main/java/biweekly/util/Google2445Utils.java#L209-L212 |
spring-projects/spring-android | spring-android-core/src/main/java/org/springframework/core/convert/support/GenericConversionService.java | GenericConversionService.getConverter | protected GenericConverter getConverter(TypeDescriptor sourceType, TypeDescriptor targetType) {
ConverterCacheKey key = new ConverterCacheKey(sourceType, targetType);
GenericConverter converter = this.converterCache.get(key);
if (converter != null) {
return (converter != NO_MATCH ? converter : null);
}
converter = this.converters.find(sourceType, targetType);
if (converter == null) {
converter = getDefaultConverter(sourceType, targetType);
}
if (converter != null) {
this.converterCache.put(key, converter);
return converter;
}
this.converterCache.put(key, NO_MATCH);
return null;
} | java | protected GenericConverter getConverter(TypeDescriptor sourceType, TypeDescriptor targetType) {
ConverterCacheKey key = new ConverterCacheKey(sourceType, targetType);
GenericConverter converter = this.converterCache.get(key);
if (converter != null) {
return (converter != NO_MATCH ? converter : null);
}
converter = this.converters.find(sourceType, targetType);
if (converter == null) {
converter = getDefaultConverter(sourceType, targetType);
}
if (converter != null) {
this.converterCache.put(key, converter);
return converter;
}
this.converterCache.put(key, NO_MATCH);
return null;
} | [
"protected",
"GenericConverter",
"getConverter",
"(",
"TypeDescriptor",
"sourceType",
",",
"TypeDescriptor",
"targetType",
")",
"{",
"ConverterCacheKey",
"key",
"=",
"new",
"ConverterCacheKey",
"(",
"sourceType",
",",
"targetType",
")",
";",
"GenericConverter",
"convert... | Hook method to lookup the converter for a given sourceType/targetType pair.
First queries this ConversionService's converter cache.
On a cache miss, then performs an exhaustive search for a matching converter.
If no converter matches, returns the default converter.
Subclasses may override.
@param sourceType the source type to convert from
@param targetType the target type to convert to
@return the generic converter that will perform the conversion, or {@code null} if
no suitable converter was found
@see #getDefaultConverter(TypeDescriptor, TypeDescriptor) | [
"Hook",
"method",
"to",
"lookup",
"the",
"converter",
"for",
"a",
"given",
"sourceType",
"/",
"targetType",
"pair",
".",
"First",
"queries",
"this",
"ConversionService",
"s",
"converter",
"cache",
".",
"On",
"a",
"cache",
"miss",
"then",
"performs",
"an",
"e... | train | https://github.com/spring-projects/spring-android/blob/941296e152d49a40e0745a3e81628a974f72b7e4/spring-android-core/src/main/java/org/springframework/core/convert/support/GenericConversionService.java#L222-L241 |
Coveros/selenified | src/main/java/com/coveros/selenified/application/WaitFor.java | WaitFor.urlEquals | public void urlEquals(double seconds, String expectedURL) {
double end = System.currentTimeMillis() + (seconds * 1000);
try {
WebDriverWait wait = new WebDriverWait(app.getDriver(), (long) seconds, DEFAULT_POLLING_INTERVAL);
wait.until(ExpectedConditions.urlToBe(expectedURL));
double timeTook = Math.min((seconds * 1000) - (end - System.currentTimeMillis()), seconds * 1000) / 1000;
checkUrlEquals(expectedURL, seconds, timeTook);
} catch (TimeoutException e) {
checkUrlEquals(expectedURL, seconds, seconds);
}
} | java | public void urlEquals(double seconds, String expectedURL) {
double end = System.currentTimeMillis() + (seconds * 1000);
try {
WebDriverWait wait = new WebDriverWait(app.getDriver(), (long) seconds, DEFAULT_POLLING_INTERVAL);
wait.until(ExpectedConditions.urlToBe(expectedURL));
double timeTook = Math.min((seconds * 1000) - (end - System.currentTimeMillis()), seconds * 1000) / 1000;
checkUrlEquals(expectedURL, seconds, timeTook);
} catch (TimeoutException e) {
checkUrlEquals(expectedURL, seconds, seconds);
}
} | [
"public",
"void",
"urlEquals",
"(",
"double",
"seconds",
",",
"String",
"expectedURL",
")",
"{",
"double",
"end",
"=",
"System",
".",
"currentTimeMillis",
"(",
")",
"+",
"(",
"seconds",
"*",
"1000",
")",
";",
"try",
"{",
"WebDriverWait",
"wait",
"=",
"ne... | Asserts that the provided URL equals the actual URL the application is
currently on. This information will be logged and recorded, with a
screenshot for traceability and added debugging support.
@param seconds the number of seconds to wait
@param expectedURL - the expectedURL to wait for | [
"Asserts",
"that",
"the",
"provided",
"URL",
"equals",
"the",
"actual",
"URL",
"the",
"application",
"is",
"currently",
"on",
".",
"This",
"information",
"will",
"be",
"logged",
"and",
"recorded",
"with",
"a",
"screenshot",
"for",
"traceability",
"and",
"added... | train | https://github.com/Coveros/selenified/blob/396cc1f010dd69eed33cc5061c41253de246a4cd/src/main/java/com/coveros/selenified/application/WaitFor.java#L348-L358 |
mgm-tp/jfunk | jfunk-core/src/main/java/com/mgmtp/jfunk/core/config/JFunkBaseModule.java | JFunkBaseModule.providePerfLoadVersion | @Provides
@Singleton
@JFunkVersion
protected String providePerfLoadVersion() {
ClassLoader loader = Thread.currentThread().getContextClassLoader();
InputStream is = loader.getResourceAsStream("com/mgmtp/jfunk/common/version.txt");
try {
return IOUtils.toString(is, "UTF-8");
} catch (IOException ex) {
throw new IllegalStateException("Could not read jFunk version.", ex);
} finally {
IOUtils.closeQuietly(is);
}
} | java | @Provides
@Singleton
@JFunkVersion
protected String providePerfLoadVersion() {
ClassLoader loader = Thread.currentThread().getContextClassLoader();
InputStream is = loader.getResourceAsStream("com/mgmtp/jfunk/common/version.txt");
try {
return IOUtils.toString(is, "UTF-8");
} catch (IOException ex) {
throw new IllegalStateException("Could not read jFunk version.", ex);
} finally {
IOUtils.closeQuietly(is);
}
} | [
"@",
"Provides",
"@",
"Singleton",
"@",
"JFunkVersion",
"protected",
"String",
"providePerfLoadVersion",
"(",
")",
"{",
"ClassLoader",
"loader",
"=",
"Thread",
".",
"currentThread",
"(",
")",
".",
"getContextClassLoader",
"(",
")",
";",
"InputStream",
"is",
"=",... | Provides the version of perfLoad as specified in the Maven pom.
@return the version string | [
"Provides",
"the",
"version",
"of",
"perfLoad",
"as",
"specified",
"in",
"the",
"Maven",
"pom",
"."
] | train | https://github.com/mgm-tp/jfunk/blob/5b9fecac5778b988bb458085ded39ea9a4c7c2ae/jfunk-core/src/main/java/com/mgmtp/jfunk/core/config/JFunkBaseModule.java#L151-L164 |
jparsec/jparsec | jparsec/src/main/java/org/jparsec/Parsers.java | Parsers.or | public static <T> Parser<T> or(Parser<? extends T> p1, Parser<? extends T> p2) {
return alt(p1, p2).cast();
} | java | public static <T> Parser<T> or(Parser<? extends T> p1, Parser<? extends T> p2) {
return alt(p1, p2).cast();
} | [
"public",
"static",
"<",
"T",
">",
"Parser",
"<",
"T",
">",
"or",
"(",
"Parser",
"<",
"?",
"extends",
"T",
">",
"p1",
",",
"Parser",
"<",
"?",
"extends",
"T",
">",
"p2",
")",
"{",
"return",
"alt",
"(",
"p1",
",",
"p2",
")",
".",
"cast",
"(",
... | A {@link Parser} that tries 2 alternative parser objects.
Fallback happens regardless of partial match. | [
"A",
"{"
] | train | https://github.com/jparsec/jparsec/blob/df1280259f5da9eb5ffc537437569dddba66cb94/jparsec/src/main/java/org/jparsec/Parsers.java#L618-L620 |
overturetool/overture | ide/ui/src/main/java/org/overture/ide/ui/VdmPluginImages.java | VdmPluginImages.createUnManagedCached | private static ImageDescriptor createUnManagedCached(String prefix,
String name)
{
return new CachedImageDescriptor(create(prefix, name, true));
} | java | private static ImageDescriptor createUnManagedCached(String prefix,
String name)
{
return new CachedImageDescriptor(create(prefix, name, true));
} | [
"private",
"static",
"ImageDescriptor",
"createUnManagedCached",
"(",
"String",
"prefix",
",",
"String",
"name",
")",
"{",
"return",
"new",
"CachedImageDescriptor",
"(",
"create",
"(",
"prefix",
",",
"name",
",",
"true",
")",
")",
";",
"}"
] | /*
Creates an image descriptor for the given prefix and name in the JDT UI bundle and let tye descriptor cache the
image data. If no image could be found, the 'missing image descriptor' is returned. | [
"/",
"*",
"Creates",
"an",
"image",
"descriptor",
"for",
"the",
"given",
"prefix",
"and",
"name",
"in",
"the",
"JDT",
"UI",
"bundle",
"and",
"let",
"tye",
"descriptor",
"cache",
"the",
"image",
"data",
".",
"If",
"no",
"image",
"could",
"be",
"found",
... | train | https://github.com/overturetool/overture/blob/83175dc6c24fa171cde4fcf61ecb648eba3bdbc1/ide/ui/src/main/java/org/overture/ide/ui/VdmPluginImages.java#L802-L806 |
algolia/algoliasearch-client-java | src/main/java/com/algolia/search/saas/Index.java | Index.waitTask | public void waitTask(String taskID, long timeToWait) throws AlgoliaException {
this.waitTask(taskID, timeToWait, RequestOptions.empty);
} | java | public void waitTask(String taskID, long timeToWait) throws AlgoliaException {
this.waitTask(taskID, timeToWait, RequestOptions.empty);
} | [
"public",
"void",
"waitTask",
"(",
"String",
"taskID",
",",
"long",
"timeToWait",
")",
"throws",
"AlgoliaException",
"{",
"this",
".",
"waitTask",
"(",
"taskID",
",",
"timeToWait",
",",
"RequestOptions",
".",
"empty",
")",
";",
"}"
] | Wait the publication of a task on the server.
All server task are asynchronous and you can check with this method that the task is published.
@param taskID the id of the task returned by server
@param timeToWait time to sleep seed | [
"Wait",
"the",
"publication",
"of",
"a",
"task",
"on",
"the",
"server",
".",
"All",
"server",
"task",
"are",
"asynchronous",
"and",
"you",
"can",
"check",
"with",
"this",
"method",
"that",
"the",
"task",
"is",
"published",
"."
] | train | https://github.com/algolia/algoliasearch-client-java/blob/a05da2f66c099fe6f77295c7b6a8a12c24e95f9b/src/main/java/com/algolia/search/saas/Index.java#L841-L843 |
apache/incubator-gobblin | gobblin-hive-registration/src/main/java/org/apache/gobblin/hive/orc/HiveOrcSerDeManager.java | HiveOrcSerDeManager.addSchemaPropertiesHelper | protected void addSchemaPropertiesHelper(Path path, HiveRegistrationUnit hiveUnit) throws IOException {
TypeInfo schema = getSchemaFromLatestFile(path, this.fs);
if (schema instanceof StructTypeInfo) {
StructTypeInfo structTypeInfo = (StructTypeInfo) schema;
hiveUnit.setSerDeProp(SCHEMA_LITERAL, schema);
hiveUnit.setSerDeProp(serdeConstants.LIST_COLUMNS,
Joiner.on(",").join(structTypeInfo.getAllStructFieldNames()));
hiveUnit.setSerDeProp(serdeConstants.LIST_COLUMN_TYPES,
Joiner.on(",").join(
structTypeInfo.getAllStructFieldTypeInfos().stream().map(x -> x.getTypeName())
.collect(Collectors.toList())));
} else {
// Hive always uses a struct with a field for each of the top-level columns as the root object type.
// So for here we assume to-be-registered ORC files follow this pattern.
throw new IllegalStateException("A valid ORC schema should be an instance of struct");
}
} | java | protected void addSchemaPropertiesHelper(Path path, HiveRegistrationUnit hiveUnit) throws IOException {
TypeInfo schema = getSchemaFromLatestFile(path, this.fs);
if (schema instanceof StructTypeInfo) {
StructTypeInfo structTypeInfo = (StructTypeInfo) schema;
hiveUnit.setSerDeProp(SCHEMA_LITERAL, schema);
hiveUnit.setSerDeProp(serdeConstants.LIST_COLUMNS,
Joiner.on(",").join(structTypeInfo.getAllStructFieldNames()));
hiveUnit.setSerDeProp(serdeConstants.LIST_COLUMN_TYPES,
Joiner.on(",").join(
structTypeInfo.getAllStructFieldTypeInfos().stream().map(x -> x.getTypeName())
.collect(Collectors.toList())));
} else {
// Hive always uses a struct with a field for each of the top-level columns as the root object type.
// So for here we assume to-be-registered ORC files follow this pattern.
throw new IllegalStateException("A valid ORC schema should be an instance of struct");
}
} | [
"protected",
"void",
"addSchemaPropertiesHelper",
"(",
"Path",
"path",
",",
"HiveRegistrationUnit",
"hiveUnit",
")",
"throws",
"IOException",
"{",
"TypeInfo",
"schema",
"=",
"getSchemaFromLatestFile",
"(",
"path",
",",
"this",
".",
"fs",
")",
";",
"if",
"(",
"sc... | Extensible if there's other source-of-truth for fetching schema instead of interacting with HDFS.
For purpose of initializing {@link org.apache.hadoop.hive.ql.io.orc.OrcSerde} object, it will require:
org.apache.hadoop.hive.serde.serdeConstants#LIST_COLUMNS and
org.apache.hadoop.hive.serde.serdeConstants#LIST_COLUMN_TYPES
Keeping {@link #SCHEMA_LITERAL} will be a nice-to-have thing but not actually necessary in terms of functionality. | [
"Extensible",
"if",
"there",
"s",
"other",
"source",
"-",
"of",
"-",
"truth",
"for",
"fetching",
"schema",
"instead",
"of",
"interacting",
"with",
"HDFS",
"."
] | train | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-hive-registration/src/main/java/org/apache/gobblin/hive/orc/HiveOrcSerDeManager.java#L257-L274 |
deeplearning4j/deeplearning4j | nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/evaluation/classification/EvaluationCalibration.java | EvaluationCalibration.getResidualPlotAllClasses | public Histogram getResidualPlotAllClasses() {
String title = "Residual Plot - All Predictions and Classes";
int[] counts = residualPlotOverall.data().asInt();
return new Histogram(title, 0.0, 1.0, counts);
} | java | public Histogram getResidualPlotAllClasses() {
String title = "Residual Plot - All Predictions and Classes";
int[] counts = residualPlotOverall.data().asInt();
return new Histogram(title, 0.0, 1.0, counts);
} | [
"public",
"Histogram",
"getResidualPlotAllClasses",
"(",
")",
"{",
"String",
"title",
"=",
"\"Residual Plot - All Predictions and Classes\"",
";",
"int",
"[",
"]",
"counts",
"=",
"residualPlotOverall",
".",
"data",
"(",
")",
".",
"asInt",
"(",
")",
";",
"return",
... | Get the residual plot for all classes combined. The residual plot is defined as a histogram of<br>
|label_i - prob(class_i | input)| for all classes i and examples.<br>
In general, small residuals indicate a superior classifier to large residuals.
@return Residual plot (histogram) - all predictions/classes | [
"Get",
"the",
"residual",
"plot",
"for",
"all",
"classes",
"combined",
".",
"The",
"residual",
"plot",
"is",
"defined",
"as",
"a",
"histogram",
"of<br",
">",
"|label_i",
"-",
"prob",
"(",
"class_i",
"|",
"input",
")",
"|",
"for",
"all",
"classes",
"i",
... | train | https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/evaluation/classification/EvaluationCalibration.java#L428-L432 |
apiman/apiman | manager/api/es/src/main/java/io/apiman/manager/api/es/EsMarshalling.java | EsMarshalling.unmarshallPolicyDefinition | public static PolicyDefinitionBean unmarshallPolicyDefinition(Map<String, Object> source) {
if (source == null) {
return null;
}
PolicyDefinitionBean bean = new PolicyDefinitionBean();
bean.setId(asString(source.get("id")));
bean.setName(asString(source.get("name")));
bean.setDescription(asString(source.get("description")));
bean.setForm(asString(source.get("form")));
bean.setFormType(asEnum(source.get("formType"), PolicyFormType.class));
bean.setIcon(asString(source.get("icon")));
bean.setPluginId(asLong(source.get("pluginId")));
bean.setPolicyImpl(asString(source.get("policyImpl")));
bean.setDeleted(asBoolean(source.get("deleted")));
@SuppressWarnings("unchecked")
List<Map<String, Object>> templates = (List<Map<String, Object>>) source.get("templates");
if (templates != null && !templates.isEmpty()) {
bean.setTemplates(new HashSet<>());
for (Map<String, Object> templateMap : templates) {
PolicyDefinitionTemplateBean template = new PolicyDefinitionTemplateBean();
template.setLanguage(asString(templateMap.get("language")));
template.setTemplate(asString(templateMap.get("template")));
bean.getTemplates().add(template);
}
}
postMarshall(bean);
return bean;
} | java | public static PolicyDefinitionBean unmarshallPolicyDefinition(Map<String, Object> source) {
if (source == null) {
return null;
}
PolicyDefinitionBean bean = new PolicyDefinitionBean();
bean.setId(asString(source.get("id")));
bean.setName(asString(source.get("name")));
bean.setDescription(asString(source.get("description")));
bean.setForm(asString(source.get("form")));
bean.setFormType(asEnum(source.get("formType"), PolicyFormType.class));
bean.setIcon(asString(source.get("icon")));
bean.setPluginId(asLong(source.get("pluginId")));
bean.setPolicyImpl(asString(source.get("policyImpl")));
bean.setDeleted(asBoolean(source.get("deleted")));
@SuppressWarnings("unchecked")
List<Map<String, Object>> templates = (List<Map<String, Object>>) source.get("templates");
if (templates != null && !templates.isEmpty()) {
bean.setTemplates(new HashSet<>());
for (Map<String, Object> templateMap : templates) {
PolicyDefinitionTemplateBean template = new PolicyDefinitionTemplateBean();
template.setLanguage(asString(templateMap.get("language")));
template.setTemplate(asString(templateMap.get("template")));
bean.getTemplates().add(template);
}
}
postMarshall(bean);
return bean;
} | [
"public",
"static",
"PolicyDefinitionBean",
"unmarshallPolicyDefinition",
"(",
"Map",
"<",
"String",
",",
"Object",
">",
"source",
")",
"{",
"if",
"(",
"source",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"PolicyDefinitionBean",
"bean",
"=",
"new",
... | Unmarshals the given map source into a bean.
@param source the source
@return the policy definition | [
"Unmarshals",
"the",
"given",
"map",
"source",
"into",
"a",
"bean",
"."
] | train | https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/manager/api/es/src/main/java/io/apiman/manager/api/es/EsMarshalling.java#L1249-L1276 |
grails/grails-core | grails-web/src/main/groovy/org/grails/web/servlet/context/GrailsConfigUtils.java | GrailsConfigUtils.isConfigTrue | public static boolean isConfigTrue(GrailsApplication application, String propertyName) {
return application.getConfig().getProperty(propertyName, Boolean.class, false);
} | java | public static boolean isConfigTrue(GrailsApplication application, String propertyName) {
return application.getConfig().getProperty(propertyName, Boolean.class, false);
} | [
"public",
"static",
"boolean",
"isConfigTrue",
"(",
"GrailsApplication",
"application",
",",
"String",
"propertyName",
")",
"{",
"return",
"application",
".",
"getConfig",
"(",
")",
".",
"getProperty",
"(",
"propertyName",
",",
"Boolean",
".",
"class",
",",
"fal... | Checks if a Config parameter is true or a System property with the same name is true
@param application
@param propertyName
@return true if the Config parameter is true or the System property with the same name is true | [
"Checks",
"if",
"a",
"Config",
"parameter",
"is",
"true",
"or",
"a",
"System",
"property",
"with",
"the",
"same",
"name",
"is",
"true"
] | train | https://github.com/grails/grails-core/blob/c0b08aa995b0297143b75d05642abba8cb7b4122/grails-web/src/main/groovy/org/grails/web/servlet/context/GrailsConfigUtils.java#L117-L119 |
TheHortonMachine/hortonmachine | gears/src/main/java/org/hortonmachine/gears/io/las/utils/LasUtils.java | LasUtils.tofeature | public static SimpleFeature tofeature( LasRecord r, Integer featureId, CoordinateReferenceSystem crs ) {
final Point point = toGeometry(r);
double elev = r.z;
if (!Double.isNaN(r.groundElevation)) {
elev = r.groundElevation;
}
if (featureId == null) {
featureId = -1;
}
final Object[] values = new Object[]{point, featureId, elev, r.intensity, r.classification, r.returnNumber,
r.numberOfReturns};
SimpleFeatureBuilder lasFeatureBuilder = getLasFeatureBuilder(crs);
lasFeatureBuilder.addAll(values);
final SimpleFeature feature = lasFeatureBuilder.buildFeature(null);
return feature;
} | java | public static SimpleFeature tofeature( LasRecord r, Integer featureId, CoordinateReferenceSystem crs ) {
final Point point = toGeometry(r);
double elev = r.z;
if (!Double.isNaN(r.groundElevation)) {
elev = r.groundElevation;
}
if (featureId == null) {
featureId = -1;
}
final Object[] values = new Object[]{point, featureId, elev, r.intensity, r.classification, r.returnNumber,
r.numberOfReturns};
SimpleFeatureBuilder lasFeatureBuilder = getLasFeatureBuilder(crs);
lasFeatureBuilder.addAll(values);
final SimpleFeature feature = lasFeatureBuilder.buildFeature(null);
return feature;
} | [
"public",
"static",
"SimpleFeature",
"tofeature",
"(",
"LasRecord",
"r",
",",
"Integer",
"featureId",
",",
"CoordinateReferenceSystem",
"crs",
")",
"{",
"final",
"Point",
"point",
"=",
"toGeometry",
"(",
"r",
")",
";",
"double",
"elev",
"=",
"r",
".",
"z",
... | Convert a record to a feature.
@param r the record to convert.
@param featureId an optional feature id, if not available, the id is set to -1.
@param crs the crs to apply.
@return the feature. | [
"Convert",
"a",
"record",
"to",
"a",
"feature",
"."
] | train | https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/org/hortonmachine/gears/io/las/utils/LasUtils.java#L161-L176 |
couchbase/couchbase-java-client | src/main/java/com/couchbase/client/java/util/Blocking.java | Blocking.blockForSingle | public static <T> T blockForSingle(final Observable<? extends T> observable, final long timeout,
final TimeUnit tu) {
final CountDownLatch latch = new CountDownLatch(1);
TrackingSubscriber<T> subscriber = new TrackingSubscriber<T>(latch);
Subscription subscription = observable.subscribe(subscriber);
try {
if (!latch.await(timeout, tu)) {
if (!subscription.isUnsubscribed()) {
subscription.unsubscribe();
}
throw new RuntimeException(new TimeoutException());
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException("Interrupted while waiting for subscription to complete.", e);
}
if (subscriber.returnException() != null) {
if (subscriber.returnException() instanceof RuntimeException) {
throw (RuntimeException) subscriber.returnException();
} else {
throw new RuntimeException(subscriber.returnException());
}
}
return subscriber.returnItem();
} | java | public static <T> T blockForSingle(final Observable<? extends T> observable, final long timeout,
final TimeUnit tu) {
final CountDownLatch latch = new CountDownLatch(1);
TrackingSubscriber<T> subscriber = new TrackingSubscriber<T>(latch);
Subscription subscription = observable.subscribe(subscriber);
try {
if (!latch.await(timeout, tu)) {
if (!subscription.isUnsubscribed()) {
subscription.unsubscribe();
}
throw new RuntimeException(new TimeoutException());
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException("Interrupted while waiting for subscription to complete.", e);
}
if (subscriber.returnException() != null) {
if (subscriber.returnException() instanceof RuntimeException) {
throw (RuntimeException) subscriber.returnException();
} else {
throw new RuntimeException(subscriber.returnException());
}
}
return subscriber.returnItem();
} | [
"public",
"static",
"<",
"T",
">",
"T",
"blockForSingle",
"(",
"final",
"Observable",
"<",
"?",
"extends",
"T",
">",
"observable",
",",
"final",
"long",
"timeout",
",",
"final",
"TimeUnit",
"tu",
")",
"{",
"final",
"CountDownLatch",
"latch",
"=",
"new",
... | Blocks on an {@link Observable} and returns a single event or throws an {@link Exception}.
Note that when this method is used, only the first item emitted will be returned. The caller needs to make
sure that the source {@link Observable} only ever returns a single item (or none). The {@link BlockingObservable}
code applies different operators like single, last, first and more, these need to be applied manually.
This code is based on {@link BlockingObservable#blockForSingle}, but does not wait forever. Instead, it
utilizes the internal {@link CountDownLatch} to optimize the timeout case, with less GC and CPU overhead
than chaining in an {@link Observable#timeout(long, TimeUnit)} operator.
If an error happens inside the {@link Observable}, it will be raised as an {@link Exception}. If the timeout
kicks in, a {@link TimeoutException} nested in a {@link RuntimeException} is thrown to be fully compatible
with the {@link Observable#timeout(long, TimeUnit)} behavior.
@param observable the source {@link Observable}
@param timeout the maximum timeout before an exception is thrown.
@param tu the timeout unit.
@param <T> the type returned.
@return the extracted value from the {@link Observable} or throws in an error case. | [
"Blocks",
"on",
"an",
"{",
"@link",
"Observable",
"}",
"and",
"returns",
"a",
"single",
"event",
"or",
"throws",
"an",
"{",
"@link",
"Exception",
"}",
"."
] | train | https://github.com/couchbase/couchbase-java-client/blob/f36a0ee0c66923bdde47838ca543e50cbaa99e14/src/main/java/com/couchbase/client/java/util/Blocking.java#L65-L93 |
adessoAG/wicked-charts | showcase/wicked-charts-showcase-wicket7/src/main/java/de/adesso/wickedcharts/showcase/HomepageHighcharts.java | HomepageHighcharts.addThemeLinks | private void addThemeLinks(PageParameters parameters){
List<INamedParameters.NamedPair> pairs = parameters.getAllNamed();
if (parameters.getAllNamed().size() < 2) {
add(new UpdateThemeLink("defaultTheme", "chart"));
add(new UpdateThemeLink("grid", "chart"));
add(new UpdateThemeLink("skies", "chart"));
add(new UpdateThemeLink("gray", "chart"));
add(new UpdateThemeLink("darkblue", "chart"));
} else {
String chartString = parameters.getAllNamed().get(1).getValue();
add(new UpdateThemeLink("defaultTheme", chartString));
add(new UpdateThemeLink("grid", chartString));
add(new UpdateThemeLink("skies", chartString));
add(new UpdateThemeLink("gray", chartString));
add(new UpdateThemeLink("darkblue", chartString));
}
} | java | private void addThemeLinks(PageParameters parameters){
List<INamedParameters.NamedPair> pairs = parameters.getAllNamed();
if (parameters.getAllNamed().size() < 2) {
add(new UpdateThemeLink("defaultTheme", "chart"));
add(new UpdateThemeLink("grid", "chart"));
add(new UpdateThemeLink("skies", "chart"));
add(new UpdateThemeLink("gray", "chart"));
add(new UpdateThemeLink("darkblue", "chart"));
} else {
String chartString = parameters.getAllNamed().get(1).getValue();
add(new UpdateThemeLink("defaultTheme", chartString));
add(new UpdateThemeLink("grid", chartString));
add(new UpdateThemeLink("skies", chartString));
add(new UpdateThemeLink("gray", chartString));
add(new UpdateThemeLink("darkblue", chartString));
}
} | [
"private",
"void",
"addThemeLinks",
"(",
"PageParameters",
"parameters",
")",
"{",
"List",
"<",
"INamedParameters",
".",
"NamedPair",
">",
"pairs",
"=",
"parameters",
".",
"getAllNamed",
"(",
")",
";",
"if",
"(",
"parameters",
".",
"getAllNamed",
"(",
")",
"... | Adds links to the different themes
@param parameters the page parameters from the page URI | [
"Adds",
"links",
"to",
"the",
"different",
"themes"
] | train | https://github.com/adessoAG/wicked-charts/blob/498aceff025f612e22ba5135b26531afeabac03c/showcase/wicked-charts-showcase-wicket7/src/main/java/de/adesso/wickedcharts/showcase/HomepageHighcharts.java#L63-L79 |
stapler/stapler | core/src/main/java/org/kohsuke/stapler/CrumbIssuer.java | CrumbIssuer.validateCrumb | public void validateCrumb(StaplerRequest request, String submittedCrumb) {
if (!issueCrumb(request).equals(submittedCrumb)) {
throw new SecurityException("Request failed to pass the crumb test (try clearing your cookies)");
}
} | java | public void validateCrumb(StaplerRequest request, String submittedCrumb) {
if (!issueCrumb(request).equals(submittedCrumb)) {
throw new SecurityException("Request failed to pass the crumb test (try clearing your cookies)");
}
} | [
"public",
"void",
"validateCrumb",
"(",
"StaplerRequest",
"request",
",",
"String",
"submittedCrumb",
")",
"{",
"if",
"(",
"!",
"issueCrumb",
"(",
"request",
")",
".",
"equals",
"(",
"submittedCrumb",
")",
")",
"{",
"throw",
"new",
"SecurityException",
"(",
... | Validates a crumb that was submitted along with the request.
@param request
The request that submitted the crumb
@param submittedCrumb
The submitted crumb value to be validated.
@throws SecurityException
If the crumb doesn't match and the request processing should abort. | [
"Validates",
"a",
"crumb",
"that",
"was",
"submitted",
"along",
"with",
"the",
"request",
"."
] | train | https://github.com/stapler/stapler/blob/11ad5af185e062fb46e01bf9fbed66f3ebf2a8f7/core/src/main/java/org/kohsuke/stapler/CrumbIssuer.java#L44-L48 |
b3dgs/lionengine | lionengine-network/src/main/java/com/b3dgs/lionengine/network/message/NetworkMessageEntity.java | NetworkMessageEntity.addAction | public void addAction(M element, double value)
{
actions.put(element, Double.valueOf(value));
} | java | public void addAction(M element, double value)
{
actions.put(element, Double.valueOf(value));
} | [
"public",
"void",
"addAction",
"(",
"M",
"element",
",",
"double",
"value",
")",
"{",
"actions",
".",
"put",
"(",
"element",
",",
"Double",
".",
"valueOf",
"(",
"value",
")",
")",
";",
"}"
] | Add an action.
@param element The action type.
@param value The action value. | [
"Add",
"an",
"action",
"."
] | train | https://github.com/b3dgs/lionengine/blob/cac3d5578532cf11724a737b9f09e71bf9995ab2/lionengine-network/src/main/java/com/b3dgs/lionengine/network/message/NetworkMessageEntity.java#L166-L169 |
westnordost/osmapi | src/main/java/de/westnordost/osmapi/map/MapDataDao.java | MapDataDao.openChangeset | public long openChangeset(Map<String, String> tags)
{
return osm.makeAuthenticatedRequest("changeset/create", "PUT",
createOsmChangesetTagsWriter(tags), new IdResponseReader());
} | java | public long openChangeset(Map<String, String> tags)
{
return osm.makeAuthenticatedRequest("changeset/create", "PUT",
createOsmChangesetTagsWriter(tags), new IdResponseReader());
} | [
"public",
"long",
"openChangeset",
"(",
"Map",
"<",
"String",
",",
"String",
">",
"tags",
")",
"{",
"return",
"osm",
".",
"makeAuthenticatedRequest",
"(",
"\"changeset/create\"",
",",
"\"PUT\"",
",",
"createOsmChangesetTagsWriter",
"(",
"tags",
")",
",",
"new",
... | Open a new changeset with the given tags
@param tags tags of this changeset. Usually it is comment and source.
@throws OsmAuthorizationException if the application does not have permission to edit the
map (Permission.MODIFY_MAP) | [
"Open",
"a",
"new",
"changeset",
"with",
"the",
"given",
"tags",
"@param",
"tags",
"tags",
"of",
"this",
"changeset",
".",
"Usually",
"it",
"is",
"comment",
"and",
"source",
"."
] | train | https://github.com/westnordost/osmapi/blob/dda6978fd12e117d0cf17812bc22037f61e22c4b/src/main/java/de/westnordost/osmapi/map/MapDataDao.java#L132-L136 |
RestComm/jss7 | map/map-impl/src/main/java/org/restcomm/protocols/ss7/map/MAPServiceBaseImpl.java | MAPServiceBaseImpl.createNewTCAPDialog | protected Dialog createNewTCAPDialog(SccpAddress origAddress, SccpAddress destAddress, Long localTrId) throws MAPException {
try {
return this.mapProviderImpl.getTCAPProvider().getNewDialog(origAddress, destAddress, localTrId);
} catch (TCAPException e) {
throw new MAPException(e.getMessage(), e);
}
} | java | protected Dialog createNewTCAPDialog(SccpAddress origAddress, SccpAddress destAddress, Long localTrId) throws MAPException {
try {
return this.mapProviderImpl.getTCAPProvider().getNewDialog(origAddress, destAddress, localTrId);
} catch (TCAPException e) {
throw new MAPException(e.getMessage(), e);
}
} | [
"protected",
"Dialog",
"createNewTCAPDialog",
"(",
"SccpAddress",
"origAddress",
",",
"SccpAddress",
"destAddress",
",",
"Long",
"localTrId",
")",
"throws",
"MAPException",
"{",
"try",
"{",
"return",
"this",
".",
"mapProviderImpl",
".",
"getTCAPProvider",
"(",
")",
... | Creating new outgoing TCAP Dialog. Used when creating a new outgoing MAP Dialog
@param origAddress
@param destAddress
@return
@throws MAPException | [
"Creating",
"new",
"outgoing",
"TCAP",
"Dialog",
".",
"Used",
"when",
"creating",
"a",
"new",
"outgoing",
"MAP",
"Dialog"
] | train | https://github.com/RestComm/jss7/blob/402b4b3984e581c581e309cb5f6a858fde6dbc33/map/map-impl/src/main/java/org/restcomm/protocols/ss7/map/MAPServiceBaseImpl.java#L82-L88 |
facebook/fresco | imagepipeline-base/src/main/java/com/facebook/imagepipeline/bitmaps/PlatformBitmapFactory.java | PlatformBitmapFactory.createBitmap | public CloseableReference<Bitmap> createBitmap(int width, int height) {
return createBitmap(width, height, Bitmap.Config.ARGB_8888);
} | java | public CloseableReference<Bitmap> createBitmap(int width, int height) {
return createBitmap(width, height, Bitmap.Config.ARGB_8888);
} | [
"public",
"CloseableReference",
"<",
"Bitmap",
">",
"createBitmap",
"(",
"int",
"width",
",",
"int",
"height",
")",
"{",
"return",
"createBitmap",
"(",
"width",
",",
"height",
",",
"Bitmap",
".",
"Config",
".",
"ARGB_8888",
")",
";",
"}"
] | Creates a bitmap of the specified width and height.
The bitmap will be created with the default ARGB_8888 configuration
@param width the width of the bitmap
@param height the height of the bitmap
@return a reference to the bitmap
@throws TooManyBitmapsException if the pool is full
@throws java.lang.OutOfMemoryError if the Bitmap cannot be allocated | [
"Creates",
"a",
"bitmap",
"of",
"the",
"specified",
"width",
"and",
"height",
".",
"The",
"bitmap",
"will",
"be",
"created",
"with",
"the",
"default",
"ARGB_8888",
"configuration"
] | train | https://github.com/facebook/fresco/blob/0b85879d51c5036d5e46e627a6651afefc0b971a/imagepipeline-base/src/main/java/com/facebook/imagepipeline/bitmaps/PlatformBitmapFactory.java#L54-L56 |
camunda/camunda-bpm-platform | engine-cdi/src/main/java/org/camunda/bpm/engine/cdi/jsf/TaskForm.java | TaskForm.startProcessInstanceByKeyForm | @Deprecated
public void startProcessInstanceByKeyForm(String processDefinitionKey, String callbackUrl) {
this.url = callbackUrl;
this.processDefinitionKey = processDefinitionKey;
beginConversation();
} | java | @Deprecated
public void startProcessInstanceByKeyForm(String processDefinitionKey, String callbackUrl) {
this.url = callbackUrl;
this.processDefinitionKey = processDefinitionKey;
beginConversation();
} | [
"@",
"Deprecated",
"public",
"void",
"startProcessInstanceByKeyForm",
"(",
"String",
"processDefinitionKey",
",",
"String",
"callbackUrl",
")",
"{",
"this",
".",
"url",
"=",
"callbackUrl",
";",
"this",
".",
"processDefinitionKey",
"=",
"processDefinitionKey",
";",
"... | @deprecated use {@link startProcessInstanceByKeyForm()} instead
@param processDefinitionKey
@param callbackUrl | [
"@deprecated",
"use",
"{",
"@link",
"startProcessInstanceByKeyForm",
"()",
"}",
"instead"
] | train | https://github.com/camunda/camunda-bpm-platform/blob/1a464fc887ef3760e53d6f91b9e5b871a0d77cc0/engine-cdi/src/main/java/org/camunda/bpm/engine/cdi/jsf/TaskForm.java#L161-L166 |
jfinal/jfinal | src/main/java/com/jfinal/plugin/activerecord/Db.java | Db.queryColumn | public static <T> T queryColumn(String sql, Object... paras) {
return MAIN.queryColumn(sql, paras);
} | java | public static <T> T queryColumn(String sql, Object... paras) {
return MAIN.queryColumn(sql, paras);
} | [
"public",
"static",
"<",
"T",
">",
"T",
"queryColumn",
"(",
"String",
"sql",
",",
"Object",
"...",
"paras",
")",
"{",
"return",
"MAIN",
".",
"queryColumn",
"(",
"sql",
",",
"paras",
")",
";",
"}"
] | Execute sql query just return one column.
@param <T> the type of the column that in your sql's select statement
@param sql an SQL statement that may contain one or more '?' IN parameter placeholders
@param paras the parameters of sql
@return <T> T | [
"Execute",
"sql",
"query",
"just",
"return",
"one",
"column",
"."
] | train | https://github.com/jfinal/jfinal/blob/fc07f0f5d56e85ccd3cfcdd587b56b8dd9c663e9/src/main/java/com/jfinal/plugin/activerecord/Db.java#L115-L117 |
btc-ag/redg | redg-generator/src/main/java/com/btc/redg/generator/CodeGenerator.java | CodeGenerator.generateMainClass | public String generateMainClass(final Collection<TableModel> tables, final boolean enableVisualizationSupport) {
Objects.requireNonNull(tables);
//get package from the table models
final String targetPackage = ((TableModel) tables.toArray()[0]).getPackageName();
final ST template = this.stGroup.getInstanceOf("mainClass");
LOG.debug("Filling main class template containing helpers for {} classes...", tables.size());
template.add("package", targetPackage);
// TODO: make prefix usable
template.add("prefix", "");
template.add("enableVisualizationSupport", enableVisualizationSupport);
LOG.debug("Package is {} | Prefix is {}", targetPackage, "");
template.add("tables", tables);
return template.render();
} | java | public String generateMainClass(final Collection<TableModel> tables, final boolean enableVisualizationSupport) {
Objects.requireNonNull(tables);
//get package from the table models
final String targetPackage = ((TableModel) tables.toArray()[0]).getPackageName();
final ST template = this.stGroup.getInstanceOf("mainClass");
LOG.debug("Filling main class template containing helpers for {} classes...", tables.size());
template.add("package", targetPackage);
// TODO: make prefix usable
template.add("prefix", "");
template.add("enableVisualizationSupport", enableVisualizationSupport);
LOG.debug("Package is {} | Prefix is {}", targetPackage, "");
template.add("tables", tables);
return template.render();
} | [
"public",
"String",
"generateMainClass",
"(",
"final",
"Collection",
"<",
"TableModel",
">",
"tables",
",",
"final",
"boolean",
"enableVisualizationSupport",
")",
"{",
"Objects",
".",
"requireNonNull",
"(",
"tables",
")",
";",
"//get package from the table models\r",
... | Generates the main class used for creating the extractor objects and later generating the insert statements.
For each passed table a appropriate creation method will be generated that will return the new object and internally add it to the list of objects that
will be used to generate the insert strings
@param tables All tables that should get a creation method in the main class
@param enableVisualizationSupport If {@code true}, the RedG visualization features will be enabled for the generated code. This will result in a small
performance hit and slightly more memory usage if activated.
@return The generated source code | [
"Generates",
"the",
"main",
"class",
"used",
"for",
"creating",
"the",
"extractor",
"objects",
"and",
"later",
"generating",
"the",
"insert",
"statements",
".",
"For",
"each",
"passed",
"table",
"a",
"appropriate",
"creation",
"method",
"will",
"be",
"generated"... | train | https://github.com/btc-ag/redg/blob/416a68639d002512cabfebff09afd2e1909e27df/redg-generator/src/main/java/com/btc/redg/generator/CodeGenerator.java#L223-L239 |
OpenLiberty/open-liberty | dev/com.ibm.ws.webserver.plugin.utility/src/com/ibm/ws/webserver/plugin/utility/WebServerPluginUtility.java | WebServerPluginUtility.looksLikeHelp | private static boolean looksLikeHelp(HelpTask help, String taskname) {
if (taskname == null)
return false; // applied paranoia, since this isn't in a performance path
int start = 0, len = taskname.length();
while (start < len && !Character.isLetter(taskname.charAt(start)))
++start;
return help.getTaskName().equalsIgnoreCase(taskname.substring(start).toLowerCase());
} | java | private static boolean looksLikeHelp(HelpTask help, String taskname) {
if (taskname == null)
return false; // applied paranoia, since this isn't in a performance path
int start = 0, len = taskname.length();
while (start < len && !Character.isLetter(taskname.charAt(start)))
++start;
return help.getTaskName().equalsIgnoreCase(taskname.substring(start).toLowerCase());
} | [
"private",
"static",
"boolean",
"looksLikeHelp",
"(",
"HelpTask",
"help",
",",
"String",
"taskname",
")",
"{",
"if",
"(",
"taskname",
"==",
"null",
")",
"return",
"false",
";",
"// applied paranoia, since this isn't in a performance path",
"int",
"start",
"=",
"0",
... | note that the string is already trim()'d by command-line parsing unless user explicitly escaped a space | [
"note",
"that",
"the",
"string",
"is",
"already",
"trim",
"()",
"d",
"by",
"command",
"-",
"line",
"parsing",
"unless",
"user",
"explicitly",
"escaped",
"a",
"space"
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.webserver.plugin.utility/src/com/ibm/ws/webserver/plugin/utility/WebServerPluginUtility.java#L114-L121 |
wmdietl/jsr308-langtools | src/share/classes/com/sun/tools/javac/jvm/ClassReader.java | ClassReader.enterClass | public ClassSymbol enterClass(Name name, TypeSymbol owner) {
Name flatname = TypeSymbol.formFlatName(name, owner);
ClassSymbol c = classes.get(flatname);
if (c == null) {
c = defineClass(name, owner);
classes.put(flatname, c);
} else if ((c.name != name || c.owner != owner) && owner.kind == TYP && c.owner.kind == PCK) {
// reassign fields of classes that might have been loaded with
// their flat names.
c.owner.members().remove(c);
c.name = name;
c.owner = owner;
c.fullname = ClassSymbol.formFullName(name, owner);
}
return c;
} | java | public ClassSymbol enterClass(Name name, TypeSymbol owner) {
Name flatname = TypeSymbol.formFlatName(name, owner);
ClassSymbol c = classes.get(flatname);
if (c == null) {
c = defineClass(name, owner);
classes.put(flatname, c);
} else if ((c.name != name || c.owner != owner) && owner.kind == TYP && c.owner.kind == PCK) {
// reassign fields of classes that might have been loaded with
// their flat names.
c.owner.members().remove(c);
c.name = name;
c.owner = owner;
c.fullname = ClassSymbol.formFullName(name, owner);
}
return c;
} | [
"public",
"ClassSymbol",
"enterClass",
"(",
"Name",
"name",
",",
"TypeSymbol",
"owner",
")",
"{",
"Name",
"flatname",
"=",
"TypeSymbol",
".",
"formFlatName",
"(",
"name",
",",
"owner",
")",
";",
"ClassSymbol",
"c",
"=",
"classes",
".",
"get",
"(",
"flatnam... | Create a new toplevel or member class symbol with given name
and owner and enter in `classes' unless already there. | [
"Create",
"a",
"new",
"toplevel",
"or",
"member",
"class",
"symbol",
"with",
"given",
"name",
"and",
"owner",
"and",
"enter",
"in",
"classes",
"unless",
"already",
"there",
"."
] | train | https://github.com/wmdietl/jsr308-langtools/blob/8812d28c20f4de070a0dd6de1b45602431379834/src/share/classes/com/sun/tools/javac/jvm/ClassReader.java#L2381-L2396 |
lievendoclo/Valkyrie-RCP | valkyrie-rcp-core/src/main/java/org/valkyriercp/command/support/DefaultCommandManager.java | DefaultCommandManager.createCommandGroup | @Override
public CommandGroup createCommandGroup(String groupId, List<? extends AbstractCommand> members) {
return createCommandGroup(groupId, members.toArray(), false, null);
} | java | @Override
public CommandGroup createCommandGroup(String groupId, List<? extends AbstractCommand> members) {
return createCommandGroup(groupId, members.toArray(), false, null);
} | [
"@",
"Override",
"public",
"CommandGroup",
"createCommandGroup",
"(",
"String",
"groupId",
",",
"List",
"<",
"?",
"extends",
"AbstractCommand",
">",
"members",
")",
"{",
"return",
"createCommandGroup",
"(",
"groupId",
",",
"members",
".",
"toArray",
"(",
")",
... | Create a command group which holds all the given members.
@param groupId the id to configure the group.
@param members members to add to the group.
@return a {@link CommandGroup} which contains all the members. | [
"Create",
"a",
"command",
"group",
"which",
"holds",
"all",
"the",
"given",
"members",
"."
] | train | https://github.com/lievendoclo/Valkyrie-RCP/blob/6aad6e640b348cda8f3b0841f6e42025233f1eb8/valkyrie-rcp-core/src/main/java/org/valkyriercp/command/support/DefaultCommandManager.java#L304-L307 |
crnk-project/crnk-framework | crnk-core/src/main/java/io/crnk/core/engine/information/resource/ResourceInformation.java | ResourceInformation.absentAnySetter | private static boolean absentAnySetter(Method jsonAnyGetter, Method jsonAnySetter) {
return (jsonAnySetter == null && jsonAnyGetter != null) ||
(jsonAnySetter != null && jsonAnyGetter == null);
} | java | private static boolean absentAnySetter(Method jsonAnyGetter, Method jsonAnySetter) {
return (jsonAnySetter == null && jsonAnyGetter != null) ||
(jsonAnySetter != null && jsonAnyGetter == null);
} | [
"private",
"static",
"boolean",
"absentAnySetter",
"(",
"Method",
"jsonAnyGetter",
",",
"Method",
"jsonAnySetter",
")",
"{",
"return",
"(",
"jsonAnySetter",
"==",
"null",
"&&",
"jsonAnyGetter",
"!=",
"null",
")",
"||",
"(",
"jsonAnySetter",
"!=",
"null",
"&&",
... | The resource has to have both method annotated with {@link JsonAnySetter} and {@link JsonAnyGetter} to allow
proper handling.
@return <i>true</i> if resource definition is incomplete, <i>false</i> otherwise | [
"The",
"resource",
"has",
"to",
"have",
"both",
"method",
"annotated",
"with",
"{",
"@link",
"JsonAnySetter",
"}",
"and",
"{",
"@link",
"JsonAnyGetter",
"}",
"to",
"allow",
"proper",
"handling",
"."
] | train | https://github.com/crnk-project/crnk-framework/blob/2fd3ef9a991788d46fd2e83b43c8ea37cbaf8681/crnk-core/src/main/java/io/crnk/core/engine/information/resource/ResourceInformation.java#L416-L419 |
weld/core | impl/src/main/java/org/jboss/weld/bean/proxy/InterceptedSubclassFactory.java | InterceptedSubclassFactory.addSpecialMethods | protected void addSpecialMethods(ClassFile proxyClassType, ClassMethod staticConstructor) {
try {
// Add special methods for interceptors
for (Method method : LifecycleMixin.class.getMethods()) {
BeanLogger.LOG.addingMethodToProxy(method);
MethodInformation methodInfo = new RuntimeMethodInformation(method);
createInterceptorBody(proxyClassType.addMethod(method), methodInfo, false, staticConstructor);
}
Method getInstanceMethod = TargetInstanceProxy.class.getMethod("weld_getTargetInstance");
Method getInstanceClassMethod = TargetInstanceProxy.class.getMethod("weld_getTargetClass");
generateGetTargetInstanceBody(proxyClassType.addMethod(getInstanceMethod));
generateGetTargetClassBody(proxyClassType.addMethod(getInstanceClassMethod));
Method setMethodHandlerMethod = ProxyObject.class.getMethod("weld_setHandler", MethodHandler.class);
generateSetMethodHandlerBody(proxyClassType.addMethod(setMethodHandlerMethod));
Method getMethodHandlerMethod = ProxyObject.class.getMethod("weld_getHandler");
generateGetMethodHandlerBody(proxyClassType.addMethod(getMethodHandlerMethod));
} catch (Exception e) {
throw new WeldException(e);
}
} | java | protected void addSpecialMethods(ClassFile proxyClassType, ClassMethod staticConstructor) {
try {
// Add special methods for interceptors
for (Method method : LifecycleMixin.class.getMethods()) {
BeanLogger.LOG.addingMethodToProxy(method);
MethodInformation methodInfo = new RuntimeMethodInformation(method);
createInterceptorBody(proxyClassType.addMethod(method), methodInfo, false, staticConstructor);
}
Method getInstanceMethod = TargetInstanceProxy.class.getMethod("weld_getTargetInstance");
Method getInstanceClassMethod = TargetInstanceProxy.class.getMethod("weld_getTargetClass");
generateGetTargetInstanceBody(proxyClassType.addMethod(getInstanceMethod));
generateGetTargetClassBody(proxyClassType.addMethod(getInstanceClassMethod));
Method setMethodHandlerMethod = ProxyObject.class.getMethod("weld_setHandler", MethodHandler.class);
generateSetMethodHandlerBody(proxyClassType.addMethod(setMethodHandlerMethod));
Method getMethodHandlerMethod = ProxyObject.class.getMethod("weld_getHandler");
generateGetMethodHandlerBody(proxyClassType.addMethod(getMethodHandlerMethod));
} catch (Exception e) {
throw new WeldException(e);
}
} | [
"protected",
"void",
"addSpecialMethods",
"(",
"ClassFile",
"proxyClassType",
",",
"ClassMethod",
"staticConstructor",
")",
"{",
"try",
"{",
"// Add special methods for interceptors",
"for",
"(",
"Method",
"method",
":",
"LifecycleMixin",
".",
"class",
".",
"getMethods"... | Adds methods requiring special implementations rather than just
delegation.
@param proxyClassType the Javassist class description for the proxy type | [
"Adds",
"methods",
"requiring",
"special",
"implementations",
"rather",
"than",
"just",
"delegation",
"."
] | train | https://github.com/weld/core/blob/567a2eaf95b168597d23a56be89bf05a7834b2aa/impl/src/main/java/org/jboss/weld/bean/proxy/InterceptedSubclassFactory.java#L472-L493 |
OpenBEL/openbel-framework | org.openbel.framework.tools/src/main/java/org/openbel/framework/tools/PhaseOneApplication.java | PhaseOneApplication.processFiles | private void processFiles(File[] files) {
phaseOutput(format("=== %s ===", getApplicationName()));
phaseOutput(format("Compiling %d BEL Document(s)", files.length));
boolean pedantic = withPedantic();
boolean verbose = withVerbose();
int validated = 0;
for (int i = 1; i <= files.length; i++) {
File file = files[i - 1];
if (verbose) {
phaseOutput("Compiling " + i + " of " + files.length
+ " BEL Document(s)");
}
// validate document
Document document = stage1(file);
if (document == null) {
if (pedantic) {
bail(VALIDATION_FAILURE);
}
continue;
}
validated++;
// run stages 2 - 7
runCommonStages(pedantic, document);
}
if (validated == 0) {
bail(NO_VALID_DOCUMENTS);
}
} | java | private void processFiles(File[] files) {
phaseOutput(format("=== %s ===", getApplicationName()));
phaseOutput(format("Compiling %d BEL Document(s)", files.length));
boolean pedantic = withPedantic();
boolean verbose = withVerbose();
int validated = 0;
for (int i = 1; i <= files.length; i++) {
File file = files[i - 1];
if (verbose) {
phaseOutput("Compiling " + i + " of " + files.length
+ " BEL Document(s)");
}
// validate document
Document document = stage1(file);
if (document == null) {
if (pedantic) {
bail(VALIDATION_FAILURE);
}
continue;
}
validated++;
// run stages 2 - 7
runCommonStages(pedantic, document);
}
if (validated == 0) {
bail(NO_VALID_DOCUMENTS);
}
} | [
"private",
"void",
"processFiles",
"(",
"File",
"[",
"]",
"files",
")",
"{",
"phaseOutput",
"(",
"format",
"(",
"\"=== %s ===\"",
",",
"getApplicationName",
"(",
")",
")",
")",
";",
"phaseOutput",
"(",
"format",
"(",
"\"Compiling %d BEL Document(s)\"",
",",
"f... | Starts phase one compilation from {@link File XBEL files}.
@param files the {@link File XBEL files} to compile | [
"Starts",
"phase",
"one",
"compilation",
"from",
"{",
"@link",
"File",
"XBEL",
"files",
"}",
"."
] | train | https://github.com/OpenBEL/openbel-framework/blob/149f80b1d6eabb15ab15815b6f745b0afa9fd2d3/org.openbel.framework.tools/src/main/java/org/openbel/framework/tools/PhaseOneApplication.java#L260-L294 |
alkacon/opencms-core | src/org/opencms/i18n/CmsVfsBundleLoaderProperties.java | CmsVfsBundleLoaderProperties.getEncoding | private String getEncoding(CmsObject cms, CmsResource res) {
String defaultEncoding = OpenCms.getSystemInfo().getDefaultEncoding();
try {
CmsProperty encProp = cms.readPropertyObject(res, CmsPropertyDefinition.PROPERTY_CONTENT_ENCODING, true);
String encoding = encProp.getValue(defaultEncoding);
return encoding;
} catch (Exception e) {
LOG.warn(e.getLocalizedMessage(), e);
return defaultEncoding;
}
} | java | private String getEncoding(CmsObject cms, CmsResource res) {
String defaultEncoding = OpenCms.getSystemInfo().getDefaultEncoding();
try {
CmsProperty encProp = cms.readPropertyObject(res, CmsPropertyDefinition.PROPERTY_CONTENT_ENCODING, true);
String encoding = encProp.getValue(defaultEncoding);
return encoding;
} catch (Exception e) {
LOG.warn(e.getLocalizedMessage(), e);
return defaultEncoding;
}
} | [
"private",
"String",
"getEncoding",
"(",
"CmsObject",
"cms",
",",
"CmsResource",
"res",
")",
"{",
"String",
"defaultEncoding",
"=",
"OpenCms",
".",
"getSystemInfo",
"(",
")",
".",
"getDefaultEncoding",
"(",
")",
";",
"try",
"{",
"CmsProperty",
"encProp",
"=",
... | Gets the encoding which should be used to read the properties file.<p>
@param cms the CMS context to use
@param res the resource for which we want the encoding
@return the encoding value | [
"Gets",
"the",
"encoding",
"which",
"should",
"be",
"used",
"to",
"read",
"the",
"properties",
"file",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/i18n/CmsVfsBundleLoaderProperties.java#L85-L96 |
apache/flink | flink-filesystems/flink-fs-hadoop-shaded/src/main/java/org/apache/hadoop/conf/Configuration.java | Configuration.getTimeDurationHelper | public long getTimeDurationHelper(String name, String vStr, TimeUnit unit) {
vStr = vStr.trim();
vStr = StringUtils.toLowerCase(vStr);
ParsedTimeDuration vUnit = ParsedTimeDuration.unitFor(vStr);
if (null == vUnit) {
logDeprecation("No unit for " + name + "(" + vStr + ") assuming " + unit);
vUnit = ParsedTimeDuration.unitFor(unit);
} else {
vStr = vStr.substring(0, vStr.lastIndexOf(vUnit.suffix()));
}
long raw = Long.parseLong(vStr);
long converted = unit.convert(raw, vUnit.unit());
if (vUnit.unit().convert(converted, unit) < raw) {
logDeprecation("Possible loss of precision converting " + vStr
+ vUnit.suffix() + " to " + unit + " for " + name);
}
return converted;
} | java | public long getTimeDurationHelper(String name, String vStr, TimeUnit unit) {
vStr = vStr.trim();
vStr = StringUtils.toLowerCase(vStr);
ParsedTimeDuration vUnit = ParsedTimeDuration.unitFor(vStr);
if (null == vUnit) {
logDeprecation("No unit for " + name + "(" + vStr + ") assuming " + unit);
vUnit = ParsedTimeDuration.unitFor(unit);
} else {
vStr = vStr.substring(0, vStr.lastIndexOf(vUnit.suffix()));
}
long raw = Long.parseLong(vStr);
long converted = unit.convert(raw, vUnit.unit());
if (vUnit.unit().convert(converted, unit) < raw) {
logDeprecation("Possible loss of precision converting " + vStr
+ vUnit.suffix() + " to " + unit + " for " + name);
}
return converted;
} | [
"public",
"long",
"getTimeDurationHelper",
"(",
"String",
"name",
",",
"String",
"vStr",
",",
"TimeUnit",
"unit",
")",
"{",
"vStr",
"=",
"vStr",
".",
"trim",
"(",
")",
";",
"vStr",
"=",
"StringUtils",
".",
"toLowerCase",
"(",
"vStr",
")",
";",
"ParsedTim... | Return time duration in the given time unit. Valid units are encoded in
properties as suffixes: nanoseconds (ns), microseconds (us), milliseconds
(ms), seconds (s), minutes (m), hours (h), and days (d).
@param name Property name
@param vStr The string value with time unit suffix to be converted.
@param unit Unit to convert the stored property, if it exists. | [
"Return",
"time",
"duration",
"in",
"the",
"given",
"time",
"unit",
".",
"Valid",
"units",
"are",
"encoded",
"in",
"properties",
"as",
"suffixes",
":",
"nanoseconds",
"(",
"ns",
")",
"microseconds",
"(",
"us",
")",
"milliseconds",
"(",
"ms",
")",
"seconds"... | train | https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-filesystems/flink-fs-hadoop-shaded/src/main/java/org/apache/hadoop/conf/Configuration.java#L1688-L1706 |
geomajas/geomajas-project-client-gwt2 | impl/src/main/java/org/geomajas/gwt2/client/service/TileService.java | TileService.getWorldBoundsForTile | public static Bbox getWorldBoundsForTile(TileConfiguration tileConfiguration, TileCode tileCode) {
double resolution = tileConfiguration.getResolution(tileCode.getTileLevel());
double worldTileWidth = tileConfiguration.getTileWidth() * resolution;
double worldTileHeight = tileConfiguration.getTileHeight() * resolution;
double x = tileConfiguration.getTileOrigin().getX() + tileCode.getX() * worldTileWidth;
double y = tileConfiguration.getTileOrigin().getY() + tileCode.getY() * worldTileHeight;
return new Bbox(x, y, worldTileWidth, worldTileHeight);
} | java | public static Bbox getWorldBoundsForTile(TileConfiguration tileConfiguration, TileCode tileCode) {
double resolution = tileConfiguration.getResolution(tileCode.getTileLevel());
double worldTileWidth = tileConfiguration.getTileWidth() * resolution;
double worldTileHeight = tileConfiguration.getTileHeight() * resolution;
double x = tileConfiguration.getTileOrigin().getX() + tileCode.getX() * worldTileWidth;
double y = tileConfiguration.getTileOrigin().getY() + tileCode.getY() * worldTileHeight;
return new Bbox(x, y, worldTileWidth, worldTileHeight);
} | [
"public",
"static",
"Bbox",
"getWorldBoundsForTile",
"(",
"TileConfiguration",
"tileConfiguration",
",",
"TileCode",
"tileCode",
")",
"{",
"double",
"resolution",
"=",
"tileConfiguration",
".",
"getResolution",
"(",
"tileCode",
".",
"getTileLevel",
"(",
")",
")",
";... | Given a tile for a layer, what are the tiles bounds in world space.
@param tileConfiguration The basic tile configuration.
@param tileCode The tile code.
@return The tile bounds in map CRS. | [
"Given",
"a",
"tile",
"for",
"a",
"layer",
"what",
"are",
"the",
"tiles",
"bounds",
"in",
"world",
"space",
"."
] | train | https://github.com/geomajas/geomajas-project-client-gwt2/blob/bd8d7904e861fa80522eed7b83c4ea99844180c7/impl/src/main/java/org/geomajas/gwt2/client/service/TileService.java#L83-L91 |
google/j2objc | jre_emul/openjdk/src/share/classes/java/math/BigDecimal.java | BigDecimal.divideAndRound | private static BigDecimal divideAndRound(long ldividend, long ldivisor, int scale, int roundingMode,
int preferredScale) {
int qsign; // quotient sign
long q = ldividend / ldivisor; // store quotient in long
if (roundingMode == ROUND_DOWN && scale == preferredScale)
return valueOf(q, scale);
long r = ldividend % ldivisor; // store remainder in long
qsign = ((ldividend < 0) == (ldivisor < 0)) ? 1 : -1;
if (r != 0) {
boolean increment = needIncrement(ldivisor, roundingMode, qsign, q, r);
return valueOf((increment ? q + qsign : q), scale);
} else {
if (preferredScale != scale)
return createAndStripZerosToMatchScale(q, scale, preferredScale);
else
return valueOf(q, scale);
}
} | java | private static BigDecimal divideAndRound(long ldividend, long ldivisor, int scale, int roundingMode,
int preferredScale) {
int qsign; // quotient sign
long q = ldividend / ldivisor; // store quotient in long
if (roundingMode == ROUND_DOWN && scale == preferredScale)
return valueOf(q, scale);
long r = ldividend % ldivisor; // store remainder in long
qsign = ((ldividend < 0) == (ldivisor < 0)) ? 1 : -1;
if (r != 0) {
boolean increment = needIncrement(ldivisor, roundingMode, qsign, q, r);
return valueOf((increment ? q + qsign : q), scale);
} else {
if (preferredScale != scale)
return createAndStripZerosToMatchScale(q, scale, preferredScale);
else
return valueOf(q, scale);
}
} | [
"private",
"static",
"BigDecimal",
"divideAndRound",
"(",
"long",
"ldividend",
",",
"long",
"ldivisor",
",",
"int",
"scale",
",",
"int",
"roundingMode",
",",
"int",
"preferredScale",
")",
"{",
"int",
"qsign",
";",
"// quotient sign",
"long",
"q",
"=",
"ldivide... | Internally used for division operation for division {@code long} by
{@code long}.
The returned {@code BigDecimal} object is the quotient whose scale is set
to the passed in scale. If the remainder is not zero, it will be rounded
based on the passed in roundingMode. Also, if the remainder is zero and
the last parameter, i.e. preferredScale is NOT equal to scale, the
trailing zeros of the result is stripped to match the preferredScale. | [
"Internally",
"used",
"for",
"division",
"operation",
"for",
"division",
"{"
] | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/openjdk/src/share/classes/java/math/BigDecimal.java#L4104-L4122 |
j256/ormlite-android | src/main/java/com/j256/ormlite/android/apptools/OrmLiteConfigUtil.java | OrmLiteConfigUtil.writeConfigFile | public static void writeConfigFile(OutputStream outputStream, Class<?>[] classes, boolean sortClasses)
throws SQLException, IOException {
if (sortClasses) {
// sort our class list to make the output more deterministic
Class<?>[] sortedClasses = new Class<?>[classes.length];
System.arraycopy(classes, 0, sortedClasses, 0, classes.length);
Arrays.sort(sortedClasses, classComparator);
classes = sortedClasses;
}
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream), 4096);
try {
writeHeader(writer);
for (Class<?> clazz : classes) {
writeConfigForTable(writer, clazz, sortClasses);
}
// NOTE: done is here because this is public
System.out.println("Done.");
} finally {
writer.close();
}
} | java | public static void writeConfigFile(OutputStream outputStream, Class<?>[] classes, boolean sortClasses)
throws SQLException, IOException {
if (sortClasses) {
// sort our class list to make the output more deterministic
Class<?>[] sortedClasses = new Class<?>[classes.length];
System.arraycopy(classes, 0, sortedClasses, 0, classes.length);
Arrays.sort(sortedClasses, classComparator);
classes = sortedClasses;
}
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream), 4096);
try {
writeHeader(writer);
for (Class<?> clazz : classes) {
writeConfigForTable(writer, clazz, sortClasses);
}
// NOTE: done is here because this is public
System.out.println("Done.");
} finally {
writer.close();
}
} | [
"public",
"static",
"void",
"writeConfigFile",
"(",
"OutputStream",
"outputStream",
",",
"Class",
"<",
"?",
">",
"[",
"]",
"classes",
",",
"boolean",
"sortClasses",
")",
"throws",
"SQLException",
",",
"IOException",
"{",
"if",
"(",
"sortClasses",
")",
"{",
"... | Write a configuration file to an output stream with the configuration for classes.
@param sortClasses
Set to true to sort the classes and fields by name before the file is generated. | [
"Write",
"a",
"configuration",
"file",
"to",
"an",
"output",
"stream",
"with",
"the",
"configuration",
"for",
"classes",
"."
] | train | https://github.com/j256/ormlite-android/blob/e82327a868ae242f994730fe2389f79684d7bcab/src/main/java/com/j256/ormlite/android/apptools/OrmLiteConfigUtil.java#L235-L255 |
imsweb/naaccr-xml | src/main/java/com/imsweb/naaccrxml/runtime/NaaccrStreamConfiguration.java | NaaccrStreamConfiguration.createXStream | protected XStream createXStream(HierarchicalStreamDriver driver, NaaccrPatientConverter patientConverter) {
XStream xstream = new XStream(driver) {
@Override
protected void setupConverters() {
registerConverter(new NullConverter(), PRIORITY_VERY_HIGH);
registerConverter(new IntConverter(), PRIORITY_NORMAL);
registerConverter(new FloatConverter(), PRIORITY_NORMAL);
registerConverter(new DoubleConverter(), PRIORITY_NORMAL);
registerConverter(new LongConverter(), PRIORITY_NORMAL);
registerConverter(new ShortConverter(), PRIORITY_NORMAL);
registerConverter(new BooleanConverter(), PRIORITY_NORMAL);
registerConverter(new ByteConverter(), PRIORITY_NORMAL);
registerConverter(new StringConverter(), PRIORITY_NORMAL);
registerConverter(new DateConverter(), PRIORITY_NORMAL);
registerConverter(new CollectionConverter(getMapper()), PRIORITY_NORMAL);
registerConverter(new ReflectionConverter(getMapper(), getReflectionProvider()), PRIORITY_VERY_LOW);
}
};
// setup proper security environment
xstream.addPermission(NoTypePermission.NONE);
xstream.addPermission(new WildcardTypePermission(new String[] {"com.imsweb.naaccrxml.**"}));
// tell XStream how to read/write our main entities
xstream.alias(NaaccrXmlUtils.NAACCR_XML_TAG_ROOT, NaaccrData.class);
xstream.alias(NaaccrXmlUtils.NAACCR_XML_TAG_ITEM, Item.class);
xstream.alias(NaaccrXmlUtils.NAACCR_XML_TAG_PATIENT, Patient.class);
// add some attributes
xstream.aliasAttribute(NaaccrData.class, "_baseDictionaryUri", NaaccrXmlUtils.NAACCR_XML_ROOT_ATT_BASE_DICT);
xstream.aliasAttribute(NaaccrData.class, "_userDictionaryUri", NaaccrXmlUtils.NAACCR_XML_ROOT_ATT_USER_DICT);
xstream.aliasAttribute(NaaccrData.class, "_recordType", NaaccrXmlUtils.NAACCR_XML_ROOT_ATT_REC_TYPE);
xstream.aliasAttribute(NaaccrData.class, "_timeGenerated", NaaccrXmlUtils.NAACCR_XML_ROOT_ATT_TIME_GENERATED);
xstream.aliasAttribute(NaaccrData.class, "_specificationVersion", NaaccrXmlUtils.NAACCR_XML_ROOT_ATT_SPEC_VERSION);
// all collections should be wrap into collection tags, but it's nicer to omit them in the XML; we have to tell XStream though
xstream.addImplicitCollection(NaaccrData.class, "_items", Item.class);
xstream.addImplicitCollection(NaaccrData.class, "_patients", Patient.class);
// handle patients
xstream.registerConverter(patientConverter);
return xstream;
} | java | protected XStream createXStream(HierarchicalStreamDriver driver, NaaccrPatientConverter patientConverter) {
XStream xstream = new XStream(driver) {
@Override
protected void setupConverters() {
registerConverter(new NullConverter(), PRIORITY_VERY_HIGH);
registerConverter(new IntConverter(), PRIORITY_NORMAL);
registerConverter(new FloatConverter(), PRIORITY_NORMAL);
registerConverter(new DoubleConverter(), PRIORITY_NORMAL);
registerConverter(new LongConverter(), PRIORITY_NORMAL);
registerConverter(new ShortConverter(), PRIORITY_NORMAL);
registerConverter(new BooleanConverter(), PRIORITY_NORMAL);
registerConverter(new ByteConverter(), PRIORITY_NORMAL);
registerConverter(new StringConverter(), PRIORITY_NORMAL);
registerConverter(new DateConverter(), PRIORITY_NORMAL);
registerConverter(new CollectionConverter(getMapper()), PRIORITY_NORMAL);
registerConverter(new ReflectionConverter(getMapper(), getReflectionProvider()), PRIORITY_VERY_LOW);
}
};
// setup proper security environment
xstream.addPermission(NoTypePermission.NONE);
xstream.addPermission(new WildcardTypePermission(new String[] {"com.imsweb.naaccrxml.**"}));
// tell XStream how to read/write our main entities
xstream.alias(NaaccrXmlUtils.NAACCR_XML_TAG_ROOT, NaaccrData.class);
xstream.alias(NaaccrXmlUtils.NAACCR_XML_TAG_ITEM, Item.class);
xstream.alias(NaaccrXmlUtils.NAACCR_XML_TAG_PATIENT, Patient.class);
// add some attributes
xstream.aliasAttribute(NaaccrData.class, "_baseDictionaryUri", NaaccrXmlUtils.NAACCR_XML_ROOT_ATT_BASE_DICT);
xstream.aliasAttribute(NaaccrData.class, "_userDictionaryUri", NaaccrXmlUtils.NAACCR_XML_ROOT_ATT_USER_DICT);
xstream.aliasAttribute(NaaccrData.class, "_recordType", NaaccrXmlUtils.NAACCR_XML_ROOT_ATT_REC_TYPE);
xstream.aliasAttribute(NaaccrData.class, "_timeGenerated", NaaccrXmlUtils.NAACCR_XML_ROOT_ATT_TIME_GENERATED);
xstream.aliasAttribute(NaaccrData.class, "_specificationVersion", NaaccrXmlUtils.NAACCR_XML_ROOT_ATT_SPEC_VERSION);
// all collections should be wrap into collection tags, but it's nicer to omit them in the XML; we have to tell XStream though
xstream.addImplicitCollection(NaaccrData.class, "_items", Item.class);
xstream.addImplicitCollection(NaaccrData.class, "_patients", Patient.class);
// handle patients
xstream.registerConverter(patientConverter);
return xstream;
} | [
"protected",
"XStream",
"createXStream",
"(",
"HierarchicalStreamDriver",
"driver",
",",
"NaaccrPatientConverter",
"patientConverter",
")",
"{",
"XStream",
"xstream",
"=",
"new",
"XStream",
"(",
"driver",
")",
"{",
"@",
"Override",
"protected",
"void",
"setupConverter... | Creates the instance of XStream to us for all reading and writing operations
@param driver an XStream driver (see createDriver())
@param patientConverter a patient converter (see createPatientConverter())
@return an instance of XStream, never null | [
"Creates",
"the",
"instance",
"of",
"XStream",
"to",
"us",
"for",
"all",
"reading",
"and",
"writing",
"operations"
] | train | https://github.com/imsweb/naaccr-xml/blob/a3a501faa2a0c3411dd5248b2c1379f279131696/src/main/java/com/imsweb/naaccrxml/runtime/NaaccrStreamConfiguration.java#L134-L177 |
xwiki/xwiki-rendering | xwiki-rendering-syntaxes/xwiki-rendering-syntax-plain/src/main/java/org/xwiki/rendering/internal/parser/plain/PlainTextStreamParser.java | PlainTextStreamParser.readChar | private int readChar(Reader source) throws ParseException
{
int c;
try {
c = source.read();
} catch (IOException e) {
throw new ParseException("Failed to read input source", e);
}
return c;
} | java | private int readChar(Reader source) throws ParseException
{
int c;
try {
c = source.read();
} catch (IOException e) {
throw new ParseException("Failed to read input source", e);
}
return c;
} | [
"private",
"int",
"readChar",
"(",
"Reader",
"source",
")",
"throws",
"ParseException",
"{",
"int",
"c",
";",
"try",
"{",
"c",
"=",
"source",
".",
"read",
"(",
")",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"throw",
"new",
"ParseException",... | Read a single char from an Reader source.
@param source the input to read from
@return the char read
@throws ParseException in case of reading error | [
"Read",
"a",
"single",
"char",
"from",
"an",
"Reader",
"source",
"."
] | train | https://github.com/xwiki/xwiki-rendering/blob/a21cdfcb64ef5b76872e3eedf78c530f26d7beb0/xwiki-rendering-syntaxes/xwiki-rendering-syntax-plain/src/main/java/org/xwiki/rendering/internal/parser/plain/PlainTextStreamParser.java#L67-L78 |
lessthanoptimal/BoofCV | main/boofcv-feature/src/main/java/boofcv/alg/feature/describe/SurfDescribeOps.java | SurfDescribeOps.rotatedWidth | public static double rotatedWidth( double width , double c , double s )
{
return Math.abs(c)*width + Math.abs(s)*width;
} | java | public static double rotatedWidth( double width , double c , double s )
{
return Math.abs(c)*width + Math.abs(s)*width;
} | [
"public",
"static",
"double",
"rotatedWidth",
"(",
"double",
"width",
",",
"double",
"c",
",",
"double",
"s",
")",
"{",
"return",
"Math",
".",
"abs",
"(",
"c",
")",
"*",
"width",
"+",
"Math",
".",
"abs",
"(",
"s",
")",
"*",
"width",
";",
"}"
] | Computes the width of a square containment region that contains a rotated rectangle.
@param width Size of the original rectangle.
@param c Cosine(theta)
@param s Sine(theta)
@return Side length of the containment square. | [
"Computes",
"the",
"width",
"of",
"a",
"square",
"containment",
"region",
"that",
"contains",
"a",
"rotated",
"rectangle",
"."
] | train | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-feature/src/main/java/boofcv/alg/feature/describe/SurfDescribeOps.java#L214-L217 |
sawano/java-commons | src/main/java/se/sawano/java/commons/lang/validate/Validate.java | Validate.noNullElements | public static <T extends Iterable<?>> T noNullElements(final T iterable, final String message, final Object... values) {
return INSTANCE.noNullElements(iterable, message, values);
} | java | public static <T extends Iterable<?>> T noNullElements(final T iterable, final String message, final Object... values) {
return INSTANCE.noNullElements(iterable, message, values);
} | [
"public",
"static",
"<",
"T",
"extends",
"Iterable",
"<",
"?",
">",
">",
"T",
"noNullElements",
"(",
"final",
"T",
"iterable",
",",
"final",
"String",
"message",
",",
"final",
"Object",
"...",
"values",
")",
"{",
"return",
"INSTANCE",
".",
"noNullElements"... | <p>Validate that the specified argument iterable is neither {@code null} nor contains any elements that are {@code null}; otherwise throwing an exception with the specified message.
<pre>Validate.noNullElements(myCollection, "The collection contains null at position %d");</pre>
<p>If the iterable is {@code null}, then the message in the exception is "The validated object is null".</p><p>If the iterable has a {@code null} element, then the iteration index of
the invalid element is appended to the {@code values} argument.</p>
@param <T>
the iterable type
@param iterable
the iterable to check, validated not null by this method
@param message
the {@link String#format(String, Object...)} exception message if invalid, not null
@param values
the optional values for the formatted exception message, null array not recommended
@return the validated iterable (never {@code null} method for chaining)
@throws NullPointerValidationException
if the array is {@code null}
@throws IllegalArgumentException
if an element is {@code null}
@see #noNullElements(Iterable) | [
"<p",
">",
"Validate",
"that",
"the",
"specified",
"argument",
"iterable",
"is",
"neither",
"{",
"@code",
"null",
"}",
"nor",
"contains",
"any",
"elements",
"that",
"are",
"{",
"@code",
"null",
"}",
";",
"otherwise",
"throwing",
"an",
"exception",
"with",
... | train | https://github.com/sawano/java-commons/blob/6f219c9e8dec4401dbe528d17ae6ec1ef9c0d284/src/main/java/se/sawano/java/commons/lang/validate/Validate.java#L1122-L1124 |
jbundle/jbundle | base/screen/view/html/src/main/java/org/jbundle/base/screen/view/html/opt/HBlinkImageView.java | HBlinkImageView.printInputControl | public void printInputControl(PrintWriter out, String strFieldDesc, String strFieldName, String strSize, String strMaxSize, String strValue, String strControlType, int iHtmlAttributes)
{
String strImage = "";
out.println("<td>" + strImage + "</td>");
} | java | public void printInputControl(PrintWriter out, String strFieldDesc, String strFieldName, String strSize, String strMaxSize, String strValue, String strControlType, int iHtmlAttributes)
{
String strImage = "";
out.println("<td>" + strImage + "</td>");
} | [
"public",
"void",
"printInputControl",
"(",
"PrintWriter",
"out",
",",
"String",
"strFieldDesc",
",",
"String",
"strFieldName",
",",
"String",
"strSize",
",",
"String",
"strMaxSize",
",",
"String",
"strValue",
",",
"String",
"strControlType",
",",
"int",
"iHtmlAtt... | display this field in html input format.
@param out The html out stream.
@param strFieldDesc The field description.
@param strFieldName The field name.
@param strSize The control size.
@param strMaxSize The string max size.
@param strValue The default value.
@param strControlType The control type.
@param iHtmlAttribures The attributes. | [
"display",
"this",
"field",
"in",
"html",
"input",
"format",
"."
] | train | https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/base/screen/view/html/src/main/java/org/jbundle/base/screen/view/html/opt/HBlinkImageView.java#L69-L73 |
mfornos/humanize | humanize-slim/src/main/java/humanize/Humanize.java | Humanize.naturalTime | public static String naturalTime(final Date reference, final Date duration, final TimeMillis precision,
final Locale locale)
{
return naturalTime(reference, duration, precision.millis(), locale);
} | java | public static String naturalTime(final Date reference, final Date duration, final TimeMillis precision,
final Locale locale)
{
return naturalTime(reference, duration, precision.millis(), locale);
} | [
"public",
"static",
"String",
"naturalTime",
"(",
"final",
"Date",
"reference",
",",
"final",
"Date",
"duration",
",",
"final",
"TimeMillis",
"precision",
",",
"final",
"Locale",
"locale",
")",
"{",
"return",
"naturalTime",
"(",
"reference",
",",
"duration",
"... | Same as {@link #naturalTime(Date, Date, long, Locale)}.
@param reference
The reference
@param duration
The duration
@param precision
The precesion to retain in milliseconds
@param locale
The locale
@return String representing the relative date | [
"Same",
"as",
"{",
"@link",
"#naturalTime",
"(",
"Date",
"Date",
"long",
"Locale",
")",
"}",
"."
] | train | https://github.com/mfornos/humanize/blob/59fc103045de9d217c9e77dbcb7621f992f46c63/humanize-slim/src/main/java/humanize/Humanize.java#L1651-L1655 |
csc19601128/Phynixx | phynixx/phynixx-watchdog/src/main/java/org/csc/phynixx/watchdog/WatchdogRegistry.java | WatchdogRegistry.registerWatchdog | private synchronized void registerWatchdog(Long key, Watchdog wd) {
if (wd == null) {
throw new NullPointerException("Thread");
}
if (wd.getThread() == null) {
wd.restart();
}
registeredWachdogs.put(key, wd);
} | java | private synchronized void registerWatchdog(Long key, Watchdog wd) {
if (wd == null) {
throw new NullPointerException("Thread");
}
if (wd.getThread() == null) {
wd.restart();
}
registeredWachdogs.put(key, wd);
} | [
"private",
"synchronized",
"void",
"registerWatchdog",
"(",
"Long",
"key",
",",
"Watchdog",
"wd",
")",
"{",
"if",
"(",
"wd",
"==",
"null",
")",
"{",
"throw",
"new",
"NullPointerException",
"(",
"\"Thread\"",
")",
";",
"}",
"if",
"(",
"wd",
".",
"getThrea... | Fuegt einen Thread hinzu
@param key String Schluessel unter dem der Thread gespeichert wird
@param wd Watchdog
@throws IllegalStateException falls Thread NICHT zur aktuellen ThreadGroup( ==this) geh�rt; | [
"Fuegt",
"einen",
"Thread",
"hinzu"
] | train | https://github.com/csc19601128/Phynixx/blob/a26c03bc229a8882c647799834115bec6bdc0ac8/phynixx/phynixx-watchdog/src/main/java/org/csc/phynixx/watchdog/WatchdogRegistry.java#L230-L238 |
bbossgroups/bboss-elasticsearch | bboss-elasticsearch-rest/src/main/java/org/frameworkset/elasticsearch/client/ConfigRestClientUtil.java | ConfigRestClientUtil.createIndiceMapping | public String createIndiceMapping(String indexName, String templateName, Object parameter) throws ElasticSearchException {
return super.createIndiceMapping(indexName, ESTemplateHelper.evalTemplate(esUtil,templateName, parameter));
} | java | public String createIndiceMapping(String indexName, String templateName, Object parameter) throws ElasticSearchException {
return super.createIndiceMapping(indexName, ESTemplateHelper.evalTemplate(esUtil,templateName, parameter));
} | [
"public",
"String",
"createIndiceMapping",
"(",
"String",
"indexName",
",",
"String",
"templateName",
",",
"Object",
"parameter",
")",
"throws",
"ElasticSearchException",
"{",
"return",
"super",
".",
"createIndiceMapping",
"(",
"indexName",
",",
"ESTemplateHelper",
".... | 创建索引定义
curl -XPUT 'localhost:9200/test?pretty' -H 'Content-Type: application/json' -d'
{
"settings" : {
"number_of_shards" : 1
},
"mappings" : {
"type1" : {
"properties" : {
"field1" : { "type" : "text" }
}
}
}
}
@return
@throws ElasticSearchException | [
"创建索引定义",
"curl",
"-",
"XPUT",
"localhost",
":",
"9200",
"/",
"test?pretty",
"-",
"H",
"Content",
"-",
"Type",
":",
"application",
"/",
"json",
"-",
"d",
"{",
"settings",
":",
"{",
"number_of_shards",
":",
"1",
"}",
"mappings",
":",
"{",
"type1",
":",
... | train | https://github.com/bbossgroups/bboss-elasticsearch/blob/31717c8aa2c4c880987be53aeeb8a0cf5183c3a7/bboss-elasticsearch-rest/src/main/java/org/frameworkset/elasticsearch/client/ConfigRestClientUtil.java#L696-L698 |
inkstand-io/scribble | scribble-file/src/main/java/io/inkstand/scribble/rules/builder/ZipFileBuilder.java | ZipFileBuilder.addClasspathResource | public ZipFileBuilder addClasspathResource(final String zipEntryPath, final String pathToResource) {
final Class<?> callerClass = getCallerClass();
final URL resource = resolver.resolve(pathToResource, callerClass);
addResource(zipEntryPath, resource);
return this;
} | java | public ZipFileBuilder addClasspathResource(final String zipEntryPath, final String pathToResource) {
final Class<?> callerClass = getCallerClass();
final URL resource = resolver.resolve(pathToResource, callerClass);
addResource(zipEntryPath, resource);
return this;
} | [
"public",
"ZipFileBuilder",
"addClasspathResource",
"(",
"final",
"String",
"zipEntryPath",
",",
"final",
"String",
"pathToResource",
")",
"{",
"final",
"Class",
"<",
"?",
">",
"callerClass",
"=",
"getCallerClass",
"(",
")",
";",
"final",
"URL",
"resource",
"=",... | Adds an entry to the zip file from a classpath resource.
@param zipEntryPath
the path of the entry in the zip file. If the path denotes a path (ends with '/') the resource is put
under its own name on that location. If it denotes a file, it will be put as this file into the zip. Note
that even if the path ist defined absolute, starting with a '/', the created entry in the zip file won't
start with a '/'
@param pathToResource
the path to the resource in the classpath
@return this builder | [
"Adds",
"an",
"entry",
"to",
"the",
"zip",
"file",
"from",
"a",
"classpath",
"resource",
"."
] | train | https://github.com/inkstand-io/scribble/blob/66e67553bad4b1ff817e1715fd1d3dd833406744/scribble-file/src/main/java/io/inkstand/scribble/rules/builder/ZipFileBuilder.java#L68-L74 |
Azure/azure-sdk-for-java | cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/ModelsImpl.java | ModelsImpl.deleteCompositeEntityRoleAsync | public Observable<OperationStatus> deleteCompositeEntityRoleAsync(UUID appId, String versionId, UUID cEntityId, UUID roleId) {
return deleteCompositeEntityRoleWithServiceResponseAsync(appId, versionId, cEntityId, roleId).map(new Func1<ServiceResponse<OperationStatus>, OperationStatus>() {
@Override
public OperationStatus call(ServiceResponse<OperationStatus> response) {
return response.body();
}
});
} | java | public Observable<OperationStatus> deleteCompositeEntityRoleAsync(UUID appId, String versionId, UUID cEntityId, UUID roleId) {
return deleteCompositeEntityRoleWithServiceResponseAsync(appId, versionId, cEntityId, roleId).map(new Func1<ServiceResponse<OperationStatus>, OperationStatus>() {
@Override
public OperationStatus call(ServiceResponse<OperationStatus> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"OperationStatus",
">",
"deleteCompositeEntityRoleAsync",
"(",
"UUID",
"appId",
",",
"String",
"versionId",
",",
"UUID",
"cEntityId",
",",
"UUID",
"roleId",
")",
"{",
"return",
"deleteCompositeEntityRoleWithServiceResponseAsync",
"(",
"appId... | Delete an entity role.
@param appId The application ID.
@param versionId The version ID.
@param cEntityId The composite entity extractor ID.
@param roleId The entity role Id.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the OperationStatus object | [
"Delete",
"an",
"entity",
"role",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/ModelsImpl.java#L12688-L12695 |
lessthanoptimal/BoofCV | main/boofcv-ip/src/main/java/boofcv/abst/distort/FDistort.java | FDistort.setRefs | public FDistort setRefs( ImageBase input, ImageBase output ) {
this.input = input;
this.output = output;
inputType = input.getImageType();
return this;
} | java | public FDistort setRefs( ImageBase input, ImageBase output ) {
this.input = input;
this.output = output;
inputType = input.getImageType();
return this;
} | [
"public",
"FDistort",
"setRefs",
"(",
"ImageBase",
"input",
",",
"ImageBase",
"output",
")",
"{",
"this",
".",
"input",
"=",
"input",
";",
"this",
".",
"output",
"=",
"output",
";",
"inputType",
"=",
"input",
".",
"getImageType",
"(",
")",
";",
"return",... | All this does is set the references to the images. Nothing else is changed and its up to the
user to correctly update everything else.
If called the first time you need to do the following
<pre>
1) specify the interpolation method
2) specify the transform
3) specify the border
</pre>
If called again and the image shape has changed you need to do the following:
<pre>
1) Update the transform
</pre> | [
"All",
"this",
"does",
"is",
"set",
"the",
"references",
"to",
"the",
"images",
".",
"Nothing",
"else",
"is",
"changed",
"and",
"its",
"up",
"to",
"the",
"user",
"to",
"correctly",
"update",
"everything",
"else",
"."
] | train | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-ip/src/main/java/boofcv/abst/distort/FDistort.java#L128-L134 |
phax/ph-css | ph-css/src/main/java/com/helger/css/reader/CSSReaderDeclarationList.java | CSSReaderDeclarationList.readFromStream | @Nullable
public static CSSDeclarationList readFromStream (@Nonnull @WillClose final InputStream aIS,
@Nonnull final Charset aCharset,
@Nonnull final ECSSVersion eVersion)
{
return readFromReader (StreamHelper.createReader (aIS, aCharset),
new CSSReaderSettings ().setCSSVersion (eVersion));
} | java | @Nullable
public static CSSDeclarationList readFromStream (@Nonnull @WillClose final InputStream aIS,
@Nonnull final Charset aCharset,
@Nonnull final ECSSVersion eVersion)
{
return readFromReader (StreamHelper.createReader (aIS, aCharset),
new CSSReaderSettings ().setCSSVersion (eVersion));
} | [
"@",
"Nullable",
"public",
"static",
"CSSDeclarationList",
"readFromStream",
"(",
"@",
"Nonnull",
"@",
"WillClose",
"final",
"InputStream",
"aIS",
",",
"@",
"Nonnull",
"final",
"Charset",
"aCharset",
",",
"@",
"Nonnull",
"final",
"ECSSVersion",
"eVersion",
")",
... | Read the CSS from the passed {@link InputStream}.
@param aIS
The input stream to use. Will be closed automatically after reading
- independent of success or error. May not be <code>null</code>.
@param aCharset
The charset to be used. May not be <code>null</code>.
@param eVersion
The CSS version to use. May not be <code>null</code>.
@return <code>null</code> if reading failed, the CSS declarations
otherwise.
@since 3.7.4 | [
"Read",
"the",
"CSS",
"from",
"the",
"passed",
"{",
"@link",
"InputStream",
"}",
"."
] | train | https://github.com/phax/ph-css/blob/c9da5bb4decc681de6e27ce31712aad4c00adafa/ph-css/src/main/java/com/helger/css/reader/CSSReaderDeclarationList.java#L552-L559 |
VoltDB/voltdb | src/hsqldb19b3/org/hsqldb_voltpatches/ParserDML.java | ParserDML.compileMigrateStatement | StatementDMQL compileMigrateStatement(RangeVariable[] outerRanges) {
final Expression condition;
assert token.tokenType == Tokens.MIGRATE;
read();
readThis(Tokens.FROM);
RangeVariable[] rangeVariables = { readSimpleRangeVariable(StatementTypes.MIGRATE_WHERE) };
Table table = rangeVariables[0].getTable();
if (token.tokenType == Tokens.WHERE) {
read();
condition = XreadBooleanValueExpression();
HsqlList unresolved =
condition.resolveColumnReferences(outerRanges, null);
unresolved = Expression.resolveColumnSet(rangeVariables,
unresolved, null);
ExpressionColumn.checkColumnsResolved(unresolved);
condition.resolveTypes(session, null);
if (condition.isParam()) {
condition.dataType = Type.SQL_BOOLEAN;
}
if (condition.getDataType() != Type.SQL_BOOLEAN) {
throw Error.error(ErrorCode.X_42568);
}
} else {
throw Error.error(ErrorCode.X_47000);
}
// check WHERE condition
RangeVariableResolver resolver =
new RangeVariableResolver(rangeVariables, condition,
compileContext);
resolver.processConditions();
rangeVariables = resolver.rangeVariables;
return new StatementDML(session, table, rangeVariables, compileContext);
} | java | StatementDMQL compileMigrateStatement(RangeVariable[] outerRanges) {
final Expression condition;
assert token.tokenType == Tokens.MIGRATE;
read();
readThis(Tokens.FROM);
RangeVariable[] rangeVariables = { readSimpleRangeVariable(StatementTypes.MIGRATE_WHERE) };
Table table = rangeVariables[0].getTable();
if (token.tokenType == Tokens.WHERE) {
read();
condition = XreadBooleanValueExpression();
HsqlList unresolved =
condition.resolveColumnReferences(outerRanges, null);
unresolved = Expression.resolveColumnSet(rangeVariables,
unresolved, null);
ExpressionColumn.checkColumnsResolved(unresolved);
condition.resolveTypes(session, null);
if (condition.isParam()) {
condition.dataType = Type.SQL_BOOLEAN;
}
if (condition.getDataType() != Type.SQL_BOOLEAN) {
throw Error.error(ErrorCode.X_42568);
}
} else {
throw Error.error(ErrorCode.X_47000);
}
// check WHERE condition
RangeVariableResolver resolver =
new RangeVariableResolver(rangeVariables, condition,
compileContext);
resolver.processConditions();
rangeVariables = resolver.rangeVariables;
return new StatementDML(session, table, rangeVariables, compileContext);
} | [
"StatementDMQL",
"compileMigrateStatement",
"(",
"RangeVariable",
"[",
"]",
"outerRanges",
")",
"{",
"final",
"Expression",
"condition",
";",
"assert",
"token",
".",
"tokenType",
"==",
"Tokens",
".",
"MIGRATE",
";",
"read",
"(",
")",
";",
"readThis",
"(",
"Tok... | Creates a MIGRATE-type statement from this parser context (i.e.
MIGRATE FROM tbl WHERE ...
@param outerRanges
@return compiled statement | [
"Creates",
"a",
"MIGRATE",
"-",
"type",
"statement",
"from",
"this",
"parser",
"context",
"(",
"i",
".",
"e",
".",
"MIGRATE",
"FROM",
"tbl",
"WHERE",
"..."
] | train | https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/hsqldb19b3/org/hsqldb_voltpatches/ParserDML.java#L334-L377 |
brunocvcunha/inutils4j | src/main/java/org/brunocvcunha/inutils4j/MyStringUtils.java | MyStringUtils.getLine | public static String getLine(String content, int line) {
if (content == null) {
return null;
}
String[] contentSplit = content.replace("\r\n", "\n").split("\n");
if (contentSplit.length < line) {
return null;
}
return contentSplit[line - 1];
} | java | public static String getLine(String content, int line) {
if (content == null) {
return null;
}
String[] contentSplit = content.replace("\r\n", "\n").split("\n");
if (contentSplit.length < line) {
return null;
}
return contentSplit[line - 1];
} | [
"public",
"static",
"String",
"getLine",
"(",
"String",
"content",
",",
"int",
"line",
")",
"{",
"if",
"(",
"content",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"String",
"[",
"]",
"contentSplit",
"=",
"content",
".",
"replace",
"(",
"\"\\r\\... | Gets a specific line of a text (String)
@param content text
@param line line to get
@return the specified line | [
"Gets",
"a",
"specific",
"line",
"of",
"a",
"text",
"(",
"String",
")"
] | train | https://github.com/brunocvcunha/inutils4j/blob/223c4443c2cee662576ce644e552588fa114aa94/src/main/java/org/brunocvcunha/inutils4j/MyStringUtils.java#L471-L482 |
alkacon/opencms-core | src-gwt/org/opencms/gwt/client/util/CmsToolTipHandler.java | CmsToolTipHandler.setToolTipPosition | private void setToolTipPosition(int clientLeft, int clientTop) {
if (m_toolTip != null) {
int height = m_toolTip.getOffsetHeight();
int width = m_toolTip.getOffsetWidth();
int windowHeight = Window.getClientHeight();
int windowWidth = Window.getClientWidth();
int scrollLeft = Window.getScrollLeft();
int scrollTop = Window.getScrollTop();
int left = clientLeft + scrollLeft + m_offsetLeft;
if ((left + width) > (windowWidth + scrollLeft)) {
left = (windowWidth + scrollLeft) - m_offsetLeft - width;
}
m_toolTip.getStyle().setLeft(left, Unit.PX);
int top = clientTop + scrollTop + m_offsetTop;
if (((top + height) > (windowHeight + scrollTop)) && ((height + m_offsetTop) < clientTop)) {
top = (clientTop + scrollTop) - m_offsetTop - height;
}
m_toolTip.getStyle().setTop(top, Unit.PX);
}
} | java | private void setToolTipPosition(int clientLeft, int clientTop) {
if (m_toolTip != null) {
int height = m_toolTip.getOffsetHeight();
int width = m_toolTip.getOffsetWidth();
int windowHeight = Window.getClientHeight();
int windowWidth = Window.getClientWidth();
int scrollLeft = Window.getScrollLeft();
int scrollTop = Window.getScrollTop();
int left = clientLeft + scrollLeft + m_offsetLeft;
if ((left + width) > (windowWidth + scrollLeft)) {
left = (windowWidth + scrollLeft) - m_offsetLeft - width;
}
m_toolTip.getStyle().setLeft(left, Unit.PX);
int top = clientTop + scrollTop + m_offsetTop;
if (((top + height) > (windowHeight + scrollTop)) && ((height + m_offsetTop) < clientTop)) {
top = (clientTop + scrollTop) - m_offsetTop - height;
}
m_toolTip.getStyle().setTop(top, Unit.PX);
}
} | [
"private",
"void",
"setToolTipPosition",
"(",
"int",
"clientLeft",
",",
"int",
"clientTop",
")",
"{",
"if",
"(",
"m_toolTip",
"!=",
"null",
")",
"{",
"int",
"height",
"=",
"m_toolTip",
".",
"getOffsetHeight",
"(",
")",
";",
"int",
"width",
"=",
"m_toolTip"... | Sets the tool-tip position.<p>
@param clientLeft the mouse pointer left position relative to the client window
@param clientTop the mouse pointer top position relative to the client window | [
"Sets",
"the",
"tool",
"-",
"tip",
"position",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/gwt/client/util/CmsToolTipHandler.java#L266-L286 |
kubernetes-client/java | util/src/main/java/io/kubernetes/client/util/Yaml.java | Yaml.loadAs | public static <T> T loadAs(File f, Class<T> clazz) throws IOException {
return getSnakeYaml().loadAs(new FileReader(f), clazz);
} | java | public static <T> T loadAs(File f, Class<T> clazz) throws IOException {
return getSnakeYaml().loadAs(new FileReader(f), clazz);
} | [
"public",
"static",
"<",
"T",
">",
"T",
"loadAs",
"(",
"File",
"f",
",",
"Class",
"<",
"T",
">",
"clazz",
")",
"throws",
"IOException",
"{",
"return",
"getSnakeYaml",
"(",
")",
".",
"loadAs",
"(",
"new",
"FileReader",
"(",
"f",
")",
",",
"clazz",
"... | Load an API object from a YAML file. Returns a concrete typed object using the type specified.
@param f The YAML file
@param clazz The class of object to return.
@return An instantiation of the object.
@throws IOException If an error occurs while reading the YAML. | [
"Load",
"an",
"API",
"object",
"from",
"a",
"YAML",
"file",
".",
"Returns",
"a",
"concrete",
"typed",
"object",
"using",
"the",
"type",
"specified",
"."
] | train | https://github.com/kubernetes-client/java/blob/7413e98bd904f09d1ad00fb60e8c6ff787f3f560/util/src/main/java/io/kubernetes/client/util/Yaml.java#L208-L210 |
logic-ng/LogicNG | src/main/java/org/logicng/solvers/maxsat/encodings/Encoder.java | Encoder.encodeCardinality | public void encodeCardinality(final MiniSatStyleSolver s, final LNGIntVector lits, int rhs) {
switch (this.cardinalityEncoding) {
case TOTALIZER:
this.totalizer.build(s, lits, rhs);
if (this.totalizer.hasCreatedEncoding())
this.totalizer.update(s, rhs);
break;
case MTOTALIZER:
this.mtotalizer.encode(s, lits, rhs);
break;
default:
throw new IllegalStateException("Unknown cardinality encoding: " + this.cardinalityEncoding);
}
} | java | public void encodeCardinality(final MiniSatStyleSolver s, final LNGIntVector lits, int rhs) {
switch (this.cardinalityEncoding) {
case TOTALIZER:
this.totalizer.build(s, lits, rhs);
if (this.totalizer.hasCreatedEncoding())
this.totalizer.update(s, rhs);
break;
case MTOTALIZER:
this.mtotalizer.encode(s, lits, rhs);
break;
default:
throw new IllegalStateException("Unknown cardinality encoding: " + this.cardinalityEncoding);
}
} | [
"public",
"void",
"encodeCardinality",
"(",
"final",
"MiniSatStyleSolver",
"s",
",",
"final",
"LNGIntVector",
"lits",
",",
"int",
"rhs",
")",
"{",
"switch",
"(",
"this",
".",
"cardinalityEncoding",
")",
"{",
"case",
"TOTALIZER",
":",
"this",
".",
"totalizer",
... | Encodes a cardinality constraint in the given solver.
@param s the solver
@param lits the literals for the constraint
@param rhs the right hand side of the constraint
@throws IllegalStateException if the cardinality encoding is unknown | [
"Encodes",
"a",
"cardinality",
"constraint",
"in",
"the",
"given",
"solver",
"."
] | train | https://github.com/logic-ng/LogicNG/blob/bb9eb88a768be4be8e02a76cfc4a59e6c3fb7f2e/src/main/java/org/logicng/solvers/maxsat/encodings/Encoder.java#L168-L181 |
VoltDB/voltdb | src/hsqldb19b3/org/hsqldb_voltpatches/types/DateTimeType.java | DateTimeType.convertSQLToJavaGMT | public Object convertSQLToJavaGMT(SessionInterface session, Object a) {
long millis;
switch (typeCode) {
case Types.SQL_TIME :
case Types.SQL_TIME_WITH_TIME_ZONE :
millis = ((TimeData) a).getSeconds() * 1000;
return new java.sql.Time(millis);
case Types.SQL_DATE :
millis = ((TimestampData) a).getSeconds() * 1000;
return new java.sql.Date(millis);
case Types.SQL_TIMESTAMP :
case Types.SQL_TIMESTAMP_WITH_TIME_ZONE :
millis = ((TimestampData) a).getSeconds() * 1000;
java.sql.Timestamp value = new java.sql.Timestamp(millis);
value.setNanos(((TimestampData) a).getNanos());
return value;
default :
throw Error.runtimeError(ErrorCode.U_S0500, "DateTimeType");
}
} | java | public Object convertSQLToJavaGMT(SessionInterface session, Object a) {
long millis;
switch (typeCode) {
case Types.SQL_TIME :
case Types.SQL_TIME_WITH_TIME_ZONE :
millis = ((TimeData) a).getSeconds() * 1000;
return new java.sql.Time(millis);
case Types.SQL_DATE :
millis = ((TimestampData) a).getSeconds() * 1000;
return new java.sql.Date(millis);
case Types.SQL_TIMESTAMP :
case Types.SQL_TIMESTAMP_WITH_TIME_ZONE :
millis = ((TimestampData) a).getSeconds() * 1000;
java.sql.Timestamp value = new java.sql.Timestamp(millis);
value.setNanos(((TimestampData) a).getNanos());
return value;
default :
throw Error.runtimeError(ErrorCode.U_S0500, "DateTimeType");
}
} | [
"public",
"Object",
"convertSQLToJavaGMT",
"(",
"SessionInterface",
"session",
",",
"Object",
"a",
")",
"{",
"long",
"millis",
";",
"switch",
"(",
"typeCode",
")",
"{",
"case",
"Types",
".",
"SQL_TIME",
":",
"case",
"Types",
".",
"SQL_TIME_WITH_TIME_ZONE",
":"... | /*
return (Time) Type.SQL_TIME.getJavaDateObject(session, t, 0);
java.sql.Timestamp value = new java.sql.Timestamp(
(((TimestampData) o).getSeconds() - ((TimestampData) o)
.getZone()) * 1000); | [
"/",
"*",
"return",
"(",
"Time",
")",
"Type",
".",
"SQL_TIME",
".",
"getJavaDateObject",
"(",
"session",
"t",
"0",
")",
";",
"java",
".",
"sql",
".",
"Timestamp",
"value",
"=",
"new",
"java",
".",
"sql",
".",
"Timestamp",
"(",
"(((",
"TimestampData",
... | train | https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/hsqldb19b3/org/hsqldb_voltpatches/types/DateTimeType.java#L775-L805 |
apache/flink | flink-table/flink-table-planner/src/main/java/org/apache/flink/table/operations/AliasOperationUtils.java | AliasOperationUtils.createAliasList | public static List<Expression> createAliasList(List<Expression> aliases, TableOperation child) {
TableSchema childSchema = child.getTableSchema();
if (aliases.size() > childSchema.getFieldCount()) {
throw new ValidationException("Aliasing more fields than we actually have.");
}
List<ValueLiteralExpression> fieldAliases = aliases.stream()
.map(f -> f.accept(aliasLiteralValidator))
.collect(Collectors.toList());
String[] childNames = childSchema.getFieldNames();
return IntStream.range(0, childNames.length)
.mapToObj(idx -> {
UnresolvedReferenceExpression oldField = new UnresolvedReferenceExpression(childNames[idx]);
if (idx < fieldAliases.size()) {
ValueLiteralExpression alias = fieldAliases.get(idx);
return new CallExpression(BuiltInFunctionDefinitions.AS, Arrays.asList(oldField, alias));
} else {
return oldField;
}
}).collect(Collectors.toList());
} | java | public static List<Expression> createAliasList(List<Expression> aliases, TableOperation child) {
TableSchema childSchema = child.getTableSchema();
if (aliases.size() > childSchema.getFieldCount()) {
throw new ValidationException("Aliasing more fields than we actually have.");
}
List<ValueLiteralExpression> fieldAliases = aliases.stream()
.map(f -> f.accept(aliasLiteralValidator))
.collect(Collectors.toList());
String[] childNames = childSchema.getFieldNames();
return IntStream.range(0, childNames.length)
.mapToObj(idx -> {
UnresolvedReferenceExpression oldField = new UnresolvedReferenceExpression(childNames[idx]);
if (idx < fieldAliases.size()) {
ValueLiteralExpression alias = fieldAliases.get(idx);
return new CallExpression(BuiltInFunctionDefinitions.AS, Arrays.asList(oldField, alias));
} else {
return oldField;
}
}).collect(Collectors.toList());
} | [
"public",
"static",
"List",
"<",
"Expression",
">",
"createAliasList",
"(",
"List",
"<",
"Expression",
">",
"aliases",
",",
"TableOperation",
"child",
")",
"{",
"TableSchema",
"childSchema",
"=",
"child",
".",
"getTableSchema",
"(",
")",
";",
"if",
"(",
"ali... | Creates a list of valid alias expressions. Resulting expression might still contain
{@link UnresolvedReferenceExpression}.
@param aliases aliases to validate
@param child relational operation on top of which to apply the aliases
@return validated list of aliases | [
"Creates",
"a",
"list",
"of",
"valid",
"alias",
"expressions",
".",
"Resulting",
"expression",
"might",
"still",
"contain",
"{",
"@link",
"UnresolvedReferenceExpression",
"}",
"."
] | train | https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-table/flink-table-planner/src/main/java/org/apache/flink/table/operations/AliasOperationUtils.java#L55-L77 |
OpenLiberty/open-liberty | dev/com.ibm.ws.security.mp.jwt/src/com/ibm/ws/security/mp/jwt/tai/TAIRequestHelper.java | TAIRequestHelper.shouldDeferToJwtSso | private boolean shouldDeferToJwtSso(HttpServletRequest req, MicroProfileJwtConfig config, MicroProfileJwtConfig jwtssoConfig) {
if ((!isJwtSsoFeatureActive(config)) && (jwtssoConfig == null)) {
return false;
}
String hdrValue = req.getHeader(Authorization_Header);
if (tc.isDebugEnabled()) {
Tr.debug(tc, "Authorization header=", hdrValue);
}
boolean haveValidBearerHeader = (hdrValue != null && hdrValue.startsWith("Bearer "));
return !haveValidBearerHeader;
} | java | private boolean shouldDeferToJwtSso(HttpServletRequest req, MicroProfileJwtConfig config, MicroProfileJwtConfig jwtssoConfig) {
if ((!isJwtSsoFeatureActive(config)) && (jwtssoConfig == null)) {
return false;
}
String hdrValue = req.getHeader(Authorization_Header);
if (tc.isDebugEnabled()) {
Tr.debug(tc, "Authorization header=", hdrValue);
}
boolean haveValidBearerHeader = (hdrValue != null && hdrValue.startsWith("Bearer "));
return !haveValidBearerHeader;
} | [
"private",
"boolean",
"shouldDeferToJwtSso",
"(",
"HttpServletRequest",
"req",
",",
"MicroProfileJwtConfig",
"config",
",",
"MicroProfileJwtConfig",
"jwtssoConfig",
")",
"{",
"if",
"(",
"(",
"!",
"isJwtSsoFeatureActive",
"(",
"config",
")",
")",
"&&",
"(",
"jwtssoCo... | if we don't have a valid bearer header, and jwtsso is active, we should defer. | [
"if",
"we",
"don",
"t",
"have",
"a",
"valid",
"bearer",
"header",
"and",
"jwtsso",
"is",
"active",
"we",
"should",
"defer",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.security.mp.jwt/src/com/ibm/ws/security/mp/jwt/tai/TAIRequestHelper.java#L106-L118 |
mebigfatguy/fb-contrib | src/main/java/com/mebigfatguy/fbcontrib/utils/SignatureUtils.java | SignatureUtils.isWonkyEclipseSignature | private static boolean isWonkyEclipseSignature(String sig, int startIndex) {
return (sig.length() > startIndex) && (ECLIPSE_WEIRD_SIG_CHARS.indexOf(sig.charAt(startIndex)) >= 0);
} | java | private static boolean isWonkyEclipseSignature(String sig, int startIndex) {
return (sig.length() > startIndex) && (ECLIPSE_WEIRD_SIG_CHARS.indexOf(sig.charAt(startIndex)) >= 0);
} | [
"private",
"static",
"boolean",
"isWonkyEclipseSignature",
"(",
"String",
"sig",
",",
"int",
"startIndex",
")",
"{",
"return",
"(",
"sig",
".",
"length",
"(",
")",
">",
"startIndex",
")",
"&&",
"(",
"ECLIPSE_WEIRD_SIG_CHARS",
".",
"indexOf",
"(",
"sig",
".",... | Eclipse makes weird class signatures.
@param sig
the signature in type table
@param startIndex
the index into the signature where the wonkyness begins
@return if this signature has eclipse meta chars | [
"Eclipse",
"makes",
"weird",
"class",
"signatures",
"."
] | train | https://github.com/mebigfatguy/fb-contrib/blob/3b5203196f627b399fbcea3c2ab2b1f4e56cc7b8/src/main/java/com/mebigfatguy/fbcontrib/utils/SignatureUtils.java#L455-L457 |
UrielCh/ovh-java-sdk | ovh-java-sdk-dbaaslogs/src/main/java/net/minidev/ovh/api/ApiOvhDbaaslogs.java | ApiOvhDbaaslogs.serviceName_cluster_clusterId_allowedNetwork_POST | public OvhOperation serviceName_cluster_clusterId_allowedNetwork_POST(String serviceName, String clusterId, OvhClusterAllowedNetworkFlowTypeEnum flowType, String network) throws IOException {
String qPath = "/dbaas/logs/{serviceName}/cluster/{clusterId}/allowedNetwork";
StringBuilder sb = path(qPath, serviceName, clusterId);
HashMap<String, Object>o = new HashMap<String, Object>();
addBody(o, "flowType", flowType);
addBody(o, "network", network);
String resp = exec(qPath, "POST", sb.toString(), o);
return convertTo(resp, OvhOperation.class);
} | java | public OvhOperation serviceName_cluster_clusterId_allowedNetwork_POST(String serviceName, String clusterId, OvhClusterAllowedNetworkFlowTypeEnum flowType, String network) throws IOException {
String qPath = "/dbaas/logs/{serviceName}/cluster/{clusterId}/allowedNetwork";
StringBuilder sb = path(qPath, serviceName, clusterId);
HashMap<String, Object>o = new HashMap<String, Object>();
addBody(o, "flowType", flowType);
addBody(o, "network", network);
String resp = exec(qPath, "POST", sb.toString(), o);
return convertTo(resp, OvhOperation.class);
} | [
"public",
"OvhOperation",
"serviceName_cluster_clusterId_allowedNetwork_POST",
"(",
"String",
"serviceName",
",",
"String",
"clusterId",
",",
"OvhClusterAllowedNetworkFlowTypeEnum",
"flowType",
",",
"String",
"network",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
... | Allow an IP to contact cluster
REST: POST /dbaas/logs/{serviceName}/cluster/{clusterId}/allowedNetwork
@param serviceName [required] Service name
@param clusterId [required] Cluster ID
@param network [required] IP block
@param flowType [required] Flow type | [
"Allow",
"an",
"IP",
"to",
"contact",
"cluster"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-dbaaslogs/src/main/java/net/minidev/ovh/api/ApiOvhDbaaslogs.java#L158-L166 |
salesforce/Argus | ArgusWebServices/src/main/java/com/salesforce/dva/argus/ws/resources/AlertResources.java | AlertResources.updateAlert | @PUT
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@Path("/{alertId}")
@Description("Updates an alert having the given ID.")
public AlertDto updateAlert(@Context HttpServletRequest req, @PathParam("alertId") BigInteger alertId, AlertDto alertDto) {
if (alertId == null || alertId.compareTo(BigInteger.ZERO) < 1) {
throw new WebApplicationException("Alert Id cannot be null and must be a positive non-zero number.", Status.BAD_REQUEST);
}
if (alertDto == null) {
throw new WebApplicationException("Null object cannot be updated.", Status.BAD_REQUEST);
}
PrincipalUser owner = validateAndGetOwner(req, alertDto.getOwnerName());
Alert oldAlert = alertService.findAlertByPrimaryKey(alertId);
if (oldAlert == null) {
throw new WebApplicationException(Response.Status.NOT_FOUND.getReasonPhrase(), Response.Status.NOT_FOUND);
}
validateResourceAuthorization(req, oldAlert.getOwner(), owner);
copyProperties(oldAlert, alertDto);
oldAlert.setModifiedBy(getRemoteUser(req));
return AlertDto.transformToDto(alertService.updateAlert(oldAlert));
} | java | @PUT
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@Path("/{alertId}")
@Description("Updates an alert having the given ID.")
public AlertDto updateAlert(@Context HttpServletRequest req, @PathParam("alertId") BigInteger alertId, AlertDto alertDto) {
if (alertId == null || alertId.compareTo(BigInteger.ZERO) < 1) {
throw new WebApplicationException("Alert Id cannot be null and must be a positive non-zero number.", Status.BAD_REQUEST);
}
if (alertDto == null) {
throw new WebApplicationException("Null object cannot be updated.", Status.BAD_REQUEST);
}
PrincipalUser owner = validateAndGetOwner(req, alertDto.getOwnerName());
Alert oldAlert = alertService.findAlertByPrimaryKey(alertId);
if (oldAlert == null) {
throw new WebApplicationException(Response.Status.NOT_FOUND.getReasonPhrase(), Response.Status.NOT_FOUND);
}
validateResourceAuthorization(req, oldAlert.getOwner(), owner);
copyProperties(oldAlert, alertDto);
oldAlert.setModifiedBy(getRemoteUser(req));
return AlertDto.transformToDto(alertService.updateAlert(oldAlert));
} | [
"@",
"PUT",
"@",
"Produces",
"(",
"MediaType",
".",
"APPLICATION_JSON",
")",
"@",
"Consumes",
"(",
"MediaType",
".",
"APPLICATION_JSON",
")",
"@",
"Path",
"(",
"\"/{alertId}\"",
")",
"@",
"Description",
"(",
"\"Updates an alert having the given ID.\"",
")",
"publi... | Updates existing alert.
@param req The HttpServlet request object. Cannot be null.
@param alertId The id of an alert. Cannot be null.
@param alertDto The new alert object. Cannot be null.
@return Updated alert object.
@throws WebApplicationException The exception with 404 status will be thrown if the alert does not exist. | [
"Updates",
"existing",
"alert",
"."
] | train | https://github.com/salesforce/Argus/blob/121b59a268da264316cded6a3e9271366a23cd86/ArgusWebServices/src/main/java/com/salesforce/dva/argus/ws/resources/AlertResources.java#L663-L689 |
looly/hutool | hutool-core/src/main/java/cn/hutool/core/util/ArrayUtil.java | ArrayUtil.append | @SafeVarargs
public static <T> Object append(Object array, T... newElements) {
if(isEmpty(array)) {
return newElements;
}
return insert(array, length(array), newElements);
} | java | @SafeVarargs
public static <T> Object append(Object array, T... newElements) {
if(isEmpty(array)) {
return newElements;
}
return insert(array, length(array), newElements);
} | [
"@",
"SafeVarargs",
"public",
"static",
"<",
"T",
">",
"Object",
"append",
"(",
"Object",
"array",
",",
"T",
"...",
"newElements",
")",
"{",
"if",
"(",
"isEmpty",
"(",
"array",
")",
")",
"{",
"return",
"newElements",
";",
"}",
"return",
"insert",
"(",
... | 将新元素添加到已有数组中<br>
添加新元素会生成一个新的数组,不影响原数组
@param <T> 数组元素类型
@param array 已有数组
@param newElements 新元素
@return 新数组 | [
"将新元素添加到已有数组中<br",
">",
"添加新元素会生成一个新的数组,不影响原数组"
] | train | https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/util/ArrayUtil.java#L399-L405 |
aNNiMON/Lightweight-Stream-API | stream/src/main/java/com/annimon/stream/Stream.java | Stream.mapToDouble | @NotNull
public DoubleStream mapToDouble(@NotNull final ToDoubleFunction<? super T> mapper) {
return new DoubleStream(params, new ObjMapToDouble<T>(iterator, mapper));
} | java | @NotNull
public DoubleStream mapToDouble(@NotNull final ToDoubleFunction<? super T> mapper) {
return new DoubleStream(params, new ObjMapToDouble<T>(iterator, mapper));
} | [
"@",
"NotNull",
"public",
"DoubleStream",
"mapToDouble",
"(",
"@",
"NotNull",
"final",
"ToDoubleFunction",
"<",
"?",
"super",
"T",
">",
"mapper",
")",
"{",
"return",
"new",
"DoubleStream",
"(",
"params",
",",
"new",
"ObjMapToDouble",
"<",
"T",
">",
"(",
"i... | Returns {@code DoubleStream} with elements that obtained by applying the given function.
<p>This is an intermediate operation.
@param mapper the mapper function used to apply to each element
@return the new {@code DoubleStream}
@since 1.1.4
@see #map(com.annimon.stream.function.Function) | [
"Returns",
"{",
"@code",
"DoubleStream",
"}",
"with",
"elements",
"that",
"obtained",
"by",
"applying",
"the",
"given",
"function",
"."
] | train | https://github.com/aNNiMON/Lightweight-Stream-API/blob/f29fd57208c20252a4549b084d55ed082c3e58f0/stream/src/main/java/com/annimon/stream/Stream.java#L841-L844 |
moparisthebest/beehive | beehive-netui-tags/src/main/java/org/apache/beehive/netui/tags/javascript/ScriptContainer.java | ScriptContainer.addTagIdMappings | public void addTagIdMappings(String tagId, String realId, String realName)
{
assert (tagId != null) : "The parameter 'tagId' must not be null";
assert (realId != null) : "The parameter 'realId' must not be null";
_writeId = true;
if (realName != null) {
if (_idToNameMap == null)
_idToNameMap = new HashMap/*<String, String>*/();
_idToNameMap.put(tagId, realName);
}
} | java | public void addTagIdMappings(String tagId, String realId, String realName)
{
assert (tagId != null) : "The parameter 'tagId' must not be null";
assert (realId != null) : "The parameter 'realId' must not be null";
_writeId = true;
if (realName != null) {
if (_idToNameMap == null)
_idToNameMap = new HashMap/*<String, String>*/();
_idToNameMap.put(tagId, realName);
}
} | [
"public",
"void",
"addTagIdMappings",
"(",
"String",
"tagId",
",",
"String",
"realId",
",",
"String",
"realName",
")",
"{",
"assert",
"(",
"tagId",
"!=",
"null",
")",
":",
"\"The parameter 'tagId' must not be null\"",
";",
"assert",
"(",
"realId",
"!=",
"null",
... | This will add the mapping between the tagId and the real name to the NameMap hashmap.
@param tagId
@param realId
@param realName | [
"This",
"will",
"add",
"the",
"mapping",
"between",
"the",
"tagId",
"and",
"the",
"real",
"name",
"to",
"the",
"NameMap",
"hashmap",
"."
] | train | https://github.com/moparisthebest/beehive/blob/4246a0cc40ce3c05f1a02c2da2653ac622703d77/beehive-netui-tags/src/main/java/org/apache/beehive/netui/tags/javascript/ScriptContainer.java#L161-L173 |
vatbub/common | updater/src/main/java/com/github/vatbub/common/updater/UpdateChecker.java | UpdateChecker.isUpdateAvailable | public static UpdateInfo isUpdateAvailable(URL repoBaseURL, String mavenGroupID, String mavenArtifactID,
String mavenClassifier) {
return isUpdateAvailable(repoBaseURL, mavenGroupID, mavenArtifactID, mavenClassifier, "jar");
} | java | public static UpdateInfo isUpdateAvailable(URL repoBaseURL, String mavenGroupID, String mavenArtifactID,
String mavenClassifier) {
return isUpdateAvailable(repoBaseURL, mavenGroupID, mavenArtifactID, mavenClassifier, "jar");
} | [
"public",
"static",
"UpdateInfo",
"isUpdateAvailable",
"(",
"URL",
"repoBaseURL",
",",
"String",
"mavenGroupID",
",",
"String",
"mavenArtifactID",
",",
"String",
"mavenClassifier",
")",
"{",
"return",
"isUpdateAvailable",
"(",
"repoBaseURL",
",",
"mavenGroupID",
",",
... | Checks if a new release has been published on the website. This does not
compare the current app version to the release version on the website,
just checks if something happened on the website. This ensures that
updates that were ignored by the user do not show up again. Assumes that
the artifact has a jar-packaging.
@param repoBaseURL The base url of the maven repo to use
@param mavenGroupID The maven groupId of the artifact to update
@param mavenArtifactID The maven artifactId of the artifact to update
@param mavenClassifier The maven classifier of the artifact to update
@return {@code true} if a new release is available and the user did not
ignore it. | [
"Checks",
"if",
"a",
"new",
"release",
"has",
"been",
"published",
"on",
"the",
"website",
".",
"This",
"does",
"not",
"compare",
"the",
"current",
"app",
"version",
"to",
"the",
"release",
"version",
"on",
"the",
"website",
"just",
"checks",
"if",
"someth... | train | https://github.com/vatbub/common/blob/8b9fd2ece0a23d520ce53b66c84cbd094e378443/updater/src/main/java/com/github/vatbub/common/updater/UpdateChecker.java#L104-L107 |
TheHortonMachine/hortonmachine | apps/src/main/java/org/hortonmachine/database/SqlDocument.java | SqlDocument.commentLinesBefore | private boolean commentLinesBefore( String content, int line ) {
int offset = rootElement.getElement(line).getStartOffset();
// Start of comment not found, nothing to do
int startDelimiter = lastIndexOf(content, getStartDelimiter(), offset - 2);
if (startDelimiter < 0)
return false;
// Matching start/end of comment found, nothing to do
int endDelimiter = indexOf(content, getEndDelimiter(), startDelimiter);
if (endDelimiter < offset & endDelimiter != -1)
return false;
// End of comment not found, highlight the lines
doc.setCharacterAttributes(startDelimiter, offset - startDelimiter + 1, comment, false);
return true;
} | java | private boolean commentLinesBefore( String content, int line ) {
int offset = rootElement.getElement(line).getStartOffset();
// Start of comment not found, nothing to do
int startDelimiter = lastIndexOf(content, getStartDelimiter(), offset - 2);
if (startDelimiter < 0)
return false;
// Matching start/end of comment found, nothing to do
int endDelimiter = indexOf(content, getEndDelimiter(), startDelimiter);
if (endDelimiter < offset & endDelimiter != -1)
return false;
// End of comment not found, highlight the lines
doc.setCharacterAttributes(startDelimiter, offset - startDelimiter + 1, comment, false);
return true;
} | [
"private",
"boolean",
"commentLinesBefore",
"(",
"String",
"content",
",",
"int",
"line",
")",
"{",
"int",
"offset",
"=",
"rootElement",
".",
"getElement",
"(",
"line",
")",
".",
"getStartOffset",
"(",
")",
";",
"// Start of comment not found, nothing to do",
"int... | /*
Highlight lines when a multi line comment is still 'open'
(ie. matching end delimiter has not yet been encountered) | [
"/",
"*",
"Highlight",
"lines",
"when",
"a",
"multi",
"line",
"comment",
"is",
"still",
"open",
"(",
"ie",
".",
"matching",
"end",
"delimiter",
"has",
"not",
"yet",
"been",
"encountered",
")"
] | train | https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/apps/src/main/java/org/hortonmachine/database/SqlDocument.java#L128-L141 |
couchbase/couchbase-java-client | src/main/java/com/couchbase/client/java/query/dsl/functions/Collections.java | Collections.everyIn | public static SatisfiesBuilder everyIn(String variable, Expression expression) {
return new SatisfiesBuilder(x("EVERY"), variable, expression, true);
} | java | public static SatisfiesBuilder everyIn(String variable, Expression expression) {
return new SatisfiesBuilder(x("EVERY"), variable, expression, true);
} | [
"public",
"static",
"SatisfiesBuilder",
"everyIn",
"(",
"String",
"variable",
",",
"Expression",
"expression",
")",
"{",
"return",
"new",
"SatisfiesBuilder",
"(",
"x",
"(",
"\"EVERY\"",
")",
",",
"variable",
",",
"expression",
",",
"true",
")",
";",
"}"
] | Create an EVERY comprehension with a first IN range.
EVERY is a range predicate that allows you to test a Boolean condition over the elements or attributes of a
collection, object, or objects. It uses the IN and WITHIN operators to range through the collection.
IN ranges in the direct elements of its array expression, WITHIN also ranges in its descendants.
If every array element satisfies the EVERY expression, it returns TRUE. Otherwise it returns FALSE.
If the array is empty, it returns TRUE. | [
"Create",
"an",
"EVERY",
"comprehension",
"with",
"a",
"first",
"IN",
"range",
"."
] | train | https://github.com/couchbase/couchbase-java-client/blob/f36a0ee0c66923bdde47838ca543e50cbaa99e14/src/main/java/com/couchbase/client/java/query/dsl/functions/Collections.java#L199-L201 |
netty/netty | handler/src/main/java/io/netty/handler/ssl/ReferenceCountedOpenSslContext.java | ReferenceCountedOpenSslContext.providerFor | static OpenSslKeyMaterialProvider providerFor(KeyManagerFactory factory, String password) {
if (factory instanceof OpenSslX509KeyManagerFactory) {
return ((OpenSslX509KeyManagerFactory) factory).newProvider();
}
X509KeyManager keyManager = chooseX509KeyManager(factory.getKeyManagers());
if (factory instanceof OpenSslCachingX509KeyManagerFactory) {
// The user explicit used OpenSslCachingX509KeyManagerFactory which signals us that its fine to cache.
return new OpenSslCachingKeyMaterialProvider(keyManager, password);
}
// We can not be sure if the material may change at runtime so we will not cache it.
return new OpenSslKeyMaterialProvider(keyManager, password);
} | java | static OpenSslKeyMaterialProvider providerFor(KeyManagerFactory factory, String password) {
if (factory instanceof OpenSslX509KeyManagerFactory) {
return ((OpenSslX509KeyManagerFactory) factory).newProvider();
}
X509KeyManager keyManager = chooseX509KeyManager(factory.getKeyManagers());
if (factory instanceof OpenSslCachingX509KeyManagerFactory) {
// The user explicit used OpenSslCachingX509KeyManagerFactory which signals us that its fine to cache.
return new OpenSslCachingKeyMaterialProvider(keyManager, password);
}
// We can not be sure if the material may change at runtime so we will not cache it.
return new OpenSslKeyMaterialProvider(keyManager, password);
} | [
"static",
"OpenSslKeyMaterialProvider",
"providerFor",
"(",
"KeyManagerFactory",
"factory",
",",
"String",
"password",
")",
"{",
"if",
"(",
"factory",
"instanceof",
"OpenSslX509KeyManagerFactory",
")",
"{",
"return",
"(",
"(",
"OpenSslX509KeyManagerFactory",
")",
"facto... | Returns the {@link OpenSslKeyMaterialProvider} that should be used for OpenSSL. Depending on the given
{@link KeyManagerFactory} this may cache the {@link OpenSslKeyMaterial} for better performance if it can
ensure that the same material is always returned for the same alias. | [
"Returns",
"the",
"{"
] | train | https://github.com/netty/netty/blob/ba06eafa1c1824bd154f1a380019e7ea2edf3c4c/handler/src/main/java/io/netty/handler/ssl/ReferenceCountedOpenSslContext.java#L899-L911 |
threerings/nenya | core/src/main/java/com/threerings/resource/ResourceManager.java | ResourceManager.getResource | public InputStream getResource (String rset, String path)
throws IOException
{
// grab the resource bundles in the specified resource set
ResourceBundle[] bundles = getResourceSet(rset);
if (bundles == null) {
throw new FileNotFoundException(
"Unable to locate resource [set=" + rset + ", path=" + path + "]");
}
String localePath = getLocalePath(path);
// look for the resource in any of the bundles
for (ResourceBundle bundle : bundles) {
InputStream in;
// Try a localized version first.
if (localePath != null) {
in = bundle.getResource(localePath);
if (in != null) {
return in;
}
}
// If we didn't find that, try a generic.
in = bundle.getResource(path);
if (in != null) {
return in;
}
}
throw new FileNotFoundException(
"Unable to locate resource [set=" + rset + ", path=" + path + "]");
} | java | public InputStream getResource (String rset, String path)
throws IOException
{
// grab the resource bundles in the specified resource set
ResourceBundle[] bundles = getResourceSet(rset);
if (bundles == null) {
throw new FileNotFoundException(
"Unable to locate resource [set=" + rset + ", path=" + path + "]");
}
String localePath = getLocalePath(path);
// look for the resource in any of the bundles
for (ResourceBundle bundle : bundles) {
InputStream in;
// Try a localized version first.
if (localePath != null) {
in = bundle.getResource(localePath);
if (in != null) {
return in;
}
}
// If we didn't find that, try a generic.
in = bundle.getResource(path);
if (in != null) {
return in;
}
}
throw new FileNotFoundException(
"Unable to locate resource [set=" + rset + ", path=" + path + "]");
} | [
"public",
"InputStream",
"getResource",
"(",
"String",
"rset",
",",
"String",
"path",
")",
"throws",
"IOException",
"{",
"// grab the resource bundles in the specified resource set",
"ResourceBundle",
"[",
"]",
"bundles",
"=",
"getResourceSet",
"(",
"rset",
")",
";",
... | Returns an input stream from which the requested resource can be loaded. <em>Note:</em> this
performs a linear search of all of the bundles in the set and returns the first resource
found with the specified path, thus it is not extremely efficient and will behave
unexpectedly if you use the same paths in different resource bundles.
@exception FileNotFoundException thrown if the resource could not be located in any of the
bundles in the specified set, or if the specified set does not exist.
@exception IOException thrown if a problem occurs locating or reading the resource. | [
"Returns",
"an",
"input",
"stream",
"from",
"which",
"the",
"requested",
"resource",
"can",
"be",
"loaded",
".",
"<em",
">",
"Note",
":",
"<",
"/",
"em",
">",
"this",
"performs",
"a",
"linear",
"search",
"of",
"all",
"of",
"the",
"bundles",
"in",
"the"... | train | https://github.com/threerings/nenya/blob/3165a012fd859009db3367f87bd2a5b820cc760a/core/src/main/java/com/threerings/resource/ResourceManager.java#L641-L671 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.