repository_name stringlengths 7 58 | func_path_in_repository stringlengths 18 188 | func_name stringlengths 7 127 | whole_func_string stringlengths 77 3.91k | language stringclasses 1
value | func_code_string stringlengths 77 3.91k | func_code_tokens listlengths 20 745 | func_documentation_string stringlengths 61 1.98k | func_documentation_tokens listlengths 1 477 | split_name stringclasses 1
value | func_code_url stringlengths 111 288 |
|---|---|---|---|---|---|---|---|---|---|---|
lessthanoptimal/BoofCV | main/boofcv-feature/src/main/java/boofcv/factory/feature/detect/interest/FactoryDetectPoint.java | FactoryDetectPoint.createFast | @SuppressWarnings("UnnecessaryLocalVariable")
public static <T extends ImageGray<T>, D extends ImageGray<D>>
GeneralFeatureDetector<T, D> createFast( @Nullable ConfigFastCorner configFast ,
ConfigGeneralDetector configDetector , Class<T> imageType) {
if( configFast == null )
configFast = new ConfigFastCorner();
configFast.checkValidity();
FastCornerDetector<T> alg = FactoryIntensityPointAlg.fast(configFast.pixelTol, configFast.minContinuous, imageType);
alg.setMaxFeaturesFraction(configFast.maxFeatures);
GeneralFeatureIntensity<T, D> intensity = new WrapperFastCornerIntensity<>(alg);
return createGeneral(intensity, configDetector);
} | java | @SuppressWarnings("UnnecessaryLocalVariable")
public static <T extends ImageGray<T>, D extends ImageGray<D>>
GeneralFeatureDetector<T, D> createFast( @Nullable ConfigFastCorner configFast ,
ConfigGeneralDetector configDetector , Class<T> imageType) {
if( configFast == null )
configFast = new ConfigFastCorner();
configFast.checkValidity();
FastCornerDetector<T> alg = FactoryIntensityPointAlg.fast(configFast.pixelTol, configFast.minContinuous, imageType);
alg.setMaxFeaturesFraction(configFast.maxFeatures);
GeneralFeatureIntensity<T, D> intensity = new WrapperFastCornerIntensity<>(alg);
return createGeneral(intensity, configDetector);
} | [
"@",
"SuppressWarnings",
"(",
"\"UnnecessaryLocalVariable\"",
")",
"public",
"static",
"<",
"T",
"extends",
"ImageGray",
"<",
"T",
">",
",",
"D",
"extends",
"ImageGray",
"<",
"D",
">",
">",
"GeneralFeatureDetector",
"<",
"T",
",",
"D",
">",
"createFast",
"("... | Creates a Fast corner detector with feature intensity for additional pruning. Fast features
have minimums and maximums.
@param configFast Configuration for FAST feature detector
@param configDetector Configuration for feature extractor.
@param imageType ype of input image.
@see FastCornerDetector | [
"Creates",
"a",
"Fast",
"corner",
"detector",
"with",
"feature",
"intensity",
"for",
"additional",
"pruning",
".",
"Fast",
"features",
"have",
"minimums",
"and",
"maximums",
"."
] | train | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-feature/src/main/java/boofcv/factory/feature/detect/interest/FactoryDetectPoint.java#L128-L141 |
UrielCh/ovh-java-sdk | ovh-java-sdk-order/src/main/java/net/minidev/ovh/api/ApiOvhOrder.java | ApiOvhOrder.hosting_web_new_duration_POST | public OvhOrder hosting_web_new_duration_POST(String duration, OvhDnsZoneEnum dnsZone, String domain, OvhOrderableNameEnum module, net.minidev.ovh.api.hosting.web.OvhOfferEnum offer, Boolean waiveRetractationPeriod) throws IOException {
String qPath = "/order/hosting/web/new/{duration}";
StringBuilder sb = path(qPath, duration);
HashMap<String, Object>o = new HashMap<String, Object>();
addBody(o, "dnsZone", dnsZone);
addBody(o, "domain", domain);
addBody(o, "module", module);
addBody(o, "offer", offer);
addBody(o, "waiveRetractationPeriod", waiveRetractationPeriod);
String resp = exec(qPath, "POST", sb.toString(), o);
return convertTo(resp, OvhOrder.class);
} | java | public OvhOrder hosting_web_new_duration_POST(String duration, OvhDnsZoneEnum dnsZone, String domain, OvhOrderableNameEnum module, net.minidev.ovh.api.hosting.web.OvhOfferEnum offer, Boolean waiveRetractationPeriod) throws IOException {
String qPath = "/order/hosting/web/new/{duration}";
StringBuilder sb = path(qPath, duration);
HashMap<String, Object>o = new HashMap<String, Object>();
addBody(o, "dnsZone", dnsZone);
addBody(o, "domain", domain);
addBody(o, "module", module);
addBody(o, "offer", offer);
addBody(o, "waiveRetractationPeriod", waiveRetractationPeriod);
String resp = exec(qPath, "POST", sb.toString(), o);
return convertTo(resp, OvhOrder.class);
} | [
"public",
"OvhOrder",
"hosting_web_new_duration_POST",
"(",
"String",
"duration",
",",
"OvhDnsZoneEnum",
"dnsZone",
",",
"String",
"domain",
",",
"OvhOrderableNameEnum",
"module",
",",
"net",
".",
"minidev",
".",
"ovh",
".",
"api",
".",
"hosting",
".",
"web",
".... | Create order
REST: POST /order/hosting/web/new/{duration}
@param domain [required] Domain name which will be linked to this hosting account
@param module [required] Module installation ready to use
@param dnsZone [required] Dns zone modification possibilities ( by default : RESET_ALL )
@param offer [required] Offer for your new hosting account
@param waiveRetractationPeriod [required] Indicates that order will be processed with waiving retractation period
@param duration [required] Duration | [
"Create",
"order"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-order/src/main/java/net/minidev/ovh/api/ApiOvhOrder.java#L4732-L4743 |
samskivert/samskivert | src/main/java/com/samskivert/util/ByteEnumUtil.java | ByteEnumUtil.fromByte | public static <E extends Enum<E> & ByteEnum> E fromByte (Class<E> eclass, byte code)
{
for (E value : eclass.getEnumConstants()) {
if (value.toByte() == code) {
return value;
}
}
throw new IllegalArgumentException(eclass + " has no value with code " + code);
} | java | public static <E extends Enum<E> & ByteEnum> E fromByte (Class<E> eclass, byte code)
{
for (E value : eclass.getEnumConstants()) {
if (value.toByte() == code) {
return value;
}
}
throw new IllegalArgumentException(eclass + " has no value with code " + code);
} | [
"public",
"static",
"<",
"E",
"extends",
"Enum",
"<",
"E",
">",
"&",
"ByteEnum",
">",
"E",
"fromByte",
"(",
"Class",
"<",
"E",
">",
"eclass",
",",
"byte",
"code",
")",
"{",
"for",
"(",
"E",
"value",
":",
"eclass",
".",
"getEnumConstants",
"(",
")",... | Returns the enum value with the specified code in the supplied enum class.
@exception IllegalArgumentException thrown if the enum lacks a value that maps to the
supplied code. | [
"Returns",
"the",
"enum",
"value",
"with",
"the",
"specified",
"code",
"in",
"the",
"supplied",
"enum",
"class",
"."
] | train | https://github.com/samskivert/samskivert/blob/a64d9ef42b69819bdb2c66bddac6a64caef928b6/src/main/java/com/samskivert/util/ByteEnumUtil.java#L22-L30 |
JodaOrg/joda-time | src/main/java/org/joda/time/chrono/GJDayOfWeekDateTimeField.java | GJDayOfWeekDateTimeField.getAsShortText | public String getAsShortText(int fieldValue, Locale locale) {
return GJLocaleSymbols.forLocale(locale).dayOfWeekValueToShortText(fieldValue);
} | java | public String getAsShortText(int fieldValue, Locale locale) {
return GJLocaleSymbols.forLocale(locale).dayOfWeekValueToShortText(fieldValue);
} | [
"public",
"String",
"getAsShortText",
"(",
"int",
"fieldValue",
",",
"Locale",
"locale",
")",
"{",
"return",
"GJLocaleSymbols",
".",
"forLocale",
"(",
"locale",
")",
".",
"dayOfWeekValueToShortText",
"(",
"fieldValue",
")",
";",
"}"
] | Get the abbreviated textual value of the specified time instant.
@param fieldValue the field value to query
@param locale the locale to use
@return the day of the week, such as 'Mon' | [
"Get",
"the",
"abbreviated",
"textual",
"value",
"of",
"the",
"specified",
"time",
"instant",
"."
] | train | https://github.com/JodaOrg/joda-time/blob/bd79f1c4245e79b3c2c56d7b04fde2a6e191fa42/src/main/java/org/joda/time/chrono/GJDayOfWeekDateTimeField.java#L78-L80 |
jbundle/jbundle | app/program/demo/src/main/java/org/jbundle/app/program/demo/BaseRegistrationScreen.java | BaseRegistrationScreen.doCommand | public boolean doCommand(String strCommand, ScreenField sourceSField, int iCommandOptions)
{
boolean bSuccess = super.doCommand(strCommand, sourceSField, iCommandOptions);
if (MenuConstants.SUBMIT.equalsIgnoreCase(strCommand))
if (bSuccess)
{
//this.setupUserInfo(); // Success, set up their databases
}
return bSuccess;
} | java | public boolean doCommand(String strCommand, ScreenField sourceSField, int iCommandOptions)
{
boolean bSuccess = super.doCommand(strCommand, sourceSField, iCommandOptions);
if (MenuConstants.SUBMIT.equalsIgnoreCase(strCommand))
if (bSuccess)
{
//this.setupUserInfo(); // Success, set up their databases
}
return bSuccess;
} | [
"public",
"boolean",
"doCommand",
"(",
"String",
"strCommand",
",",
"ScreenField",
"sourceSField",
",",
"int",
"iCommandOptions",
")",
"{",
"boolean",
"bSuccess",
"=",
"super",
".",
"doCommand",
"(",
"strCommand",
",",
"sourceSField",
",",
"iCommandOptions",
")",
... | Process the command.
<br />Step 1 - Process the command if possible and return true if processed.
<br />Step 2 - If I can't process, pass to all children (with me as the source).
<br />Step 3 - If children didn't process, pass to parent (with me as the source).
<br />Note: Never pass to a parent or child that matches the source (to avoid an endless loop).
@param strCommand The command to process.
@param sourceSField The source screen field (to avoid echos).
@param iCommandOptions If this command creates a new screen, create in a new window?
@return true if success. | [
"Process",
"the",
"command",
".",
"<br",
"/",
">",
"Step",
"1",
"-",
"Process",
"the",
"command",
"if",
"possible",
"and",
"return",
"true",
"if",
"processed",
".",
"<br",
"/",
">",
"Step",
"2",
"-",
"If",
"I",
"can",
"t",
"process",
"pass",
"to",
... | train | https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/app/program/demo/src/main/java/org/jbundle/app/program/demo/BaseRegistrationScreen.java#L141-L150 |
hankcs/HanLP | src/main/java/com/hankcs/hanlp/model/perceptron/cli/Args.java | Args.byStaticMethodInvocation | public static ValueCreator byStaticMethodInvocation(final Class<?> compatibleType, final String methodName)
{
return new ValueCreator()
{
public Object createValue(Class<?> type, String value)
{
Object v = null;
if (compatibleType.isAssignableFrom(type))
{
try
{
Method m = type.getMethod(methodName, String.class);
return m.invoke(null, value);
}
catch (NoSuchMethodException e)
{
// ignore
}
catch (Exception e)
{
throw new IllegalArgumentException(String.format("could not invoke %s#%s to create an obejct from %s", type.toString(), methodName, value));
}
}
return v;
}
};
} | java | public static ValueCreator byStaticMethodInvocation(final Class<?> compatibleType, final String methodName)
{
return new ValueCreator()
{
public Object createValue(Class<?> type, String value)
{
Object v = null;
if (compatibleType.isAssignableFrom(type))
{
try
{
Method m = type.getMethod(methodName, String.class);
return m.invoke(null, value);
}
catch (NoSuchMethodException e)
{
// ignore
}
catch (Exception e)
{
throw new IllegalArgumentException(String.format("could not invoke %s#%s to create an obejct from %s", type.toString(), methodName, value));
}
}
return v;
}
};
} | [
"public",
"static",
"ValueCreator",
"byStaticMethodInvocation",
"(",
"final",
"Class",
"<",
"?",
">",
"compatibleType",
",",
"final",
"String",
"methodName",
")",
"{",
"return",
"new",
"ValueCreator",
"(",
")",
"{",
"public",
"Object",
"createValue",
"(",
"Class... | Creates a {@link ValueCreator} object able to create object assignable from given type,
using a static one arg method which name is the the given one taking a String object as parameter
@param compatibleType the base assignable for which this object will try to invoke the given method
@param methodName the name of the one arg method taking a String as parameter that will be used to built a new value
@return null if the object could not be created, the value otherwise | [
"Creates",
"a",
"{",
"@link",
"ValueCreator",
"}",
"object",
"able",
"to",
"create",
"object",
"assignable",
"from",
"given",
"type",
"using",
"a",
"static",
"one",
"arg",
"method",
"which",
"name",
"is",
"the",
"the",
"given",
"one",
"taking",
"a",
"Strin... | train | https://github.com/hankcs/HanLP/blob/a538d0722ab2e4980a9dcd9ea40324fc3ddba7ce/src/main/java/com/hankcs/hanlp/model/perceptron/cli/Args.java#L599-L625 |
ZieIony/Carbon | carbon/src/main/java/carbon/internal/Menu.java | Menu.findItemsWithShortcutForKey | @SuppressWarnings("deprecation")
void findItemsWithShortcutForKey(List<MenuItem> items, int keyCode, KeyEvent event) {
final boolean qwerty = isQwertyMode();
final int metaState = event.getMetaState();
final KeyCharacterMap.KeyData possibleChars = new KeyCharacterMap.KeyData();
// Get the chars associated with the keyCode (i.e using any chording combo)
final boolean isKeyCodeMapped = event.getKeyData(possibleChars);
// The delete key is not mapped to '\b' so we treat it specially
if (!isKeyCodeMapped && (keyCode != KeyEvent.KEYCODE_DEL)) {
return;
}
// Look for an item whose shortcut is this key.
final int N = mItems.size();
for (int i = 0; i < N; i++) {
MenuItem item = mItems.get(i);
if (item.hasSubMenu()) {
((Menu) item.getSubMenu()).findItemsWithShortcutForKey(items, keyCode, event);
}
final char shortcutChar = qwerty ? item.getAlphabeticShortcut() : item.getNumericShortcut();
if (((metaState & (KeyEvent.META_SHIFT_ON | KeyEvent.META_SYM_ON)) == 0) &&
(shortcutChar != 0) &&
(shortcutChar == possibleChars.meta[0]
|| shortcutChar == possibleChars.meta[2]
|| (qwerty && shortcutChar == '\b' &&
keyCode == KeyEvent.KEYCODE_DEL)) &&
item.isEnabled()) {
items.add(item);
}
}
} | java | @SuppressWarnings("deprecation")
void findItemsWithShortcutForKey(List<MenuItem> items, int keyCode, KeyEvent event) {
final boolean qwerty = isQwertyMode();
final int metaState = event.getMetaState();
final KeyCharacterMap.KeyData possibleChars = new KeyCharacterMap.KeyData();
// Get the chars associated with the keyCode (i.e using any chording combo)
final boolean isKeyCodeMapped = event.getKeyData(possibleChars);
// The delete key is not mapped to '\b' so we treat it specially
if (!isKeyCodeMapped && (keyCode != KeyEvent.KEYCODE_DEL)) {
return;
}
// Look for an item whose shortcut is this key.
final int N = mItems.size();
for (int i = 0; i < N; i++) {
MenuItem item = mItems.get(i);
if (item.hasSubMenu()) {
((Menu) item.getSubMenu()).findItemsWithShortcutForKey(items, keyCode, event);
}
final char shortcutChar = qwerty ? item.getAlphabeticShortcut() : item.getNumericShortcut();
if (((metaState & (KeyEvent.META_SHIFT_ON | KeyEvent.META_SYM_ON)) == 0) &&
(shortcutChar != 0) &&
(shortcutChar == possibleChars.meta[0]
|| shortcutChar == possibleChars.meta[2]
|| (qwerty && shortcutChar == '\b' &&
keyCode == KeyEvent.KEYCODE_DEL)) &&
item.isEnabled()) {
items.add(item);
}
}
} | [
"@",
"SuppressWarnings",
"(",
"\"deprecation\"",
")",
"void",
"findItemsWithShortcutForKey",
"(",
"List",
"<",
"MenuItem",
">",
"items",
",",
"int",
"keyCode",
",",
"KeyEvent",
"event",
")",
"{",
"final",
"boolean",
"qwerty",
"=",
"isQwertyMode",
"(",
")",
";"... | /*
This function will return all the menu and sub-menu items that can
be directly (the shortcut directly corresponds) and indirectly
(the ALT-enabled char corresponds to the shortcut) associated
with the keyCode. | [
"/",
"*",
"This",
"function",
"will",
"return",
"all",
"the",
"menu",
"and",
"sub",
"-",
"menu",
"items",
"that",
"can",
"be",
"directly",
"(",
"the",
"shortcut",
"directly",
"corresponds",
")",
"and",
"indirectly",
"(",
"the",
"ALT",
"-",
"enabled",
"ch... | train | https://github.com/ZieIony/Carbon/blob/78b0a432bd49edc7a6a13ce111cab274085d1693/carbon/src/main/java/carbon/internal/Menu.java#L624-L654 |
io7m/jaffirm | com.io7m.jaffirm.core/src/main/java/com/io7m/jaffirm/core/Invariants.java | Invariants.checkInvariant | public static <T> T checkInvariant(
final T value,
final Predicate<T> predicate,
final Function<T, String> describer)
{
final boolean ok;
try {
ok = predicate.test(value);
} catch (final Throwable e) {
final Violations violations = singleViolation(failedPredicate(e));
throw new InvariantViolationException(
failedMessage(value, violations), e, violations.count());
}
return innerCheckInvariant(value, ok, describer);
} | java | public static <T> T checkInvariant(
final T value,
final Predicate<T> predicate,
final Function<T, String> describer)
{
final boolean ok;
try {
ok = predicate.test(value);
} catch (final Throwable e) {
final Violations violations = singleViolation(failedPredicate(e));
throw new InvariantViolationException(
failedMessage(value, violations), e, violations.count());
}
return innerCheckInvariant(value, ok, describer);
} | [
"public",
"static",
"<",
"T",
">",
"T",
"checkInvariant",
"(",
"final",
"T",
"value",
",",
"final",
"Predicate",
"<",
"T",
">",
"predicate",
",",
"final",
"Function",
"<",
"T",
",",
"String",
">",
"describer",
")",
"{",
"final",
"boolean",
"ok",
";",
... | <p>Evaluate the given {@code predicate} using {@code value} as input.</p>
<p>The function throws {@link InvariantViolationException} if the predicate
is false.</p>
@param value The value
@param predicate The predicate
@param describer A describer for the predicate
@param <T> The type of values
@return value
@throws InvariantViolationException If the predicate is false | [
"<p",
">",
"Evaluate",
"the",
"given",
"{",
"@code",
"predicate",
"}",
"using",
"{",
"@code",
"value",
"}",
"as",
"input",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/io7m/jaffirm/blob/c97d246242d381e48832838737418cfe4cb57b4d/com.io7m.jaffirm.core/src/main/java/com/io7m/jaffirm/core/Invariants.java#L204-L219 |
infinispan/infinispan | core/src/main/java/org/infinispan/transaction/impl/TransactionTable.java | TransactionTable.remoteTransactionCommitted | public void remoteTransactionCommitted(GlobalTransaction gtx, boolean onePc) {
boolean optimisticWih1Pc = onePc && (configuration.transaction().lockingMode() == LockingMode.OPTIMISTIC);
if (configuration.transaction().transactionProtocol().isTotalOrder() || optimisticWih1Pc) {
removeRemoteTransaction(gtx);
}
} | java | public void remoteTransactionCommitted(GlobalTransaction gtx, boolean onePc) {
boolean optimisticWih1Pc = onePc && (configuration.transaction().lockingMode() == LockingMode.OPTIMISTIC);
if (configuration.transaction().transactionProtocol().isTotalOrder() || optimisticWih1Pc) {
removeRemoteTransaction(gtx);
}
} | [
"public",
"void",
"remoteTransactionCommitted",
"(",
"GlobalTransaction",
"gtx",
",",
"boolean",
"onePc",
")",
"{",
"boolean",
"optimisticWih1Pc",
"=",
"onePc",
"&&",
"(",
"configuration",
".",
"transaction",
"(",
")",
".",
"lockingMode",
"(",
")",
"==",
"Lockin... | Removes the {@link RemoteTransaction} corresponding to the given tx. | [
"Removes",
"the",
"{"
] | train | https://github.com/infinispan/infinispan/blob/7c62b94886c3febb4774ae8376acf2baa0265ab5/core/src/main/java/org/infinispan/transaction/impl/TransactionTable.java#L482-L487 |
LevelFourAB/commons | commons-config/src/main/java/se/l4/commons/config/internal/RawFormatReader.java | RawFormatReader.readDynamic | private static Object readDynamic(StreamingInput input)
throws IOException
{
switch(input.peek())
{
case VALUE:
input.next();
return input.getValue();
case NULL:
input.next();
return input.getValue();
case LIST_START:
return readList(input);
case OBJECT_START:
return readMap(input);
}
throw new SerializationException("Unable to read file, unknown start of value: " + input.peek());
} | java | private static Object readDynamic(StreamingInput input)
throws IOException
{
switch(input.peek())
{
case VALUE:
input.next();
return input.getValue();
case NULL:
input.next();
return input.getValue();
case LIST_START:
return readList(input);
case OBJECT_START:
return readMap(input);
}
throw new SerializationException("Unable to read file, unknown start of value: " + input.peek());
} | [
"private",
"static",
"Object",
"readDynamic",
"(",
"StreamingInput",
"input",
")",
"throws",
"IOException",
"{",
"switch",
"(",
"input",
".",
"peek",
"(",
")",
")",
"{",
"case",
"VALUE",
":",
"input",
".",
"next",
"(",
")",
";",
"return",
"input",
".",
... | Depending on the next token read either a value, a list or a map.
@param input
@return
@throws IOException | [
"Depending",
"on",
"the",
"next",
"token",
"read",
"either",
"a",
"value",
"a",
"list",
"or",
"a",
"map",
"."
] | train | https://github.com/LevelFourAB/commons/blob/aa121b3a5504b43d0c10450a1b984694fcd2b8ee/commons-config/src/main/java/se/l4/commons/config/internal/RawFormatReader.java#L145-L163 |
wisdom-framework/wisdom | core/wisdom-maven-plugin/src/main/java/org/wisdom/maven/node/NPM.java | NPM.findExecutable | public File findExecutable(String binary) throws IOException, ParseException {
File npmDirectory = getNPMDirectory();
File packageFile = new File(npmDirectory, PACKAGE_JSON);
if (!packageFile.isFile()) {
throw new IllegalStateException("Invalid NPM " + npmName + " - " + packageFile.getAbsolutePath() + " does not" +
" exist");
}
FileReader reader = null;
try {
reader = new FileReader(packageFile);
JSONObject json = (JSONObject) JSONValue.parseWithException(reader);
JSONObject bin = (JSONObject) json.get("bin");
if (bin == null) {
log.error("No `bin` object in " + packageFile.getAbsolutePath());
return null;
} else {
String exec = (String) bin.get(binary);
if (exec == null) {
log.error("No `" + binary + "` object in the `bin` object from " + packageFile
.getAbsolutePath());
return null;
}
File file = new File(npmDirectory, exec);
if (!file.isFile()) {
log.error("To execute " + npmName + ", an entry was found for " + binary + " in 'package.json', " +
"but the specified file does not exist - " + file.getAbsolutePath());
return null;
}
return file;
}
} finally {
IOUtils.closeQuietly(reader);
}
} | java | public File findExecutable(String binary) throws IOException, ParseException {
File npmDirectory = getNPMDirectory();
File packageFile = new File(npmDirectory, PACKAGE_JSON);
if (!packageFile.isFile()) {
throw new IllegalStateException("Invalid NPM " + npmName + " - " + packageFile.getAbsolutePath() + " does not" +
" exist");
}
FileReader reader = null;
try {
reader = new FileReader(packageFile);
JSONObject json = (JSONObject) JSONValue.parseWithException(reader);
JSONObject bin = (JSONObject) json.get("bin");
if (bin == null) {
log.error("No `bin` object in " + packageFile.getAbsolutePath());
return null;
} else {
String exec = (String) bin.get(binary);
if (exec == null) {
log.error("No `" + binary + "` object in the `bin` object from " + packageFile
.getAbsolutePath());
return null;
}
File file = new File(npmDirectory, exec);
if (!file.isFile()) {
log.error("To execute " + npmName + ", an entry was found for " + binary + " in 'package.json', " +
"but the specified file does not exist - " + file.getAbsolutePath());
return null;
}
return file;
}
} finally {
IOUtils.closeQuietly(reader);
}
} | [
"public",
"File",
"findExecutable",
"(",
"String",
"binary",
")",
"throws",
"IOException",
",",
"ParseException",
"{",
"File",
"npmDirectory",
"=",
"getNPMDirectory",
"(",
")",
";",
"File",
"packageFile",
"=",
"new",
"File",
"(",
"npmDirectory",
",",
"PACKAGE_JS... | Tries to find the main JS file.
This search is based on the `package.json` file and it's `bin` entry.
If there is an entry in the `bin` object matching `binary`, it uses this javascript file.
If the search failed, `null` is returned
@return the JavaScript file to execute, null if not found | [
"Tries",
"to",
"find",
"the",
"main",
"JS",
"file",
".",
"This",
"search",
"is",
"based",
"on",
"the",
"package",
".",
"json",
"file",
"and",
"it",
"s",
"bin",
"entry",
".",
"If",
"there",
"is",
"an",
"entry",
"in",
"the",
"bin",
"object",
"matching"... | train | https://github.com/wisdom-framework/wisdom/blob/a35b6431200fec56b178c0ff60837ed73fd7874d/core/wisdom-maven-plugin/src/main/java/org/wisdom/maven/node/NPM.java#L269-L302 |
eclipse/xtext-core | org.eclipse.xtext.ide/xtend-gen/org/eclipse/xtext/ide/editor/contentassist/IdeContentProposalProvider.java | IdeContentProposalProvider.createProposals | public void createProposals(final Collection<ContentAssistContext> contexts, final IIdeContentProposalAcceptor acceptor) {
Iterable<ContentAssistContext> _filteredContexts = this.getFilteredContexts(contexts);
for (final ContentAssistContext context : _filteredContexts) {
ImmutableList<AbstractElement> _firstSetGrammarElements = context.getFirstSetGrammarElements();
for (final AbstractElement element : _firstSetGrammarElements) {
{
boolean _canAcceptMoreProposals = acceptor.canAcceptMoreProposals();
boolean _not = (!_canAcceptMoreProposals);
if (_not) {
return;
}
this.createProposals(element, context, acceptor);
}
}
}
} | java | public void createProposals(final Collection<ContentAssistContext> contexts, final IIdeContentProposalAcceptor acceptor) {
Iterable<ContentAssistContext> _filteredContexts = this.getFilteredContexts(contexts);
for (final ContentAssistContext context : _filteredContexts) {
ImmutableList<AbstractElement> _firstSetGrammarElements = context.getFirstSetGrammarElements();
for (final AbstractElement element : _firstSetGrammarElements) {
{
boolean _canAcceptMoreProposals = acceptor.canAcceptMoreProposals();
boolean _not = (!_canAcceptMoreProposals);
if (_not) {
return;
}
this.createProposals(element, context, acceptor);
}
}
}
} | [
"public",
"void",
"createProposals",
"(",
"final",
"Collection",
"<",
"ContentAssistContext",
">",
"contexts",
",",
"final",
"IIdeContentProposalAcceptor",
"acceptor",
")",
"{",
"Iterable",
"<",
"ContentAssistContext",
">",
"_filteredContexts",
"=",
"this",
".",
"getF... | Create content assist proposals and pass them to the given acceptor. | [
"Create",
"content",
"assist",
"proposals",
"and",
"pass",
"them",
"to",
"the",
"given",
"acceptor",
"."
] | train | https://github.com/eclipse/xtext-core/blob/bac941cb75cb24706519845ec174cfef874d7557/org.eclipse.xtext.ide/xtend-gen/org/eclipse/xtext/ide/editor/contentassist/IdeContentProposalProvider.java#L83-L98 |
tvesalainen/bcc | src/main/java/org/vesalainen/bcc/MethodCompiler.java | MethodCompiler.nameArgument | public final void nameArgument(String name, int index)
{
VariableElement lv = getLocalVariable(index);
if (lv instanceof UpdateableElement)
{
UpdateableElement ue = (UpdateableElement) lv;
ue.setSimpleName(El.getName(name));
}
else
{
throw new IllegalArgumentException("local variable at index "+index+" cannot be named");
}
} | java | public final void nameArgument(String name, int index)
{
VariableElement lv = getLocalVariable(index);
if (lv instanceof UpdateableElement)
{
UpdateableElement ue = (UpdateableElement) lv;
ue.setSimpleName(El.getName(name));
}
else
{
throw new IllegalArgumentException("local variable at index "+index+" cannot be named");
}
} | [
"public",
"final",
"void",
"nameArgument",
"(",
"String",
"name",
",",
"int",
"index",
")",
"{",
"VariableElement",
"lv",
"=",
"getLocalVariable",
"(",
"index",
")",
";",
"if",
"(",
"lv",
"instanceof",
"UpdateableElement",
")",
"{",
"UpdateableElement",
"ue",
... | Names an argument
@param name Argument name
@param index First argument is 1, this = 0 | [
"Names",
"an",
"argument"
] | train | https://github.com/tvesalainen/bcc/blob/4e84e313018d487f1a8cca3952d71bc21e77d16b/src/main/java/org/vesalainen/bcc/MethodCompiler.java#L178-L190 |
Netflix/Hystrix | hystrix-core/src/main/java/com/netflix/hystrix/strategy/executionhook/HystrixCommandExecutionHook.java | HystrixCommandExecutionHook.onRunSuccess | @Deprecated
public <T> T onRunSuccess(HystrixCommand<T> commandInstance, T response) {
// pass-thru by default
return response;
} | java | @Deprecated
public <T> T onRunSuccess(HystrixCommand<T> commandInstance, T response) {
// pass-thru by default
return response;
} | [
"@",
"Deprecated",
"public",
"<",
"T",
">",
"T",
"onRunSuccess",
"(",
"HystrixCommand",
"<",
"T",
">",
"commandInstance",
",",
"T",
"response",
")",
"{",
"// pass-thru by default",
"return",
"response",
";",
"}"
] | DEPRECATED: Change usages of this to {@link #onExecutionEmit} if you want to add a hook for each value emitted by the command
or to {@link #onExecutionSuccess} if you want to add a hook when the command successfully executes
Invoked after successful execution of {@link HystrixCommand#run()} with response value.
In a {@link HystrixCommand} using {@link ExecutionIsolationStrategy#THREAD}, this will get invoked if the Hystrix thread
successfully runs, regardless of whether the calling thread encountered a timeout.
@param commandInstance
The executing HystrixCommand instance.
@param response
from {@link HystrixCommand#run()}
@return T response object that can be modified, decorated, replaced or just returned as a pass-thru.
@since 1.2 | [
"DEPRECATED",
":",
"Change",
"usages",
"of",
"this",
"to",
"{",
"@link",
"#onExecutionEmit",
"}",
"if",
"you",
"want",
"to",
"add",
"a",
"hook",
"for",
"each",
"value",
"emitted",
"by",
"the",
"command",
"or",
"to",
"{",
"@link",
"#onExecutionSuccess",
"}"... | train | https://github.com/Netflix/Hystrix/blob/3cb21589895e9f8f87cfcdbc9d96d9f63d48b848/hystrix-core/src/main/java/com/netflix/hystrix/strategy/executionhook/HystrixCommandExecutionHook.java#L276-L280 |
sitoolkit/sit-util-td | src/main/java/io/sitoolkit/util/tabledata/TableDataMapper.java | TableDataMapper.map | public <T> T map(String beanId, RowData rowData, Class<T> type) {
T bean = beanFactory.getBean(beanId, type);
Table table = tableMap.get(beanId);
for (Column column : table.getColumn()) {
map(bean, column, rowData);
}
return bean;
} | java | public <T> T map(String beanId, RowData rowData, Class<T> type) {
T bean = beanFactory.getBean(beanId, type);
Table table = tableMap.get(beanId);
for (Column column : table.getColumn()) {
map(bean, column, rowData);
}
return bean;
} | [
"public",
"<",
"T",
">",
"T",
"map",
"(",
"String",
"beanId",
",",
"RowData",
"rowData",
",",
"Class",
"<",
"T",
">",
"type",
")",
"{",
"T",
"bean",
"=",
"beanFactory",
".",
"getBean",
"(",
"beanId",
",",
"type",
")",
";",
"Table",
"table",
"=",
... | 1行分のデータをSpring Beanの各プロパティに設定します。 行内の列とプロパティとの対応は、designDoc.xmlの定義に従います。
designDoc.xmlは、{@link #init() }で予め読み込まれている事が前提です。
@param <T>
Spring Beanの型
@param beanId
Spring Beanを指定するID
@param rowData
1行分のデータ
@param type
Spring Beanの型
@return 1行分のデータを設定されたSpring Bean | [
"1行分のデータをSpring",
"Beanの各プロパティに設定します。",
"行内の列とプロパティとの対応は、designDoc",
".",
"xmlの定義に従います。",
"designDoc",
".",
"xmlは、",
"{",
"@link",
"#init",
"()",
"}",
"で予め読み込まれている事が前提です。"
] | train | https://github.com/sitoolkit/sit-util-td/blob/63afd9909c9d404e93884b449f8bf48e867c80de/src/main/java/io/sitoolkit/util/tabledata/TableDataMapper.java#L111-L119 |
clanie/clanie-core | src/main/java/dk/clanie/collections/NumberMap.java | NumberMap.newDoubleMap | public static <K> NumberMap<K, Double> newDoubleMap() {
return new NumberMap<K, Double>() {
@Override
public void add(K key, Double addend) {
put(key, containsKey(key) ? (get(key) + addend) : addend);
}
@Override
public void sub(K key, Double subtrahend) {
put(key, (containsKey(key) ? get(key) : 0d) - subtrahend);
}
};
} | java | public static <K> NumberMap<K, Double> newDoubleMap() {
return new NumberMap<K, Double>() {
@Override
public void add(K key, Double addend) {
put(key, containsKey(key) ? (get(key) + addend) : addend);
}
@Override
public void sub(K key, Double subtrahend) {
put(key, (containsKey(key) ? get(key) : 0d) - subtrahend);
}
};
} | [
"public",
"static",
"<",
"K",
">",
"NumberMap",
"<",
"K",
",",
"Double",
">",
"newDoubleMap",
"(",
")",
"{",
"return",
"new",
"NumberMap",
"<",
"K",
",",
"Double",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"void",
"add",
"(",
"K",
"key",
",",
... | Creates a NumberMap for Doubles.
@param <K>
@return NumberMap<K, Double> | [
"Creates",
"a",
"NumberMap",
"for",
"Doubles",
"."
] | train | https://github.com/clanie/clanie-core/blob/ac8a655b93127f0e281b741c4d53f429be2816ad/src/main/java/dk/clanie/collections/NumberMap.java#L132-L143 |
aws/aws-sdk-java | aws-java-sdk-s3/src/main/java/com/amazonaws/services/s3/internal/crypto/AesCtr.java | AesCtr.computeJ0 | private byte[] computeJ0(byte[] nonce) {
final int blockSize = getBlockSizeInBytes();
byte[] J0 = new byte[blockSize];
System.arraycopy(nonce, 0, J0, 0, nonce.length);
J0[blockSize - 1] = 0x01;
return incrementBlocks(J0, 1);
} | java | private byte[] computeJ0(byte[] nonce) {
final int blockSize = getBlockSizeInBytes();
byte[] J0 = new byte[blockSize];
System.arraycopy(nonce, 0, J0, 0, nonce.length);
J0[blockSize - 1] = 0x01;
return incrementBlocks(J0, 1);
} | [
"private",
"byte",
"[",
"]",
"computeJ0",
"(",
"byte",
"[",
"]",
"nonce",
")",
"{",
"final",
"int",
"blockSize",
"=",
"getBlockSizeInBytes",
"(",
")",
";",
"byte",
"[",
"]",
"J0",
"=",
"new",
"byte",
"[",
"blockSize",
"]",
";",
"System",
".",
"arrayc... | See <a href=
"http://csrc.nist.gov/publications/nistpubs/800-38D/SP-800-38D.pdf">
NIST Special Publication 800-38D.</a> for the definition of J0, the
"pre-counter block".
<p>
Reference: <a href=
"https://github.com/bcgit/bc-java/blob/master/core/src/main/java/org/bouncycastle/crypto/modes/GCMBlockCipher.java"
>GCMBlockCipher.java</a> | [
"See",
"<a",
"href",
"=",
"http",
":",
"//",
"csrc",
".",
"nist",
".",
"gov",
"/",
"publications",
"/",
"nistpubs",
"/",
"800",
"-",
"38D",
"/",
"SP",
"-",
"800",
"-",
"38D",
".",
"pdf",
">",
"NIST",
"Special",
"Publication",
"800",
"-",
"38D",
"... | train | https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-s3/src/main/java/com/amazonaws/services/s3/internal/crypto/AesCtr.java#L53-L59 |
lionsoul2014/jcseg | jcseg-core/src/main/java/org/lionsoul/jcseg/util/IIntQueue.java | IIntQueue.enQueue | public boolean enQueue( int data )
{
Entry o = new Entry(data, tail.prev, tail);
tail.prev.next = o;
tail.prev = o;
//set the size
size++;
return true;
} | java | public boolean enQueue( int data )
{
Entry o = new Entry(data, tail.prev, tail);
tail.prev.next = o;
tail.prev = o;
//set the size
size++;
return true;
} | [
"public",
"boolean",
"enQueue",
"(",
"int",
"data",
")",
"{",
"Entry",
"o",
"=",
"new",
"Entry",
"(",
"data",
",",
"tail",
".",
"prev",
",",
"tail",
")",
";",
"tail",
".",
"prev",
".",
"next",
"=",
"o",
";",
"tail",
".",
"prev",
"=",
"o",
";",
... | append a int from the tail
@param data
@return boolean | [
"append",
"a",
"int",
"from",
"the",
"tail"
] | train | https://github.com/lionsoul2014/jcseg/blob/7c8a912e3bbcaf4f8de701180b9c24e2e444a94b/jcseg-core/src/main/java/org/lionsoul/jcseg/util/IIntQueue.java#L30-L40 |
ManfredTremmel/gwt-bean-validators | mt-bean-validators/src/main/java/de/knightsoftnet/validators/server/data/CreateTinMapConstantsClass.java | CreateTinMapConstantsClass.create | public static TinMapSharedConstants create() {
if (tinMapConstants == null) { // NOPMD it's thread save!
synchronized (TinMapConstantsImpl.class) {
if (tinMapConstants == null) {
tinMapConstants =
new TinMapConstantsImpl(readMapFromProperties("TinMapConstants", "tins"));
}
}
}
return tinMapConstants;
} | java | public static TinMapSharedConstants create() {
if (tinMapConstants == null) { // NOPMD it's thread save!
synchronized (TinMapConstantsImpl.class) {
if (tinMapConstants == null) {
tinMapConstants =
new TinMapConstantsImpl(readMapFromProperties("TinMapConstants", "tins"));
}
}
}
return tinMapConstants;
} | [
"public",
"static",
"TinMapSharedConstants",
"create",
"(",
")",
"{",
"if",
"(",
"tinMapConstants",
"==",
"null",
")",
"{",
"// NOPMD it's thread save!",
"synchronized",
"(",
"TinMapConstantsImpl",
".",
"class",
")",
"{",
"if",
"(",
"tinMapConstants",
"==",
"null"... | Instantiates a class via deferred binding.
@return the new instance, which must be cast to the requested class | [
"Instantiates",
"a",
"class",
"via",
"deferred",
"binding",
"."
] | train | https://github.com/ManfredTremmel/gwt-bean-validators/blob/cff7a2c3d68c2d17bf9d3cc57c79cc16fa8b4d5c/mt-bean-validators/src/main/java/de/knightsoftnet/validators/server/data/CreateTinMapConstantsClass.java#L35-L45 |
reinert/requestor | requestor/core/requestor-api/src/main/java/io/reinert/requestor/WebTarget.java | WebTarget.matrixParam | public WebTarget matrixParam(String name, Object... values) {
final UriBuilder copy = cloneUriBuilder();
copy.matrixParam(name, values);
return newWebTarget(copy);
} | java | public WebTarget matrixParam(String name, Object... values) {
final UriBuilder copy = cloneUriBuilder();
copy.matrixParam(name, values);
return newWebTarget(copy);
} | [
"public",
"WebTarget",
"matrixParam",
"(",
"String",
"name",
",",
"Object",
"...",
"values",
")",
"{",
"final",
"UriBuilder",
"copy",
"=",
"cloneUriBuilder",
"(",
")",
";",
"copy",
".",
"matrixParam",
"(",
"name",
",",
"values",
")",
";",
"return",
"newWeb... | Create a new WebTarget instance by appending a matrix parameter to the existing set of matrix parameters of the
current final segment of the URI of the current target instance. If multiple values are supplied the parameter
will be added once per value.
<p/>
Note that the matrix parameters are tied to a particular path segment; appending a value to an existing matrix
parameter name will not affect the position of the matrix parameter in the URI path.
<p/>
A snapshot of the present configuration of the current (parent) target instance is taken and is inherited by the
newly constructed (child) target instance.
@param name the matrix parameter name, may contain URI template parameters.
@param values the query parameter value(s), each object will be converted to a {@code String} using its
{@code toString()} method. Stringified values may contain URI template parameters.
@return a new target instance. | [
"Create",
"a",
"new",
"WebTarget",
"instance",
"by",
"appending",
"a",
"matrix",
"parameter",
"to",
"the",
"existing",
"set",
"of",
"matrix",
"parameters",
"of",
"the",
"current",
"final",
"segment",
"of",
"the",
"URI",
"of",
"the",
"current",
"target",
"ins... | train | https://github.com/reinert/requestor/blob/40163a75cd17815d5089935d0dd97b8d652ad6d4/requestor/core/requestor-api/src/main/java/io/reinert/requestor/WebTarget.java#L151-L155 |
Appendium/flatpack | flatpack/src/main/java/net/sf/flatpack/xml/MapParser.java | MapParser.parseMap | public static MetaData parseMap(final Reader xmlStreamReader, final Parser pzparser)
throws IOException, ParserConfigurationException, SAXException {
final Map map = parse(xmlStreamReader, pzparser);
final List<ColumnMetaData> col = (List<ColumnMetaData>) map.get(FPConstants.DETAIL_ID);
map.remove(FPConstants.DETAIL_ID);
final Map m = (Map) map.get(FPConstants.COL_IDX);
map.remove(FPConstants.COL_IDX);
// loop through the map and remove anything else that is an index of FPConstancts.COL_IDX + _
// these were put in for the writer.
// TODO maybe these should be thrown into the MetaData instead of just discarded, but they are unused
// in the Reader the moment. This parseMap is not utilized in the writer so it is safe to remove them here
final Iterator entrySetIt = map.entrySet().iterator();
while (entrySetIt.hasNext()) {
final Entry e = (Entry) entrySetIt.next();
if (((String) e.getKey()).startsWith(FPConstants.COL_IDX + "_")) {
entrySetIt.remove();
}
}
return new MetaData(col, m, map);
} | java | public static MetaData parseMap(final Reader xmlStreamReader, final Parser pzparser)
throws IOException, ParserConfigurationException, SAXException {
final Map map = parse(xmlStreamReader, pzparser);
final List<ColumnMetaData> col = (List<ColumnMetaData>) map.get(FPConstants.DETAIL_ID);
map.remove(FPConstants.DETAIL_ID);
final Map m = (Map) map.get(FPConstants.COL_IDX);
map.remove(FPConstants.COL_IDX);
// loop through the map and remove anything else that is an index of FPConstancts.COL_IDX + _
// these were put in for the writer.
// TODO maybe these should be thrown into the MetaData instead of just discarded, but they are unused
// in the Reader the moment. This parseMap is not utilized in the writer so it is safe to remove them here
final Iterator entrySetIt = map.entrySet().iterator();
while (entrySetIt.hasNext()) {
final Entry e = (Entry) entrySetIt.next();
if (((String) e.getKey()).startsWith(FPConstants.COL_IDX + "_")) {
entrySetIt.remove();
}
}
return new MetaData(col, m, map);
} | [
"public",
"static",
"MetaData",
"parseMap",
"(",
"final",
"Reader",
"xmlStreamReader",
",",
"final",
"Parser",
"pzparser",
")",
"throws",
"IOException",
",",
"ParserConfigurationException",
",",
"SAXException",
"{",
"final",
"Map",
"map",
"=",
"parse",
"(",
"xmlSt... | New method based on Reader. Reads the XMLDocument for a PZMetaData
file from an InputStream, WebStart compatible. Parses the XML file, and
returns a Map containing Lists of ColumnMetaData.
@param xmlStreamReader
@param pzparser
Can be null. Allows additional opts to be set during the XML map read
@return Map <records> with their corresponding
@throws IOException
@throws SAXException
@throws ParserConfigurationException | [
"New",
"method",
"based",
"on",
"Reader",
".",
"Reads",
"the",
"XMLDocument",
"for",
"a",
"PZMetaData",
"file",
"from",
"an",
"InputStream",
"WebStart",
"compatible",
".",
"Parses",
"the",
"XML",
"file",
"and",
"returns",
"a",
"Map",
"containing",
"Lists",
"... | train | https://github.com/Appendium/flatpack/blob/5e09875d97db7038e3ba6af9468f5313d99b0082/flatpack/src/main/java/net/sf/flatpack/xml/MapParser.java#L254-L277 |
sagiegurari/fax4j | src/main/java/org/fax4j/bridge/email/DefaultMailMessageParser.java | DefaultMailMessageParser.getFileInfo | protected FileInfo getFileInfo(Message mailMessage) throws MessagingException,IOException
{
//get content
Object messageContent=mailMessage.getContent();
String charset=null;
if(mailMessage instanceof MimeMessage)
{
//get mime message
MimeMessage mimeMessage=(MimeMessage)mailMessage;
//get charset
charset=mimeMessage.getEncoding();
}
String name="fax.txt";
byte[] content=null;
if(messageContent instanceof String)
{
//get content
content=IOHelper.convertStringToBinary((String)messageContent,charset);
}
else if(messageContent instanceof Multipart)
{
//get multi part
Multipart multiPart=(Multipart)messageContent;
//get parts amount
int amount=multiPart.getCount();
Part part=null;
DataHandler dataHandler=null;
if(amount>0)
{
//handle only the first body part
part=multiPart.getBodyPart(0);
//get data handler
dataHandler=part.getDataHandler();
//get values
name=dataHandler.getName();
if(name==null)
{
name="fax.txt";
}
//get data
content=IOHelper.readStream(part.getInputStream());
}
}
//create file info
FileInfo fileInfo=new FileInfo(name,content);
return fileInfo;
} | java | protected FileInfo getFileInfo(Message mailMessage) throws MessagingException,IOException
{
//get content
Object messageContent=mailMessage.getContent();
String charset=null;
if(mailMessage instanceof MimeMessage)
{
//get mime message
MimeMessage mimeMessage=(MimeMessage)mailMessage;
//get charset
charset=mimeMessage.getEncoding();
}
String name="fax.txt";
byte[] content=null;
if(messageContent instanceof String)
{
//get content
content=IOHelper.convertStringToBinary((String)messageContent,charset);
}
else if(messageContent instanceof Multipart)
{
//get multi part
Multipart multiPart=(Multipart)messageContent;
//get parts amount
int amount=multiPart.getCount();
Part part=null;
DataHandler dataHandler=null;
if(amount>0)
{
//handle only the first body part
part=multiPart.getBodyPart(0);
//get data handler
dataHandler=part.getDataHandler();
//get values
name=dataHandler.getName();
if(name==null)
{
name="fax.txt";
}
//get data
content=IOHelper.readStream(part.getInputStream());
}
}
//create file info
FileInfo fileInfo=new FileInfo(name,content);
return fileInfo;
} | [
"protected",
"FileInfo",
"getFileInfo",
"(",
"Message",
"mailMessage",
")",
"throws",
"MessagingException",
",",
"IOException",
"{",
"//get content",
"Object",
"messageContent",
"=",
"mailMessage",
".",
"getContent",
"(",
")",
";",
"String",
"charset",
"=",
"null",
... | Returns the file info from the provided mail object.<br>
This function does not handle multiple file attachments.
@param mailMessage
The mail message with the fax data
@return The file info
@throws MessagingException
Any exception while handling the mail message
@throws IOException
Any IO exception | [
"Returns",
"the",
"file",
"info",
"from",
"the",
"provided",
"mail",
"object",
".",
"<br",
">",
"This",
"function",
"does",
"not",
"handle",
"multiple",
"file",
"attachments",
"."
] | train | https://github.com/sagiegurari/fax4j/blob/42fa51acabe7bf279e27ab3dd1cf76146b27955f/src/main/java/org/fax4j/bridge/email/DefaultMailMessageParser.java#L174-L230 |
brettwooldridge/SansOrm | src/main/java/com/zaxxer/sansorm/OrmElf.java | OrmElf.objectFromClause | public static <T> T objectFromClause(Connection connection, Class<T> clazz, String clause, Object... args) throws SQLException
{
return OrmReader.objectFromClause(connection, clazz, clause, args);
} | java | public static <T> T objectFromClause(Connection connection, Class<T> clazz, String clause, Object... args) throws SQLException
{
return OrmReader.objectFromClause(connection, clazz, clause, args);
} | [
"public",
"static",
"<",
"T",
">",
"T",
"objectFromClause",
"(",
"Connection",
"connection",
",",
"Class",
"<",
"T",
">",
"clazz",
",",
"String",
"clause",
",",
"Object",
"...",
"args",
")",
"throws",
"SQLException",
"{",
"return",
"OrmReader",
".",
"objec... | Load an object using the specified clause. If the specified clause contains the text
"WHERE" or "JOIN", the clause is appended directly to the generated "SELECT .. FROM" SQL.
However, if the clause contains neither "WHERE" nor "JOIN", it is assumed to be
just be the conditional portion that would normally appear after the "WHERE", and therefore
the clause "WHERE" is automatically appended to the generated "SELECT .. FROM" SQL, followed
by the specified clause. For example:<p>
{@code User user = OrmElf.objectFromClause(connection, User.class, "username=?", userName);}
@param connection a SQL Connection object
@param clazz the class of the object to load
@param clause the conditional part of a SQL where clause
@param args the query parameters used to find the object
@param <T> the type of the object to load
@return the populated object
@throws SQLException if a {@link SQLException} occurs | [
"Load",
"an",
"object",
"using",
"the",
"specified",
"clause",
".",
"If",
"the",
"specified",
"clause",
"contains",
"the",
"text",
"WHERE",
"or",
"JOIN",
"the",
"clause",
"is",
"appended",
"directly",
"to",
"the",
"generated",
"SELECT",
"..",
"FROM",
"SQL",
... | train | https://github.com/brettwooldridge/SansOrm/blob/ab22721db79c5f20c0e8483f09eda2844d596557/src/main/java/com/zaxxer/sansorm/OrmElf.java#L83-L86 |
ironjacamar/ironjacamar | web/src/main/java/org/ironjacamar/web/console/Server.java | Server.getMBeanAttribute | public static String getMBeanAttribute(String name, String attrName) throws JMException
{
MBeanServer server = getMBeanServer();
ObjectName objName = new ObjectName(name);
String value = null;
try
{
Object attr = server.getAttribute(objName, attrName);
if (attr != null)
value = attr.toString();
}
catch (JMException e)
{
value = e.getMessage();
}
return value;
} | java | public static String getMBeanAttribute(String name, String attrName) throws JMException
{
MBeanServer server = getMBeanServer();
ObjectName objName = new ObjectName(name);
String value = null;
try
{
Object attr = server.getAttribute(objName, attrName);
if (attr != null)
value = attr.toString();
}
catch (JMException e)
{
value = e.getMessage();
}
return value;
} | [
"public",
"static",
"String",
"getMBeanAttribute",
"(",
"String",
"name",
",",
"String",
"attrName",
")",
"throws",
"JMException",
"{",
"MBeanServer",
"server",
"=",
"getMBeanServer",
"(",
")",
";",
"ObjectName",
"objName",
"=",
"new",
"ObjectName",
"(",
"name",... | Get MBean attribute
@param name The bean name
@param attrName The attribute name
@return The data
@exception JMException Thrown if an error occurs | [
"Get",
"MBean",
"attribute"
] | train | https://github.com/ironjacamar/ironjacamar/blob/f0389ee7e62aa8b40ba09b251edad76d220ea796/web/src/main/java/org/ironjacamar/web/console/Server.java#L183-L200 |
JodaOrg/joda-time | src/main/java/org/joda/time/YearMonth.java | YearMonth.withMonthOfYear | public YearMonth withMonthOfYear(int monthOfYear) {
int[] newValues = getValues();
newValues = getChronology().monthOfYear().set(this, MONTH_OF_YEAR, newValues, monthOfYear);
return new YearMonth(this, newValues);
} | java | public YearMonth withMonthOfYear(int monthOfYear) {
int[] newValues = getValues();
newValues = getChronology().monthOfYear().set(this, MONTH_OF_YEAR, newValues, monthOfYear);
return new YearMonth(this, newValues);
} | [
"public",
"YearMonth",
"withMonthOfYear",
"(",
"int",
"monthOfYear",
")",
"{",
"int",
"[",
"]",
"newValues",
"=",
"getValues",
"(",
")",
";",
"newValues",
"=",
"getChronology",
"(",
")",
".",
"monthOfYear",
"(",
")",
".",
"set",
"(",
"this",
",",
"MONTH_... | Returns a copy of this year-month with the month of year field updated.
<p>
YearMonth is immutable, so there are no set methods.
Instead, this method returns a new instance with the value of
month of year changed.
@param monthOfYear the month of year to set
@return a copy of this object with the field set, never null
@throws IllegalArgumentException if the value is invalid | [
"Returns",
"a",
"copy",
"of",
"this",
"year",
"-",
"month",
"with",
"the",
"month",
"of",
"year",
"field",
"updated",
".",
"<p",
">",
"YearMonth",
"is",
"immutable",
"so",
"there",
"are",
"no",
"set",
"methods",
".",
"Instead",
"this",
"method",
"returns... | train | https://github.com/JodaOrg/joda-time/blob/bd79f1c4245e79b3c2c56d7b04fde2a6e191fa42/src/main/java/org/joda/time/YearMonth.java#L751-L755 |
threerings/nenya | core/src/main/java/com/threerings/resource/ResourceManager.java | ResourceManager.getResourceFile | public File getResourceFile (String path)
{
if (_rdir == null) {
return null;
}
if ('/' != File.separatorChar) {
path = path.replace('/', File.separatorChar);
}
// first try a locale-specific file
String localePath = getLocalePath(path);
if (localePath != null) {
File file = new File(_rdir, localePath);
if (file.exists()) {
return file;
}
}
return new File(_rdir, path);
} | java | public File getResourceFile (String path)
{
if (_rdir == null) {
return null;
}
if ('/' != File.separatorChar) {
path = path.replace('/', File.separatorChar);
}
// first try a locale-specific file
String localePath = getLocalePath(path);
if (localePath != null) {
File file = new File(_rdir, localePath);
if (file.exists()) {
return file;
}
}
return new File(_rdir, path);
} | [
"public",
"File",
"getResourceFile",
"(",
"String",
"path",
")",
"{",
"if",
"(",
"_rdir",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"if",
"(",
"'",
"'",
"!=",
"File",
".",
"separatorChar",
")",
"{",
"path",
"=",
"path",
".",
"replace",
"(... | Given a path relative to the resource directory, the path is properly jimmied (assuming we
always use /) and combined with the resource directory to yield a {@link File} object that
can be used to access the resource.
@return a file referencing the specified resource or null if the resource manager was never
configured with a resource directory. | [
"Given",
"a",
"path",
"relative",
"to",
"the",
"resource",
"directory",
"the",
"path",
"is",
"properly",
"jimmied",
"(",
"assuming",
"we",
"always",
"use",
"/",
")",
"and",
"combined",
"with",
"the",
"resource",
"directory",
"to",
"yield",
"a",
"{",
"@link... | train | https://github.com/threerings/nenya/blob/3165a012fd859009db3367f87bd2a5b820cc760a/core/src/main/java/com/threerings/resource/ResourceManager.java#L405-L422 |
vipshop/vjtools | vjtop/src/main/java/com/vip/vjtools/vjtop/util/Formats.java | Formats.rightStr | public static String rightStr(String str, int length) {
return str.substring(Math.max(0, str.length() - length));
} | java | public static String rightStr(String str, int length) {
return str.substring(Math.max(0, str.length() - length));
} | [
"public",
"static",
"String",
"rightStr",
"(",
"String",
"str",
",",
"int",
"length",
")",
"{",
"return",
"str",
".",
"substring",
"(",
"Math",
".",
"max",
"(",
"0",
",",
"str",
".",
"length",
"(",
")",
"-",
"length",
")",
")",
";",
"}"
] | Returns a substring of the given string, representing the 'length' most-right characters | [
"Returns",
"a",
"substring",
"of",
"the",
"given",
"string",
"representing",
"the",
"length",
"most",
"-",
"right",
"characters"
] | train | https://github.com/vipshop/vjtools/blob/60c743da35913d72f37f2d79afa90ad2bf73cb89/vjtop/src/main/java/com/vip/vjtools/vjtop/util/Formats.java#L185-L187 |
mcxiaoke/Android-Next | recycler/src/main/java/com/mcxiaoke/next/recycler/HeaderFooterRecyclerAdapter.java | HeaderFooterRecyclerAdapter.notifyFooterItemMoved | public final void notifyFooterItemMoved(int fromPosition, int toPosition) {
if (fromPosition < 0 || toPosition < 0 || fromPosition >= footerItemCount || toPosition >= footerItemCount) {
throw new IndexOutOfBoundsException("The given fromPosition " + fromPosition
+ " or toPosition " + toPosition + " is not within the position bounds for footer items [0 - "
+ (footerItemCount - 1) + "].");
}
notifyItemMoved(fromPosition + headerItemCount + contentItemCount, toPosition + headerItemCount + contentItemCount);
} | java | public final void notifyFooterItemMoved(int fromPosition, int toPosition) {
if (fromPosition < 0 || toPosition < 0 || fromPosition >= footerItemCount || toPosition >= footerItemCount) {
throw new IndexOutOfBoundsException("The given fromPosition " + fromPosition
+ " or toPosition " + toPosition + " is not within the position bounds for footer items [0 - "
+ (footerItemCount - 1) + "].");
}
notifyItemMoved(fromPosition + headerItemCount + contentItemCount, toPosition + headerItemCount + contentItemCount);
} | [
"public",
"final",
"void",
"notifyFooterItemMoved",
"(",
"int",
"fromPosition",
",",
"int",
"toPosition",
")",
"{",
"if",
"(",
"fromPosition",
"<",
"0",
"||",
"toPosition",
"<",
"0",
"||",
"fromPosition",
">=",
"footerItemCount",
"||",
"toPosition",
">=",
"foo... | Notifies that an existing footer item is moved to another position.
@param fromPosition the original position.
@param toPosition the new position. | [
"Notifies",
"that",
"an",
"existing",
"footer",
"item",
"is",
"moved",
"to",
"another",
"position",
"."
] | train | https://github.com/mcxiaoke/Android-Next/blob/1bfdf99d0b81a849aa0fa6697c53ed673151ca39/recycler/src/main/java/com/mcxiaoke/next/recycler/HeaderFooterRecyclerAdapter.java#L376-L383 |
amsa-code/risky | geo-analyzer/src/main/java/au/gov/amsa/util/navigation/Position.java | Position.getEarthLimb | public final Position[] getEarthLimb(int radials) {
Position[] result = new Position[radials];
double radialDegrees = 0.0;
double incDegrees = 360.0 / radials;
double quarterEarthKm = circumferenceEarthKm / 4.0;
Position surfacePosition = new Position(this.lat, this.lon, 0.0);
// Assert( this.alt>0.0, "getEarthLimb() requires Position a positive
// altitude");
for (int i = 0; i < radials; i++) {
// TODO: base the distance on the altitude above the Earth
result[i] = surfacePosition.predict(quarterEarthKm, radialDegrees);
radialDegrees += incDegrees;
}
return result;
} | java | public final Position[] getEarthLimb(int radials) {
Position[] result = new Position[radials];
double radialDegrees = 0.0;
double incDegrees = 360.0 / radials;
double quarterEarthKm = circumferenceEarthKm / 4.0;
Position surfacePosition = new Position(this.lat, this.lon, 0.0);
// Assert( this.alt>0.0, "getEarthLimb() requires Position a positive
// altitude");
for (int i = 0; i < radials; i++) {
// TODO: base the distance on the altitude above the Earth
result[i] = surfacePosition.predict(quarterEarthKm, radialDegrees);
radialDegrees += incDegrees;
}
return result;
} | [
"public",
"final",
"Position",
"[",
"]",
"getEarthLimb",
"(",
"int",
"radials",
")",
"{",
"Position",
"[",
"]",
"result",
"=",
"new",
"Position",
"[",
"radials",
"]",
";",
"double",
"radialDegrees",
"=",
"0.0",
";",
"double",
"incDegrees",
"=",
"360.0",
... | Return an array of Positions representing the earths limb (aka: horizon)
as viewed from this Position in space. This position must have altitude >
0
The array returned will have the specified number of elements (radials).
This method is useful for the calculation of satellite footprints or the
position of the Earth's day/night terminator.
This formula from Aviation Formula by Ed Williams
(http://williams.best.vwh.net/avform.htm)
@param radials
the number of radials to calculated (evenly spaced around the
circumference of the circle
@return An array of radial points a fixed distance from this point
representing the Earth's limb as viewed from this point in space. | [
"Return",
"an",
"array",
"of",
"Positions",
"representing",
"the",
"earths",
"limb",
"(",
"aka",
":",
"horizon",
")",
"as",
"viewed",
"from",
"this",
"Position",
"in",
"space",
".",
"This",
"position",
"must",
"have",
"altitude",
">",
"0"
] | train | https://github.com/amsa-code/risky/blob/13649942aeddfdb9210eec072c605bc5d7a6daf3/geo-analyzer/src/main/java/au/gov/amsa/util/navigation/Position.java#L241-L261 |
future-architect/uroborosql | src/main/java/jp/co/future/uroborosql/parameter/mapper/JdbcParameterFactory.java | JdbcParameterFactory.createStruct | public static Struct createStruct(final Connection conn, final String typeName, final Object[] attributes) {
try {
return conn.createStruct(typeName, attributes);
} catch (SQLException e) {
throw new UroborosqlRuntimeException(e);
}
} | java | public static Struct createStruct(final Connection conn, final String typeName, final Object[] attributes) {
try {
return conn.createStruct(typeName, attributes);
} catch (SQLException e) {
throw new UroborosqlRuntimeException(e);
}
} | [
"public",
"static",
"Struct",
"createStruct",
"(",
"final",
"Connection",
"conn",
",",
"final",
"String",
"typeName",
",",
"final",
"Object",
"[",
"]",
"attributes",
")",
"{",
"try",
"{",
"return",
"conn",
".",
"createStruct",
"(",
"typeName",
",",
"attribut... | {@link java.sql.Connection#createStruct(String, Object[])}のラッパー
@param conn コネクション
@param typeName このStructオブジェクトがマッピングされるSQL構造化型のSQL型名。typeNameは、このデータベースに定義されたユーザー定義型の名前。これは、Struct.getSQLTypeNameで返される値。
@param attributes 返されるオブジェクトを生成する属性
@return 指定されたSQL型にマッピングされ、かつ指定された属性で生成されるStructオブジェクト
@see java.sql.Connection#createStruct(String, Object[]) | [
"{",
"@link",
"java",
".",
"sql",
".",
"Connection#createStruct",
"(",
"String",
"Object",
"[]",
")",
"}",
"のラッパー"
] | train | https://github.com/future-architect/uroborosql/blob/4c26db51defdac3c6ed16866e33ab45e190e2e0c/src/main/java/jp/co/future/uroborosql/parameter/mapper/JdbcParameterFactory.java#L124-L130 |
google/j2objc | xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xml/serializer/NamespaceMappings.java | NamespaceMappings.initNamespaces | private void initNamespaces()
{
// The initial prefix mappings will never be deleted because they are at element depth -1
// (a kludge)
// Define the default namespace (initially maps to "" uri)
Stack stack;
MappingRecord nn;
nn = new MappingRecord(EMPTYSTRING, EMPTYSTRING, -1);
stack = createPrefixStack(EMPTYSTRING);
stack.push(nn);
// define "xml" namespace
nn = new MappingRecord(XML_PREFIX, "http://www.w3.org/XML/1998/namespace", -1);
stack = createPrefixStack(XML_PREFIX);
stack.push(nn);
} | java | private void initNamespaces()
{
// The initial prefix mappings will never be deleted because they are at element depth -1
// (a kludge)
// Define the default namespace (initially maps to "" uri)
Stack stack;
MappingRecord nn;
nn = new MappingRecord(EMPTYSTRING, EMPTYSTRING, -1);
stack = createPrefixStack(EMPTYSTRING);
stack.push(nn);
// define "xml" namespace
nn = new MappingRecord(XML_PREFIX, "http://www.w3.org/XML/1998/namespace", -1);
stack = createPrefixStack(XML_PREFIX);
stack.push(nn);
} | [
"private",
"void",
"initNamespaces",
"(",
")",
"{",
"// The initial prefix mappings will never be deleted because they are at element depth -1",
"// (a kludge)",
"// Define the default namespace (initially maps to \"\" uri)",
"Stack",
"stack",
";",
"MappingRecord",
"nn",
";",
"nn",
"... | This method initializes the namespace object with appropriate stacks
and predefines a few prefix/uri pairs which always exist. | [
"This",
"method",
"initializes",
"the",
"namespace",
"object",
"with",
"appropriate",
"stacks",
"and",
"predefines",
"a",
"few",
"prefix",
"/",
"uri",
"pairs",
"which",
"always",
"exist",
"."
] | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xml/serializer/NamespaceMappings.java#L113-L129 |
stevespringett/Alpine | alpine/src/main/java/alpine/auth/JsonWebToken.java | JsonWebToken.createToken | public String createToken(final Map<String, Object> claims) {
final JwtBuilder jwtBuilder = Jwts.builder();
jwtBuilder.setClaims(claims);
return jwtBuilder.signWith(SignatureAlgorithm.HS256, key).compact();
} | java | public String createToken(final Map<String, Object> claims) {
final JwtBuilder jwtBuilder = Jwts.builder();
jwtBuilder.setClaims(claims);
return jwtBuilder.signWith(SignatureAlgorithm.HS256, key).compact();
} | [
"public",
"String",
"createToken",
"(",
"final",
"Map",
"<",
"String",
",",
"Object",
">",
"claims",
")",
"{",
"final",
"JwtBuilder",
"jwtBuilder",
"=",
"Jwts",
".",
"builder",
"(",
")",
";",
"jwtBuilder",
".",
"setClaims",
"(",
"claims",
")",
";",
"retu... | Creates a new JWT for the specified principal. Token is signed using
the SecretKey with an HMAC 256 algorithm.
@param claims a Map of all claims
@return a String representation of the generated token
@since 1.0.0 | [
"Creates",
"a",
"new",
"JWT",
"for",
"the",
"specified",
"principal",
".",
"Token",
"is",
"signed",
"using",
"the",
"SecretKey",
"with",
"an",
"HMAC",
"256",
"algorithm",
"."
] | train | https://github.com/stevespringett/Alpine/blob/6c5ef5e1ba4f38922096f1307d3950c09edb3093/alpine/src/main/java/alpine/auth/JsonWebToken.java#L135-L139 |
OpenLiberty/open-liberty | dev/com.ibm.ws.monitor/src/com/ibm/ws/monitor/internal/ProbeManagerImpl.java | ProbeManagerImpl.activate | synchronized void activate(ComponentContext componentContext) throws Exception {
this.componentContext = componentContext;
this.classAvailableTransformer = new ClassAvailableTransformer(this, instrumentation, includeBootstrap);
this.transformer = new ProbeClassFileTransformer(this, instrumentation, includeBootstrap);
this.proxyActivator = new MonitoringProxyActivator(componentContext.getBundleContext(), this, this.instrumentation);
this.proxyActivator.activate();
// The class available transformer is registered as retransform incapable
// to avoid having to keep track of which classes have been updated with
// static initializers and serialVersionUID fields. The probe transformer
// however, must run through the listener config every time a retransform
// occurs to allow it to discover new probes and replace currently active
// probes
//RTCD 89497-Update the set with the classes
for (Class<?> clazz : MonitoringUtility.loadMonitoringClasses(componentContext.getBundleContext().getBundle())) {
for (int i = 0; i < clazz.getMethods().length; i++) {
Annotation anno = ((clazz.getMethods()[i]).getAnnotation(ProbeSite.class));
if (anno != null) {
String temp = ((ProbeSite) anno).clazz();
probeMonitorSet.add(temp);
}
}
}
//Update to the set ended.
//RTC D89497 adding instrumentors moved below as the MonitoringUtility.loadMonitoringClasses
//was resulting in loading classes and in turn getting called during with transform process which
//might cause hang in some situations
this.instrumentation.addTransformer(this.transformer, true);
this.instrumentation.addTransformer(this.classAvailableTransformer);
// We're active so if we have any listeners, we can run down the loaded
// classes.
for (Class<?> clazz : this.instrumentation.getAllLoadedClasses()) {
classAvailable(clazz);
}
} | java | synchronized void activate(ComponentContext componentContext) throws Exception {
this.componentContext = componentContext;
this.classAvailableTransformer = new ClassAvailableTransformer(this, instrumentation, includeBootstrap);
this.transformer = new ProbeClassFileTransformer(this, instrumentation, includeBootstrap);
this.proxyActivator = new MonitoringProxyActivator(componentContext.getBundleContext(), this, this.instrumentation);
this.proxyActivator.activate();
// The class available transformer is registered as retransform incapable
// to avoid having to keep track of which classes have been updated with
// static initializers and serialVersionUID fields. The probe transformer
// however, must run through the listener config every time a retransform
// occurs to allow it to discover new probes and replace currently active
// probes
//RTCD 89497-Update the set with the classes
for (Class<?> clazz : MonitoringUtility.loadMonitoringClasses(componentContext.getBundleContext().getBundle())) {
for (int i = 0; i < clazz.getMethods().length; i++) {
Annotation anno = ((clazz.getMethods()[i]).getAnnotation(ProbeSite.class));
if (anno != null) {
String temp = ((ProbeSite) anno).clazz();
probeMonitorSet.add(temp);
}
}
}
//Update to the set ended.
//RTC D89497 adding instrumentors moved below as the MonitoringUtility.loadMonitoringClasses
//was resulting in loading classes and in turn getting called during with transform process which
//might cause hang in some situations
this.instrumentation.addTransformer(this.transformer, true);
this.instrumentation.addTransformer(this.classAvailableTransformer);
// We're active so if we have any listeners, we can run down the loaded
// classes.
for (Class<?> clazz : this.instrumentation.getAllLoadedClasses()) {
classAvailable(clazz);
}
} | [
"synchronized",
"void",
"activate",
"(",
"ComponentContext",
"componentContext",
")",
"throws",
"Exception",
"{",
"this",
".",
"componentContext",
"=",
"componentContext",
";",
"this",
".",
"classAvailableTransformer",
"=",
"new",
"ClassAvailableTransformer",
"(",
"this... | Activation callback from the Declarative Services runtime where the
component is ready for activation.
@param bundleContext the bundleContext | [
"Activation",
"callback",
"from",
"the",
"Declarative",
"Services",
"runtime",
"where",
"the",
"component",
"is",
"ready",
"for",
"activation",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.monitor/src/com/ibm/ws/monitor/internal/ProbeManagerImpl.java#L175-L210 |
ahome-it/lienzo-core | src/main/java/com/ait/lienzo/shared/core/types/Color.java | Color.fromNormalizedHSL | public static final Color fromNormalizedHSL(final double h, final double s, final double l)
{
// see http://www.w3.org/TR/css3-color/
//
// HOW TO RETURN hsl.to.rgb(h, s, l):
// SELECT:
// l<=0.5: PUT l*(s+1) IN m2
// ELSE: PUT l+s-l*s IN m2
// PUT l*2-m2 IN m1
// PUT hue.to.rgb(m1, m2, h+1/3) IN r
// PUT hue.to.rgb(m1, m2, h ) IN g
// PUT hue.to.rgb(m1, m2, h-1/3) IN b
// RETURN (r, g, b)
final double m2 = (l <= 0.5) ? (l * (s + 1)) : ((l + s) - (l * s));
final double m1 = (l * 2) - m2;
return new Color(fixRGB((int) Math.round(255 * hueToRGB(m1, m2, h + (1.0 / 3)))), fixRGB((int) Math.round(255 * hueToRGB(m1, m2, h))), fixRGB((int) Math.round(255 * hueToRGB(m1, m2, h - (1.0 / 3)))));
} | java | public static final Color fromNormalizedHSL(final double h, final double s, final double l)
{
// see http://www.w3.org/TR/css3-color/
//
// HOW TO RETURN hsl.to.rgb(h, s, l):
// SELECT:
// l<=0.5: PUT l*(s+1) IN m2
// ELSE: PUT l+s-l*s IN m2
// PUT l*2-m2 IN m1
// PUT hue.to.rgb(m1, m2, h+1/3) IN r
// PUT hue.to.rgb(m1, m2, h ) IN g
// PUT hue.to.rgb(m1, m2, h-1/3) IN b
// RETURN (r, g, b)
final double m2 = (l <= 0.5) ? (l * (s + 1)) : ((l + s) - (l * s));
final double m1 = (l * 2) - m2;
return new Color(fixRGB((int) Math.round(255 * hueToRGB(m1, m2, h + (1.0 / 3)))), fixRGB((int) Math.round(255 * hueToRGB(m1, m2, h))), fixRGB((int) Math.round(255 * hueToRGB(m1, m2, h - (1.0 / 3)))));
} | [
"public",
"static",
"final",
"Color",
"fromNormalizedHSL",
"(",
"final",
"double",
"h",
",",
"final",
"double",
"s",
",",
"final",
"double",
"l",
")",
"{",
"// see http://www.w3.org/TR/css3-color/",
"//",
"// HOW TO RETURN hsl.to.rgb(h, s, l):",
"// SELECT:",
"// l<=0.5... | Converts HSL (hue, saturation, lightness) to RGB.
HSL values should already be normalized to [0,1]
@param h in [0,1]
@param s in [0,1]
@param l in [0,1]
@return Color with RGB values | [
"Converts",
"HSL",
"(",
"hue",
"saturation",
"lightness",
")",
"to",
"RGB",
".",
"HSL",
"values",
"should",
"already",
"be",
"normalized",
"to",
"[",
"0",
"1",
"]"
] | train | https://github.com/ahome-it/lienzo-core/blob/8e03723700dec366f77064d12fb8676d8cd6be99/src/main/java/com/ait/lienzo/shared/core/types/Color.java#L255-L274 |
matthewhorridge/owlapi-gwt | owlapi-gwt-serialization/src/main/java/uk/ac/manchester/cs/owl/owlapi/OWLSubClassOfAxiomImpl_CustomFieldSerializer.java | OWLSubClassOfAxiomImpl_CustomFieldSerializer.serializeInstance | @Override
public void serializeInstance(SerializationStreamWriter streamWriter, OWLSubClassOfAxiomImpl instance) throws SerializationException {
serialize(streamWriter, instance);
} | java | @Override
public void serializeInstance(SerializationStreamWriter streamWriter, OWLSubClassOfAxiomImpl instance) throws SerializationException {
serialize(streamWriter, instance);
} | [
"@",
"Override",
"public",
"void",
"serializeInstance",
"(",
"SerializationStreamWriter",
"streamWriter",
",",
"OWLSubClassOfAxiomImpl",
"instance",
")",
"throws",
"SerializationException",
"{",
"serialize",
"(",
"streamWriter",
",",
"instance",
")",
";",
"}"
] | Serializes the content of the object into the
{@link com.google.gwt.user.client.rpc.SerializationStreamWriter}.
@param streamWriter the {@link com.google.gwt.user.client.rpc.SerializationStreamWriter} to write the
object's content to
@param instance the object instance to serialize
@throws com.google.gwt.user.client.rpc.SerializationException
if the serialization operation is not
successful | [
"Serializes",
"the",
"content",
"of",
"the",
"object",
"into",
"the",
"{",
"@link",
"com",
".",
"google",
".",
"gwt",
".",
"user",
".",
"client",
".",
"rpc",
".",
"SerializationStreamWriter",
"}",
"."
] | train | https://github.com/matthewhorridge/owlapi-gwt/blob/7ab975fb6cef3c8947099983551672a3b5d4e2fd/owlapi-gwt-serialization/src/main/java/uk/ac/manchester/cs/owl/owlapi/OWLSubClassOfAxiomImpl_CustomFieldSerializer.java#L75-L78 |
FXMisc/WellBehavedFX | src/main/java/org/fxmisc/wellbehaved/event/template/InputMapTemplate.java | InputMapTemplate.ifConsumed | public InputMapTemplate<S, E> ifConsumed(BiConsumer<? super S, ? super E> postConsumption) {
return postResult(Result.CONSUME, postConsumption);
} | java | public InputMapTemplate<S, E> ifConsumed(BiConsumer<? super S, ? super E> postConsumption) {
return postResult(Result.CONSUME, postConsumption);
} | [
"public",
"InputMapTemplate",
"<",
"S",
",",
"E",
">",
"ifConsumed",
"(",
"BiConsumer",
"<",
"?",
"super",
"S",
",",
"?",
"super",
"E",
">",
"postConsumption",
")",
"{",
"return",
"postResult",
"(",
"Result",
".",
"CONSUME",
",",
"postConsumption",
")",
... | Executes some additional handler if the event was consumed (e.g. {@link InputHandler#process(Event)} returns
{@link Result#CONSUME}). | [
"Executes",
"some",
"additional",
"handler",
"if",
"the",
"event",
"was",
"consumed",
"(",
"e",
".",
"g",
".",
"{"
] | train | https://github.com/FXMisc/WellBehavedFX/blob/ca889734481f5439655ca8deb6f742964b5654b0/src/main/java/org/fxmisc/wellbehaved/event/template/InputMapTemplate.java#L176-L178 |
arnaudroger/SimpleFlatMapper | sfm-datastax/src/main/java/org/simpleflatmapper/datastax/DatastaxMapperBuilder.java | DatastaxMapperBuilder.addMapping | public DatastaxMapperBuilder<T> addMapping(final String column, final int index, final DataType dataType, Object... properties) {
return addMapping(new DatastaxColumnKey(column, index, dataType), properties);
} | java | public DatastaxMapperBuilder<T> addMapping(final String column, final int index, final DataType dataType, Object... properties) {
return addMapping(new DatastaxColumnKey(column, index, dataType), properties);
} | [
"public",
"DatastaxMapperBuilder",
"<",
"T",
">",
"addMapping",
"(",
"final",
"String",
"column",
",",
"final",
"int",
"index",
",",
"final",
"DataType",
"dataType",
",",
"Object",
"...",
"properties",
")",
"{",
"return",
"addMapping",
"(",
"new",
"DatastaxCol... | add a new mapping to the specified property with the specified index, the specified type.
@param column the property name
@param index the property index
@param dataType the property type, @see java.sql.Types
@param properties the property properties
@return the current builder | [
"add",
"a",
"new",
"mapping",
"to",
"the",
"specified",
"property",
"with",
"the",
"specified",
"index",
"the",
"specified",
"type",
"."
] | train | https://github.com/arnaudroger/SimpleFlatMapper/blob/93435438c18f26c87963d5e0f3ebf0f264dcd8c2/sfm-datastax/src/main/java/org/simpleflatmapper/datastax/DatastaxMapperBuilder.java#L99-L101 |
mnlipp/jgrapes | org.jgrapes.util/src/org/jgrapes/util/JsonConfigurationStore.java | JsonConfigurationStore.onConfigurationUpdate | @Handler(dynamic = true)
@SuppressWarnings({ "PMD.DataflowAnomalyAnalysis",
"PMD.AvoidLiteralsInIfCondition",
"PMD.AvoidInstantiatingObjectsInLoops" })
public void onConfigurationUpdate(ConfigurationUpdate event)
throws IOException {
boolean changed = false;
for (String path : event.paths()) {
if ("/".equals(path) && !event.values(path).isPresent()) {
// Special case, "remove root", i.e. all configuration data
cache.clear();
changed = true;
}
changed = changed || handleSegment(cache,
new StringTokenizer(path, "/"), event.values(path));
}
if (changed) {
try (Writer out = new OutputStreamWriter(
Files.newOutputStream(file.toPath()), "utf-8");
JsonBeanEncoder enc = JsonBeanEncoder.create(out)) {
enc.writeObject(cache);
}
}
} | java | @Handler(dynamic = true)
@SuppressWarnings({ "PMD.DataflowAnomalyAnalysis",
"PMD.AvoidLiteralsInIfCondition",
"PMD.AvoidInstantiatingObjectsInLoops" })
public void onConfigurationUpdate(ConfigurationUpdate event)
throws IOException {
boolean changed = false;
for (String path : event.paths()) {
if ("/".equals(path) && !event.values(path).isPresent()) {
// Special case, "remove root", i.e. all configuration data
cache.clear();
changed = true;
}
changed = changed || handleSegment(cache,
new StringTokenizer(path, "/"), event.values(path));
}
if (changed) {
try (Writer out = new OutputStreamWriter(
Files.newOutputStream(file.toPath()), "utf-8");
JsonBeanEncoder enc = JsonBeanEncoder.create(out)) {
enc.writeObject(cache);
}
}
} | [
"@",
"Handler",
"(",
"dynamic",
"=",
"true",
")",
"@",
"SuppressWarnings",
"(",
"{",
"\"PMD.DataflowAnomalyAnalysis\"",
",",
"\"PMD.AvoidLiteralsInIfCondition\"",
",",
"\"PMD.AvoidInstantiatingObjectsInLoops\"",
"}",
")",
"public",
"void",
"onConfigurationUpdate",
"(",
"C... | Merges and saves configuration updates.
@param event the event
@throws IOException Signals that an I/O exception has occurred. | [
"Merges",
"and",
"saves",
"configuration",
"updates",
"."
] | train | https://github.com/mnlipp/jgrapes/blob/8b5d874935d84c34a52d3e3d3745e869b5203fa0/org.jgrapes.util/src/org/jgrapes/util/JsonConfigurationStore.java#L158-L181 |
infinispan/infinispan | commons/src/main/java/org/infinispan/commons/configuration/JsonReader.java | JsonReader.readJson | public void readJson(ConfigurationBuilderInfo builderInfo, String json) {
readJson(builderInfo, "", Json.read(json));
} | java | public void readJson(ConfigurationBuilderInfo builderInfo, String json) {
readJson(builderInfo, "", Json.read(json));
} | [
"public",
"void",
"readJson",
"(",
"ConfigurationBuilderInfo",
"builderInfo",
",",
"String",
"json",
")",
"{",
"readJson",
"(",
"builderInfo",
",",
"\"\"",
",",
"Json",
".",
"read",
"(",
"json",
")",
")",
";",
"}"
] | Parses a JSON document into the supplied builder.
@param builderInfo The configuration builder to use when reading.
@param json the JSON document. | [
"Parses",
"a",
"JSON",
"document",
"into",
"the",
"supplied",
"builder",
"."
] | train | https://github.com/infinispan/infinispan/blob/7c62b94886c3febb4774ae8376acf2baa0265ab5/commons/src/main/java/org/infinispan/commons/configuration/JsonReader.java#L25-L27 |
xmlet/XsdAsmFaster | src/main/java/org/xmlet/xsdasmfaster/classes/XsdAsmInterfaces.java | XsdAsmInterfaces.getAttributeGroupSignature | private StringBuilder getAttributeGroupSignature(String[] interfaces, String apiName) {
StringBuilder signature = new StringBuilder("<T::L" + elementType + "<TT;TZ;>;Z::" + elementTypeDesc + ">" + JAVA_OBJECT_DESC);
if (interfaces.length == 0){
signature.append("L").append(elementType).append("<TT;TZ;>;");
} else {
for (String anInterface : interfaces) {
signature.append("L").append(getFullClassTypeName(anInterface, apiName)).append("<TT;TZ;>;");
}
}
return signature;
} | java | private StringBuilder getAttributeGroupSignature(String[] interfaces, String apiName) {
StringBuilder signature = new StringBuilder("<T::L" + elementType + "<TT;TZ;>;Z::" + elementTypeDesc + ">" + JAVA_OBJECT_DESC);
if (interfaces.length == 0){
signature.append("L").append(elementType).append("<TT;TZ;>;");
} else {
for (String anInterface : interfaces) {
signature.append("L").append(getFullClassTypeName(anInterface, apiName)).append("<TT;TZ;>;");
}
}
return signature;
} | [
"private",
"StringBuilder",
"getAttributeGroupSignature",
"(",
"String",
"[",
"]",
"interfaces",
",",
"String",
"apiName",
")",
"{",
"StringBuilder",
"signature",
"=",
"new",
"StringBuilder",
"(",
"\"<T::L\"",
"+",
"elementType",
"+",
"\"<TT;TZ;>;Z::\"",
"+",
"eleme... | Obtains the signature for the attribute group interfaces based on the implemented interfaces.
@param interfaces The implemented interfaces.
@return The signature of this interface. | [
"Obtains",
"the",
"signature",
"for",
"the",
"attribute",
"group",
"interfaces",
"based",
"on",
"the",
"implemented",
"interfaces",
"."
] | train | https://github.com/xmlet/XsdAsmFaster/blob/ccb78f9dd4b957ad5ac1ca349eaf24338c421e94/src/main/java/org/xmlet/xsdasmfaster/classes/XsdAsmInterfaces.java#L297-L309 |
andrehertwig/admintool | admin-tools-core/src/main/java/de/chandre/admintool/core/controller/AbstractAdminController.java | AbstractAdminController.addCommonContextVars | protected String addCommonContextVars(ModelMap model, HttpServletRequest request, String overrideName, String overrideTarget)
{
LOGGER.debug(String.format("receiving request: ctxPath: %s, uri: %s", request.getContextPath(), request.getRequestURI()));
final String name = menuUtils.getMenuName(request, overrideName);
//get menu entry by name
MenuEntrySearchResult result = adminTool.searchComponent(name);
model.put("internationalizationEnabled", coreConfig.isInternationalizationEnabled());
model.put("rootContext", getRootContext(request));
model.put("adminToolContext", AdminTool.ROOTCONTEXT);
String targetTpl = coreConfig.isEnabled() ? "content/error404" : AdminTool.GENERIC_DEACTIVATED_TEMPLATE_NAME;
if (null != result) {
LOGGER.trace("Component found: " + String.valueOf(null != result.getComponent()) +
" | menu found: " + String.valueOf(result.getMenuEntry()));
model.put(MenuEntrySearchResult.NAME, result);
MenuEntry entry = result.getMenuEntry();
//set alternative target
targetTpl = (StringUtils.isEmpty(overrideTarget) ? entry.getTarget() : AdminToolMenuUtils.normalizeTarget(overrideTarget));
model.put("contentPage", AdminTool.ROOTCONTEXT_NAME + AdminTool.SLASH + targetTpl);
if (null != entry.getVariables()) {
model.putAll(entry.getVariables());
}
model.put("activeMenu", entry);
//since 1.1.6
String overriddenActive = entry.getActiveName();
if (!StringUtils.isEmpty(overriddenActive)) {
MenuEntrySearchResult overriddenResult = adminTool.searchComponent(overriddenActive);
if (null != overriddenResult) {
model.put("activeMenu", overriddenResult.getMenuEntry());
}
}
} else {
model.put("contentPage", AdminTool.ROOTCONTEXT_NAME + AdminTool.SLASH + targetTpl);
}
return targetTpl;
} | java | protected String addCommonContextVars(ModelMap model, HttpServletRequest request, String overrideName, String overrideTarget)
{
LOGGER.debug(String.format("receiving request: ctxPath: %s, uri: %s", request.getContextPath(), request.getRequestURI()));
final String name = menuUtils.getMenuName(request, overrideName);
//get menu entry by name
MenuEntrySearchResult result = adminTool.searchComponent(name);
model.put("internationalizationEnabled", coreConfig.isInternationalizationEnabled());
model.put("rootContext", getRootContext(request));
model.put("adminToolContext", AdminTool.ROOTCONTEXT);
String targetTpl = coreConfig.isEnabled() ? "content/error404" : AdminTool.GENERIC_DEACTIVATED_TEMPLATE_NAME;
if (null != result) {
LOGGER.trace("Component found: " + String.valueOf(null != result.getComponent()) +
" | menu found: " + String.valueOf(result.getMenuEntry()));
model.put(MenuEntrySearchResult.NAME, result);
MenuEntry entry = result.getMenuEntry();
//set alternative target
targetTpl = (StringUtils.isEmpty(overrideTarget) ? entry.getTarget() : AdminToolMenuUtils.normalizeTarget(overrideTarget));
model.put("contentPage", AdminTool.ROOTCONTEXT_NAME + AdminTool.SLASH + targetTpl);
if (null != entry.getVariables()) {
model.putAll(entry.getVariables());
}
model.put("activeMenu", entry);
//since 1.1.6
String overriddenActive = entry.getActiveName();
if (!StringUtils.isEmpty(overriddenActive)) {
MenuEntrySearchResult overriddenResult = adminTool.searchComponent(overriddenActive);
if (null != overriddenResult) {
model.put("activeMenu", overriddenResult.getMenuEntry());
}
}
} else {
model.put("contentPage", AdminTool.ROOTCONTEXT_NAME + AdminTool.SLASH + targetTpl);
}
return targetTpl;
} | [
"protected",
"String",
"addCommonContextVars",
"(",
"ModelMap",
"model",
",",
"HttpServletRequest",
"request",
",",
"String",
"overrideName",
",",
"String",
"overrideTarget",
")",
"{",
"LOGGER",
".",
"debug",
"(",
"String",
".",
"format",
"(",
"\"receiving request: ... | sets common context variables and will override the template name.<br>
this method can be used if you want your special request mappings should resolve a other template
<ul>
<li>contentPage</li>
<li>activeMenuName</li>
<li>activeMenu</li>
<li>rootContext</li>
<li></li>
</ul>
@param model
@param request
@param overrideName | [
"sets",
"common",
"context",
"variables",
"and",
"will",
"override",
"the",
"template",
"name",
".",
"<br",
">",
"this",
"method",
"can",
"be",
"used",
"if",
"you",
"want",
"your",
"special",
"request",
"mappings",
"should",
"resolve",
"a",
"other",
"templat... | train | https://github.com/andrehertwig/admintool/blob/6d391e2d26969b70e3ccabfc34202abe8d915080/admin-tools-core/src/main/java/de/chandre/admintool/core/controller/AbstractAdminController.java#L77-L114 |
oasp/oasp4j | modules/security/src/main/java/io/oasp/module/security/common/base/accesscontrol/AbstractAccessControlProvider.java | AbstractAccessControlProvider.collectPermissionNodes | public void collectPermissionNodes(AccessControlGroup group, Set<AccessControl> permissions) {
boolean added = permissions.add(group);
if (!added) {
// we have already visited this node, stop recursion...
return;
}
for (AccessControlPermission permission : group.getPermissions()) {
permissions.add(permission);
}
for (AccessControlGroup inheritedGroup : group.getInherits()) {
collectPermissionNodes(inheritedGroup, permissions);
}
} | java | public void collectPermissionNodes(AccessControlGroup group, Set<AccessControl> permissions) {
boolean added = permissions.add(group);
if (!added) {
// we have already visited this node, stop recursion...
return;
}
for (AccessControlPermission permission : group.getPermissions()) {
permissions.add(permission);
}
for (AccessControlGroup inheritedGroup : group.getInherits()) {
collectPermissionNodes(inheritedGroup, permissions);
}
} | [
"public",
"void",
"collectPermissionNodes",
"(",
"AccessControlGroup",
"group",
",",
"Set",
"<",
"AccessControl",
">",
"permissions",
")",
"{",
"boolean",
"added",
"=",
"permissions",
".",
"add",
"(",
"group",
")",
";",
"if",
"(",
"!",
"added",
")",
"{",
"... | Recursive implementation of {@link #collectAccessControls(String, Set)} for {@link AccessControlGroup}s.
@param group is the {@link AccessControlGroup} to traverse.
@param permissions is the {@link Set} used to collect. | [
"Recursive",
"implementation",
"of",
"{",
"@link",
"#collectAccessControls",
"(",
"String",
"Set",
")",
"}",
"for",
"{",
"@link",
"AccessControlGroup",
"}",
"s",
"."
] | train | https://github.com/oasp/oasp4j/blob/03f90132699fad95e52ec8efa54aa391f8d3c7e4/modules/security/src/main/java/io/oasp/module/security/common/base/accesscontrol/AbstractAccessControlProvider.java#L212-L225 |
apache/incubator-gobblin | gobblin-modules/gobblin-kafka-common/src/main/java/org/apache/gobblin/kafka/serialize/MD5Digest.java | MD5Digest.fromBytes | public static MD5Digest fromBytes(byte[] md5Bytes)
{
Preconditions.checkArgument(md5Bytes.length == MD5_BYTES_LENGTH,
"md5 bytes must be " + MD5_BYTES_LENGTH + " bytes in length, found " + md5Bytes.length + " bytes.");
String md5String = Hex.encodeHexString(md5Bytes);
return new MD5Digest(md5String, md5Bytes);
} | java | public static MD5Digest fromBytes(byte[] md5Bytes)
{
Preconditions.checkArgument(md5Bytes.length == MD5_BYTES_LENGTH,
"md5 bytes must be " + MD5_BYTES_LENGTH + " bytes in length, found " + md5Bytes.length + " bytes.");
String md5String = Hex.encodeHexString(md5Bytes);
return new MD5Digest(md5String, md5Bytes);
} | [
"public",
"static",
"MD5Digest",
"fromBytes",
"(",
"byte",
"[",
"]",
"md5Bytes",
")",
"{",
"Preconditions",
".",
"checkArgument",
"(",
"md5Bytes",
".",
"length",
"==",
"MD5_BYTES_LENGTH",
",",
"\"md5 bytes must be \"",
"+",
"MD5_BYTES_LENGTH",
"+",
"\" bytes in leng... | Static method to get an MD5Digest from a binary byte representation
@param md5Bytes
@return a filled out MD5Digest | [
"Static",
"method",
"to",
"get",
"an",
"MD5Digest",
"from",
"a",
"binary",
"byte",
"representation"
] | train | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-modules/gobblin-kafka-common/src/main/java/org/apache/gobblin/kafka/serialize/MD5Digest.java#L72-L78 |
salesforce/Argus | ArgusSDK/src/main/java/com/salesforce/dva/argus/sdk/AuthService.java | AuthService.login | public void login(String username, String password) throws IOException {
String requestUrl = RESOURCE + "/login";
Credentials creds = new Credentials();
creds.setPassword(password);
creds.setUsername(username);
ArgusResponse response = getClient().executeHttpRequest(ArgusHttpClient.RequestType.POST, requestUrl, creds);
try {
assertValidResponse(response, requestUrl);
} catch (TokenExpiredException e) {
//This should never happen
throw new RuntimeException("This should never happen. login() method should never throw a TokenExpiredException", e);
}
Map<String, String> tokens = fromJson(response.getResult(), new TypeReference<Map<String, String>>() {});
getClient().accessToken = tokens.get("accessToken");
getClient().refreshToken = tokens.get("refreshToken");
} | java | public void login(String username, String password) throws IOException {
String requestUrl = RESOURCE + "/login";
Credentials creds = new Credentials();
creds.setPassword(password);
creds.setUsername(username);
ArgusResponse response = getClient().executeHttpRequest(ArgusHttpClient.RequestType.POST, requestUrl, creds);
try {
assertValidResponse(response, requestUrl);
} catch (TokenExpiredException e) {
//This should never happen
throw new RuntimeException("This should never happen. login() method should never throw a TokenExpiredException", e);
}
Map<String, String> tokens = fromJson(response.getResult(), new TypeReference<Map<String, String>>() {});
getClient().accessToken = tokens.get("accessToken");
getClient().refreshToken = tokens.get("refreshToken");
} | [
"public",
"void",
"login",
"(",
"String",
"username",
",",
"String",
"password",
")",
"throws",
"IOException",
"{",
"String",
"requestUrl",
"=",
"RESOURCE",
"+",
"\"/login\"",
";",
"Credentials",
"creds",
"=",
"new",
"Credentials",
"(",
")",
";",
"creds",
".... | Logs into Argus.
@param username The username.
@param password The password.
@throws IOException If the server is unavailable. | [
"Logs",
"into",
"Argus",
"."
] | train | https://github.com/salesforce/Argus/blob/121b59a268da264316cded6a3e9271366a23cd86/ArgusSDK/src/main/java/com/salesforce/dva/argus/sdk/AuthService.java#L77-L96 |
avianey/facebook-api-android-maven | facebook/src/main/java/com/facebook/Request.java | Request.executePostRequestAsync | @Deprecated
public static RequestAsyncTask executePostRequestAsync(Session session, String graphPath, GraphObject graphObject,
Callback callback) {
return newPostRequest(session, graphPath, graphObject, callback).executeAsync();
} | java | @Deprecated
public static RequestAsyncTask executePostRequestAsync(Session session, String graphPath, GraphObject graphObject,
Callback callback) {
return newPostRequest(session, graphPath, graphObject, callback).executeAsync();
} | [
"@",
"Deprecated",
"public",
"static",
"RequestAsyncTask",
"executePostRequestAsync",
"(",
"Session",
"session",
",",
"String",
"graphPath",
",",
"GraphObject",
"graphObject",
",",
"Callback",
"callback",
")",
"{",
"return",
"newPostRequest",
"(",
"session",
",",
"g... | Starts a new Request configured to post a GraphObject to a particular graph path, to either create or update the
object at that path.
<p/>
This should only be called from the UI thread.
This method is deprecated. Prefer to call Request.newPostRequest(...).executeAsync();
@param session
the Session to use, or null; if non-null, the session must be in an opened state
@param graphPath
the graph path to retrieve, create, or delete
@param graphObject
the GraphObject to create or update
@param callback
a callback that will be called when the request is completed to handle success or error conditions
@return a RequestAsyncTask that is executing the request | [
"Starts",
"a",
"new",
"Request",
"configured",
"to",
"post",
"a",
"GraphObject",
"to",
"a",
"particular",
"graph",
"path",
"to",
"either",
"create",
"or",
"update",
"the",
"object",
"at",
"that",
"path",
".",
"<p",
"/",
">",
"This",
"should",
"only",
"be... | train | https://github.com/avianey/facebook-api-android-maven/blob/ae6c7aa7ae45739ee19f18c1983e05f7e35b9ede/facebook/src/main/java/com/facebook/Request.java#L1096-L1100 |
deeplearning4j/deeplearning4j | deeplearning4j/deeplearning4j-nn/src/main/java/org/deeplearning4j/gradientcheck/GradientCheckUtil.java | GradientCheckUtil.checkGradients | public static boolean checkGradients(ComputationGraph graph, double epsilon, double maxRelError,
double minAbsoluteError, boolean print, boolean exitOnFirstError, INDArray[] inputs,
INDArray[] labels) {
return checkGradients(graph, epsilon, maxRelError, minAbsoluteError, print, exitOnFirstError, inputs, labels, null, null, null);
} | java | public static boolean checkGradients(ComputationGraph graph, double epsilon, double maxRelError,
double minAbsoluteError, boolean print, boolean exitOnFirstError, INDArray[] inputs,
INDArray[] labels) {
return checkGradients(graph, epsilon, maxRelError, minAbsoluteError, print, exitOnFirstError, inputs, labels, null, null, null);
} | [
"public",
"static",
"boolean",
"checkGradients",
"(",
"ComputationGraph",
"graph",
",",
"double",
"epsilon",
",",
"double",
"maxRelError",
",",
"double",
"minAbsoluteError",
",",
"boolean",
"print",
",",
"boolean",
"exitOnFirstError",
",",
"INDArray",
"[",
"]",
"i... | Check backprop gradients for a ComputationGraph
@param graph ComputationGraph to test. This must be initialized.
@param epsilon Usually on the order of 1e-4 or so.
@param maxRelError Maximum relative error. Usually < 0.01, though maybe more for deep networks
@param minAbsoluteError Minimum absolute error to cause a failure. Numerical gradients can be non-zero due to precision issues.
For example, 0.0 vs. 1e-18: relative error is 1.0, but not really a failure
@param print Whether to print full pass/failure details for each parameter gradient
@param exitOnFirstError If true: return upon first failure. If false: continue checking even if
one parameter gradient has failed. Typically use false for debugging, true for unit tests.
@param inputs Input arrays to use for forward pass. May be mini-batch data.
@param labels Labels/targets (output) arrays to use to calculate backprop gradient. May be mini-batch data.
@return true if gradients are passed, false otherwise. | [
"Check",
"backprop",
"gradients",
"for",
"a",
"ComputationGraph"
] | train | https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/deeplearning4j/deeplearning4j-nn/src/main/java/org/deeplearning4j/gradientcheck/GradientCheckUtil.java#L423-L427 |
apache/incubator-gobblin | gobblin-utility/src/main/java/org/apache/gobblin/util/HadoopUtils.java | HadoopUtils.safeRenameIfNotExists | public synchronized static boolean safeRenameIfNotExists(FileSystem fs, Path from, Path to) throws IOException {
return unsafeRenameIfNotExists(fs, from, to);
} | java | public synchronized static boolean safeRenameIfNotExists(FileSystem fs, Path from, Path to) throws IOException {
return unsafeRenameIfNotExists(fs, from, to);
} | [
"public",
"synchronized",
"static",
"boolean",
"safeRenameIfNotExists",
"(",
"FileSystem",
"fs",
",",
"Path",
"from",
",",
"Path",
"to",
")",
"throws",
"IOException",
"{",
"return",
"unsafeRenameIfNotExists",
"(",
"fs",
",",
"from",
",",
"to",
")",
";",
"}"
] | Renames from to to if to doesn't exist in a thread-safe way. This method is necessary because
{@link FileSystem#rename} is inconsistent across file system implementations, e.g. in some of them rename(foo, bar)
will create bar/foo if bar already existed, but it will only create bar if it didn't.
<p>
The thread-safety is only guaranteed among calls to this method. An external modification to the relevant
target directory could still cause unexpected results in the renaming.
</p>
@param fs filesystem where rename will be executed.
@param from origin {@link Path}.
@param to target {@link Path}.
@return true if rename succeeded, false if the target already exists.
@throws IOException if rename failed for reasons other than target exists. | [
"Renames",
"from",
"to",
"to",
"if",
"to",
"doesn",
"t",
"exist",
"in",
"a",
"thread",
"-",
"safe",
"way",
".",
"This",
"method",
"is",
"necessary",
"because",
"{",
"@link",
"FileSystem#rename",
"}",
"is",
"inconsistent",
"across",
"file",
"system",
"imple... | train | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-utility/src/main/java/org/apache/gobblin/util/HadoopUtils.java#L635-L637 |
Carbonado/Carbonado | src/main/java/com/amazon/carbonado/info/ChainedProperty.java | ChainedProperty.trim | public ChainedProperty<S> trim() {
if (getChainCount() == 0) {
throw new IllegalStateException();
}
if (getChainCount() == 1) {
if (!isOuterJoin(0)) {
return get(mPrime);
} else {
return get(mPrime, null, new boolean[] {true});
}
}
StorableProperty<?>[] newChain = new StorableProperty[getChainCount() - 1];
System.arraycopy(mChain, 0, newChain, 0, newChain.length);
boolean[] newOuterJoin = mOuterJoin;
if (newOuterJoin != null && newOuterJoin.length > (newChain.length + 1)) {
newOuterJoin = new boolean[newChain.length + 1];
System.arraycopy(mOuterJoin, 0, newOuterJoin, 0, newChain.length + 1);
}
return get(mPrime, newChain, newOuterJoin);
} | java | public ChainedProperty<S> trim() {
if (getChainCount() == 0) {
throw new IllegalStateException();
}
if (getChainCount() == 1) {
if (!isOuterJoin(0)) {
return get(mPrime);
} else {
return get(mPrime, null, new boolean[] {true});
}
}
StorableProperty<?>[] newChain = new StorableProperty[getChainCount() - 1];
System.arraycopy(mChain, 0, newChain, 0, newChain.length);
boolean[] newOuterJoin = mOuterJoin;
if (newOuterJoin != null && newOuterJoin.length > (newChain.length + 1)) {
newOuterJoin = new boolean[newChain.length + 1];
System.arraycopy(mOuterJoin, 0, newOuterJoin, 0, newChain.length + 1);
}
return get(mPrime, newChain, newOuterJoin);
} | [
"public",
"ChainedProperty",
"<",
"S",
">",
"trim",
"(",
")",
"{",
"if",
"(",
"getChainCount",
"(",
")",
"==",
"0",
")",
"{",
"throw",
"new",
"IllegalStateException",
"(",
")",
";",
"}",
"if",
"(",
"getChainCount",
"(",
")",
"==",
"1",
")",
"{",
"i... | Returns a new ChainedProperty with the last property in the chain removed.
@throws IllegalStateException if chain count is zero | [
"Returns",
"a",
"new",
"ChainedProperty",
"with",
"the",
"last",
"property",
"in",
"the",
"chain",
"removed",
"."
] | train | https://github.com/Carbonado/Carbonado/blob/eee29b365a61c8f03e1a1dc6bed0692e6b04b1db/src/main/java/com/amazon/carbonado/info/ChainedProperty.java#L410-L432 |
reactor/reactor-netty | src/main/java/reactor/netty/http/server/HttpServer.java | HttpServer.cookieCodec | public final HttpServer cookieCodec(ServerCookieEncoder encoder, ServerCookieDecoder decoder) {
return tcpConfiguration(tcp -> tcp.bootstrap(
b -> HttpServerConfiguration.cookieCodec(b, encoder, decoder)));
} | java | public final HttpServer cookieCodec(ServerCookieEncoder encoder, ServerCookieDecoder decoder) {
return tcpConfiguration(tcp -> tcp.bootstrap(
b -> HttpServerConfiguration.cookieCodec(b, encoder, decoder)));
} | [
"public",
"final",
"HttpServer",
"cookieCodec",
"(",
"ServerCookieEncoder",
"encoder",
",",
"ServerCookieDecoder",
"decoder",
")",
"{",
"return",
"tcpConfiguration",
"(",
"tcp",
"->",
"tcp",
".",
"bootstrap",
"(",
"b",
"->",
"HttpServerConfiguration",
".",
"cookieCo... | Configure the
{@link ServerCookieEncoder} and {@link ServerCookieDecoder}
@param encoder the preferred ServerCookieEncoder
@param decoder the preferred ServerCookieDecoder
@return a new {@link HttpServer} | [
"Configure",
"the",
"{",
"@link",
"ServerCookieEncoder",
"}",
"and",
"{",
"@link",
"ServerCookieDecoder",
"}"
] | train | https://github.com/reactor/reactor-netty/blob/4ed14316e1d7fca3cecd18d6caa5f2251e159e49/src/main/java/reactor/netty/http/server/HttpServer.java#L340-L343 |
mapbox/mapbox-java | services-core/src/main/java/com/mapbox/core/utils/TextUtils.java | TextUtils.formatRadiuses | public static String formatRadiuses(double[] radiuses) {
if (radiuses == null || radiuses.length == 0) {
return null;
}
String[] radiusesFormatted = new String[radiuses.length];
for (int i = 0; i < radiuses.length; i++) {
if (radiuses[i] == Double.POSITIVE_INFINITY) {
radiusesFormatted[i] = "unlimited";
} else {
radiusesFormatted[i] = String.format(Locale.US, "%s",
TextUtils.formatCoordinate(radiuses[i]));
}
}
return join(";", radiusesFormatted);
} | java | public static String formatRadiuses(double[] radiuses) {
if (radiuses == null || radiuses.length == 0) {
return null;
}
String[] radiusesFormatted = new String[radiuses.length];
for (int i = 0; i < radiuses.length; i++) {
if (radiuses[i] == Double.POSITIVE_INFINITY) {
radiusesFormatted[i] = "unlimited";
} else {
radiusesFormatted[i] = String.format(Locale.US, "%s",
TextUtils.formatCoordinate(radiuses[i]));
}
}
return join(";", radiusesFormatted);
} | [
"public",
"static",
"String",
"formatRadiuses",
"(",
"double",
"[",
"]",
"radiuses",
")",
"{",
"if",
"(",
"radiuses",
"==",
"null",
"||",
"radiuses",
".",
"length",
"==",
"0",
")",
"{",
"return",
"null",
";",
"}",
"String",
"[",
"]",
"radiusesFormatted",... | Used in various APIs to format the user provided radiuses to a String matching the APIs format.
@param radiuses a double array which represents the radius values
@return a String ready for being passed into the Retrofit call
@since 3.0.0 | [
"Used",
"in",
"various",
"APIs",
"to",
"format",
"the",
"user",
"provided",
"radiuses",
"to",
"a",
"String",
"matching",
"the",
"APIs",
"format",
"."
] | train | https://github.com/mapbox/mapbox-java/blob/c0be138f462f91441388584c668f3760ba0e18e2/services-core/src/main/java/com/mapbox/core/utils/TextUtils.java#L97-L112 |
Alluxio/alluxio | core/server/worker/src/main/java/alluxio/worker/block/meta/StorageDir.java | StorageDir.getBlockMeta | public BlockMeta getBlockMeta(long blockId) throws BlockDoesNotExistException {
BlockMeta blockMeta = mBlockIdToBlockMap.get(blockId);
if (blockMeta == null) {
throw new BlockDoesNotExistException(ExceptionMessage.BLOCK_META_NOT_FOUND, blockId);
}
return blockMeta;
} | java | public BlockMeta getBlockMeta(long blockId) throws BlockDoesNotExistException {
BlockMeta blockMeta = mBlockIdToBlockMap.get(blockId);
if (blockMeta == null) {
throw new BlockDoesNotExistException(ExceptionMessage.BLOCK_META_NOT_FOUND, blockId);
}
return blockMeta;
} | [
"public",
"BlockMeta",
"getBlockMeta",
"(",
"long",
"blockId",
")",
"throws",
"BlockDoesNotExistException",
"{",
"BlockMeta",
"blockMeta",
"=",
"mBlockIdToBlockMap",
".",
"get",
"(",
"blockId",
")",
";",
"if",
"(",
"blockMeta",
"==",
"null",
")",
"{",
"throw",
... | Gets the {@link BlockMeta} from this storage dir by its block id.
@param blockId the block id
@return {@link BlockMeta} of the given block or null
@throws BlockDoesNotExistException if no block is found | [
"Gets",
"the",
"{",
"@link",
"BlockMeta",
"}",
"from",
"this",
"storage",
"dir",
"by",
"its",
"block",
"id",
"."
] | train | https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/server/worker/src/main/java/alluxio/worker/block/meta/StorageDir.java#L247-L253 |
Netflix/karyon | karyon2-governator/src/main/java/netflix/karyon/Karyon.java | Karyon.forHttpServer | public static KaryonServer forHttpServer(HttpServer<?, ?> server, Module... modules) {
return forHttpServer(server, toBootstrapModule(modules));
} | java | public static KaryonServer forHttpServer(HttpServer<?, ?> server, Module... modules) {
return forHttpServer(server, toBootstrapModule(modules));
} | [
"public",
"static",
"KaryonServer",
"forHttpServer",
"(",
"HttpServer",
"<",
"?",
",",
"?",
">",
"server",
",",
"Module",
"...",
"modules",
")",
"{",
"return",
"forHttpServer",
"(",
"server",
",",
"toBootstrapModule",
"(",
"modules",
")",
")",
";",
"}"
] | Creates a new {@link KaryonServer} which combines lifecycle of the passed {@link HttpServer} with
it's own lifecycle.
@param server HTTP server
@param modules Additional bootstrapModules if any.
@return {@link KaryonServer} which is to be used to start the created server. | [
"Creates",
"a",
"new",
"{",
"@link",
"KaryonServer",
"}",
"which",
"combines",
"lifecycle",
"of",
"the",
"passed",
"{",
"@link",
"HttpServer",
"}",
"with",
"it",
"s",
"own",
"lifecycle",
"."
] | train | https://github.com/Netflix/karyon/blob/d50bc0ff37693ef3fbda373e90a109d1f92e0b9a/karyon2-governator/src/main/java/netflix/karyon/Karyon.java#L177-L179 |
graphhopper/map-matching | matching-web/src/main/java/com/graphhopper/matching/cli/MeasurementCommand.java | MeasurementCommand.printTimeOfMapMatchQuery | private void printTimeOfMapMatchQuery(final GraphHopper hopper, final MapMatching mapMatching) {
// pick random start/end points to create a route, then pick random points from the route,
// and then run the random points through map-matching.
final double latDelta = bbox.maxLat - bbox.minLat;
final double lonDelta = bbox.maxLon - bbox.minLon;
final Random rand = new Random(seed);
MiniPerfTest miniPerf = new MiniPerfTest() {
@Override
public int doCalc(boolean warmup, int run) {
// keep going until we find a path (which we may not for certain start/end points)
while (true) {
// create random points and find route between:
double lat0 = bbox.minLat + rand.nextDouble() * latDelta;
double lon0 = bbox.minLon + rand.nextDouble() * lonDelta;
double lat1 = bbox.minLat + rand.nextDouble() * latDelta;
double lon1 = bbox.minLon + rand.nextDouble() * lonDelta;
GHResponse r = hopper.route(new GHRequest(lat0, lon0, lat1, lon1));
// if found, use it for map matching:
if (!r.hasErrors()) {
double sampleProportion = rand.nextDouble();
GHPoint prev = null;
List<Observation> mock = new ArrayList<>();
PointList points = r.getBest().getPoints();
// loop through points and add (approximately) sampleProportion of them:
for (GHPoint p : points) {
if (null != prev && rand.nextDouble() < sampleProportion) {
// randomise the point lat/lon (i.e. so it's not
// exactly on the route):
GHPoint randomised = distCalc.projectCoordinate(p.lat, p.lon,
20 * rand.nextDouble(), 360 * rand.nextDouble());
mock.add(new Observation(randomised));
}
prev = p;
}
// now match, provided there are enough points
if (mock.size() > 2) {
MatchResult match = mapMatching.doWork(mock);
// return something non-trivial, to avoid JVM optimizing away
return match.getEdgeMatches().size();
}
}
}
}
}.setIterations(count).start();
print("map_match", miniPerf);
} | java | private void printTimeOfMapMatchQuery(final GraphHopper hopper, final MapMatching mapMatching) {
// pick random start/end points to create a route, then pick random points from the route,
// and then run the random points through map-matching.
final double latDelta = bbox.maxLat - bbox.minLat;
final double lonDelta = bbox.maxLon - bbox.minLon;
final Random rand = new Random(seed);
MiniPerfTest miniPerf = new MiniPerfTest() {
@Override
public int doCalc(boolean warmup, int run) {
// keep going until we find a path (which we may not for certain start/end points)
while (true) {
// create random points and find route between:
double lat0 = bbox.minLat + rand.nextDouble() * latDelta;
double lon0 = bbox.minLon + rand.nextDouble() * lonDelta;
double lat1 = bbox.minLat + rand.nextDouble() * latDelta;
double lon1 = bbox.minLon + rand.nextDouble() * lonDelta;
GHResponse r = hopper.route(new GHRequest(lat0, lon0, lat1, lon1));
// if found, use it for map matching:
if (!r.hasErrors()) {
double sampleProportion = rand.nextDouble();
GHPoint prev = null;
List<Observation> mock = new ArrayList<>();
PointList points = r.getBest().getPoints();
// loop through points and add (approximately) sampleProportion of them:
for (GHPoint p : points) {
if (null != prev && rand.nextDouble() < sampleProportion) {
// randomise the point lat/lon (i.e. so it's not
// exactly on the route):
GHPoint randomised = distCalc.projectCoordinate(p.lat, p.lon,
20 * rand.nextDouble(), 360 * rand.nextDouble());
mock.add(new Observation(randomised));
}
prev = p;
}
// now match, provided there are enough points
if (mock.size() > 2) {
MatchResult match = mapMatching.doWork(mock);
// return something non-trivial, to avoid JVM optimizing away
return match.getEdgeMatches().size();
}
}
}
}
}.setIterations(count).start();
print("map_match", miniPerf);
} | [
"private",
"void",
"printTimeOfMapMatchQuery",
"(",
"final",
"GraphHopper",
"hopper",
",",
"final",
"MapMatching",
"mapMatching",
")",
"{",
"// pick random start/end points to create a route, then pick random points from the route,",
"// and then run the random points through map-matchin... | Test the time taken for map matching on random routes. Note that this includes the index
lookups (previous tests), so will be affected by those. Otherwise this is largely testing the
routing and HMM performance. | [
"Test",
"the",
"time",
"taken",
"for",
"map",
"matching",
"on",
"random",
"routes",
".",
"Note",
"that",
"this",
"includes",
"the",
"index",
"lookups",
"(",
"previous",
"tests",
")",
"so",
"will",
"be",
"affected",
"by",
"those",
".",
"Otherwise",
"this",
... | train | https://github.com/graphhopper/map-matching/blob/32cd83f14cb990c2be83c8781f22dfb59e0dbeb4/matching-web/src/main/java/com/graphhopper/matching/cli/MeasurementCommand.java#L165-L212 |
alibaba/canal | client/src/main/java/com/alibaba/otter/canal/client/kafka/KafkaOffsetCanalConnector.java | KafkaOffsetCanalConnector.getFlatListWithoutAck | public List<KafkaFlatMessage> getFlatListWithoutAck(Long timeout, TimeUnit unit, long offset) throws CanalClientException {
waitClientRunning();
if (!running) {
return Lists.newArrayList();
}
if (offset > -1) {
TopicPartition tp = new TopicPartition(topic, partition == null ? 0 : partition);
kafkaConsumer2.seek(tp, offset);
}
ConsumerRecords<String, String> records = kafkaConsumer2.poll(unit.toMillis(timeout));
if (!records.isEmpty()) {
List<KafkaFlatMessage> flatMessages = new ArrayList<>();
for (ConsumerRecord<String, String> record : records) {
String flatMessageJson = record.value();
FlatMessage flatMessage = JSON.parseObject(flatMessageJson, FlatMessage.class);
KafkaFlatMessage message = new KafkaFlatMessage(flatMessage, record.offset());
flatMessages.add(message);
}
return flatMessages;
}
return Lists.newArrayList();
} | java | public List<KafkaFlatMessage> getFlatListWithoutAck(Long timeout, TimeUnit unit, long offset) throws CanalClientException {
waitClientRunning();
if (!running) {
return Lists.newArrayList();
}
if (offset > -1) {
TopicPartition tp = new TopicPartition(topic, partition == null ? 0 : partition);
kafkaConsumer2.seek(tp, offset);
}
ConsumerRecords<String, String> records = kafkaConsumer2.poll(unit.toMillis(timeout));
if (!records.isEmpty()) {
List<KafkaFlatMessage> flatMessages = new ArrayList<>();
for (ConsumerRecord<String, String> record : records) {
String flatMessageJson = record.value();
FlatMessage flatMessage = JSON.parseObject(flatMessageJson, FlatMessage.class);
KafkaFlatMessage message = new KafkaFlatMessage(flatMessage, record.offset());
flatMessages.add(message);
}
return flatMessages;
}
return Lists.newArrayList();
} | [
"public",
"List",
"<",
"KafkaFlatMessage",
">",
"getFlatListWithoutAck",
"(",
"Long",
"timeout",
",",
"TimeUnit",
"unit",
",",
"long",
"offset",
")",
"throws",
"CanalClientException",
"{",
"waitClientRunning",
"(",
")",
";",
"if",
"(",
"!",
"running",
")",
"{"... | 获取Kafka消息,不确认
@param timeout
@param unit
@param offset 消息偏移地址(-1为不偏移)
@return
@throws CanalClientException | [
"获取Kafka消息,不确认"
] | train | https://github.com/alibaba/canal/blob/8f088cddc0755f4350c5aaae95c6e4002d90a40f/client/src/main/java/com/alibaba/otter/canal/client/kafka/KafkaOffsetCanalConnector.java#L76-L100 |
Activiti/Activiti | activiti-engine/src/main/java/org/activiti/engine/impl/util/ReflectUtil.java | ReflectUtil.getField | public static Field getField(String fieldName, Object object) {
return getField(fieldName, object.getClass());
} | java | public static Field getField(String fieldName, Object object) {
return getField(fieldName, object.getClass());
} | [
"public",
"static",
"Field",
"getField",
"(",
"String",
"fieldName",
",",
"Object",
"object",
")",
"{",
"return",
"getField",
"(",
"fieldName",
",",
"object",
".",
"getClass",
"(",
")",
")",
";",
"}"
] | Returns the field of the given object or null if it doesn't exist. | [
"Returns",
"the",
"field",
"of",
"the",
"given",
"object",
"or",
"null",
"if",
"it",
"doesn",
"t",
"exist",
"."
] | train | https://github.com/Activiti/Activiti/blob/82e2b2cd2083b2f734ca0efc7815389c0f2517d9/activiti-engine/src/main/java/org/activiti/engine/impl/util/ReflectUtil.java#L155-L157 |
wisdom-framework/wisdom | core/wisdom-maven-plugin/src/main/java/org/wisdom/maven/mojos/BundlePackagerMojo.java | BundlePackagerMojo.accept | @Override
public boolean accept(File file) {
return WatcherUtils.isInDirectory(file, WatcherUtils.getJavaSource(basedir))
|| WatcherUtils.isInDirectory(file, WatcherUtils.getResources(basedir))
|| file.getAbsolutePath().equals(new File(basedir, INSTRUCTIONS_FILE).getAbsolutePath());
} | java | @Override
public boolean accept(File file) {
return WatcherUtils.isInDirectory(file, WatcherUtils.getJavaSource(basedir))
|| WatcherUtils.isInDirectory(file, WatcherUtils.getResources(basedir))
|| file.getAbsolutePath().equals(new File(basedir, INSTRUCTIONS_FILE).getAbsolutePath());
} | [
"@",
"Override",
"public",
"boolean",
"accept",
"(",
"File",
"file",
")",
"{",
"return",
"WatcherUtils",
".",
"isInDirectory",
"(",
"file",
",",
"WatcherUtils",
".",
"getJavaSource",
"(",
"basedir",
")",
")",
"||",
"WatcherUtils",
".",
"isInDirectory",
"(",
... | The bundle packaging has to be triggered when: a Java source file is modified,
an internal resource is modified or the `osgi.bnd` file (containing BND instructions) is modified.
@param file the file
@return {@literal true} if an event on the given file should trigger the recreation of the bundle. | [
"The",
"bundle",
"packaging",
"has",
"to",
"be",
"triggered",
"when",
":",
"a",
"Java",
"source",
"file",
"is",
"modified",
"an",
"internal",
"resource",
"is",
"modified",
"or",
"the",
"osgi",
".",
"bnd",
"file",
"(",
"containing",
"BND",
"instructions",
"... | train | https://github.com/wisdom-framework/wisdom/blob/a35b6431200fec56b178c0ff60837ed73fd7874d/core/wisdom-maven-plugin/src/main/java/org/wisdom/maven/mojos/BundlePackagerMojo.java#L217-L222 |
Impetus/Kundera | src/jpa-engine/fallback-impl/src/main/java/com/impetus/kundera/index/DocumentIndexer.java | DocumentIndexer.createSuperColumnDocument | protected void createSuperColumnDocument(EntityMetadata metadata, Object object, Document currentDoc,
Object embeddedObject, EmbeddableType superColumn, MetamodelImpl metamodel) {
// Add all super column fields into document
Set<Attribute> attributes = superColumn.getAttributes();
Iterator<Attribute> iter = attributes.iterator();
while (iter.hasNext()) {
Attribute attr = iter.next();
java.lang.reflect.Field field = (java.lang.reflect.Field) attr.getJavaMember();
String colName = field.getName();
String indexName = metadata.getIndexName();
addFieldToDocument(embeddedObject, currentDoc, field, colName, indexName);
}
// Add all entity fields to document
addEntityFieldsToDocument(metadata, object, currentDoc, metamodel);
} | java | protected void createSuperColumnDocument(EntityMetadata metadata, Object object, Document currentDoc,
Object embeddedObject, EmbeddableType superColumn, MetamodelImpl metamodel) {
// Add all super column fields into document
Set<Attribute> attributes = superColumn.getAttributes();
Iterator<Attribute> iter = attributes.iterator();
while (iter.hasNext()) {
Attribute attr = iter.next();
java.lang.reflect.Field field = (java.lang.reflect.Field) attr.getJavaMember();
String colName = field.getName();
String indexName = metadata.getIndexName();
addFieldToDocument(embeddedObject, currentDoc, field, colName, indexName);
}
// Add all entity fields to document
addEntityFieldsToDocument(metadata, object, currentDoc, metamodel);
} | [
"protected",
"void",
"createSuperColumnDocument",
"(",
"EntityMetadata",
"metadata",
",",
"Object",
"object",
",",
"Document",
"currentDoc",
",",
"Object",
"embeddedObject",
",",
"EmbeddableType",
"superColumn",
",",
"MetamodelImpl",
"metamodel",
")",
"{",
"// Add all s... | Index super column.
@param metadata
the metadata
@param object
the object
@param currentDoc
the current doc
@param embeddedObject
the embedded object
@param superColumn
the super column
@param metamodel | [
"Index",
"super",
"column",
"."
] | train | https://github.com/Impetus/Kundera/blob/268958ab1ec09d14ec4d9184f0c8ded7a9158908/src/jpa-engine/fallback-impl/src/main/java/com/impetus/kundera/index/DocumentIndexer.java#L168-L185 |
RoaringBitmap/RoaringBitmap | jmh/src/main/java/org/roaringbitmap/bithacking/SelectBenchmark.java | SelectBenchmark.select | public static int select(long w, int j) {
int part1 = (int) (w & 0xFFFFFFFF);
int wfirsthalf = Integer.bitCount(part1);
if (wfirsthalf > j) {
return select(part1, j);
} else {
return select((int) (w >>> 32), j - wfirsthalf) + 32;
}
} | java | public static int select(long w, int j) {
int part1 = (int) (w & 0xFFFFFFFF);
int wfirsthalf = Integer.bitCount(part1);
if (wfirsthalf > j) {
return select(part1, j);
} else {
return select((int) (w >>> 32), j - wfirsthalf) + 32;
}
} | [
"public",
"static",
"int",
"select",
"(",
"long",
"w",
",",
"int",
"j",
")",
"{",
"int",
"part1",
"=",
"(",
"int",
")",
"(",
"w",
"&",
"0xFFFFFFFF",
")",
";",
"int",
"wfirsthalf",
"=",
"Integer",
".",
"bitCount",
"(",
"part1",
")",
";",
"if",
"("... | Given a word w, return the position of the jth true bit.
@param w word
@param j index
@return position of jth true bit in w | [
"Given",
"a",
"word",
"w",
"return",
"the",
"position",
"of",
"the",
"jth",
"true",
"bit",
"."
] | train | https://github.com/RoaringBitmap/RoaringBitmap/blob/b26fd0a1330fd4d2877f4d74feb69ceb812e9efa/jmh/src/main/java/org/roaringbitmap/bithacking/SelectBenchmark.java#L120-L128 |
strator-dev/greenpepper | greenpepper-open/confluence/greenpepper-confluence-code/src/main/java/com/greenpepper/confluence/macros/historic/AbstractChartBuilder.java | AbstractChartBuilder.customizeTitle | protected void customizeTitle(TextTitle title, Font font)
{
title.setFont(font);
title.setTextAlignment(HorizontalAlignment.LEFT);
title.setPaint(Color.BLACK);
title.setBackgroundPaint(TRANSPARENT_COLOR);
} | java | protected void customizeTitle(TextTitle title, Font font)
{
title.setFont(font);
title.setTextAlignment(HorizontalAlignment.LEFT);
title.setPaint(Color.BLACK);
title.setBackgroundPaint(TRANSPARENT_COLOR);
} | [
"protected",
"void",
"customizeTitle",
"(",
"TextTitle",
"title",
",",
"Font",
"font",
")",
"{",
"title",
".",
"setFont",
"(",
"font",
")",
";",
"title",
".",
"setTextAlignment",
"(",
"HorizontalAlignment",
".",
"LEFT",
")",
";",
"title",
".",
"setPaint",
... | <p>customizeTitle.</p>
@param title a {@link org.jfree.chart.title.TextTitle} object.
@param font a {@link java.awt.Font} object. | [
"<p",
">",
"customizeTitle",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/strator-dev/greenpepper/blob/2a61e6c179b74085babcc559d677490b0cad2d30/greenpepper-open/confluence/greenpepper-confluence-code/src/main/java/com/greenpepper/confluence/macros/historic/AbstractChartBuilder.java#L154-L160 |
vincentbrison/dualcache | dualcache-library/src/main/java/com/vincentbrison/openlibraries/android/dualcache/Logger.java | Logger.logInfo | void logInfo(String tag, String msg) {
log(Log.INFO, tag, msg);
} | java | void logInfo(String tag, String msg) {
log(Log.INFO, tag, msg);
} | [
"void",
"logInfo",
"(",
"String",
"tag",
",",
"String",
"msg",
")",
"{",
"log",
"(",
"Log",
".",
"INFO",
",",
"tag",
",",
"msg",
")",
";",
"}"
] | Log with level info.
@param tag is the tag to used.
@param msg is the msg to log. | [
"Log",
"with",
"level",
"info",
"."
] | train | https://github.com/vincentbrison/dualcache/blob/76ec6e08d5b8b17aca97d01e5fb5f36cb4beff5f/dualcache-library/src/main/java/com/vincentbrison/openlibraries/android/dualcache/Logger.java#L44-L46 |
facebook/fresco | samples/zoomable/src/main/java/com/facebook/samples/zoomable/DefaultZoomableController.java | DefaultZoomableController.isMatrixIdentity | private boolean isMatrixIdentity(Matrix transform, float eps) {
// Checks whether the given matrix is close enough to the identity matrix:
// 1 0 0
// 0 1 0
// 0 0 1
// Or equivalently to the zero matrix, after subtracting 1.0f from the diagonal elements:
// 0 0 0
// 0 0 0
// 0 0 0
transform.getValues(mTempValues);
mTempValues[0] -= 1.0f; // m00
mTempValues[4] -= 1.0f; // m11
mTempValues[8] -= 1.0f; // m22
for (int i = 0; i < 9; i++) {
if (Math.abs(mTempValues[i]) > eps) {
return false;
}
}
return true;
} | java | private boolean isMatrixIdentity(Matrix transform, float eps) {
// Checks whether the given matrix is close enough to the identity matrix:
// 1 0 0
// 0 1 0
// 0 0 1
// Or equivalently to the zero matrix, after subtracting 1.0f from the diagonal elements:
// 0 0 0
// 0 0 0
// 0 0 0
transform.getValues(mTempValues);
mTempValues[0] -= 1.0f; // m00
mTempValues[4] -= 1.0f; // m11
mTempValues[8] -= 1.0f; // m22
for (int i = 0; i < 9; i++) {
if (Math.abs(mTempValues[i]) > eps) {
return false;
}
}
return true;
} | [
"private",
"boolean",
"isMatrixIdentity",
"(",
"Matrix",
"transform",
",",
"float",
"eps",
")",
"{",
"// Checks whether the given matrix is close enough to the identity matrix:",
"// 1 0 0",
"// 0 1 0",
"// 0 0 1",
"// Or equivalently to the zero matrix, after subtracting 1.0f fr... | Same as {@code Matrix.isIdentity()}, but with tolerance {@code eps}. | [
"Same",
"as",
"{"
] | train | https://github.com/facebook/fresco/blob/0b85879d51c5036d5e46e627a6651afefc0b971a/samples/zoomable/src/main/java/com/facebook/samples/zoomable/DefaultZoomableController.java#L609-L628 |
igniterealtime/Smack | smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/Node.java | Node.modifyAffiliationAsOwner | public PubSub modifyAffiliationAsOwner(List<Affiliation> affiliations) throws NoResponseException,
XMPPErrorException, NotConnectedException, InterruptedException {
for (Affiliation affiliation : affiliations) {
if (affiliation.getPubSubNamespace() != PubSubNamespace.owner) {
throw new IllegalArgumentException("Must use Affiliation(BareJid, Type) affiliations");
}
}
PubSub pubSub = createPubsubPacket(Type.set, new AffiliationsExtension(AffiliationNamespace.owner, affiliations, getId()));
return sendPubsubPacket(pubSub);
} | java | public PubSub modifyAffiliationAsOwner(List<Affiliation> affiliations) throws NoResponseException,
XMPPErrorException, NotConnectedException, InterruptedException {
for (Affiliation affiliation : affiliations) {
if (affiliation.getPubSubNamespace() != PubSubNamespace.owner) {
throw new IllegalArgumentException("Must use Affiliation(BareJid, Type) affiliations");
}
}
PubSub pubSub = createPubsubPacket(Type.set, new AffiliationsExtension(AffiliationNamespace.owner, affiliations, getId()));
return sendPubsubPacket(pubSub);
} | [
"public",
"PubSub",
"modifyAffiliationAsOwner",
"(",
"List",
"<",
"Affiliation",
">",
"affiliations",
")",
"throws",
"NoResponseException",
",",
"XMPPErrorException",
",",
"NotConnectedException",
",",
"InterruptedException",
"{",
"for",
"(",
"Affiliation",
"affiliation",... | Modify the affiliations for this PubSub node as owner. The {@link Affiliation}s given must be created with the
{@link Affiliation#Affiliation(org.jxmpp.jid.BareJid, Affiliation.Type)} constructor.
<p>
Note that this is an <b>optional</b> PubSub feature ('pubsub#modify-affiliations').
</p>
@param affiliations
@return <code>null</code> or a PubSub stanza with additional information on success.
@throws NoResponseException
@throws XMPPErrorException
@throws NotConnectedException
@throws InterruptedException
@see <a href="http://www.xmpp.org/extensions/xep-0060.html#owner-affiliations-modify">XEP-60 § 8.9.2 Modify Affiliation</a>
@since 4.2 | [
"Modify",
"the",
"affiliations",
"for",
"this",
"PubSub",
"node",
"as",
"owner",
".",
"The",
"{",
"@link",
"Affiliation",
"}",
"s",
"given",
"must",
"be",
"created",
"with",
"the",
"{",
"@link",
"Affiliation#Affiliation",
"(",
"org",
".",
"jxmpp",
".",
"ji... | train | https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/Node.java#L359-L369 |
osiam/connector4java | src/main/java/org/osiam/client/OsiamConnector.java | OsiamConnector.replaceGroup | public Group replaceGroup(String id, Group group, AccessToken accessToken) {
return getGroupService().replaceGroup(id, group, accessToken);
} | java | public Group replaceGroup(String id, Group group, AccessToken accessToken) {
return getGroupService().replaceGroup(id, group, accessToken);
} | [
"public",
"Group",
"replaceGroup",
"(",
"String",
"id",
",",
"Group",
"group",
",",
"AccessToken",
"accessToken",
")",
"{",
"return",
"getGroupService",
"(",
")",
".",
"replaceGroup",
"(",
"id",
",",
"group",
",",
"accessToken",
")",
";",
"}"
] | replaces the {@link Group} with the given id with the given {@link Group}
@param id The id of the Group to be replaced
@param group The {@link Group} who will repleace the old {@link Group}
@param accessToken the OSIAM access token from for the current session
@return the replaced User
@throws InvalidAttributeException in case the id or the Group is null or empty
@throws UnauthorizedException if the request could not be authorized.
@throws ConflictException if the Group could not be replaced
@throws NoResultException if no Group with the given id can be found
@throws ForbiddenException if the scope doesn't allow this request
@throws ConnectionInitializationException if the connection to the given OSIAM service could not be initialized
@throws IllegalStateException if OSIAM's endpoint(s) are not properly configured | [
"replaces",
"the",
"{",
"@link",
"Group",
"}",
"with",
"the",
"given",
"id",
"with",
"the",
"given",
"{",
"@link",
"Group",
"}"
] | train | https://github.com/osiam/connector4java/blob/a5e6ae1e706f4889d662a069fe2f3bf8e3848d12/src/main/java/org/osiam/client/OsiamConnector.java#L586-L588 |
geomajas/geomajas-project-client-gwt | client/src/main/java/org/geomajas/gwt/client/spatial/Mathlib.java | Mathlib.lineSegmentIntersection | public Coordinate lineSegmentIntersection(Coordinate c1, Coordinate c2, Coordinate c3, Coordinate c4) {
LineSegment ls1 = new LineSegment(c1, c2);
LineSegment ls2 = new LineSegment(c3, c4);
return ls1.getIntersectionSegments(ls2);
} | java | public Coordinate lineSegmentIntersection(Coordinate c1, Coordinate c2, Coordinate c3, Coordinate c4) {
LineSegment ls1 = new LineSegment(c1, c2);
LineSegment ls2 = new LineSegment(c3, c4);
return ls1.getIntersectionSegments(ls2);
} | [
"public",
"Coordinate",
"lineSegmentIntersection",
"(",
"Coordinate",
"c1",
",",
"Coordinate",
"c2",
",",
"Coordinate",
"c3",
",",
"Coordinate",
"c4",
")",
"{",
"LineSegment",
"ls1",
"=",
"new",
"LineSegment",
"(",
"c1",
",",
"c2",
")",
";",
"LineSegment",
"... | Calculates the intersection point of 2 line segments.
@param c1
Start point of the first line segment.
@param c2
End point of the first line segment.
@param c3
Start point of the second line segment.
@param c4
End point of the second line segment.
@return Returns a coordinate or null if not a single intersection point. | [
"Calculates",
"the",
"intersection",
"point",
"of",
"2",
"line",
"segments",
"."
] | train | https://github.com/geomajas/geomajas-project-client-gwt/blob/1c1adc48deb192ed825265eebcc74d70bbf45670/client/src/main/java/org/geomajas/gwt/client/spatial/Mathlib.java#L83-L87 |
xebialabs/overcast | src/main/java/com/xebialabs/overcast/support/libvirt/jdom/DiskXml.java | DiskXml.updateDisks | public static void updateDisks(Document domainXml, List<StorageVol> volumes) throws LibvirtException {
XPathFactory xpf = XPathFactory.instance();
XPathExpression<Element> diskExpr = xpf.compile(XPATH_DISK, Filters.element());
XPathExpression<Attribute> fileExpr = xpf.compile(XPATH_DISK_FILE, Filters.attribute());
List<Element> disks = diskExpr.evaluate(domainXml);
Iterator<StorageVol> cloneDiskIter = volumes.iterator();
for (Element disk : disks) {
Attribute file = fileExpr.evaluateFirst(disk);
StorageVol cloneDisk = cloneDiskIter.next();
file.setValue(cloneDisk.getPath());
}
} | java | public static void updateDisks(Document domainXml, List<StorageVol> volumes) throws LibvirtException {
XPathFactory xpf = XPathFactory.instance();
XPathExpression<Element> diskExpr = xpf.compile(XPATH_DISK, Filters.element());
XPathExpression<Attribute> fileExpr = xpf.compile(XPATH_DISK_FILE, Filters.attribute());
List<Element> disks = diskExpr.evaluate(domainXml);
Iterator<StorageVol> cloneDiskIter = volumes.iterator();
for (Element disk : disks) {
Attribute file = fileExpr.evaluateFirst(disk);
StorageVol cloneDisk = cloneDiskIter.next();
file.setValue(cloneDisk.getPath());
}
} | [
"public",
"static",
"void",
"updateDisks",
"(",
"Document",
"domainXml",
",",
"List",
"<",
"StorageVol",
">",
"volumes",
")",
"throws",
"LibvirtException",
"{",
"XPathFactory",
"xpf",
"=",
"XPathFactory",
".",
"instance",
"(",
")",
";",
"XPathExpression",
"<",
... | update the disks in the domain XML. It is assumed that the the size of the volumes is the same as the number of
disk elements and that the order is the same. | [
"update",
"the",
"disks",
"in",
"the",
"domain",
"XML",
".",
"It",
"is",
"assumed",
"that",
"the",
"the",
"size",
"of",
"the",
"volumes",
"is",
"the",
"same",
"as",
"the",
"number",
"of",
"disk",
"elements",
"and",
"that",
"the",
"order",
"is",
"the",
... | train | https://github.com/xebialabs/overcast/blob/716e57b66870c9afe51edc3b6045863a34fb0061/src/main/java/com/xebialabs/overcast/support/libvirt/jdom/DiskXml.java#L51-L62 |
wildfly/wildfly-core | controller/src/main/java/org/jboss/as/controller/AbstractAttributeDefinitionBuilder.java | AbstractAttributeDefinitionBuilder.setCapabilityReference | public BUILDER setCapabilityReference(String referencedCapability, RuntimeCapability<?> dependentCapability) {
if (dependentCapability.isDynamicallyNamed()) {
return setCapabilityReference(referencedCapability, dependentCapability.getName());
} else {
//noinspection deprecation
return setCapabilityReference(referencedCapability, dependentCapability.getName(), false);
}
} | java | public BUILDER setCapabilityReference(String referencedCapability, RuntimeCapability<?> dependentCapability) {
if (dependentCapability.isDynamicallyNamed()) {
return setCapabilityReference(referencedCapability, dependentCapability.getName());
} else {
//noinspection deprecation
return setCapabilityReference(referencedCapability, dependentCapability.getName(), false);
}
} | [
"public",
"BUILDER",
"setCapabilityReference",
"(",
"String",
"referencedCapability",
",",
"RuntimeCapability",
"<",
"?",
">",
"dependentCapability",
")",
"{",
"if",
"(",
"dependentCapability",
".",
"isDynamicallyNamed",
"(",
")",
")",
"{",
"return",
"setCapabilityRef... | Records that this attribute's value represents a reference to an instance of a
{@link org.jboss.as.controller.capability.RuntimeCapability#isDynamicallyNamed() dynamic capability}.
<p>
This method is a convenience method equivalent to calling
{@link #setCapabilityReference(CapabilityReferenceRecorder)}
passing in a {@link org.jboss.as.controller.CapabilityReferenceRecorder.DefaultCapabilityReferenceRecorder}
constructed using the parameters passed to this method.
@param referencedCapability the name of the dynamic capability the dynamic portion of whose name is
represented by the attribute's value
@param dependentCapability the capability that depends on {@code referencedCapability}
@return the builder
@see AttributeDefinition#addCapabilityRequirements(OperationContext, org.jboss.as.controller.registry.Resource, ModelNode)
@see AttributeDefinition#removeCapabilityRequirements(OperationContext, org.jboss.as.controller.registry.Resource, ModelNode) | [
"Records",
"that",
"this",
"attribute",
"s",
"value",
"represents",
"a",
"reference",
"to",
"an",
"instance",
"of",
"a",
"{",
"@link",
"org",
".",
"jboss",
".",
"as",
".",
"controller",
".",
"capability",
".",
"RuntimeCapability#isDynamicallyNamed",
"()",
"dyn... | train | https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/controller/src/main/java/org/jboss/as/controller/AbstractAttributeDefinitionBuilder.java#L854-L861 |
padrig64/ValidationFramework | validationframework-swing/src/main/java/com/google/code/validationframework/swing/decoration/anchor/AnchorLink.java | AnchorLink.getRelativeSlaveLocation | public Point getRelativeSlaveLocation(final Dimension masterSize, final Dimension slaveSize) {
return getRelativeSlaveLocation(masterSize.width, masterSize.height, slaveSize.width, slaveSize.height);
} | java | public Point getRelativeSlaveLocation(final Dimension masterSize, final Dimension slaveSize) {
return getRelativeSlaveLocation(masterSize.width, masterSize.height, slaveSize.width, slaveSize.height);
} | [
"public",
"Point",
"getRelativeSlaveLocation",
"(",
"final",
"Dimension",
"masterSize",
",",
"final",
"Dimension",
"slaveSize",
")",
"{",
"return",
"getRelativeSlaveLocation",
"(",
"masterSize",
".",
"width",
",",
"masterSize",
".",
"height",
",",
"slaveSize",
".",
... | Computes the location of the slave component (whose size is specified) that is slaved to the master component
(whose size is specified) using this anchor link.
@param masterSize Size of the master component to which the other component is slaved.
@param slaveSize Size of the slave component that is slaved to the master component.
@return Location where the slave component should be. | [
"Computes",
"the",
"location",
"of",
"the",
"slave",
"component",
"(",
"whose",
"size",
"is",
"specified",
")",
"that",
"is",
"slaved",
"to",
"the",
"master",
"component",
"(",
"whose",
"size",
"is",
"specified",
")",
"using",
"this",
"anchor",
"link",
"."... | train | https://github.com/padrig64/ValidationFramework/blob/2dd3c7b3403993db366d24a927645f467ccd1dda/validationframework-swing/src/main/java/com/google/code/validationframework/swing/decoration/anchor/AnchorLink.java#L127-L129 |
facebookarchive/hadoop-20 | src/core/org/apache/hadoop/record/meta/StructTypeID.java | StructTypeID.genericReadTypeID | private TypeID genericReadTypeID(RecordInput rin, String tag) throws IOException {
byte typeVal = rin.readByte(tag);
switch (typeVal) {
case TypeID.RIOType.BOOL:
return TypeID.BoolTypeID;
case TypeID.RIOType.BUFFER:
return TypeID.BufferTypeID;
case TypeID.RIOType.BYTE:
return TypeID.ByteTypeID;
case TypeID.RIOType.DOUBLE:
return TypeID.DoubleTypeID;
case TypeID.RIOType.FLOAT:
return TypeID.FloatTypeID;
case TypeID.RIOType.INT:
return TypeID.IntTypeID;
case TypeID.RIOType.LONG:
return TypeID.LongTypeID;
case TypeID.RIOType.MAP:
{
TypeID tIDKey = genericReadTypeID(rin, tag);
TypeID tIDValue = genericReadTypeID(rin, tag);
return new MapTypeID(tIDKey, tIDValue);
}
case TypeID.RIOType.STRING:
return TypeID.StringTypeID;
case TypeID.RIOType.STRUCT:
{
StructTypeID stID = new StructTypeID();
int numElems = rin.readInt(tag);
for (int i=0; i<numElems; i++) {
stID.add(genericReadTypeInfo(rin, tag));
}
return stID;
}
case TypeID.RIOType.VECTOR:
{
TypeID tID = genericReadTypeID(rin, tag);
return new VectorTypeID(tID);
}
default:
// shouldn't be here
throw new IOException("Unknown type read");
}
} | java | private TypeID genericReadTypeID(RecordInput rin, String tag) throws IOException {
byte typeVal = rin.readByte(tag);
switch (typeVal) {
case TypeID.RIOType.BOOL:
return TypeID.BoolTypeID;
case TypeID.RIOType.BUFFER:
return TypeID.BufferTypeID;
case TypeID.RIOType.BYTE:
return TypeID.ByteTypeID;
case TypeID.RIOType.DOUBLE:
return TypeID.DoubleTypeID;
case TypeID.RIOType.FLOAT:
return TypeID.FloatTypeID;
case TypeID.RIOType.INT:
return TypeID.IntTypeID;
case TypeID.RIOType.LONG:
return TypeID.LongTypeID;
case TypeID.RIOType.MAP:
{
TypeID tIDKey = genericReadTypeID(rin, tag);
TypeID tIDValue = genericReadTypeID(rin, tag);
return new MapTypeID(tIDKey, tIDValue);
}
case TypeID.RIOType.STRING:
return TypeID.StringTypeID;
case TypeID.RIOType.STRUCT:
{
StructTypeID stID = new StructTypeID();
int numElems = rin.readInt(tag);
for (int i=0; i<numElems; i++) {
stID.add(genericReadTypeInfo(rin, tag));
}
return stID;
}
case TypeID.RIOType.VECTOR:
{
TypeID tID = genericReadTypeID(rin, tag);
return new VectorTypeID(tID);
}
default:
// shouldn't be here
throw new IOException("Unknown type read");
}
} | [
"private",
"TypeID",
"genericReadTypeID",
"(",
"RecordInput",
"rin",
",",
"String",
"tag",
")",
"throws",
"IOException",
"{",
"byte",
"typeVal",
"=",
"rin",
".",
"readByte",
"(",
"tag",
")",
";",
"switch",
"(",
"typeVal",
")",
"{",
"case",
"TypeID",
".",
... | generic reader: reads the next TypeID object from stream and returns it | [
"generic",
"reader",
":",
"reads",
"the",
"next",
"TypeID",
"object",
"from",
"stream",
"and",
"returns",
"it"
] | train | https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/core/org/apache/hadoop/record/meta/StructTypeID.java#L106-L149 |
netty/netty | codec-http/src/main/java/io/netty/handler/codec/http/HttpResponseStatus.java | HttpResponseStatus.parseLine | public static HttpResponseStatus parseLine(String line) {
try {
int space = line.indexOf(' ');
return space == -1 ? valueOf(parseInt(line)) :
valueOf(parseInt(line.substring(0, space)), line.substring(space + 1));
} catch (Exception e) {
throw new IllegalArgumentException("malformed status line: " + line, e);
}
} | java | public static HttpResponseStatus parseLine(String line) {
try {
int space = line.indexOf(' ');
return space == -1 ? valueOf(parseInt(line)) :
valueOf(parseInt(line.substring(0, space)), line.substring(space + 1));
} catch (Exception e) {
throw new IllegalArgumentException("malformed status line: " + line, e);
}
} | [
"public",
"static",
"HttpResponseStatus",
"parseLine",
"(",
"String",
"line",
")",
"{",
"try",
"{",
"int",
"space",
"=",
"line",
".",
"indexOf",
"(",
"'",
"'",
")",
";",
"return",
"space",
"==",
"-",
"1",
"?",
"valueOf",
"(",
"parseInt",
"(",
"line",
... | Parses the specified HTTP status line into a {@link HttpResponseStatus}. The expected formats of the line are:
<ul>
<li>{@code statusCode} (e.g. 200)</li>
<li>{@code statusCode} {@code reasonPhrase} (e.g. 404 Not Found)</li>
</ul>
@throws IllegalArgumentException if the specified status line is malformed | [
"Parses",
"the",
"specified",
"HTTP",
"status",
"line",
"into",
"a",
"{",
"@link",
"HttpResponseStatus",
"}",
".",
"The",
"expected",
"formats",
"of",
"the",
"line",
"are",
":",
"<ul",
">",
"<li",
">",
"{",
"@code",
"statusCode",
"}",
"(",
"e",
".",
"g... | train | https://github.com/netty/netty/blob/ba06eafa1c1824bd154f1a380019e7ea2edf3c4c/codec-http/src/main/java/io/netty/handler/codec/http/HttpResponseStatus.java#L492-L500 |
krummas/DrizzleJDBC | src/main/java/org/drizzle/jdbc/DrizzlePreparedStatement.java | DrizzlePreparedStatement.setCharacterStream | public void setCharacterStream(final int parameterIndex, final Reader reader, final long length) throws SQLException {
if(reader == null) {
setNull(parameterIndex, Types.BLOB);
return;
}
try {
setParameter(parameterIndex, new ReaderParameter(reader, length));
} catch (IOException e) {
throw SQLExceptionMapper.getSQLException("Could not read stream: " + e.getMessage(), e);
}
} | java | public void setCharacterStream(final int parameterIndex, final Reader reader, final long length) throws SQLException {
if(reader == null) {
setNull(parameterIndex, Types.BLOB);
return;
}
try {
setParameter(parameterIndex, new ReaderParameter(reader, length));
} catch (IOException e) {
throw SQLExceptionMapper.getSQLException("Could not read stream: " + e.getMessage(), e);
}
} | [
"public",
"void",
"setCharacterStream",
"(",
"final",
"int",
"parameterIndex",
",",
"final",
"Reader",
"reader",
",",
"final",
"long",
"length",
")",
"throws",
"SQLException",
"{",
"if",
"(",
"reader",
"==",
"null",
")",
"{",
"setNull",
"(",
"parameterIndex",
... | Sets the designated parameter to the given <code>Reader</code> object, which is the given number of characters
long. When a very large UNICODE value is input to a <code>LONGVARCHAR</code> parameter, it may be more practical
to send it via a <code>java.io.Reader</code> object. The data will be read from the stream as needed until
end-of-file is reached. The JDBC driver will do any necessary conversion from UNICODE to the database char
format.
<p/>
<P><B>Note:</B> This stream object can either be a standard Java stream object or your own subclass that
implements the standard interface.
@param parameterIndex the first parameter is 1, the second is 2, ...
@param reader the <code>java.io.Reader</code> object that contains the Unicode data
@param length the number of characters in the stream
@throws java.sql.SQLException if parameterIndex does not correspond to a parameter marker in the SQL statement;
if a database access error occurs or this method is called on a closed
<code>PreparedStatement</code>
@since 1.6 | [
"Sets",
"the",
"designated",
"parameter",
"to",
"the",
"given",
"<code",
">",
"Reader<",
"/",
"code",
">",
"object",
"which",
"is",
"the",
"given",
"number",
"of",
"characters",
"long",
".",
"When",
"a",
"very",
"large",
"UNICODE",
"value",
"is",
"input",
... | train | https://github.com/krummas/DrizzleJDBC/blob/716f31fd71f3cc289edf69844d8117deb86d98d6/src/main/java/org/drizzle/jdbc/DrizzlePreparedStatement.java#L819-L830 |
Azure/azure-sdk-for-java | network/resource-manager/v2018_04_01/src/main/java/com/microsoft/azure/management/network/v2018_04_01/implementation/SubnetsInner.java | SubnetsInner.beginCreateOrUpdate | public SubnetInner beginCreateOrUpdate(String resourceGroupName, String virtualNetworkName, String subnetName, SubnetInner subnetParameters) {
return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, virtualNetworkName, subnetName, subnetParameters).toBlocking().single().body();
} | java | public SubnetInner beginCreateOrUpdate(String resourceGroupName, String virtualNetworkName, String subnetName, SubnetInner subnetParameters) {
return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, virtualNetworkName, subnetName, subnetParameters).toBlocking().single().body();
} | [
"public",
"SubnetInner",
"beginCreateOrUpdate",
"(",
"String",
"resourceGroupName",
",",
"String",
"virtualNetworkName",
",",
"String",
"subnetName",
",",
"SubnetInner",
"subnetParameters",
")",
"{",
"return",
"beginCreateOrUpdateWithServiceResponseAsync",
"(",
"resourceGroup... | Creates or updates a subnet in the specified virtual network.
@param resourceGroupName The name of the resource group.
@param virtualNetworkName The name of the virtual network.
@param subnetName The name of the subnet.
@param subnetParameters Parameters supplied to the create or update subnet operation.
@throws IllegalArgumentException thrown if parameters fail the validation
@throws CloudException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the SubnetInner object if successful. | [
"Creates",
"or",
"updates",
"a",
"subnet",
"in",
"the",
"specified",
"virtual",
"network",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2018_04_01/src/main/java/com/microsoft/azure/management/network/v2018_04_01/implementation/SubnetsInner.java#L533-L535 |
xerial/snappy-java | src/main/java/org/xerial/snappy/Snappy.java | Snappy.rawCompress | public static long rawCompress(long inputAddr, long inputSize, long destAddr)
throws IOException
{
return impl.rawCompress(inputAddr, inputSize, destAddr);
} | java | public static long rawCompress(long inputAddr, long inputSize, long destAddr)
throws IOException
{
return impl.rawCompress(inputAddr, inputSize, destAddr);
} | [
"public",
"static",
"long",
"rawCompress",
"(",
"long",
"inputAddr",
",",
"long",
"inputSize",
",",
"long",
"destAddr",
")",
"throws",
"IOException",
"{",
"return",
"impl",
".",
"rawCompress",
"(",
"inputAddr",
",",
"inputSize",
",",
"destAddr",
")",
";",
"}... | Zero-copy compress using memory addresses.
@param inputAddr input memory address
@param inputSize input byte size
@param destAddr destination address of the compressed data
@return the compressed data size
@throws IOException | [
"Zero",
"-",
"copy",
"compress",
"using",
"memory",
"addresses",
"."
] | train | https://github.com/xerial/snappy-java/blob/9df6ed7bbce88186c82f2e7cdcb7b974421b3340/src/main/java/org/xerial/snappy/Snappy.java#L388-L392 |
google/jimfs | jimfs/src/main/java/com/google/common/jimfs/JimfsFileStore.java | JimfsFileStore.lookUp | DirectoryEntry lookUp(File workingDirectory, JimfsPath path, Set<? super LinkOption> options)
throws IOException {
state.checkOpen();
return tree.lookUp(workingDirectory, path, options);
} | java | DirectoryEntry lookUp(File workingDirectory, JimfsPath path, Set<? super LinkOption> options)
throws IOException {
state.checkOpen();
return tree.lookUp(workingDirectory, path, options);
} | [
"DirectoryEntry",
"lookUp",
"(",
"File",
"workingDirectory",
",",
"JimfsPath",
"path",
",",
"Set",
"<",
"?",
"super",
"LinkOption",
">",
"options",
")",
"throws",
"IOException",
"{",
"state",
".",
"checkOpen",
"(",
")",
";",
"return",
"tree",
".",
"lookUp",
... | Looks up the file at the given path using the given link options. If the path is relative, the
lookup is relative to the given working directory.
@throws NoSuchFileException if an element of the path other than the final element does not
resolve to a directory or symbolic link (e.g. it doesn't exist or is a regular file)
@throws IOException if a symbolic link cycle is detected or the depth of symbolic link
recursion otherwise exceeds a threshold | [
"Looks",
"up",
"the",
"file",
"at",
"the",
"given",
"path",
"using",
"the",
"given",
"link",
"options",
".",
"If",
"the",
"path",
"is",
"relative",
"the",
"lookup",
"is",
"relative",
"to",
"the",
"given",
"working",
"directory",
"."
] | train | https://github.com/google/jimfs/blob/3eadff747a3afa7b498030f420d2d04ce700534a/jimfs/src/main/java/com/google/common/jimfs/JimfsFileStore.java#L125-L129 |
intuit/QuickBooks-V3-Java-SDK | ipp-v3-java-devkit/src/main/java/com/intuit/ipp/interceptors/SerializeInterceptor.java | SerializeInterceptor.getContent | private byte[] getContent(InputStream in) throws FMSException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] content = null;
try {
int nRead;
byte[] data = new byte[1028];
while ((nRead = in.read(data, 0, data.length)) != -1) {
baos.write(data, 0, nRead);
}
baos.flush();
content = baos.toByteArray();
} catch (IOException e) {
throw new FMSException("Error while reading the upload file.", e);
} finally {
close(baos);
close(in);
}
return content;
} | java | private byte[] getContent(InputStream in) throws FMSException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] content = null;
try {
int nRead;
byte[] data = new byte[1028];
while ((nRead = in.read(data, 0, data.length)) != -1) {
baos.write(data, 0, nRead);
}
baos.flush();
content = baos.toByteArray();
} catch (IOException e) {
throw new FMSException("Error while reading the upload file.", e);
} finally {
close(baos);
close(in);
}
return content;
} | [
"private",
"byte",
"[",
"]",
"getContent",
"(",
"InputStream",
"in",
")",
"throws",
"FMSException",
"{",
"ByteArrayOutputStream",
"baos",
"=",
"new",
"ByteArrayOutputStream",
"(",
")",
";",
"byte",
"[",
"]",
"content",
"=",
"null",
";",
"try",
"{",
"int",
... | Method to return the byte[] value of the given file input stream
@param in the input stream
@return byte[] the file content
@throws FMSException | [
"Method",
"to",
"return",
"the",
"byte",
"[]",
"value",
"of",
"the",
"given",
"file",
"input",
"stream"
] | train | https://github.com/intuit/QuickBooks-V3-Java-SDK/blob/59f988d0776d46620d0b34711c411b2b5b1da06b/ipp-v3-java-devkit/src/main/java/com/intuit/ipp/interceptors/SerializeInterceptor.java#L133-L151 |
snowflakedb/snowflake-jdbc | src/main/java/net/snowflake/client/jdbc/SnowflakeStatementV1.java | SnowflakeStatementV1.setParameter | void setParameter(String name, Object value) throws Exception
{
logger.debug("public void setParameter");
try
{
if (this.sfStatement != null)
{
this.sfStatement.addProperty(name, value);
}
}
catch (SFException ex)
{
throw new SnowflakeSQLException(ex);
}
} | java | void setParameter(String name, Object value) throws Exception
{
logger.debug("public void setParameter");
try
{
if (this.sfStatement != null)
{
this.sfStatement.addProperty(name, value);
}
}
catch (SFException ex)
{
throw new SnowflakeSQLException(ex);
}
} | [
"void",
"setParameter",
"(",
"String",
"name",
",",
"Object",
"value",
")",
"throws",
"Exception",
"{",
"logger",
".",
"debug",
"(",
"\"public void setParameter\"",
")",
";",
"try",
"{",
"if",
"(",
"this",
".",
"sfStatement",
"!=",
"null",
")",
"{",
"this"... | Sets a parameter at the statement level. Used for internal testing.
@param name parameter name.
@param value parameter value.
@throws Exception if any SQL error occurs. | [
"Sets",
"a",
"parameter",
"at",
"the",
"statement",
"level",
".",
"Used",
"for",
"internal",
"testing",
"."
] | train | https://github.com/snowflakedb/snowflake-jdbc/blob/98567b5a57753f29d51446809640b969a099658f/src/main/java/net/snowflake/client/jdbc/SnowflakeStatementV1.java#L766-L781 |
googleads/googleads-java-lib | modules/adwords_axis/src/main/java/com/google/api/ads/adwords/axis/utils/v201809/shopping/ProductPartitionTreeImpl.java | ProductPartitionTreeImpl.createAddOperations | private List<OperationPair> createAddOperations(ProductPartitionNode node) {
AdGroupCriterionOperation addOp = new AdGroupCriterionOperation();
addOp.setOperator(Operator.ADD);
// Set the node's ID to a new temporary ID.
node.setProductPartitionId(idGenerator.next());
addOp.setOperand(ProductPartitionNodeAdapter.createCriterionForAdd(node, adGroupId,
getBiddingStrategyConfiguration()));
List<OperationPair> operationsList = Lists.newArrayList();
operationsList.add(new OperationPair(node, addOp));
// Recursively add all of this node's children to the operations list.
for (ProductPartitionNode child : node.getChildren()) {
operationsList.addAll(createAddOperations(child));
}
return operationsList;
} | java | private List<OperationPair> createAddOperations(ProductPartitionNode node) {
AdGroupCriterionOperation addOp = new AdGroupCriterionOperation();
addOp.setOperator(Operator.ADD);
// Set the node's ID to a new temporary ID.
node.setProductPartitionId(idGenerator.next());
addOp.setOperand(ProductPartitionNodeAdapter.createCriterionForAdd(node, adGroupId,
getBiddingStrategyConfiguration()));
List<OperationPair> operationsList = Lists.newArrayList();
operationsList.add(new OperationPair(node, addOp));
// Recursively add all of this node's children to the operations list.
for (ProductPartitionNode child : node.getChildren()) {
operationsList.addAll(createAddOperations(child));
}
return operationsList;
} | [
"private",
"List",
"<",
"OperationPair",
">",
"createAddOperations",
"(",
"ProductPartitionNode",
"node",
")",
"{",
"AdGroupCriterionOperation",
"addOp",
"=",
"new",
"AdGroupCriterionOperation",
"(",
")",
";",
"addOp",
".",
"setOperator",
"(",
"Operator",
".",
"ADD"... | Creates ADD operations for the node and ALL of its children and adds them to the provided
operations list. | [
"Creates",
"ADD",
"operations",
"for",
"the",
"node",
"and",
"ALL",
"of",
"its",
"children",
"and",
"adds",
"them",
"to",
"the",
"provided",
"operations",
"list",
"."
] | train | https://github.com/googleads/googleads-java-lib/blob/967957cc4f6076514e3a7926fe653e4f1f7cc9c9/modules/adwords_axis/src/main/java/com/google/api/ads/adwords/axis/utils/v201809/shopping/ProductPartitionTreeImpl.java#L511-L529 |
Azure/azure-sdk-for-java | appservice/resource-manager/v2016_03_01/src/main/java/com/microsoft/azure/management/appservice/v2016_03_01/implementation/DiagnosticsInner.java | DiagnosticsInner.getSiteDetectorResponseSlot | public DetectorResponseInner getSiteDetectorResponseSlot(String resourceGroupName, String siteName, String detectorName, String slot, DateTime startTime, DateTime endTime, String timeGrain) {
return getSiteDetectorResponseSlotWithServiceResponseAsync(resourceGroupName, siteName, detectorName, slot, startTime, endTime, timeGrain).toBlocking().single().body();
} | java | public DetectorResponseInner getSiteDetectorResponseSlot(String resourceGroupName, String siteName, String detectorName, String slot, DateTime startTime, DateTime endTime, String timeGrain) {
return getSiteDetectorResponseSlotWithServiceResponseAsync(resourceGroupName, siteName, detectorName, slot, startTime, endTime, timeGrain).toBlocking().single().body();
} | [
"public",
"DetectorResponseInner",
"getSiteDetectorResponseSlot",
"(",
"String",
"resourceGroupName",
",",
"String",
"siteName",
",",
"String",
"detectorName",
",",
"String",
"slot",
",",
"DateTime",
"startTime",
",",
"DateTime",
"endTime",
",",
"String",
"timeGrain",
... | Get site detector response.
Get site detector response.
@param resourceGroupName Name of the resource group to which the resource belongs.
@param siteName Site Name
@param detectorName Detector Resource Name
@param slot Slot Name
@param startTime Start Time
@param endTime End Time
@param timeGrain Time Grain
@throws IllegalArgumentException thrown if parameters fail the validation
@throws CloudException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the DetectorResponseInner object if successful. | [
"Get",
"site",
"detector",
"response",
".",
"Get",
"site",
"detector",
"response",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/appservice/resource-manager/v2016_03_01/src/main/java/com/microsoft/azure/management/appservice/v2016_03_01/implementation/DiagnosticsInner.java#L2285-L2287 |
google/j2objc | jre_emul/openjdk/src/share/classes/java/math/BigDecimal.java | BigDecimal.compareMagnitudeNormalized | private static int compareMagnitudeNormalized(long xs, int xscale, BigInteger ys, int yscale) {
// assert "ys can't be represented as long"
if (xs == 0)
return -1;
int sdiff = xscale - yscale;
if (sdiff < 0) {
if (longMultiplyPowerTen(xs, -sdiff) == INFLATED ) {
return bigMultiplyPowerTen(xs, -sdiff).compareMagnitude(ys);
}
}
return -1;
} | java | private static int compareMagnitudeNormalized(long xs, int xscale, BigInteger ys, int yscale) {
// assert "ys can't be represented as long"
if (xs == 0)
return -1;
int sdiff = xscale - yscale;
if (sdiff < 0) {
if (longMultiplyPowerTen(xs, -sdiff) == INFLATED ) {
return bigMultiplyPowerTen(xs, -sdiff).compareMagnitude(ys);
}
}
return -1;
} | [
"private",
"static",
"int",
"compareMagnitudeNormalized",
"(",
"long",
"xs",
",",
"int",
"xscale",
",",
"BigInteger",
"ys",
",",
"int",
"yscale",
")",
"{",
"// assert \"ys can't be represented as long\"",
"if",
"(",
"xs",
"==",
"0",
")",
"return",
"-",
"1",
";... | Compare Normalize dividend & divisor so that both fall into [0.1, 0.999...] | [
"Compare",
"Normalize",
"dividend",
"&",
"divisor",
"so",
"that",
"both",
"fall",
"into",
"[",
"0",
".",
"1",
"0",
".",
"999",
"...",
"]"
] | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/openjdk/src/share/classes/java/math/BigDecimal.java#L4969-L4980 |
netty/netty | codec/src/main/java/io/netty/handler/codec/compression/Bzip2BlockCompressor.java | Bzip2BlockCompressor.writeRun | private void writeRun(final int value, int runLength) {
final int blockLength = this.blockLength;
final byte[] block = this.block;
blockValuesPresent[value] = true;
crc.updateCRC(value, runLength);
final byte byteValue = (byte) value;
switch (runLength) {
case 1:
block[blockLength] = byteValue;
this.blockLength = blockLength + 1;
break;
case 2:
block[blockLength] = byteValue;
block[blockLength + 1] = byteValue;
this.blockLength = blockLength + 2;
break;
case 3:
block[blockLength] = byteValue;
block[blockLength + 1] = byteValue;
block[blockLength + 2] = byteValue;
this.blockLength = blockLength + 3;
break;
default:
runLength -= 4;
blockValuesPresent[runLength] = true;
block[blockLength] = byteValue;
block[blockLength + 1] = byteValue;
block[blockLength + 2] = byteValue;
block[blockLength + 3] = byteValue;
block[blockLength + 4] = (byte) runLength;
this.blockLength = blockLength + 5;
break;
}
} | java | private void writeRun(final int value, int runLength) {
final int blockLength = this.blockLength;
final byte[] block = this.block;
blockValuesPresent[value] = true;
crc.updateCRC(value, runLength);
final byte byteValue = (byte) value;
switch (runLength) {
case 1:
block[blockLength] = byteValue;
this.blockLength = blockLength + 1;
break;
case 2:
block[blockLength] = byteValue;
block[blockLength + 1] = byteValue;
this.blockLength = blockLength + 2;
break;
case 3:
block[blockLength] = byteValue;
block[blockLength + 1] = byteValue;
block[blockLength + 2] = byteValue;
this.blockLength = blockLength + 3;
break;
default:
runLength -= 4;
blockValuesPresent[runLength] = true;
block[blockLength] = byteValue;
block[blockLength + 1] = byteValue;
block[blockLength + 2] = byteValue;
block[blockLength + 3] = byteValue;
block[blockLength + 4] = (byte) runLength;
this.blockLength = blockLength + 5;
break;
}
} | [
"private",
"void",
"writeRun",
"(",
"final",
"int",
"value",
",",
"int",
"runLength",
")",
"{",
"final",
"int",
"blockLength",
"=",
"this",
".",
"blockLength",
";",
"final",
"byte",
"[",
"]",
"block",
"=",
"this",
".",
"block",
";",
"blockValuesPresent",
... | Writes an RLE run to the block array, updating the block CRC and present values array as required.
@param value The value to write
@param runLength The run length of the value to write | [
"Writes",
"an",
"RLE",
"run",
"to",
"the",
"block",
"array",
"updating",
"the",
"block",
"CRC",
"and",
"present",
"values",
"array",
"as",
"required",
"."
] | train | https://github.com/netty/netty/blob/ba06eafa1c1824bd154f1a380019e7ea2edf3c4c/codec/src/main/java/io/netty/handler/codec/compression/Bzip2BlockCompressor.java#L138-L173 |
cloudant/sync-android | cloudant-sync-datastore-core/src/main/java/com/cloudant/sync/internal/sqlite/SQLDatabaseFactory.java | SQLDatabaseFactory.updateSchema | public static void updateSchema(SQLDatabase database, Migration migration, int version)
throws SQLException {
Misc.checkArgument(version > 0, "Schema version number must be positive");
// ensure foreign keys are enforced in the case that we are up to date and no migration happen
database.execSQL("PRAGMA foreign_keys = ON;");
int dbVersion = database.getVersion();
if(dbVersion < version) {
// switch off foreign keys during the migration - so that we don't get caught out by
// "ON DELETE CASCADE" constraints etc
database.execSQL("PRAGMA foreign_keys = OFF;");
database.beginTransaction();
try {
try {
migration.runMigration(database);
database.execSQL("PRAGMA user_version = " + version + ";");
database.setTransactionSuccessful();
} catch (Exception ex) {
// don't set the transaction successful, so it'll rollback
throw new SQLException(
String.format("Migration from %1$d to %2$d failed.", dbVersion, version),
ex);
}
} finally {
database.endTransaction();
// re-enable foreign keys
database.execSQL("PRAGMA foreign_keys = ON;");
}
}
} | java | public static void updateSchema(SQLDatabase database, Migration migration, int version)
throws SQLException {
Misc.checkArgument(version > 0, "Schema version number must be positive");
// ensure foreign keys are enforced in the case that we are up to date and no migration happen
database.execSQL("PRAGMA foreign_keys = ON;");
int dbVersion = database.getVersion();
if(dbVersion < version) {
// switch off foreign keys during the migration - so that we don't get caught out by
// "ON DELETE CASCADE" constraints etc
database.execSQL("PRAGMA foreign_keys = OFF;");
database.beginTransaction();
try {
try {
migration.runMigration(database);
database.execSQL("PRAGMA user_version = " + version + ";");
database.setTransactionSuccessful();
} catch (Exception ex) {
// don't set the transaction successful, so it'll rollback
throw new SQLException(
String.format("Migration from %1$d to %2$d failed.", dbVersion, version),
ex);
}
} finally {
database.endTransaction();
// re-enable foreign keys
database.execSQL("PRAGMA foreign_keys = ON;");
}
}
} | [
"public",
"static",
"void",
"updateSchema",
"(",
"SQLDatabase",
"database",
",",
"Migration",
"migration",
",",
"int",
"version",
")",
"throws",
"SQLException",
"{",
"Misc",
".",
"checkArgument",
"(",
"version",
">",
"0",
",",
"\"Schema version number must be positi... | <p>Update schema for {@code SQLDatabase}</p>
<p>Each input schema has a version, if the database's version is
smaller than {@code version}, the schema statements are executed.</p>
<p>SQLDatabase's version is defined stored in {@code user_version} in the
database:</p>
<pre>PRAGMA user_version;</pre>
<p>This method updates {@code user_version} if the migration is successful.</p>
@param database database to perform migration in.
@param migration migration to perform.
@param version the version this migration migrates to.
@throws SQLException if migration fails
@see SQLDatabase#getVersion() | [
"<p",
">",
"Update",
"schema",
"for",
"{",
"@code",
"SQLDatabase",
"}",
"<",
"/",
"p",
">"
] | train | https://github.com/cloudant/sync-android/blob/5f1416ed1bd9ab05d7a4b8736480c8ae68bd7383/cloudant-sync-datastore-core/src/main/java/com/cloudant/sync/internal/sqlite/SQLDatabaseFactory.java#L172-L202 |
zaproxy/zaproxy | src/org/parosproxy/paros/model/SiteMap.java | SiteMap.addPath | public SiteNode addPath(HistoryReference ref, HttpMessage msg) {
return this.addPath(ref, msg, false);
} | java | public SiteNode addPath(HistoryReference ref, HttpMessage msg) {
return this.addPath(ref, msg, false);
} | [
"public",
"SiteNode",
"addPath",
"(",
"HistoryReference",
"ref",
",",
"HttpMessage",
"msg",
")",
"{",
"return",
"this",
".",
"addPath",
"(",
"ref",
",",
"msg",
",",
"false",
")",
";",
"}"
] | Add the HistoryReference with the corresponding HttpMessage into the SiteMap.
This method saves the msg to be read from the reference table. Use
this method if the HttpMessage is known.
Note that this method must only be called on the EventDispatchThread
@param msg the HttpMessage
@return the SiteNode that corresponds to the HttpMessage | [
"Add",
"the",
"HistoryReference",
"with",
"the",
"corresponding",
"HttpMessage",
"into",
"the",
"SiteMap",
".",
"This",
"method",
"saves",
"the",
"msg",
"to",
"be",
"read",
"from",
"the",
"reference",
"table",
".",
"Use",
"this",
"method",
"if",
"the",
"Http... | train | https://github.com/zaproxy/zaproxy/blob/0cbe5121f2ae1ecca222513d182759210c569bec/src/org/parosproxy/paros/model/SiteMap.java#L372-L374 |
joniles/mpxj | src/main/java/net/sf/mpxj/mpx/MPXJBaseFormat.java | MPXJBaseFormat.setAmPmText | public void setAmPmText(String am, String pm)
{
for (SimpleDateFormat format : m_formats)
{
DateFormatSymbols symbols = format.getDateFormatSymbols();
symbols.setAmPmStrings(new String[]
{
am,
pm
});
format.setDateFormatSymbols(symbols);
}
} | java | public void setAmPmText(String am, String pm)
{
for (SimpleDateFormat format : m_formats)
{
DateFormatSymbols symbols = format.getDateFormatSymbols();
symbols.setAmPmStrings(new String[]
{
am,
pm
});
format.setDateFormatSymbols(symbols);
}
} | [
"public",
"void",
"setAmPmText",
"(",
"String",
"am",
",",
"String",
"pm",
")",
"{",
"for",
"(",
"SimpleDateFormat",
"format",
":",
"m_formats",
")",
"{",
"DateFormatSymbols",
"symbols",
"=",
"format",
".",
"getDateFormatSymbols",
"(",
")",
";",
"symbols",
"... | Allows the AM/PM text to be set.
@param am AM text
@param pm PM text | [
"Allows",
"the",
"AM",
"/",
"PM",
"text",
"to",
"be",
"set",
"."
] | train | https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/mpx/MPXJBaseFormat.java#L70-L82 |
mebigfatguy/fb-contrib | src/main/java/com/mebigfatguy/fbcontrib/detect/LoggerOddities.java | LoggerOddities.isNonPrivateLogField | private boolean isNonPrivateLogField(@SlashedClassName String fieldClsName, String fieldName, String fieldSig) {
String fieldType = SignatureUtils.trimSignature(fieldSig);
if (!SLF4J_LOGGER.equals(fieldType) && !COMMONS_LOGGER.equals(fieldType) && !LOG4J_LOGGER.equals(fieldType) && !LOG4J2_LOGGER.equals(fieldType)) {
return false;
}
JavaClass cls = getClassContext().getJavaClass();
if (!cls.getClassName().equals(fieldClsName.replace('/', '.'))) {
return false;
}
for (Field f : getClassContext().getJavaClass().getFields()) {
if (f.getName().equals(fieldName)) {
return !f.isPrivate();
}
}
return true;
} | java | private boolean isNonPrivateLogField(@SlashedClassName String fieldClsName, String fieldName, String fieldSig) {
String fieldType = SignatureUtils.trimSignature(fieldSig);
if (!SLF4J_LOGGER.equals(fieldType) && !COMMONS_LOGGER.equals(fieldType) && !LOG4J_LOGGER.equals(fieldType) && !LOG4J2_LOGGER.equals(fieldType)) {
return false;
}
JavaClass cls = getClassContext().getJavaClass();
if (!cls.getClassName().equals(fieldClsName.replace('/', '.'))) {
return false;
}
for (Field f : getClassContext().getJavaClass().getFields()) {
if (f.getName().equals(fieldName)) {
return !f.isPrivate();
}
}
return true;
} | [
"private",
"boolean",
"isNonPrivateLogField",
"(",
"@",
"SlashedClassName",
"String",
"fieldClsName",
",",
"String",
"fieldName",
",",
"String",
"fieldSig",
")",
"{",
"String",
"fieldType",
"=",
"SignatureUtils",
".",
"trimSignature",
"(",
"fieldSig",
")",
";",
"i... | looks to see if this field is a logger, and declared non privately
@param fieldClsName
the owning class type of the field
@param fieldName
the name of the field
@param fieldSig
the signature of the field
@return if the field is a logger and not private | [
"looks",
"to",
"see",
"if",
"this",
"field",
"is",
"a",
"logger",
"and",
"declared",
"non",
"privately"
] | train | https://github.com/mebigfatguy/fb-contrib/blob/3b5203196f627b399fbcea3c2ab2b1f4e56cc7b8/src/main/java/com/mebigfatguy/fbcontrib/detect/LoggerOddities.java#L338-L357 |
amzn/ion-java | src/com/amazon/ion/impl/lite/IonValueLite.java | IonValueLite._setMetadata | protected final void _setMetadata(int metadata, int mask, int shift) {
assert(mask <= ELEMENT_MASK); // don't overwrite the element ID
_flags &= ~mask;
_flags |= ((metadata << shift) & mask);
} | java | protected final void _setMetadata(int metadata, int mask, int shift) {
assert(mask <= ELEMENT_MASK); // don't overwrite the element ID
_flags &= ~mask;
_flags |= ((metadata << shift) & mask);
} | [
"protected",
"final",
"void",
"_setMetadata",
"(",
"int",
"metadata",
",",
"int",
"mask",
",",
"int",
"shift",
")",
"{",
"assert",
"(",
"mask",
"<=",
"ELEMENT_MASK",
")",
";",
"// don't overwrite the element ID",
"_flags",
"&=",
"~",
"mask",
";",
"_flags",
"... | May be used by subclasses to reuse _flag bits for purposes specific
to that subclass. It is important that only flag bits not currently
used by that subclass are chosen; otherwise important data may be
overwritten. NOTE: only the lower 8 bits may be used, because the
upper 24 are reserved for the element ID.
@param metadata the metadata to set.
@param mask the location at which to set the metadata. Must be within
the lower 8 bits.
@param shift the number of bits to left-shift the metadata so that
it starts at the index of the mask's LSB. | [
"May",
"be",
"used",
"by",
"subclasses",
"to",
"reuse",
"_flag",
"bits",
"for",
"purposes",
"specific",
"to",
"that",
"subclass",
".",
"It",
"is",
"important",
"that",
"only",
"flag",
"bits",
"not",
"currently",
"used",
"by",
"that",
"subclass",
"are",
"ch... | train | https://github.com/amzn/ion-java/blob/4ce1f0f58c6a5a8e42d0425ccdb36e38be3e2270/src/com/amazon/ion/impl/lite/IonValueLite.java#L103-L107 |
nmorel/gwt-jackson | extensions/guava/src/main/java/com/github/nmorel/gwtjackson/guava/client/deser/BaseImmutableCollectionJsonDeserializer.java | BaseImmutableCollectionJsonDeserializer.buildCollection | protected void buildCollection( JsonReader reader, JsonDeserializationContext ctx, JsonDeserializerParameters params ) {
if ( JsonToken.BEGIN_ARRAY == reader.peek() ) {
reader.beginArray();
while ( JsonToken.END_ARRAY != reader.peek() ) {
T element = deserializer.deserialize( reader, ctx, params );
if ( isNullValueAllowed() || null != element ) {
addToCollection( element );
}
}
reader.endArray();
} else if ( ctx.isAcceptSingleValueAsArray() ) {
addToCollection( deserializer.deserialize( reader, ctx, params ) );
} else {
throw ctx.traceError( "Cannot deserialize a com.google.common.collect.ImmutableCollection out of " + reader
.peek() + " token", reader );
}
} | java | protected void buildCollection( JsonReader reader, JsonDeserializationContext ctx, JsonDeserializerParameters params ) {
if ( JsonToken.BEGIN_ARRAY == reader.peek() ) {
reader.beginArray();
while ( JsonToken.END_ARRAY != reader.peek() ) {
T element = deserializer.deserialize( reader, ctx, params );
if ( isNullValueAllowed() || null != element ) {
addToCollection( element );
}
}
reader.endArray();
} else if ( ctx.isAcceptSingleValueAsArray() ) {
addToCollection( deserializer.deserialize( reader, ctx, params ) );
} else {
throw ctx.traceError( "Cannot deserialize a com.google.common.collect.ImmutableCollection out of " + reader
.peek() + " token", reader );
}
} | [
"protected",
"void",
"buildCollection",
"(",
"JsonReader",
"reader",
",",
"JsonDeserializationContext",
"ctx",
",",
"JsonDeserializerParameters",
"params",
")",
"{",
"if",
"(",
"JsonToken",
".",
"BEGIN_ARRAY",
"==",
"reader",
".",
"peek",
"(",
")",
")",
"{",
"re... | Build the {@link ImmutableCollection}. It delegates the element addition to an abstract method because the
{@link ImmutableCollection.Builder} is not visible in the emulated class.
@param reader {@link JsonReader} used to read the JSON input
@param ctx Context for the full deserialization process
@param params Parameters for this deserialization | [
"Build",
"the",
"{",
"@link",
"ImmutableCollection",
"}",
".",
"It",
"delegates",
"the",
"element",
"addition",
"to",
"an",
"abstract",
"method",
"because",
"the",
"{",
"@link",
"ImmutableCollection",
".",
"Builder",
"}",
"is",
"not",
"visible",
"in",
"the",
... | train | https://github.com/nmorel/gwt-jackson/blob/3fdc4350a27a9b64fc437d5fe516bf9191b74824/extensions/guava/src/main/java/com/github/nmorel/gwtjackson/guava/client/deser/BaseImmutableCollectionJsonDeserializer.java#L53-L73 |
gosu-lang/gosu-lang | gosu-core-api/src/main/java/gw/lang/annotation/Annotations.java | Annotations.create | public static <T extends Annotation> T create(Class<T> annotationType, Object value) {
return new Builder<T>(annotationType).withValue(value).create();
} | java | public static <T extends Annotation> T create(Class<T> annotationType, Object value) {
return new Builder<T>(annotationType).withValue(value).create();
} | [
"public",
"static",
"<",
"T",
"extends",
"Annotation",
">",
"T",
"create",
"(",
"Class",
"<",
"T",
">",
"annotationType",
",",
"Object",
"value",
")",
"{",
"return",
"new",
"Builder",
"<",
"T",
">",
"(",
"annotationType",
")",
".",
"withValue",
"(",
"v... | Convenience method that constructs an annotation instance with a single "value" element. | [
"Convenience",
"method",
"that",
"constructs",
"an",
"annotation",
"instance",
"with",
"a",
"single",
"value",
"element",
"."
] | train | https://github.com/gosu-lang/gosu-lang/blob/d6e9261b137ce66fef3726cabe7826d4a1f946b7/gosu-core-api/src/main/java/gw/lang/annotation/Annotations.java#L34-L36 |
BBN-E/bue-common-open | common-core-open/src/main/java/com/bbn/bue/common/StringUtils.java | StringUtils.padWithMax | public static String padWithMax(final int numToPad, final int maxValue) {
checkArgument(numToPad >= 0);
checkArgument(numToPad <= maxValue);
final int maxLength = Integer.toString(maxValue).length();
final String baseString = Integer.toString(numToPad);
final String padding = Strings.repeat("0", maxLength - baseString.length());
return padding + numToPad;
} | java | public static String padWithMax(final int numToPad, final int maxValue) {
checkArgument(numToPad >= 0);
checkArgument(numToPad <= maxValue);
final int maxLength = Integer.toString(maxValue).length();
final String baseString = Integer.toString(numToPad);
final String padding = Strings.repeat("0", maxLength - baseString.length());
return padding + numToPad;
} | [
"public",
"static",
"String",
"padWithMax",
"(",
"final",
"int",
"numToPad",
",",
"final",
"int",
"maxValue",
")",
"{",
"checkArgument",
"(",
"numToPad",
">=",
"0",
")",
";",
"checkArgument",
"(",
"numToPad",
"<=",
"maxValue",
")",
";",
"final",
"int",
"ma... | Produces a string representation of a positive integer padded with leading zeros. Enough zeros
are adding so that the supplied {@code maxValue} would have the same number of digits. | [
"Produces",
"a",
"string",
"representation",
"of",
"a",
"positive",
"integer",
"padded",
"with",
"leading",
"zeros",
".",
"Enough",
"zeros",
"are",
"adding",
"so",
"that",
"the",
"supplied",
"{"
] | train | https://github.com/BBN-E/bue-common-open/blob/d618652674d647867306e2e4b987a21b7c29c015/common-core-open/src/main/java/com/bbn/bue/common/StringUtils.java#L583-L590 |
Breinify/brein-time-utilities | src/com/brein/time/timeseries/BucketTimeSeries.java | BucketTimeSeries.setNow | public void setNow(final long unixTimeStamp) throws IllegalTimePointMovement {
/*
* "now" strongly depends on the TimeUnit used for the timeSeries, as
* well as the bucketSize. If, e.g., the TimeUnit is MINUTES and the
* bucketSize is 5, a unix time stamp representing 01/20/1981 08:07:30
* must be mapped to 01/20/1981 08:10:00 (the next valid bucket).
*/
if (this.currentNowIdx == -1 || this.now == null) {
this.currentNowIdx = 0;
this.now = normalizeUnixTimeStamp(unixTimeStamp);
} else {
/*
* Getting the new currentNowIdx is done by calculating the
* difference between the old now and the new now and moving
* the currentNowIdx forward.
*
* [0] [1] [2] [3] [4] [5] [6]
* ↑
* currentNowIdx
*
* Assume we move the now time stamp forward by three buckets:
*
* [0] [1] [2] [3] [4] [5] [6]
* ↑
* currentNowIdx
*
* So the calculation is done in two steps:
* 1.) get the bucket of the new now
* 2.) determine the difference between the buckets, if it's negative => error,
* if it is zero => done, otherwise => erase the fields in between and reset
* to zero or null
*/
final BucketEndPoints newNow = normalizeUnixTimeStamp(unixTimeStamp);
final long diff = this.now.diff(newNow);
if (diff < 0) {
throw new IllegalTimePointMovement(String.format("Cannot move to the past (current: %s, update: %s)",
this.now, newNow));
} else if (diff > 0) {
final int newCurrentNowIdx = idx(currentNowIdx - diff);
/*
* Remove the "passed" information. There are several things we have to
* consider:
* 1.) the whole array has to be reset
* 2.) the array has to be reset partly forward
* 3.) the array has to be reset "around the corner"
*/
if (diff >= config.getTimeSeriesSize()) {
fill(-1, -1);
} else if (newCurrentNowIdx > currentNowIdx) {
fill(0, currentNowIdx);
fill(newCurrentNowIdx, -1);
} else {
fill(newCurrentNowIdx, currentNowIdx);
}
// set the values calculated
this.currentNowIdx = newCurrentNowIdx;
this.now = newNow;
}
}
} | java | public void setNow(final long unixTimeStamp) throws IllegalTimePointMovement {
/*
* "now" strongly depends on the TimeUnit used for the timeSeries, as
* well as the bucketSize. If, e.g., the TimeUnit is MINUTES and the
* bucketSize is 5, a unix time stamp representing 01/20/1981 08:07:30
* must be mapped to 01/20/1981 08:10:00 (the next valid bucket).
*/
if (this.currentNowIdx == -1 || this.now == null) {
this.currentNowIdx = 0;
this.now = normalizeUnixTimeStamp(unixTimeStamp);
} else {
/*
* Getting the new currentNowIdx is done by calculating the
* difference between the old now and the new now and moving
* the currentNowIdx forward.
*
* [0] [1] [2] [3] [4] [5] [6]
* ↑
* currentNowIdx
*
* Assume we move the now time stamp forward by three buckets:
*
* [0] [1] [2] [3] [4] [5] [6]
* ↑
* currentNowIdx
*
* So the calculation is done in two steps:
* 1.) get the bucket of the new now
* 2.) determine the difference between the buckets, if it's negative => error,
* if it is zero => done, otherwise => erase the fields in between and reset
* to zero or null
*/
final BucketEndPoints newNow = normalizeUnixTimeStamp(unixTimeStamp);
final long diff = this.now.diff(newNow);
if (diff < 0) {
throw new IllegalTimePointMovement(String.format("Cannot move to the past (current: %s, update: %s)",
this.now, newNow));
} else if (diff > 0) {
final int newCurrentNowIdx = idx(currentNowIdx - diff);
/*
* Remove the "passed" information. There are several things we have to
* consider:
* 1.) the whole array has to be reset
* 2.) the array has to be reset partly forward
* 3.) the array has to be reset "around the corner"
*/
if (diff >= config.getTimeSeriesSize()) {
fill(-1, -1);
} else if (newCurrentNowIdx > currentNowIdx) {
fill(0, currentNowIdx);
fill(newCurrentNowIdx, -1);
} else {
fill(newCurrentNowIdx, currentNowIdx);
}
// set the values calculated
this.currentNowIdx = newCurrentNowIdx;
this.now = newNow;
}
}
} | [
"public",
"void",
"setNow",
"(",
"final",
"long",
"unixTimeStamp",
")",
"throws",
"IllegalTimePointMovement",
"{",
"/*\n * \"now\" strongly depends on the TimeUnit used for the timeSeries, as\n * well as the bucketSize. If, e.g., the TimeUnit is MINUTES and the\n * buck... | Modifies the "now" unix time stamp of the time-series. This modifies, the time-series, i.e., data might be
removed if the data is pushed.
@param unixTimeStamp the new now to be used
@throws IllegalTimePointMovement if the new unix time stamp it moved into the past, e.g., if the current time
stamp is newers | [
"Modifies",
"the",
"now",
"unix",
"time",
"stamp",
"of",
"the",
"time",
"-",
"series",
".",
"This",
"modifies",
"the",
"time",
"-",
"series",
"i",
".",
"e",
".",
"data",
"might",
"be",
"removed",
"if",
"the",
"data",
"is",
"pushed",
"."
] | train | https://github.com/Breinify/brein-time-utilities/blob/ec0165a50ec1951ec7730b72c85c801c2018f314/src/com/brein/time/timeseries/BucketTimeSeries.java#L475-L539 |
OpenLiberty/open-liberty | dev/com.ibm.ws.ejbcontainer.core/src/com/ibm/ejs/container/TimerNpImpl.java | TimerNpImpl.getSerializableObject | @Override
public PassivatorSerializableHandle getSerializableObject()
{
TimerNpHandleImpl timerHandle;
timerHandle = new TimerNpHandleImpl(ivBeanId, ivTaskId); // F743-425.CodRev
return timerHandle;
} | java | @Override
public PassivatorSerializableHandle getSerializableObject()
{
TimerNpHandleImpl timerHandle;
timerHandle = new TimerNpHandleImpl(ivBeanId, ivTaskId); // F743-425.CodRev
return timerHandle;
} | [
"@",
"Override",
"public",
"PassivatorSerializableHandle",
"getSerializableObject",
"(",
")",
"{",
"TimerNpHandleImpl",
"timerHandle",
";",
"timerHandle",
"=",
"new",
"TimerNpHandleImpl",
"(",
"ivBeanId",
",",
"ivTaskId",
")",
";",
"// F743-425.CodRev",
"return",
"timer... | Get a serializable handle to the timer. This handle can be used at
a later time to re-obtain the timer reference. <p>
This method is intended for use by the Stateful passivation code, when
a Stateful EJB is being passivated, and contains a Timer (not a
TimerHanle). <p>
This method differs from {@link #getHandle} in that it performs none
of the checking required by the EJB Specification, such as if the Timer
is still valid. When passivating a Stateful EJB, none of this checking
should be performed. <p>
Also, this method 'marks' the returned TimerHandle, so that it will
be replaced by the represented Timer when read from a stream.
See {@link com.ibm.ejs.container.passivator.StatefulPassivator} <p>
@return A serializable handle to the timer. | [
"Get",
"a",
"serializable",
"handle",
"to",
"the",
"timer",
".",
"This",
"handle",
"can",
"be",
"used",
"at",
"a",
"later",
"time",
"to",
"re",
"-",
"obtain",
"the",
"timer",
"reference",
".",
"<p",
">"
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.ejbcontainer.core/src/com/ibm/ejs/container/TimerNpImpl.java#L1174-L1182 |
samskivert/pythagoras | src/main/java/pythagoras/f/Matrix4.java | Matrix4.setToSkew | public Matrix4 setToSkew (IVector3 normal, float constant, IVector3 amount) {
return setToSkew(normal.x(), normal.y(), normal.z(), constant,
amount.x(), amount.y(), amount.z());
} | java | public Matrix4 setToSkew (IVector3 normal, float constant, IVector3 amount) {
return setToSkew(normal.x(), normal.y(), normal.z(), constant,
amount.x(), amount.y(), amount.z());
} | [
"public",
"Matrix4",
"setToSkew",
"(",
"IVector3",
"normal",
",",
"float",
"constant",
",",
"IVector3",
"amount",
")",
"{",
"return",
"setToSkew",
"(",
"normal",
".",
"x",
"(",
")",
",",
"normal",
".",
"y",
"(",
")",
",",
"normal",
".",
"z",
"(",
")"... | Sets this to a skew by the specified amount relative to the given plane.
@return a reference to this matrix, for chaining. | [
"Sets",
"this",
"to",
"a",
"skew",
"by",
"the",
"specified",
"amount",
"relative",
"to",
"the",
"given",
"plane",
"."
] | train | https://github.com/samskivert/pythagoras/blob/b8fea743ee8a7d742ad9c06ee4f11f50571fbd32/src/main/java/pythagoras/f/Matrix4.java#L350-L353 |
Azure/azure-sdk-for-java | policyinsights/resource-manager/v2018_04_04/src/main/java/com/microsoft/azure/management/policyinsights/v2018_04_04/implementation/PolicyStatesInner.java | PolicyStatesInner.listQueryResultsForResourceGroupAsync | public Observable<PolicyStatesQueryResultsInner> listQueryResultsForResourceGroupAsync(PolicyStatesResource policyStatesResource, String subscriptionId, String resourceGroupName, QueryOptions queryOptions) {
return listQueryResultsForResourceGroupWithServiceResponseAsync(policyStatesResource, subscriptionId, resourceGroupName, queryOptions).map(new Func1<ServiceResponse<PolicyStatesQueryResultsInner>, PolicyStatesQueryResultsInner>() {
@Override
public PolicyStatesQueryResultsInner call(ServiceResponse<PolicyStatesQueryResultsInner> response) {
return response.body();
}
});
} | java | public Observable<PolicyStatesQueryResultsInner> listQueryResultsForResourceGroupAsync(PolicyStatesResource policyStatesResource, String subscriptionId, String resourceGroupName, QueryOptions queryOptions) {
return listQueryResultsForResourceGroupWithServiceResponseAsync(policyStatesResource, subscriptionId, resourceGroupName, queryOptions).map(new Func1<ServiceResponse<PolicyStatesQueryResultsInner>, PolicyStatesQueryResultsInner>() {
@Override
public PolicyStatesQueryResultsInner call(ServiceResponse<PolicyStatesQueryResultsInner> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"PolicyStatesQueryResultsInner",
">",
"listQueryResultsForResourceGroupAsync",
"(",
"PolicyStatesResource",
"policyStatesResource",
",",
"String",
"subscriptionId",
",",
"String",
"resourceGroupName",
",",
"QueryOptions",
"queryOptions",
")",
"{",
... | Queries policy states for the resources under the resource group.
@param policyStatesResource The virtual resource under PolicyStates resource type. In a given time range, 'latest' represents the latest policy state(s), whereas 'default' represents all policy state(s). Possible values include: 'default', 'latest'
@param subscriptionId Microsoft Azure subscription ID.
@param resourceGroupName Resource group name.
@param queryOptions Additional parameters for the operation
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the PolicyStatesQueryResultsInner object | [
"Queries",
"policy",
"states",
"for",
"the",
"resources",
"under",
"the",
"resource",
"group",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/policyinsights/resource-manager/v2018_04_04/src/main/java/com/microsoft/azure/management/policyinsights/v2018_04_04/implementation/PolicyStatesInner.java#L1011-L1018 |
google/allocation-instrumenter | src/main/java/com/google/monitoring/runtime/instrumentation/AllocationMethodAdapter.java | AllocationMethodAdapter.visitMaxs | @Override
public void visitMaxs(int maxStack, int maxLocals) {
if (localScopes != null) {
for (VariableScope scope : localScopes) {
super.visitLocalVariable(
"xxxxx$" + scope.index, scope.desc, null, scope.start, scope.end, scope.index);
}
}
super.visitMaxs(maxStack, maxLocals);
} | java | @Override
public void visitMaxs(int maxStack, int maxLocals) {
if (localScopes != null) {
for (VariableScope scope : localScopes) {
super.visitLocalVariable(
"xxxxx$" + scope.index, scope.desc, null, scope.start, scope.end, scope.index);
}
}
super.visitMaxs(maxStack, maxLocals);
} | [
"@",
"Override",
"public",
"void",
"visitMaxs",
"(",
"int",
"maxStack",
",",
"int",
"maxLocals",
")",
"{",
"if",
"(",
"localScopes",
"!=",
"null",
")",
"{",
"for",
"(",
"VariableScope",
"scope",
":",
"localScopes",
")",
"{",
"super",
".",
"visitLocalVariab... | Called by the ASM framework once the class is done being visited to compute stack & local
variable count maximums. | [
"Called",
"by",
"the",
"ASM",
"framework",
"once",
"the",
"class",
"is",
"done",
"being",
"visited",
"to",
"compute",
"stack",
"&",
"local",
"variable",
"count",
"maximums",
"."
] | train | https://github.com/google/allocation-instrumenter/blob/58d8473e8832e51f39ae7aa38328f61c4b747bff/src/main/java/com/google/monitoring/runtime/instrumentation/AllocationMethodAdapter.java#L466-L475 |
shrinkwrap/resolver | maven/impl-maven/src/main/java/org/jboss/shrinkwrap/resolver/impl/maven/bootstrap/MavenRepositorySystem.java | MavenRepositorySystem.getSession | public DefaultRepositorySystemSession getSession(final Settings settings, boolean legacyLocalRepository) {
DefaultRepositorySystemSession session = new DefaultRepositorySystemSession();
MavenManagerBuilder builder = new MavenManagerBuilder(system, settings);
session.setLocalRepositoryManager(builder.localRepositoryManager(session, legacyLocalRepository));
session.setWorkspaceReader(builder.workspaceReader());
session.setTransferListener(builder.transferListerer());
session.setRepositoryListener(builder.repositoryListener());
session.setOffline(settings.isOffline());
session.setMirrorSelector(builder.mirrorSelector());
session.setProxySelector(builder.proxySelector());
session.setDependencyManager(builder.dependencyManager());
session.setArtifactDescriptorPolicy(builder.artifactRepositoryPolicy());
session.setDependencyTraverser(builder.dependencyTraverser());
session.setDependencyGraphTransformer(builder.dependencyGraphTransformer());
// set artifact stereotypes
session.setArtifactTypeRegistry(builder.artifactTypeRegistry());
// set system properties for interpolation
session.setSystemProperties(SecurityActions.getProperties());
session.setConfigProperties(SecurityActions.getProperties());
return session;
} | java | public DefaultRepositorySystemSession getSession(final Settings settings, boolean legacyLocalRepository) {
DefaultRepositorySystemSession session = new DefaultRepositorySystemSession();
MavenManagerBuilder builder = new MavenManagerBuilder(system, settings);
session.setLocalRepositoryManager(builder.localRepositoryManager(session, legacyLocalRepository));
session.setWorkspaceReader(builder.workspaceReader());
session.setTransferListener(builder.transferListerer());
session.setRepositoryListener(builder.repositoryListener());
session.setOffline(settings.isOffline());
session.setMirrorSelector(builder.mirrorSelector());
session.setProxySelector(builder.proxySelector());
session.setDependencyManager(builder.dependencyManager());
session.setArtifactDescriptorPolicy(builder.artifactRepositoryPolicy());
session.setDependencyTraverser(builder.dependencyTraverser());
session.setDependencyGraphTransformer(builder.dependencyGraphTransformer());
// set artifact stereotypes
session.setArtifactTypeRegistry(builder.artifactTypeRegistry());
// set system properties for interpolation
session.setSystemProperties(SecurityActions.getProperties());
session.setConfigProperties(SecurityActions.getProperties());
return session;
} | [
"public",
"DefaultRepositorySystemSession",
"getSession",
"(",
"final",
"Settings",
"settings",
",",
"boolean",
"legacyLocalRepository",
")",
"{",
"DefaultRepositorySystemSession",
"session",
"=",
"new",
"DefaultRepositorySystemSession",
"(",
")",
";",
"MavenManagerBuilder",
... | Spawns a working session from the repository system. This is used to as environment for execution of Maven
commands
@param settings
A configuration of current session
@param legacyLocalRepository
Whether to ignore origin of artifacts in local repository; defaults to false
@return A working session spawned from the repository system. | [
"Spawns",
"a",
"working",
"session",
"from",
"the",
"repository",
"system",
".",
"This",
"is",
"used",
"to",
"as",
"environment",
"for",
"execution",
"of",
"Maven",
"commands"
] | train | https://github.com/shrinkwrap/resolver/blob/e881a84b8cff5b0a014f2a5ebf612be3eb9db01f/maven/impl-maven/src/main/java/org/jboss/shrinkwrap/resolver/impl/maven/bootstrap/MavenRepositorySystem.java#L75-L101 |
jmxtrans/jmxtrans | jmxtrans-output/jmxtrans-output-core/src/main/java/com/googlecode/jmxtrans/model/output/support/opentsdb/OpenTSDBMessageFormatter.java | OpenTSDBMessageFormatter.addTag | void addTag(StringBuilder resultString, String tagName, String tagValue) {
resultString.append(" ");
resultString.append(sanitizeString(tagName));
resultString.append("=");
resultString.append(sanitizeString(tagValue));
} | java | void addTag(StringBuilder resultString, String tagName, String tagValue) {
resultString.append(" ");
resultString.append(sanitizeString(tagName));
resultString.append("=");
resultString.append(sanitizeString(tagValue));
} | [
"void",
"addTag",
"(",
"StringBuilder",
"resultString",
",",
"String",
"tagName",
",",
"String",
"tagValue",
")",
"{",
"resultString",
".",
"append",
"(",
"\" \"",
")",
";",
"resultString",
".",
"append",
"(",
"sanitizeString",
"(",
"tagName",
")",
")",
";",... | Add one tag, with the provided name and value, to the given result string.
@param resultString - the string containing the metric name, timestamp, value, and possibly other content.
@return String - the new result string with the tag appended. | [
"Add",
"one",
"tag",
"with",
"the",
"provided",
"name",
"and",
"value",
"to",
"the",
"given",
"result",
"string",
"."
] | train | https://github.com/jmxtrans/jmxtrans/blob/496f342de3bcf2c2226626374b7a16edf8f4ba2a/jmxtrans-output/jmxtrans-output-core/src/main/java/com/googlecode/jmxtrans/model/output/support/opentsdb/OpenTSDBMessageFormatter.java#L119-L124 |
jbundle/jbundle | base/base/src/main/java/org/jbundle/base/field/convert/MergeConverter.java | MergeConverter.addMergeField | public void addMergeField(String strFileName, Converter converter)
{
this.checkArray();
m_vArray.addElement(new InfoList(strFileName, null, -1, converter));
} | java | public void addMergeField(String strFileName, Converter converter)
{
this.checkArray();
m_vArray.addElement(new InfoList(strFileName, null, -1, converter));
} | [
"public",
"void",
"addMergeField",
"(",
"String",
"strFileName",
",",
"Converter",
"converter",
")",
"{",
"this",
".",
"checkArray",
"(",
")",
";",
"m_vArray",
".",
"addElement",
"(",
"new",
"InfoList",
"(",
"strFileName",
",",
"null",
",",
"-",
"1",
",",
... | Add a file/converter pair.
@param strFileName The target record name.
@param converter The converter to return if this record is current. | [
"Add",
"a",
"file",
"/",
"converter",
"pair",
"."
] | train | https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/base/base/src/main/java/org/jbundle/base/field/convert/MergeConverter.java#L236-L240 |
agmip/translator-dssat | src/main/java/org/agmip/translators/dssat/DssatXFileOutput.java | DssatXFileOutput.setSecDataArr | private int setSecDataArr(HashMap m, ArrayList arr) {
if (!m.isEmpty()) {
for (int j = 0; j < arr.size(); j++) {
if (arr.get(j).equals(m)) {
return j + 1;
}
}
arr.add(m);
return arr.size();
} else {
return 0;
}
} | java | private int setSecDataArr(HashMap m, ArrayList arr) {
if (!m.isEmpty()) {
for (int j = 0; j < arr.size(); j++) {
if (arr.get(j).equals(m)) {
return j + 1;
}
}
arr.add(m);
return arr.size();
} else {
return 0;
}
} | [
"private",
"int",
"setSecDataArr",
"(",
"HashMap",
"m",
",",
"ArrayList",
"arr",
")",
"{",
"if",
"(",
"!",
"m",
".",
"isEmpty",
"(",
")",
")",
"{",
"for",
"(",
"int",
"j",
"=",
"0",
";",
"j",
"<",
"arr",
".",
"size",
"(",
")",
";",
"j",
"++",... | Get index value of the record and set new id value in the array
@param m sub data
@param arr array of sub data
@return current index value of the sub data | [
"Get",
"index",
"value",
"of",
"the",
"record",
"and",
"set",
"new",
"id",
"value",
"in",
"the",
"array"
] | train | https://github.com/agmip/translator-dssat/blob/4be61d998f106eb7234ea8701b63c3746ae688f4/src/main/java/org/agmip/translators/dssat/DssatXFileOutput.java#L1454-L1467 |
alkacon/opencms-core | src-gwt/org/opencms/ugc/client/export/CmsClientUgcSession.java | CmsClientUgcSession.uploadFiles | public void uploadFiles(
String[] fieldNames,
final I_CmsJavaScriptObjectCallback fileCallback,
I_CmsErrorCallback errorCallback) {
Set<String> fieldSet = new HashSet<String>();
for (String field : fieldNames) {
fieldSet.add(field);
}
m_formWrapper.uploadFields(fieldSet, new Function<Map<String, String>, Void>() {
public Void apply(Map<String, String> input) {
fileCallback.call(CmsJsUtils.convertMapToJsObject(input));
return null;
}
}, errorCallback);
} | java | public void uploadFiles(
String[] fieldNames,
final I_CmsJavaScriptObjectCallback fileCallback,
I_CmsErrorCallback errorCallback) {
Set<String> fieldSet = new HashSet<String>();
for (String field : fieldNames) {
fieldSet.add(field);
}
m_formWrapper.uploadFields(fieldSet, new Function<Map<String, String>, Void>() {
public Void apply(Map<String, String> input) {
fileCallback.call(CmsJsUtils.convertMapToJsObject(input));
return null;
}
}, errorCallback);
} | [
"public",
"void",
"uploadFiles",
"(",
"String",
"[",
"]",
"fieldNames",
",",
"final",
"I_CmsJavaScriptObjectCallback",
"fileCallback",
",",
"I_CmsErrorCallback",
"errorCallback",
")",
"{",
"Set",
"<",
"String",
">",
"fieldSet",
"=",
"new",
"HashSet",
"<",
"String"... | Uploads multiple files.<p>
@param fieldNames the array of form field names containing files to upload
@param fileCallback the callback for the results
@param errorCallback the error handling callback | [
"Uploads",
"multiple",
"files",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/ugc/client/export/CmsClientUgcSession.java#L236-L254 |
huahin/huahin-core | src/main/java/org/huahinframework/core/SimpleJob.java | SimpleJob.setJoin | public SimpleJob setJoin(String[] masterLabels, String[] masterColumns,
String[] dataColumns, String masterPath) throws IOException, URISyntaxException {
String separator = conf.get(SEPARATOR);
return setJoin(masterLabels, masterColumns, dataColumns, masterPath, separator, false, DEFAULT_AUTOSOMEJOIN_THRESHOLD);
} | java | public SimpleJob setJoin(String[] masterLabels, String[] masterColumns,
String[] dataColumns, String masterPath) throws IOException, URISyntaxException {
String separator = conf.get(SEPARATOR);
return setJoin(masterLabels, masterColumns, dataColumns, masterPath, separator, false, DEFAULT_AUTOSOMEJOIN_THRESHOLD);
} | [
"public",
"SimpleJob",
"setJoin",
"(",
"String",
"[",
"]",
"masterLabels",
",",
"String",
"[",
"]",
"masterColumns",
",",
"String",
"[",
"]",
"dataColumns",
",",
"String",
"masterPath",
")",
"throws",
"IOException",
",",
"URISyntaxException",
"{",
"String",
"s... | This method is to determine automatically join the Simple and Big.
@param masterLabels label of master data
@param masterColumns master column's
@param dataColumns data column's
@param masterPath master data HDFS path
@return this
@throws URISyntaxException
@throws IOException | [
"This",
"method",
"is",
"to",
"determine",
"automatically",
"join",
"the",
"Simple",
"and",
"Big",
"."
] | train | https://github.com/huahin/huahin-core/blob/a87921b5a12be92a822f753c075ab2431036e6f5/src/main/java/org/huahinframework/core/SimpleJob.java#L515-L519 |
querydsl/querydsl | querydsl-sql/src/main/java/com/querydsl/sql/mysql/AbstractMySQLQuery.java | AbstractMySQLQuery.lockInShareMode | @WithBridgeMethods(value = MySQLQuery.class, castRequired = true)
public C lockInShareMode() {
return addFlag(Position.END, LOCK_IN_SHARE_MODE);
} | java | @WithBridgeMethods(value = MySQLQuery.class, castRequired = true)
public C lockInShareMode() {
return addFlag(Position.END, LOCK_IN_SHARE_MODE);
} | [
"@",
"WithBridgeMethods",
"(",
"value",
"=",
"MySQLQuery",
".",
"class",
",",
"castRequired",
"=",
"true",
")",
"public",
"C",
"lockInShareMode",
"(",
")",
"{",
"return",
"addFlag",
"(",
"Position",
".",
"END",
",",
"LOCK_IN_SHARE_MODE",
")",
";",
"}"
] | Using LOCK IN SHARE MODE sets a shared lock that permits other transactions to read the examined
rows but not to update or delete them.
@return the current object | [
"Using",
"LOCK",
"IN",
"SHARE",
"MODE",
"sets",
"a",
"shared",
"lock",
"that",
"permits",
"other",
"transactions",
"to",
"read",
"the",
"examined",
"rows",
"but",
"not",
"to",
"update",
"or",
"delete",
"them",
"."
] | train | https://github.com/querydsl/querydsl/blob/2bf234caf78549813a1e0f44d9c30ecc5ef734e3/querydsl-sql/src/main/java/com/querydsl/sql/mysql/AbstractMySQLQuery.java#L167-L170 |
alibaba/canal | client-adapter/common/src/main/java/com/alibaba/otter/canal/client/adapter/config/common/MutablePropertySources.java | MutablePropertySources.assertLegalRelativeAddition | protected void assertLegalRelativeAddition(String relativePropertySourceName, PropertySource<?> propertySource) {
String newPropertySourceName = propertySource.getName();
if (relativePropertySourceName.equals(newPropertySourceName)) {
throw new IllegalArgumentException(
"PropertySource named '" + newPropertySourceName + "' cannot be added relative to itself");
}
} | java | protected void assertLegalRelativeAddition(String relativePropertySourceName, PropertySource<?> propertySource) {
String newPropertySourceName = propertySource.getName();
if (relativePropertySourceName.equals(newPropertySourceName)) {
throw new IllegalArgumentException(
"PropertySource named '" + newPropertySourceName + "' cannot be added relative to itself");
}
} | [
"protected",
"void",
"assertLegalRelativeAddition",
"(",
"String",
"relativePropertySourceName",
",",
"PropertySource",
"<",
"?",
">",
"propertySource",
")",
"{",
"String",
"newPropertySourceName",
"=",
"propertySource",
".",
"getName",
"(",
")",
";",
"if",
"(",
"re... | Ensure that the given property source is not being added relative to itself. | [
"Ensure",
"that",
"the",
"given",
"property",
"source",
"is",
"not",
"being",
"added",
"relative",
"to",
"itself",
"."
] | train | https://github.com/alibaba/canal/blob/8f088cddc0755f4350c5aaae95c6e4002d90a40f/client-adapter/common/src/main/java/com/alibaba/otter/canal/client/adapter/config/common/MutablePropertySources.java#L184-L190 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.