repository_name stringlengths 7 58 | func_path_in_repository stringlengths 11 204 | func_name stringlengths 5 103 | whole_func_string stringlengths 87 3.44k | language stringclasses 1
value | func_code_string stringlengths 87 3.44k | func_code_tokens listlengths 21 714 | func_documentation_string stringlengths 61 1.95k | func_documentation_tokens listlengths 1 482 | split_name stringclasses 1
value | func_code_url stringlengths 102 309 |
|---|---|---|---|---|---|---|---|---|---|---|
Azure/azure-sdk-for-java | datamigration/resource-manager/v2018_03_31_preview/src/main/java/com/microsoft/azure/management/datamigration/v2018_03_31_preview/implementation/TasksInner.java | TasksInner.cancelAsync | public Observable<ProjectTaskInner> cancelAsync(String groupName, String serviceName, String projectName, String taskName) {
return cancelWithServiceResponseAsync(groupName, serviceName, projectName, taskName).map(new Func1<ServiceResponse<ProjectTaskInner>, ProjectTaskInner>() {
@Override
public ProjectTaskInner call(ServiceResponse<ProjectTaskInner> response) {
return response.body();
}
});
} | java | public Observable<ProjectTaskInner> cancelAsync(String groupName, String serviceName, String projectName, String taskName) {
return cancelWithServiceResponseAsync(groupName, serviceName, projectName, taskName).map(new Func1<ServiceResponse<ProjectTaskInner>, ProjectTaskInner>() {
@Override
public ProjectTaskInner call(ServiceResponse<ProjectTaskInner> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"ProjectTaskInner",
">",
"cancelAsync",
"(",
"String",
"groupName",
",",
"String",
"serviceName",
",",
"String",
"projectName",
",",
"String",
"taskName",
")",
"{",
"return",
"cancelWithServiceResponseAsync",
"(",
"groupName",
",",
"serv... | Cancel a task.
The tasks resource is a nested, proxy-only resource representing work performed by a DMS instance. This method cancels a task if it's currently queued or running.
@param groupName Name of the resource group
@param serviceName Name of the service
@param projectName Name of the project
@param taskName Name of the Task
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the ProjectTaskInner object | [
"Cancel",
"a",
"task",
".",
"The",
"tasks",
"resource",
"is",
"a",
"nested",
"proxy",
"-",
"only",
"resource",
"representing",
"work",
"performed",
"by",
"a",
"DMS",
"instance",
".",
"This",
"method",
"cancels",
"a",
"task",
"if",
"it",
"s",
"currently",
... | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/datamigration/resource-manager/v2018_03_31_preview/src/main/java/com/microsoft/azure/management/datamigration/v2018_03_31_preview/implementation/TasksInner.java#L1047-L1054 |
samskivert/pythagoras | src/main/java/pythagoras/f/Arc.java | Arc.setArcByTangent | public void setArcByTangent (XY p1, XY p2, XY p3, float radius) {
// use simple geometric calculations of arc center, radius and angles by tangents
float a1 = -FloatMath.atan2(p1.y() - p2.y(), p1.x() - p2.x());
float a2 = -FloatMath.atan2(p3.y() - p2.y(), p3.x() - p2.x());
float am = (a1 + a2) / 2f;
float ah = a1 - am;
float d = radius / Math.abs(FloatMath.sin(ah));
float x = p2.x() + d * FloatMath.cos(am);
float y = p2.y() - d * FloatMath.sin(am);
ah = ah >= 0f ? FloatMath.PI * 1.5f - ah : FloatMath.PI * 0.5f - ah;
a1 = normAngle(FloatMath.toDegrees(am - ah));
a2 = normAngle(FloatMath.toDegrees(am + ah));
float delta = a2 - a1;
if (delta <= 0f) {
delta += 360f;
}
setArcByCenter(x, y, radius, a1, delta, type);
} | java | public void setArcByTangent (XY p1, XY p2, XY p3, float radius) {
// use simple geometric calculations of arc center, radius and angles by tangents
float a1 = -FloatMath.atan2(p1.y() - p2.y(), p1.x() - p2.x());
float a2 = -FloatMath.atan2(p3.y() - p2.y(), p3.x() - p2.x());
float am = (a1 + a2) / 2f;
float ah = a1 - am;
float d = radius / Math.abs(FloatMath.sin(ah));
float x = p2.x() + d * FloatMath.cos(am);
float y = p2.y() - d * FloatMath.sin(am);
ah = ah >= 0f ? FloatMath.PI * 1.5f - ah : FloatMath.PI * 0.5f - ah;
a1 = normAngle(FloatMath.toDegrees(am - ah));
a2 = normAngle(FloatMath.toDegrees(am + ah));
float delta = a2 - a1;
if (delta <= 0f) {
delta += 360f;
}
setArcByCenter(x, y, radius, a1, delta, type);
} | [
"public",
"void",
"setArcByTangent",
"(",
"XY",
"p1",
",",
"XY",
"p2",
",",
"XY",
"p3",
",",
"float",
"radius",
")",
"{",
"// use simple geometric calculations of arc center, radius and angles by tangents",
"float",
"a1",
"=",
"-",
"FloatMath",
".",
"atan2",
"(",
... | Sets the location, size, angular extents, and closure type of this arc based on the
specified values. | [
"Sets",
"the",
"location",
"size",
"angular",
"extents",
"and",
"closure",
"type",
"of",
"this",
"arc",
"based",
"on",
"the",
"specified",
"values",
"."
] | train | https://github.com/samskivert/pythagoras/blob/b8fea743ee8a7d742ad9c06ee4f11f50571fbd32/src/main/java/pythagoras/f/Arc.java#L177-L194 |
HsiangLeekwok/hlklib | hlklib/src/main/java/com/hlk/hlklib/etc/BitmapUtils.java | BitmapUtils.computeSampleSize | public static int computeSampleSize(BitmapFactory.Options options, int minSideLength, int maxNumOfPixels) {
int initialSize = computeInitialSampleSize(options, minSideLength, maxNumOfPixels);
int roundedSize;
if (initialSize <= 8) {
roundedSize = 1;
while (roundedSize < initialSize) {
roundedSize <<= 1;
}
} else {
roundedSize = (initialSize + 7) / 8 * 8;
}
return roundedSize;
} | java | public static int computeSampleSize(BitmapFactory.Options options, int minSideLength, int maxNumOfPixels) {
int initialSize = computeInitialSampleSize(options, minSideLength, maxNumOfPixels);
int roundedSize;
if (initialSize <= 8) {
roundedSize = 1;
while (roundedSize < initialSize) {
roundedSize <<= 1;
}
} else {
roundedSize = (initialSize + 7) / 8 * 8;
}
return roundedSize;
} | [
"public",
"static",
"int",
"computeSampleSize",
"(",
"BitmapFactory",
".",
"Options",
"options",
",",
"int",
"minSideLength",
",",
"int",
"maxNumOfPixels",
")",
"{",
"int",
"initialSize",
"=",
"computeInitialSampleSize",
"(",
"options",
",",
"minSideLength",
",",
... | 获取缩放倍率
@param options 原始图片的基本信息
@param minSideLength 图片最小边尺寸
@param maxNumOfPixels 要压缩成的图片的像素总数 | [
"获取缩放倍率"
] | train | https://github.com/HsiangLeekwok/hlklib/blob/b122f6dcab7cec60c8e5455e0c31613d08bec6ad/hlklib/src/main/java/com/hlk/hlklib/etc/BitmapUtils.java#L49-L61 |
nguillaumin/slick2d-maven | slick2d-core/src/main/java/org/newdawn/slick/openal/SoundStore.java | SoundStore.getWAV | public Audio getWAV(String ref) throws IOException {
return getWAV(ref, ResourceLoader.getResourceAsStream(ref));
} | java | public Audio getWAV(String ref) throws IOException {
return getWAV(ref, ResourceLoader.getResourceAsStream(ref));
} | [
"public",
"Audio",
"getWAV",
"(",
"String",
"ref",
")",
"throws",
"IOException",
"{",
"return",
"getWAV",
"(",
"ref",
",",
"ResourceLoader",
".",
"getResourceAsStream",
"(",
"ref",
")",
")",
";",
"}"
] | Get the Sound based on a specified WAV file
@param ref The reference to the WAV file in the classpath
@return The Sound read from the WAV file
@throws IOException Indicates a failure to load the WAV | [
"Get",
"the",
"Sound",
"based",
"on",
"a",
"specified",
"WAV",
"file"
] | train | https://github.com/nguillaumin/slick2d-maven/blob/8251f88a0ed6a70e726d2468842455cd1f80893f/slick2d-core/src/main/java/org/newdawn/slick/openal/SoundStore.java#L671-L673 |
pressgang-ccms/PressGangCCMSCommonUtilities | src/main/java/org/jboss/pressgang/ccms/utils/common/VersionUtilities.java | VersionUtilities.getAPIVersion | public static String getAPIVersion(final String resourceFileName, final String versionProperty) {
final Properties props = new Properties();
final URL url = ClassLoader.getSystemResource(resourceFileName);
if (url != null) {
InputStream is = null;
try {
is = url.openStream();
props.load(is);
} catch (IOException ex) {
LOG.debug("Unable to open resource file", ex);
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
}
}
}
}
String version = props.getProperty(versionProperty, "unknown");
return version;
} | java | public static String getAPIVersion(final String resourceFileName, final String versionProperty) {
final Properties props = new Properties();
final URL url = ClassLoader.getSystemResource(resourceFileName);
if (url != null) {
InputStream is = null;
try {
is = url.openStream();
props.load(is);
} catch (IOException ex) {
LOG.debug("Unable to open resource file", ex);
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
}
}
}
}
String version = props.getProperty(versionProperty, "unknown");
return version;
} | [
"public",
"static",
"String",
"getAPIVersion",
"(",
"final",
"String",
"resourceFileName",
",",
"final",
"String",
"versionProperty",
")",
"{",
"final",
"Properties",
"props",
"=",
"new",
"Properties",
"(",
")",
";",
"final",
"URL",
"url",
"=",
"ClassLoader",
... | Get the Version Number from a properties file in the Application Classpath.
@param resourceFileName The name of the properties file.
@param versionProperty The name of the version property in the properties file.
@return The Version number or "unknown" if the version couldn't be found. | [
"Get",
"the",
"Version",
"Number",
"from",
"a",
"properties",
"file",
"in",
"the",
"Application",
"Classpath",
"."
] | train | https://github.com/pressgang-ccms/PressGangCCMSCommonUtilities/blob/5ebf5ed30a94c34c33f4708caa04a8da99cbb15c/src/main/java/org/jboss/pressgang/ccms/utils/common/VersionUtilities.java#L56-L80 |
optimatika/ojAlgo-finance | src/main/java/org/ojalgo/finance/FinanceUtils.java | FinanceUtils.toAnnualReturnFromGrowthRate | public static double toAnnualReturnFromGrowthRate(double growthRate, CalendarDateUnit growthRateUnit) {
double tmpGrowthRateUnitsPerYear = growthRateUnit.convert(CalendarDateUnit.YEAR);
return PrimitiveMath.EXPM1.invoke(growthRate * tmpGrowthRateUnitsPerYear);
} | java | public static double toAnnualReturnFromGrowthRate(double growthRate, CalendarDateUnit growthRateUnit) {
double tmpGrowthRateUnitsPerYear = growthRateUnit.convert(CalendarDateUnit.YEAR);
return PrimitiveMath.EXPM1.invoke(growthRate * tmpGrowthRateUnitsPerYear);
} | [
"public",
"static",
"double",
"toAnnualReturnFromGrowthRate",
"(",
"double",
"growthRate",
",",
"CalendarDateUnit",
"growthRateUnit",
")",
"{",
"double",
"tmpGrowthRateUnitsPerYear",
"=",
"growthRateUnit",
".",
"convert",
"(",
"CalendarDateUnit",
".",
"YEAR",
")",
";",
... | AnnualReturn = exp(GrowthRate * GrowthRateUnitsPerYear) - 1.0
@param growthRate A growth rate per unit (day, week, month, year...)
@param growthRateUnit A growth rate unit
@return Annualised return (percentage per year) | [
"AnnualReturn",
"=",
"exp",
"(",
"GrowthRate",
"*",
"GrowthRateUnitsPerYear",
")",
"-",
"1",
".",
"0"
] | train | https://github.com/optimatika/ojAlgo-finance/blob/c8d3f7e1894d4263b7334bca3f4c060e466f8b15/src/main/java/org/ojalgo/finance/FinanceUtils.java#L341-L344 |
jmrozanec/cron-utils | src/main/java/com/cronutils/descriptor/CronDescriptor.java | CronDescriptor.describeDayOfWeek | public String describeDayOfWeek(final Map<CronFieldName, CronField> fields, final Map<CronFieldName, FieldDefinition> definitions) {
final String description = DescriptionStrategyFactory.daysOfWeekInstance(
resourceBundle,
fields.containsKey(CronFieldName.DAY_OF_WEEK) ? fields.get(CronFieldName.DAY_OF_WEEK).getExpression() : null,
definitions.containsKey(CronFieldName.DAY_OF_WEEK) ? definitions.get(CronFieldName.DAY_OF_WEEK) : null
).describe();
return addExpressions(description, resourceBundle.getString("day"), resourceBundle.getString("days"));
} | java | public String describeDayOfWeek(final Map<CronFieldName, CronField> fields, final Map<CronFieldName, FieldDefinition> definitions) {
final String description = DescriptionStrategyFactory.daysOfWeekInstance(
resourceBundle,
fields.containsKey(CronFieldName.DAY_OF_WEEK) ? fields.get(CronFieldName.DAY_OF_WEEK).getExpression() : null,
definitions.containsKey(CronFieldName.DAY_OF_WEEK) ? definitions.get(CronFieldName.DAY_OF_WEEK) : null
).describe();
return addExpressions(description, resourceBundle.getString("day"), resourceBundle.getString("days"));
} | [
"public",
"String",
"describeDayOfWeek",
"(",
"final",
"Map",
"<",
"CronFieldName",
",",
"CronField",
">",
"fields",
",",
"final",
"Map",
"<",
"CronFieldName",
",",
"FieldDefinition",
">",
"definitions",
")",
"{",
"final",
"String",
"description",
"=",
"Descript... | Provide description for day of week.
@param fields - fields to describe;
@return description - String | [
"Provide",
"description",
"for",
"day",
"of",
"week",
"."
] | train | https://github.com/jmrozanec/cron-utils/blob/adac5ec8fd9160b082f9762a6eedea0715731170/src/main/java/com/cronutils/descriptor/CronDescriptor.java#L129-L137 |
jpelzer/pelzer-util | src/main/java/com/pelzer/util/PropertyManager.java | PropertyManager.loadProperties | private void loadProperties(final String filename, final int depth) {
logger.warning("Loading file '" + filename + "'");
final Properties properties = new Properties();
try {
// Load our properties file.
for (final InputStream io : getInputStreamsForFile(filename)) {
properties.load(io);
logger.info("Property file loaded successfully (" + filename + ")");
io.close();
}
}
catch (final java.io.FileNotFoundException ex) {
logger.warning("Property file not found (" + filename + ")");
}
catch (final java.io.IOException ex) {
logger.warning("IOException loading file: " + ex.getMessage());
logger.log(Logging.Priority.FATAL.getLevel(), "Error occured while loading properties file (" + filename + ")", ex);
}
allProperties.putAll(properties);
final String includeFiles[] = readIncludeFiles(filename, depth);
for (final String includeFile : includeFiles) {
loadProperties(includeFile, depth + 1);
}
} | java | private void loadProperties(final String filename, final int depth) {
logger.warning("Loading file '" + filename + "'");
final Properties properties = new Properties();
try {
// Load our properties file.
for (final InputStream io : getInputStreamsForFile(filename)) {
properties.load(io);
logger.info("Property file loaded successfully (" + filename + ")");
io.close();
}
}
catch (final java.io.FileNotFoundException ex) {
logger.warning("Property file not found (" + filename + ")");
}
catch (final java.io.IOException ex) {
logger.warning("IOException loading file: " + ex.getMessage());
logger.log(Logging.Priority.FATAL.getLevel(), "Error occured while loading properties file (" + filename + ")", ex);
}
allProperties.putAll(properties);
final String includeFiles[] = readIncludeFiles(filename, depth);
for (final String includeFile : includeFiles) {
loadProperties(includeFile, depth + 1);
}
} | [
"private",
"void",
"loadProperties",
"(",
"final",
"String",
"filename",
",",
"final",
"int",
"depth",
")",
"{",
"logger",
".",
"warning",
"(",
"\"Loading file '\"",
"+",
"filename",
"+",
"\"'\"",
")",
";",
"final",
"Properties",
"properties",
"=",
"new",
"P... | Loads the given property file, plus any files that are referenced by
#include statements | [
"Loads",
"the",
"given",
"property",
"file",
"plus",
"any",
"files",
"that",
"are",
"referenced",
"by",
"#include",
"statements"
] | train | https://github.com/jpelzer/pelzer-util/blob/ec14f2573fd977d1442dba5d1507a264f5ea9aa6/src/main/java/com/pelzer/util/PropertyManager.java#L329-L352 |
beangle/beangle3 | ioc/spring/src/main/java/org/beangle/inject/spring/config/SpringConfigProcessor.java | SpringConfigProcessor.registerBean | protected BeanDefinition registerBean(Definition def, BindRegistry registry) {
BeanDefinition bd = convert(def);
if ((def.isAbstract() && def.clazz == null) || FactoryBean.class.isAssignableFrom(def.clazz)) {
try {
Class<?> target = def.targetClass;
if (null == target && def.clazz != null)
target = ((FactoryBean<?>) def.clazz.newInstance()).getObjectType();
Assert.isTrue(null != target || def.isAbstract(), "Concrete bean [%1$s] should has class.",
def.beanName);
registry.register(target, def.beanName, bd);
// register concrete factory bean
if (!def.isAbstract()) registry.register(def.clazz, "&" + def.beanName);
} catch (Exception e) {
logger.error("Cannot get Factory's Object Type {}", def.clazz);
}
} else {
registry.register(def.clazz, def.beanName, bd);
}
logger.debug("Register definition {} for {}", def.beanName, def.clazz);
return bd;
} | java | protected BeanDefinition registerBean(Definition def, BindRegistry registry) {
BeanDefinition bd = convert(def);
if ((def.isAbstract() && def.clazz == null) || FactoryBean.class.isAssignableFrom(def.clazz)) {
try {
Class<?> target = def.targetClass;
if (null == target && def.clazz != null)
target = ((FactoryBean<?>) def.clazz.newInstance()).getObjectType();
Assert.isTrue(null != target || def.isAbstract(), "Concrete bean [%1$s] should has class.",
def.beanName);
registry.register(target, def.beanName, bd);
// register concrete factory bean
if (!def.isAbstract()) registry.register(def.clazz, "&" + def.beanName);
} catch (Exception e) {
logger.error("Cannot get Factory's Object Type {}", def.clazz);
}
} else {
registry.register(def.clazz, def.beanName, bd);
}
logger.debug("Register definition {} for {}", def.beanName, def.clazz);
return bd;
} | [
"protected",
"BeanDefinition",
"registerBean",
"(",
"Definition",
"def",
",",
"BindRegistry",
"registry",
")",
"{",
"BeanDefinition",
"bd",
"=",
"convert",
"(",
"def",
")",
";",
"if",
"(",
"(",
"def",
".",
"isAbstract",
"(",
")",
"&&",
"def",
".",
"clazz",... | <p>
registerBean.
</p>
@param def bean definition.
@param registry a {@link org.beangle.commons.inject.bind.BindRegistry} object.
@return a {@link org.springframework.beans.factory.config.BeanDefinition} object. | [
"<p",
">",
"registerBean",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/beangle/beangle3/blob/33df2873a5f38e28ac174a1d3b8144eb2f808e64/ioc/spring/src/main/java/org/beangle/inject/spring/config/SpringConfigProcessor.java#L333-L355 |
JOML-CI/JOML | src/org/joml/Matrix3f.java | Matrix3f.setRow | public Matrix3f setRow(int row, float x, float y, float z) throws IndexOutOfBoundsException {
switch (row) {
case 0:
this.m00 = x;
this.m10 = y;
this.m20 = z;
break;
case 1:
this.m01 = x;
this.m11 = y;
this.m21 = z;
break;
case 2:
this.m02 = x;
this.m12 = y;
this.m22 = z;
break;
default:
throw new IndexOutOfBoundsException();
}
return this;
} | java | public Matrix3f setRow(int row, float x, float y, float z) throws IndexOutOfBoundsException {
switch (row) {
case 0:
this.m00 = x;
this.m10 = y;
this.m20 = z;
break;
case 1:
this.m01 = x;
this.m11 = y;
this.m21 = z;
break;
case 2:
this.m02 = x;
this.m12 = y;
this.m22 = z;
break;
default:
throw new IndexOutOfBoundsException();
}
return this;
} | [
"public",
"Matrix3f",
"setRow",
"(",
"int",
"row",
",",
"float",
"x",
",",
"float",
"y",
",",
"float",
"z",
")",
"throws",
"IndexOutOfBoundsException",
"{",
"switch",
"(",
"row",
")",
"{",
"case",
"0",
":",
"this",
".",
"m00",
"=",
"x",
";",
"this",
... | Set the row at the given <code>row</code> index, starting with <code>0</code>.
@param row
the row index in <code>[0..2]</code>
@param x
the first element in the row
@param y
the second element in the row
@param z
the third element in the row
@return this
@throws IndexOutOfBoundsException if <code>row</code> is not in <code>[0..2]</code> | [
"Set",
"the",
"row",
"at",
"the",
"given",
"<code",
">",
"row<",
"/",
"code",
">",
"index",
"starting",
"with",
"<code",
">",
"0<",
"/",
"code",
">",
"."
] | train | https://github.com/JOML-CI/JOML/blob/ce2652fc236b42bda3875c591f8e6645048a678f/src/org/joml/Matrix3f.java#L3266-L3287 |
xebia-france/xebia-servlet-extras | src/main/java/fr/xebia/servlet/filter/SecuredRemoteAddressFilter.java | SecuredRemoteAddressFilter.matchesOne | protected static boolean matchesOne(String str, Pattern... patterns) {
for (Pattern pattern : patterns) {
if (pattern.matcher(str).matches()) {
return true;
}
}
return false;
} | java | protected static boolean matchesOne(String str, Pattern... patterns) {
for (Pattern pattern : patterns) {
if (pattern.matcher(str).matches()) {
return true;
}
}
return false;
} | [
"protected",
"static",
"boolean",
"matchesOne",
"(",
"String",
"str",
",",
"Pattern",
"...",
"patterns",
")",
"{",
"for",
"(",
"Pattern",
"pattern",
":",
"patterns",
")",
"{",
"if",
"(",
"pattern",
".",
"matcher",
"(",
"str",
")",
".",
"matches",
"(",
... | Return <code>true</code> if the given <code>str</code> matches at least
one of the given <code>patterns</code>. | [
"Return",
"<code",
">",
"true<",
"/",
"code",
">",
"if",
"the",
"given",
"<code",
">",
"str<",
"/",
"code",
">",
"matches",
"at",
"least",
"one",
"of",
"the",
"given",
"<code",
">",
"patterns<",
"/",
"code",
">",
"."
] | train | https://github.com/xebia-france/xebia-servlet-extras/blob/b263636fc78f8794dde57d92b835edb5e95ce379/src/main/java/fr/xebia/servlet/filter/SecuredRemoteAddressFilter.java#L149-L156 |
spotbugs/spotbugs | spotbugs/src/main/java/edu/umd/cs/findbugs/BugInstance.java | BugInstance.addField | @Nonnull
public BugInstance addField(String className, String fieldName, String fieldSig, boolean isStatic) {
addField(new FieldAnnotation(className, fieldName, fieldSig, isStatic));
return this;
} | java | @Nonnull
public BugInstance addField(String className, String fieldName, String fieldSig, boolean isStatic) {
addField(new FieldAnnotation(className, fieldName, fieldSig, isStatic));
return this;
} | [
"@",
"Nonnull",
"public",
"BugInstance",
"addField",
"(",
"String",
"className",
",",
"String",
"fieldName",
",",
"String",
"fieldSig",
",",
"boolean",
"isStatic",
")",
"{",
"addField",
"(",
"new",
"FieldAnnotation",
"(",
"className",
",",
"fieldName",
",",
"f... | Add a field annotation.
@param className
name of the class containing the field
@param fieldName
the name of the field
@param fieldSig
type signature of the field
@param isStatic
whether or not the field is static
@return this object | [
"Add",
"a",
"field",
"annotation",
"."
] | train | https://github.com/spotbugs/spotbugs/blob/f6365c6eea6515035bded38efa4a7c8b46ccf28c/spotbugs/src/main/java/edu/umd/cs/findbugs/BugInstance.java#L1134-L1138 |
osglworks/java-tool | src/main/java/org/osgl/util/FastStr.java | FastStr.replaceFirst | @Override
public FastStr replaceFirst(String regex, String replacement) {
return unsafeOf(Pattern.compile(regex).matcher(this).replaceFirst(replacement));
} | java | @Override
public FastStr replaceFirst(String regex, String replacement) {
return unsafeOf(Pattern.compile(regex).matcher(this).replaceFirst(replacement));
} | [
"@",
"Override",
"public",
"FastStr",
"replaceFirst",
"(",
"String",
"regex",
",",
"String",
"replacement",
")",
"{",
"return",
"unsafeOf",
"(",
"Pattern",
".",
"compile",
"(",
"regex",
")",
".",
"matcher",
"(",
"this",
")",
".",
"replaceFirst",
"(",
"repl... | Wrapper of {@link String#replaceFirst(String, String)} but return FastStr inance
@param regex the regular expression specifies the place to be replaced
@param replacement the string to replace the found part
@return a FastStr that has the first found part replaced | [
"Wrapper",
"of",
"{",
"@link",
"String#replaceFirst",
"(",
"String",
"String",
")",
"}",
"but",
"return",
"FastStr",
"inance"
] | train | https://github.com/osglworks/java-tool/blob/8b6eee2bccb067eb32e6a7bc4a4dfef7a7d9008b/src/main/java/org/osgl/util/FastStr.java#L1168-L1171 |
lucee/Lucee | core/src/main/java/lucee/commons/lang/StringUtil.java | StringUtil.endsWithIgnoreCase | public static boolean endsWithIgnoreCase(final String base, final String end) {
if (base.length() < end.length()) {
return false;
}
return base.regionMatches(true, base.length() - end.length(), end, 0, end.length());
} | java | public static boolean endsWithIgnoreCase(final String base, final String end) {
if (base.length() < end.length()) {
return false;
}
return base.regionMatches(true, base.length() - end.length(), end, 0, end.length());
} | [
"public",
"static",
"boolean",
"endsWithIgnoreCase",
"(",
"final",
"String",
"base",
",",
"final",
"String",
"end",
")",
"{",
"if",
"(",
"base",
".",
"length",
"(",
")",
"<",
"end",
".",
"length",
"(",
")",
")",
"{",
"return",
"false",
";",
"}",
"ret... | Helper functions to query a strings end portion. The comparison is case insensitive.
@param base the base string.
@param end the ending text.
@return true, if the string ends with the given ending text. | [
"Helper",
"functions",
"to",
"query",
"a",
"strings",
"end",
"portion",
".",
"The",
"comparison",
"is",
"case",
"insensitive",
"."
] | train | https://github.com/lucee/Lucee/blob/29b153fc4e126e5edb97da937f2ee2e231b87593/core/src/main/java/lucee/commons/lang/StringUtil.java#L904-L909 |
datumbox/datumbox-framework | datumbox-framework-core/src/main/java/com/datumbox/framework/core/statistics/parametrics/independentsamples/FIndependentSamples.java | FIndependentSamples.checkCriticalValue | private static boolean checkCriticalValue(double score, int n, int m, boolean is_twoTailed, double aLevel) {
double probability=ContinuousDistributions.fCdf(score,n-1,m-1);
boolean rejectH0=false;
double a=aLevel;
if(is_twoTailed) { //if to tailed test then split the statistical significance in half
a=aLevel/2;
}
if(probability<=a || probability>=(1-a)) {
rejectH0=true;
}
return rejectH0;
} | java | private static boolean checkCriticalValue(double score, int n, int m, boolean is_twoTailed, double aLevel) {
double probability=ContinuousDistributions.fCdf(score,n-1,m-1);
boolean rejectH0=false;
double a=aLevel;
if(is_twoTailed) { //if to tailed test then split the statistical significance in half
a=aLevel/2;
}
if(probability<=a || probability>=(1-a)) {
rejectH0=true;
}
return rejectH0;
} | [
"private",
"static",
"boolean",
"checkCriticalValue",
"(",
"double",
"score",
",",
"int",
"n",
",",
"int",
"m",
",",
"boolean",
"is_twoTailed",
",",
"double",
"aLevel",
")",
"{",
"double",
"probability",
"=",
"ContinuousDistributions",
".",
"fCdf",
"(",
"score... | Checks the Critical Value to determine if the Hypothesis should be rejected
@param score
@param n
@param m
@param is_twoTailed
@param aLevel
@return | [
"Checks",
"the",
"Critical",
"Value",
"to",
"determine",
"if",
"the",
"Hypothesis",
"should",
"be",
"rejected"
] | train | https://github.com/datumbox/datumbox-framework/blob/909dff0476e80834f05ecdde0624dd2390e9b0ca/datumbox-framework-core/src/main/java/com/datumbox/framework/core/statistics/parametrics/independentsamples/FIndependentSamples.java#L62-L76 |
ppicas/custom-typeface | library/src/main/java/cat/ppicas/customtypeface/CustomTypeface.java | CustomTypeface.applyTypeface | public void applyTypeface(View view, AttributeSet attrs) {
if (!(view instanceof TextView) || view.getContext() == null) {
return;
}
TextView textView = (TextView) view;
Resources.Theme theme = view.getContext().getTheme();
List<Integer> defStyleAttrs = getHierarchyDefStyleAttrs(textView.getClass());
for (Integer defStyleAttr : defStyleAttrs) {
boolean applied = applyTypeface(textView, defStyleAttr, attrs, theme);
if (applied) {
break;
}
}
} | java | public void applyTypeface(View view, AttributeSet attrs) {
if (!(view instanceof TextView) || view.getContext() == null) {
return;
}
TextView textView = (TextView) view;
Resources.Theme theme = view.getContext().getTheme();
List<Integer> defStyleAttrs = getHierarchyDefStyleAttrs(textView.getClass());
for (Integer defStyleAttr : defStyleAttrs) {
boolean applied = applyTypeface(textView, defStyleAttr, attrs, theme);
if (applied) {
break;
}
}
} | [
"public",
"void",
"applyTypeface",
"(",
"View",
"view",
",",
"AttributeSet",
"attrs",
")",
"{",
"if",
"(",
"!",
"(",
"view",
"instanceof",
"TextView",
")",
"||",
"view",
".",
"getContext",
"(",
")",
"==",
"null",
")",
"{",
"return",
";",
"}",
"TextView... | Apply a custom {@literal Typeface} if it has a {@code customTypeface} attribute.
This method will search for a {@code customTypeface} attribute looking in the following
places:
<ul>
<li>Attributes of the tag defined in the layout</li>
<li>Attributes of the style applied to the tag</li>
<li>Attributes of the default style defined in the theme</li>
<li>Attributes of textAppearance found in any of previous places</li>
</ul>
<p>
If after search in the previous places it has not found a {@code customTypeface}, will
over iterate all the parent classes searching in the default styles until a
{@code customTypeface} is found.
</p>
<p>
This method will also look for the {@code customTypefaceIgnoreParents} attribute
in the same places as the {@code customTypeface} attribute. If this boolean attribute is
found and it's set to true, it will ignore any {@code customTypeface} defined in the parent
classes.
</p>
@param view the {@code View} to apply the typefaces
@param attrs attributes object extracted in the layout inflation | [
"Apply",
"a",
"custom",
"{",
"@literal",
"Typeface",
"}",
"if",
"it",
"has",
"a",
"{",
"@code",
"customTypeface",
"}",
"attribute",
".",
"This",
"method",
"will",
"search",
"for",
"a",
"{",
"@code",
"customTypeface",
"}",
"attribute",
"looking",
"in",
"the... | train | https://github.com/ppicas/custom-typeface/blob/3a2a68cc8584a72076c545a8b7c9f741f6002241/library/src/main/java/cat/ppicas/customtypeface/CustomTypeface.java#L288-L302 |
Stratio/deep-spark | deep-mongodb/src/main/java/com/stratio/deep/mongodb/extractor/MongoNativeExtractor.java | MongoNativeExtractor.calculateSplits | private DeepPartition[] calculateSplits(DBCollection collection) {
BasicDBList splitData = getSplitData(collection);
List<ServerAddress> serverAddressList = collection.getDB().getMongo().getServerAddressList();
if (splitData == null) {
Pair<BasicDBList, List<ServerAddress>> pair = getSplitDataCollectionShardEnviroment(getShards(collection),
collection.getDB().getName(),
collection.getName());
splitData = pair.left;
serverAddressList = pair.right;
}
Object lastKey = null; // Lower boundary of the first min split
List<String> stringHosts = new ArrayList<>();
for (ServerAddress serverAddress : serverAddressList) {
stringHosts.add(serverAddress.toString());
}
int i = 0;
MongoPartition[] partitions = new MongoPartition[splitData.size() + 1];
for (Object aSplitData : splitData) {
BasicDBObject currentKey = (BasicDBObject) aSplitData;
Object currentO = currentKey.get(MONGO_DEFAULT_ID);
partitions[i] = new MongoPartition(mongoDeepJobConfig.getRddId(), i, new DeepTokenRange(lastKey,
currentO, stringHosts), MONGO_DEFAULT_ID);
lastKey = currentO;
i++;
}
QueryBuilder queryBuilder = QueryBuilder.start(MONGO_DEFAULT_ID);
queryBuilder.greaterThanEquals(lastKey);
partitions[i] = new MongoPartition(0, i, new DeepTokenRange(lastKey, null, stringHosts), MONGO_DEFAULT_ID);
return partitions;
} | java | private DeepPartition[] calculateSplits(DBCollection collection) {
BasicDBList splitData = getSplitData(collection);
List<ServerAddress> serverAddressList = collection.getDB().getMongo().getServerAddressList();
if (splitData == null) {
Pair<BasicDBList, List<ServerAddress>> pair = getSplitDataCollectionShardEnviroment(getShards(collection),
collection.getDB().getName(),
collection.getName());
splitData = pair.left;
serverAddressList = pair.right;
}
Object lastKey = null; // Lower boundary of the first min split
List<String> stringHosts = new ArrayList<>();
for (ServerAddress serverAddress : serverAddressList) {
stringHosts.add(serverAddress.toString());
}
int i = 0;
MongoPartition[] partitions = new MongoPartition[splitData.size() + 1];
for (Object aSplitData : splitData) {
BasicDBObject currentKey = (BasicDBObject) aSplitData;
Object currentO = currentKey.get(MONGO_DEFAULT_ID);
partitions[i] = new MongoPartition(mongoDeepJobConfig.getRddId(), i, new DeepTokenRange(lastKey,
currentO, stringHosts), MONGO_DEFAULT_ID);
lastKey = currentO;
i++;
}
QueryBuilder queryBuilder = QueryBuilder.start(MONGO_DEFAULT_ID);
queryBuilder.greaterThanEquals(lastKey);
partitions[i] = new MongoPartition(0, i, new DeepTokenRange(lastKey, null, stringHosts), MONGO_DEFAULT_ID);
return partitions;
} | [
"private",
"DeepPartition",
"[",
"]",
"calculateSplits",
"(",
"DBCollection",
"collection",
")",
"{",
"BasicDBList",
"splitData",
"=",
"getSplitData",
"(",
"collection",
")",
";",
"List",
"<",
"ServerAddress",
">",
"serverAddressList",
"=",
"collection",
".",
"get... | Calculate splits.
@param collection the collection
@return the deep partition [ ] | [
"Calculate",
"splits",
"."
] | train | https://github.com/Stratio/deep-spark/blob/b9621c9b7a6d996f80fce1d073d696a157bed095/deep-mongodb/src/main/java/com/stratio/deep/mongodb/extractor/MongoNativeExtractor.java#L189-L229 |
pro-grade/pro-grade | src/main/java/net/sourceforge/prograde/policyparser/Parser.java | Parser.parsePrincipal | private ParsedPrincipal parsePrincipal() throws Exception {
lookahead = st.nextToken();
switch (lookahead) {
case '*':
lookahead = st.nextToken();
if (lookahead == '*') {
return new ParsedPrincipal(null, null);
} else {
throw new Exception("ER018: There have to be name wildcard after type wildcard.");
}
case '\"':
return new ParsedPrincipal(st.sval);
case StreamTokenizer.TT_WORD:
String principalClass = st.sval;
lookahead = st.nextToken();
switch (lookahead) {
case '*':
return new ParsedPrincipal(principalClass, null);
case '\"':
return new ParsedPrincipal(principalClass, st.sval);
default:
throw new Exception("ER019: Principal name or * expected.");
}
default:
throw new Exception("ER020: Principal type, *, or keystore alias expected.");
}
} | java | private ParsedPrincipal parsePrincipal() throws Exception {
lookahead = st.nextToken();
switch (lookahead) {
case '*':
lookahead = st.nextToken();
if (lookahead == '*') {
return new ParsedPrincipal(null, null);
} else {
throw new Exception("ER018: There have to be name wildcard after type wildcard.");
}
case '\"':
return new ParsedPrincipal(st.sval);
case StreamTokenizer.TT_WORD:
String principalClass = st.sval;
lookahead = st.nextToken();
switch (lookahead) {
case '*':
return new ParsedPrincipal(principalClass, null);
case '\"':
return new ParsedPrincipal(principalClass, st.sval);
default:
throw new Exception("ER019: Principal name or * expected.");
}
default:
throw new Exception("ER020: Principal type, *, or keystore alias expected.");
}
} | [
"private",
"ParsedPrincipal",
"parsePrincipal",
"(",
")",
"throws",
"Exception",
"{",
"lookahead",
"=",
"st",
".",
"nextToken",
"(",
")",
";",
"switch",
"(",
"lookahead",
")",
"{",
"case",
"'",
"'",
":",
"lookahead",
"=",
"st",
".",
"nextToken",
"(",
")"... | Private method for parsing principal part of policy entry.
@return parsed principal part of policy entry
@throws throws Exception when any problem occurred during parsing principal | [
"Private",
"method",
"for",
"parsing",
"principal",
"part",
"of",
"policy",
"entry",
"."
] | train | https://github.com/pro-grade/pro-grade/blob/371b0d1349c37bd048a06206d3fa1b0c3c1cd9ab/src/main/java/net/sourceforge/prograde/policyparser/Parser.java#L281-L307 |
actorapp/actor-platform | actor-sdk/sdk-core-android/android-sdk/src/main/java/im/actor/sdk/util/images/ops/ImageDrawing.java | ImageDrawing.drawRoundedCorners | public static void drawRoundedCorners(Bitmap src, Bitmap dest, int radius, int clearColor) {
clearBitmap(dest, clearColor);
Canvas canvas = new Canvas(dest);
Rect sourceRect = WorkCache.RECT1.get();
Rect destRect = WorkCache.RECT2.get();
sourceRect.set(0, 0, src.getWidth(), src.getHeight());
destRect.set(0, 0, dest.getWidth(), dest.getHeight());
RectF roundRect = WorkCache.RECTF1.get();
roundRect.set(0, 0, dest.getWidth(), dest.getHeight());
Paint paint = WorkCache.PAINT.get();
paint.reset();
paint.setStyle(Paint.Style.FILL);
paint.setColor(Color.RED);
paint.setAntiAlias(true);
canvas.drawRoundRect(roundRect, radius, radius, paint);
paint.reset();
paint.setFilterBitmap(true);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
canvas.drawBitmap(src, sourceRect, destRect, paint);
canvas.setBitmap(null);
} | java | public static void drawRoundedCorners(Bitmap src, Bitmap dest, int radius, int clearColor) {
clearBitmap(dest, clearColor);
Canvas canvas = new Canvas(dest);
Rect sourceRect = WorkCache.RECT1.get();
Rect destRect = WorkCache.RECT2.get();
sourceRect.set(0, 0, src.getWidth(), src.getHeight());
destRect.set(0, 0, dest.getWidth(), dest.getHeight());
RectF roundRect = WorkCache.RECTF1.get();
roundRect.set(0, 0, dest.getWidth(), dest.getHeight());
Paint paint = WorkCache.PAINT.get();
paint.reset();
paint.setStyle(Paint.Style.FILL);
paint.setColor(Color.RED);
paint.setAntiAlias(true);
canvas.drawRoundRect(roundRect, radius, radius, paint);
paint.reset();
paint.setFilterBitmap(true);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
canvas.drawBitmap(src, sourceRect, destRect, paint);
canvas.setBitmap(null);
} | [
"public",
"static",
"void",
"drawRoundedCorners",
"(",
"Bitmap",
"src",
",",
"Bitmap",
"dest",
",",
"int",
"radius",
",",
"int",
"clearColor",
")",
"{",
"clearBitmap",
"(",
"dest",
",",
"clearColor",
")",
";",
"Canvas",
"canvas",
"=",
"new",
"Canvas",
"(",... | Drawing src bitmap to dest bitmap with rounded corners
@param src source bitmap
@param dest destination bitmap
@param radius radius in destination bitmap scale
@param clearColor clear color | [
"Drawing",
"src",
"bitmap",
"to",
"dest",
"bitmap",
"with",
"rounded",
"corners"
] | train | https://github.com/actorapp/actor-platform/blob/5123c1584757c6eeea0ed2a0e7e043629871a0c6/actor-sdk/sdk-core-android/android-sdk/src/main/java/im/actor/sdk/util/images/ops/ImageDrawing.java#L121-L146 |
lievendoclo/Valkyrie-RCP | valkyrie-rcp-core/src/main/java/org/valkyriercp/util/ClassUtils.java | ClassUtils.getClassFieldNameWithValue | public static String getClassFieldNameWithValue(Class clazz, Object value) {
Field[] fields = clazz.getFields();
for (int i = 0; i < fields.length; i++) {
Field field = fields[i];
try {
Object constant = field.get(null);
if (value.equals(constant)) {
return clazz.getName() + "." + field.getName();
}
}
catch (Exception e) {
e.printStackTrace();
}
}
return null;
} | java | public static String getClassFieldNameWithValue(Class clazz, Object value) {
Field[] fields = clazz.getFields();
for (int i = 0; i < fields.length; i++) {
Field field = fields[i];
try {
Object constant = field.get(null);
if (value.equals(constant)) {
return clazz.getName() + "." + field.getName();
}
}
catch (Exception e) {
e.printStackTrace();
}
}
return null;
} | [
"public",
"static",
"String",
"getClassFieldNameWithValue",
"(",
"Class",
"clazz",
",",
"Object",
"value",
")",
"{",
"Field",
"[",
"]",
"fields",
"=",
"clazz",
".",
"getFields",
"(",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"fields",
... | Returns the qualified class field name with the specified value. For
example, with a class defined with a static field "NORMAL" with value =
"0", passing in "0" would return: className.NORMAL.
@return The qualified field. | [
"Returns",
"the",
"qualified",
"class",
"field",
"name",
"with",
"the",
"specified",
"value",
".",
"For",
"example",
"with",
"a",
"class",
"defined",
"with",
"a",
"static",
"field",
"NORMAL",
"with",
"value",
"=",
"0",
"passing",
"in",
"0",
"would",
"retur... | train | https://github.com/lievendoclo/Valkyrie-RCP/blob/6aad6e640b348cda8f3b0841f6e42025233f1eb8/valkyrie-rcp-core/src/main/java/org/valkyriercp/util/ClassUtils.java#L84-L99 |
contentful/contentful.java | src/main/java/com/contentful/java/cda/FetchQuery.java | FetchQuery.one | public T one(String id) {
try {
return baseQuery().one(id).blockingFirst();
} catch (NullPointerException e) {
throw new CDAResourceNotFoundException(type, id);
}
} | java | public T one(String id) {
try {
return baseQuery().one(id).blockingFirst();
} catch (NullPointerException e) {
throw new CDAResourceNotFoundException(type, id);
}
} | [
"public",
"T",
"one",
"(",
"String",
"id",
")",
"{",
"try",
"{",
"return",
"baseQuery",
"(",
")",
".",
"one",
"(",
"id",
")",
".",
"blockingFirst",
"(",
")",
";",
"}",
"catch",
"(",
"NullPointerException",
"e",
")",
"{",
"throw",
"new",
"CDAResourceN... | Fetch and return a resource matching the given {@code id}.
@param id resource id.
@return result resource, null if it does not exist. | [
"Fetch",
"and",
"return",
"a",
"resource",
"matching",
"the",
"given",
"{",
"@code",
"id",
"}",
"."
] | train | https://github.com/contentful/contentful.java/blob/6ecc2ace454c674b218b99489dc50697b1dbffcb/src/main/java/com/contentful/java/cda/FetchQuery.java#L24-L30 |
kuali/ojb-1.0.4 | src/java/org/apache/ojb/broker/ant/DataSet.java | DataSet.createInsertionSql | public void createInsertionSql(Database model, Platform platform, Writer writer) throws IOException
{
for (Iterator it = _beans.iterator(); it.hasNext();)
{
writer.write(platform.getInsertSql(model, (DynaBean)it.next()));
if (it.hasNext())
{
writer.write("\n");
}
}
} | java | public void createInsertionSql(Database model, Platform platform, Writer writer) throws IOException
{
for (Iterator it = _beans.iterator(); it.hasNext();)
{
writer.write(platform.getInsertSql(model, (DynaBean)it.next()));
if (it.hasNext())
{
writer.write("\n");
}
}
} | [
"public",
"void",
"createInsertionSql",
"(",
"Database",
"model",
",",
"Platform",
"platform",
",",
"Writer",
"writer",
")",
"throws",
"IOException",
"{",
"for",
"(",
"Iterator",
"it",
"=",
"_beans",
".",
"iterator",
"(",
")",
";",
"it",
".",
"hasNext",
"(... | Generates and writes the sql for inserting the currently contained data objects.
@param model The database model
@param platform The platform
@param writer The output stream | [
"Generates",
"and",
"writes",
"the",
"sql",
"for",
"inserting",
"the",
"currently",
"contained",
"data",
"objects",
"."
] | train | https://github.com/kuali/ojb-1.0.4/blob/9a544372f67ce965f662cdc71609dd03683c8f04/src/java/org/apache/ojb/broker/ant/DataSet.java#L55-L65 |
google/j2objc | jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/util/GlobalizationPreferences.java | GlobalizationPreferences.getDateFormat | public DateFormat getDateFormat(int dateStyle, int timeStyle) {
if (dateStyle == DF_NONE && timeStyle == DF_NONE
|| dateStyle < 0 || dateStyle >= DF_LIMIT
|| timeStyle < 0 || timeStyle >= DF_LIMIT) {
throw new IllegalArgumentException("Illegal date format style arguments");
}
DateFormat result = null;
if (dateFormats != null) {
result = dateFormats[dateStyle][timeStyle];
}
if (result != null) {
result = (DateFormat) result.clone(); // clone for safety
// Not sure overriding configuration is what we really want...
result.setTimeZone(getTimeZone());
} else {
result = guessDateFormat(dateStyle, timeStyle);
}
return result;
} | java | public DateFormat getDateFormat(int dateStyle, int timeStyle) {
if (dateStyle == DF_NONE && timeStyle == DF_NONE
|| dateStyle < 0 || dateStyle >= DF_LIMIT
|| timeStyle < 0 || timeStyle >= DF_LIMIT) {
throw new IllegalArgumentException("Illegal date format style arguments");
}
DateFormat result = null;
if (dateFormats != null) {
result = dateFormats[dateStyle][timeStyle];
}
if (result != null) {
result = (DateFormat) result.clone(); // clone for safety
// Not sure overriding configuration is what we really want...
result.setTimeZone(getTimeZone());
} else {
result = guessDateFormat(dateStyle, timeStyle);
}
return result;
} | [
"public",
"DateFormat",
"getDateFormat",
"(",
"int",
"dateStyle",
",",
"int",
"timeStyle",
")",
"{",
"if",
"(",
"dateStyle",
"==",
"DF_NONE",
"&&",
"timeStyle",
"==",
"DF_NONE",
"||",
"dateStyle",
"<",
"0",
"||",
"dateStyle",
">=",
"DF_LIMIT",
"||",
"timeSty... | Gets a date format according to the current settings. If there
is an explicit (non-null) date/time format set, a copy of that
is returned. Otherwise, the language priority list is used.
DF_NONE should be used for the style, where only the date or
time format individually is being gotten.
@param dateStyle DF_FULL, DF_LONG, DF_MEDIUM, DF_SHORT or DF_NONE
@param timeStyle DF_FULL, DF_LONG, DF_MEDIUM, DF_SHORT or DF_NONE
@return a DateFormat, according to the above description
@hide draft / provisional / internal are hidden on Android | [
"Gets",
"a",
"date",
"format",
"according",
"to",
"the",
"current",
"settings",
".",
"If",
"there",
"is",
"an",
"explicit",
"(",
"non",
"-",
"null",
")",
"date",
"/",
"time",
"format",
"set",
"a",
"copy",
"of",
"that",
"is",
"returned",
".",
"Otherwise... | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/util/GlobalizationPreferences.java#L662-L680 |
strator-dev/greenpepper-open | extensions-external/php/src/main/java/com/greenpepper/phpsud/fixtures/PHPFixture.java | PHPFixture.findClass | public static PHPClassDescriptor findClass(PHPContainer php, String className) throws PHPException {
PHPClassDescriptor desc;
desc = php.getClassDescriptor(className + "Fixture");
if (desc != null) {
return desc;
}
desc = php.getClassDescriptor(className);
if (desc != null) {
return desc;
}
String formattedClassName = Helper.formatProcedureName(className);
desc = php.getClassDescriptor(formattedClassName + "Fixture");
if (desc != null) {
return desc;
}
desc = php.getClassDescriptor(formattedClassName);
if (desc != null) {
return desc;
}
return null;
} | java | public static PHPClassDescriptor findClass(PHPContainer php, String className) throws PHPException {
PHPClassDescriptor desc;
desc = php.getClassDescriptor(className + "Fixture");
if (desc != null) {
return desc;
}
desc = php.getClassDescriptor(className);
if (desc != null) {
return desc;
}
String formattedClassName = Helper.formatProcedureName(className);
desc = php.getClassDescriptor(formattedClassName + "Fixture");
if (desc != null) {
return desc;
}
desc = php.getClassDescriptor(formattedClassName);
if (desc != null) {
return desc;
}
return null;
} | [
"public",
"static",
"PHPClassDescriptor",
"findClass",
"(",
"PHPContainer",
"php",
",",
"String",
"className",
")",
"throws",
"PHPException",
"{",
"PHPClassDescriptor",
"desc",
";",
"desc",
"=",
"php",
".",
"getClassDescriptor",
"(",
"className",
"+",
"\"Fixture\"",... | <p>findClass.</p>
@param php a {@link com.greenpepper.phpsud.container.PHPContainer} object.
@param className a {@link java.lang.String} object.
@return a {@link com.greenpepper.phpsud.container.PHPClassDescriptor} object.
@throws com.greenpepper.phpsud.exceptions.PHPException if any. | [
"<p",
">",
"findClass",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/strator-dev/greenpepper-open/blob/71fd244b4989e9cd2d07ae62dd954a1f2a269a92/extensions-external/php/src/main/java/com/greenpepper/phpsud/fixtures/PHPFixture.java#L59-L79 |
EdwardRaff/JSAT | JSAT/src/jsat/classifiers/boosting/Bagging.java | Bagging.getSampledDataSet | public static ClassificationDataSet getSampledDataSet(ClassificationDataSet dataSet, int[] sampledCounts)
{
ClassificationDataSet destination = new ClassificationDataSet(dataSet.getNumNumericalVars(), dataSet.getCategories(), dataSet.getPredicting());
for (int i = 0; i < sampledCounts.length; i++)
for(int j = 0; j < sampledCounts[i]; j++)
{
DataPoint dp = dataSet.getDataPoint(i);
destination.addDataPoint(dp.getNumericalValues(), dp.getCategoricalValues(), dataSet.getDataPointCategory(i));
}
return destination;
} | java | public static ClassificationDataSet getSampledDataSet(ClassificationDataSet dataSet, int[] sampledCounts)
{
ClassificationDataSet destination = new ClassificationDataSet(dataSet.getNumNumericalVars(), dataSet.getCategories(), dataSet.getPredicting());
for (int i = 0; i < sampledCounts.length; i++)
for(int j = 0; j < sampledCounts[i]; j++)
{
DataPoint dp = dataSet.getDataPoint(i);
destination.addDataPoint(dp.getNumericalValues(), dp.getCategoricalValues(), dataSet.getDataPointCategory(i));
}
return destination;
} | [
"public",
"static",
"ClassificationDataSet",
"getSampledDataSet",
"(",
"ClassificationDataSet",
"dataSet",
",",
"int",
"[",
"]",
"sampledCounts",
")",
"{",
"ClassificationDataSet",
"destination",
"=",
"new",
"ClassificationDataSet",
"(",
"dataSet",
".",
"getNumNumericalVa... | Creates a new data set from the given sample counts. Points sampled
multiple times will have multiple entries in the data set.
@param dataSet the data set that was sampled from
@param sampledCounts the sampling values obtained from
{@link #sampleWithReplacement(int[], int, java.util.Random) }
@return a new sampled classification data set | [
"Creates",
"a",
"new",
"data",
"set",
"from",
"the",
"given",
"sample",
"counts",
".",
"Points",
"sampled",
"multiple",
"times",
"will",
"have",
"multiple",
"entries",
"in",
"the",
"data",
"set",
"."
] | train | https://github.com/EdwardRaff/JSAT/blob/0ff53b7b39684b2379cc1da522f5b3a954b15cfb/JSAT/src/jsat/classifiers/boosting/Bagging.java#L278-L290 |
Azure/azure-sdk-for-java | containerregistry/resource-manager/v2018_02_01_preview/src/main/java/com/microsoft/azure/management/containerregistry/v2018_02_01_preview/implementation/BuildsInner.java | BuildsInner.beginUpdate | public BuildInner beginUpdate(String resourceGroupName, String registryName, String buildId) {
return beginUpdateWithServiceResponseAsync(resourceGroupName, registryName, buildId).toBlocking().single().body();
} | java | public BuildInner beginUpdate(String resourceGroupName, String registryName, String buildId) {
return beginUpdateWithServiceResponseAsync(resourceGroupName, registryName, buildId).toBlocking().single().body();
} | [
"public",
"BuildInner",
"beginUpdate",
"(",
"String",
"resourceGroupName",
",",
"String",
"registryName",
",",
"String",
"buildId",
")",
"{",
"return",
"beginUpdateWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"registryName",
",",
"buildId",
")",
".",
"toB... | Patch the build properties.
@param resourceGroupName The name of the resource group to which the container registry belongs.
@param registryName The name of the container registry.
@param buildId The build ID.
@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 BuildInner object if successful. | [
"Patch",
"the",
"build",
"properties",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/containerregistry/resource-manager/v2018_02_01_preview/src/main/java/com/microsoft/azure/management/containerregistry/v2018_02_01_preview/implementation/BuildsInner.java#L609-L611 |
jMotif/SAX | src/main/java/net/seninp/util/HeatChart.java | HeatChart.getChartImage | public Image getChartImage(boolean alpha) {
// Calculate all unknown dimensions.
measureComponents();
updateCoordinates();
// Determine image type based upon whether require alpha or not.
// Using BufferedImage.TYPE_INT_ARGB seems to break on jpg.
int imageType = (alpha ? BufferedImage.TYPE_4BYTE_ABGR : BufferedImage.TYPE_3BYTE_BGR);
// Create our chart image which we will eventually draw everything on.
BufferedImage chartImage = new BufferedImage(chartSize.width, chartSize.height, imageType);
Graphics2D chartGraphics = chartImage.createGraphics();
// Use anti-aliasing where ever possible.
chartGraphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
// Set the background.
chartGraphics.setColor(backgroundColour);
chartGraphics.fillRect(0, 0, chartSize.width, chartSize.height);
// Draw the title.
drawTitle(chartGraphics);
// Draw the heatmap image.
drawHeatMap(chartGraphics, zValues);
// Draw the axis labels.
drawXLabel(chartGraphics);
drawYLabel(chartGraphics);
// Draw the axis bars.
drawAxisBars(chartGraphics);
// Draw axis values.
drawXValues(chartGraphics);
drawYValues(chartGraphics);
return chartImage;
} | java | public Image getChartImage(boolean alpha) {
// Calculate all unknown dimensions.
measureComponents();
updateCoordinates();
// Determine image type based upon whether require alpha or not.
// Using BufferedImage.TYPE_INT_ARGB seems to break on jpg.
int imageType = (alpha ? BufferedImage.TYPE_4BYTE_ABGR : BufferedImage.TYPE_3BYTE_BGR);
// Create our chart image which we will eventually draw everything on.
BufferedImage chartImage = new BufferedImage(chartSize.width, chartSize.height, imageType);
Graphics2D chartGraphics = chartImage.createGraphics();
// Use anti-aliasing where ever possible.
chartGraphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
// Set the background.
chartGraphics.setColor(backgroundColour);
chartGraphics.fillRect(0, 0, chartSize.width, chartSize.height);
// Draw the title.
drawTitle(chartGraphics);
// Draw the heatmap image.
drawHeatMap(chartGraphics, zValues);
// Draw the axis labels.
drawXLabel(chartGraphics);
drawYLabel(chartGraphics);
// Draw the axis bars.
drawAxisBars(chartGraphics);
// Draw axis values.
drawXValues(chartGraphics);
drawYValues(chartGraphics);
return chartImage;
} | [
"public",
"Image",
"getChartImage",
"(",
"boolean",
"alpha",
")",
"{",
"// Calculate all unknown dimensions.",
"measureComponents",
"(",
")",
";",
"updateCoordinates",
"(",
")",
";",
"// Determine image type based upon whether require alpha or not.",
"// Using BufferedImage.TYPE_... | Generates and returns a new chart <code>Image</code> configured according to this object's
currently held settings. The given parameter determines whether transparency should be enabled
for the generated image.
<p>
No chart will be generated until this or the related <code>saveToFile(File)</code> method are
called. All successive calls will result in the generation of a new chart image, no caching is
used.
@param alpha whether to enable transparency.
@return A newly generated chart <code>Image</code>. The returned image is a
<code>BufferedImage</code>. | [
"Generates",
"and",
"returns",
"a",
"new",
"chart",
"<code",
">",
"Image<",
"/",
"code",
">",
"configured",
"according",
"to",
"this",
"object",
"s",
"currently",
"held",
"settings",
".",
"The",
"given",
"parameter",
"determines",
"whether",
"transparency",
"s... | train | https://github.com/jMotif/SAX/blob/39ee07a69facaa330def5130b8790aeda85f1061/src/main/java/net/seninp/util/HeatChart.java#L1225-L1264 |
trajano/caliper | caliper/src/main/java/com/google/caliper/options/CommandLineParser.java | CommandLineParser.parseShortOptions | private void parseShortOptions(String arg, Iterator<String> args) throws InvalidCommandException {
for (int i = 1; i < arg.length(); ++i) {
String name = "-" + arg.charAt(i);
InjectableOption injectable = injectionMap.getInjectableOption(name);
String value;
if (injectable.isBoolean()) {
value = "true";
} else {
// We need a value. If there's anything left, we take the rest of this "short option".
if (i + 1 < arg.length()) {
value = arg.substring(i + 1);
i = arg.length() - 1; // delayed "break"
// otherwise the next arg
} else {
value = grabNextValue(args, name);
}
}
injectNowOrLater(injectable, value);
}
} | java | private void parseShortOptions(String arg, Iterator<String> args) throws InvalidCommandException {
for (int i = 1; i < arg.length(); ++i) {
String name = "-" + arg.charAt(i);
InjectableOption injectable = injectionMap.getInjectableOption(name);
String value;
if (injectable.isBoolean()) {
value = "true";
} else {
// We need a value. If there's anything left, we take the rest of this "short option".
if (i + 1 < arg.length()) {
value = arg.substring(i + 1);
i = arg.length() - 1; // delayed "break"
// otherwise the next arg
} else {
value = grabNextValue(args, name);
}
}
injectNowOrLater(injectable, value);
}
} | [
"private",
"void",
"parseShortOptions",
"(",
"String",
"arg",
",",
"Iterator",
"<",
"String",
">",
"args",
")",
"throws",
"InvalidCommandException",
"{",
"for",
"(",
"int",
"i",
"=",
"1",
";",
"i",
"<",
"arg",
".",
"length",
"(",
")",
";",
"++",
"i",
... | (But not -abf=out.txt --- POSIX doesn't mention that either way, but GNU expressly forbids it.) | [
"(",
"But",
"not",
"-",
"abf",
"=",
"out",
".",
"txt",
"---",
"POSIX",
"doesn",
"t",
"mention",
"that",
"either",
"way",
"but",
"GNU",
"expressly",
"forbids",
"it",
".",
")"
] | train | https://github.com/trajano/caliper/blob/a8bcfd84fa9d7b893b3edfadc3b13240ae5cd658/caliper/src/main/java/com/google/caliper/options/CommandLineParser.java#L395-L416 |
sarl/sarl | main/coreplugins/io.sarl.lang/src/io/sarl/lang/extralanguage/validator/AbstractExtraLanguageValidator.java | AbstractExtraLanguageValidator.isResponsible | @SuppressWarnings("static-method")
protected boolean isResponsible(Map<Object, Object> context, EObject eObject) {
// Skip the validation of an feature call if one of its container was validated previously
if (eObject instanceof XMemberFeatureCall || eObject instanceof XFeatureCall) {
final XAbstractFeatureCall rootFeatureCall = Utils.getRootFeatureCall((XAbstractFeatureCall) eObject);
return !isCheckedFeatureCall(context, rootFeatureCall);
}
return true;
} | java | @SuppressWarnings("static-method")
protected boolean isResponsible(Map<Object, Object> context, EObject eObject) {
// Skip the validation of an feature call if one of its container was validated previously
if (eObject instanceof XMemberFeatureCall || eObject instanceof XFeatureCall) {
final XAbstractFeatureCall rootFeatureCall = Utils.getRootFeatureCall((XAbstractFeatureCall) eObject);
return !isCheckedFeatureCall(context, rootFeatureCall);
}
return true;
} | [
"@",
"SuppressWarnings",
"(",
"\"static-method\"",
")",
"protected",
"boolean",
"isResponsible",
"(",
"Map",
"<",
"Object",
",",
"Object",
">",
"context",
",",
"EObject",
"eObject",
")",
"{",
"// Skip the validation of an feature call if one of its container was validated p... | Replies if the validator is responsible to validate the given object.
@param context the context.
@param eObject the validated object.
@return {@code true} if the validator could be run. | [
"Replies",
"if",
"the",
"validator",
"is",
"responsible",
"to",
"validate",
"the",
"given",
"object",
"."
] | train | https://github.com/sarl/sarl/blob/ca00ff994598c730339972def4e19a60e0b8cace/main/coreplugins/io.sarl.lang/src/io/sarl/lang/extralanguage/validator/AbstractExtraLanguageValidator.java#L245-L253 |
apache/flink | flink-libraries/flink-streaming-python/src/main/java/org/apache/flink/streaming/python/api/datastream/PythonKeyedStream.java | PythonKeyedStream.count_window | public PythonWindowedStream count_window(long size, long slide) {
return new PythonWindowedStream<GlobalWindow>(this.stream.countWindow(size, slide));
} | java | public PythonWindowedStream count_window(long size, long slide) {
return new PythonWindowedStream<GlobalWindow>(this.stream.countWindow(size, slide));
} | [
"public",
"PythonWindowedStream",
"count_window",
"(",
"long",
"size",
",",
"long",
"slide",
")",
"{",
"return",
"new",
"PythonWindowedStream",
"<",
"GlobalWindow",
">",
"(",
"this",
".",
"stream",
".",
"countWindow",
"(",
"size",
",",
"slide",
")",
")",
";"... | A thin wrapper layer over {@link KeyedStream#countWindow(long, long)}.
@param size The size of the windows in number of elements.
@param slide The slide interval in number of elements.
@return The python windowed stream {@link PythonWindowedStream} | [
"A",
"thin",
"wrapper",
"layer",
"over",
"{",
"@link",
"KeyedStream#countWindow",
"(",
"long",
"long",
")",
"}",
"."
] | train | https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-libraries/flink-streaming-python/src/main/java/org/apache/flink/streaming/python/api/datastream/PythonKeyedStream.java#L54-L56 |
DV8FromTheWorld/JDA | src/main/java/net/dv8tion/jda/core/EmbedBuilder.java | EmbedBuilder.build | public MessageEmbed build()
{
if (isEmpty())
throw new IllegalStateException("Cannot build an empty embed!");
if (description.length() > MessageEmbed.TEXT_MAX_LENGTH)
throw new IllegalStateException(String.format("Description is longer than %d! Please limit your input!", MessageEmbed.TEXT_MAX_LENGTH));
final String descrip = this.description.length() < 1 ? null : this.description.toString();
return EntityBuilder.createMessageEmbed(url, title, descrip, EmbedType.RICH, timestamp,
color, thumbnail, null, author, null, footer, image, new LinkedList<>(fields));
} | java | public MessageEmbed build()
{
if (isEmpty())
throw new IllegalStateException("Cannot build an empty embed!");
if (description.length() > MessageEmbed.TEXT_MAX_LENGTH)
throw new IllegalStateException(String.format("Description is longer than %d! Please limit your input!", MessageEmbed.TEXT_MAX_LENGTH));
final String descrip = this.description.length() < 1 ? null : this.description.toString();
return EntityBuilder.createMessageEmbed(url, title, descrip, EmbedType.RICH, timestamp,
color, thumbnail, null, author, null, footer, image, new LinkedList<>(fields));
} | [
"public",
"MessageEmbed",
"build",
"(",
")",
"{",
"if",
"(",
"isEmpty",
"(",
")",
")",
"throw",
"new",
"IllegalStateException",
"(",
"\"Cannot build an empty embed!\"",
")",
";",
"if",
"(",
"description",
".",
"length",
"(",
")",
">",
"MessageEmbed",
".",
"T... | Returns a {@link net.dv8tion.jda.core.entities.MessageEmbed MessageEmbed}
that has been checked as being valid for sending.
@throws java.lang.IllegalStateException
If the embed is empty. Can be checked with {@link #isEmpty()}.
@return the built, sendable {@link net.dv8tion.jda.core.entities.MessageEmbed} | [
"Returns",
"a",
"{",
"@link",
"net",
".",
"dv8tion",
".",
"jda",
".",
"core",
".",
"entities",
".",
"MessageEmbed",
"MessageEmbed",
"}",
"that",
"has",
"been",
"checked",
"as",
"being",
"valid",
"for",
"sending",
"."
] | train | https://github.com/DV8FromTheWorld/JDA/blob/8ecbbe354d03f6bf448411bba573d0d4c268b560/src/main/java/net/dv8tion/jda/core/EmbedBuilder.java#L111-L121 |
centic9/commons-dost | src/main/java/org/dstadler/commons/http/HttpClientWrapper.java | HttpClientWrapper.checkAndFetch | public static HttpEntity checkAndFetch(HttpResponse response, String url) throws IOException {
int statusCode = response.getStatusLine().getStatusCode();
if(statusCode > 206) {
String msg = "Had HTTP StatusCode " + statusCode + " for request: " + url + ", response: " +
response.getStatusLine().getReasonPhrase() + "\n" +
StringUtils.abbreviate(IOUtils.toString(response.getEntity().getContent(), "UTF-8"), 1024);
log.warning(msg);
throw new IOException(msg);
}
return response.getEntity();
} | java | public static HttpEntity checkAndFetch(HttpResponse response, String url) throws IOException {
int statusCode = response.getStatusLine().getStatusCode();
if(statusCode > 206) {
String msg = "Had HTTP StatusCode " + statusCode + " for request: " + url + ", response: " +
response.getStatusLine().getReasonPhrase() + "\n" +
StringUtils.abbreviate(IOUtils.toString(response.getEntity().getContent(), "UTF-8"), 1024);
log.warning(msg);
throw new IOException(msg);
}
return response.getEntity();
} | [
"public",
"static",
"HttpEntity",
"checkAndFetch",
"(",
"HttpResponse",
"response",
",",
"String",
"url",
")",
"throws",
"IOException",
"{",
"int",
"statusCode",
"=",
"response",
".",
"getStatusLine",
"(",
")",
".",
"getStatusCode",
"(",
")",
";",
"if",
"(",
... | Helper method to check the status code of the response and throw an IOException if it is
an error or moved state.
@param response A HttpResponse that is resulting from executing a HttpMethod.
@param url The url, only used for building the error message of the exception.
@return The {@link HttpEntity} returned from response.getEntity().
@throws IOException if the HTTP status code is higher than 206. | [
"Helper",
"method",
"to",
"check",
"the",
"status",
"code",
"of",
"the",
"response",
"and",
"throw",
"an",
"IOException",
"if",
"it",
"is",
"an",
"error",
"or",
"moved",
"state",
"."
] | train | https://github.com/centic9/commons-dost/blob/f6fa4e3e0b943ff103f918824319d8abf33d0e0f/src/main/java/org/dstadler/commons/http/HttpClientWrapper.java#L353-L365 |
petergeneric/stdlib | stdlib/src/main/java/com/peterphi/std/io/FileHelper.java | FileHelper.safeMove | @Deprecated
public static boolean safeMove(File src, File dest) throws SecurityException
{
assert (src.exists());
final boolean createDestIfNotExist = true;
try
{
if (src.isFile())
FileUtils.moveFile(src, dest);
else
FileUtils.moveDirectoryToDirectory(src, dest, createDestIfNotExist);
return true;
}
catch (IOException e)
{
log.error("{safeMove} Error during move operation: " + e.getMessage(), e);
return false;
}
} | java | @Deprecated
public static boolean safeMove(File src, File dest) throws SecurityException
{
assert (src.exists());
final boolean createDestIfNotExist = true;
try
{
if (src.isFile())
FileUtils.moveFile(src, dest);
else
FileUtils.moveDirectoryToDirectory(src, dest, createDestIfNotExist);
return true;
}
catch (IOException e)
{
log.error("{safeMove} Error during move operation: " + e.getMessage(), e);
return false;
}
} | [
"@",
"Deprecated",
"public",
"static",
"boolean",
"safeMove",
"(",
"File",
"src",
",",
"File",
"dest",
")",
"throws",
"SecurityException",
"{",
"assert",
"(",
"src",
".",
"exists",
"(",
")",
")",
";",
"final",
"boolean",
"createDestIfNotExist",
"=",
"true",
... | Safely moves a file from one place to another, ensuring the filesystem is left in a consistent state
@param src
File The source file
@param dest
File The destination file
@return boolean True if the file has been completely moved to the new location, false if it is still in the original
location
@throws java.lang.SecurityException
MAY BE THROWN if permission is denied to src or dest
@deprecated use commons file utils FileUtils.moveDirectoryToDirectory instead | [
"Safely",
"moves",
"a",
"file",
"from",
"one",
"place",
"to",
"another",
"ensuring",
"the",
"filesystem",
"is",
"left",
"in",
"a",
"consistent",
"state"
] | train | https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/stdlib/src/main/java/com/peterphi/std/io/FileHelper.java#L335-L356 |
strator-dev/greenpepper | greenpepper/core/src/main/java/com/greenpepper/reflect/AbstractFixture.java | AbstractFixture.getSetter | protected Method getSetter(Class type, String name)
{
return introspector(type).getSetter( toJavaIdentifierForm(name));
} | java | protected Method getSetter(Class type, String name)
{
return introspector(type).getSetter( toJavaIdentifierForm(name));
} | [
"protected",
"Method",
"getSetter",
"(",
"Class",
"type",
",",
"String",
"name",
")",
"{",
"return",
"introspector",
"(",
"type",
")",
".",
"getSetter",
"(",
"toJavaIdentifierForm",
"(",
"name",
")",
")",
";",
"}"
] | <p>getSetter.</p>
@param type a {@link java.lang.Class} object.
@param name a {@link java.lang.String} object.
@return a {@link java.lang.reflect.Method} object. | [
"<p",
">",
"getSetter",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/strator-dev/greenpepper/blob/2a61e6c179b74085babcc559d677490b0cad2d30/greenpepper/core/src/main/java/com/greenpepper/reflect/AbstractFixture.java#L94-L97 |
biojava/biojava | biojava-structure/src/main/java/org/biojava/nbio/structure/StructureTools.java | StructureTools.hasDeuteratedEquiv | public static boolean hasDeuteratedEquiv(Atom atom, Group currentGroup) {
if(atom.getElement()==Element.H && currentGroup.hasAtom(replaceFirstChar(atom.getName(),'H', 'D'))) {
// If it's hydrogen and has a deuterated brother
return true;
}
return false;
} | java | public static boolean hasDeuteratedEquiv(Atom atom, Group currentGroup) {
if(atom.getElement()==Element.H && currentGroup.hasAtom(replaceFirstChar(atom.getName(),'H', 'D'))) {
// If it's hydrogen and has a deuterated brother
return true;
}
return false;
} | [
"public",
"static",
"boolean",
"hasDeuteratedEquiv",
"(",
"Atom",
"atom",
",",
"Group",
"currentGroup",
")",
"{",
"if",
"(",
"atom",
".",
"getElement",
"(",
")",
"==",
"Element",
".",
"H",
"&&",
"currentGroup",
".",
"hasAtom",
"(",
"replaceFirstChar",
"(",
... | Check to see if a Hydrogen has a Deuterated brother in the group.
@param atom the input atom that is putatively hydorgen
@param currentGroup the group the atom is in
@return true if the atom is hydrogen and it's Deuterium equiv exists. | [
"Check",
"to",
"see",
"if",
"a",
"Hydrogen",
"has",
"a",
"Deuterated",
"brother",
"in",
"the",
"group",
"."
] | train | https://github.com/biojava/biojava/blob/a1c71a8e3d40cc32104b1d387a3d3b560b43356e/biojava-structure/src/main/java/org/biojava/nbio/structure/StructureTools.java#L1909-L1915 |
looly/hutool | hutool-core/src/main/java/cn/hutool/core/util/XmlUtil.java | XmlUtil.getByXPath | public static Object getByXPath(String expression, Object source, QName returnType) {
final XPath xPath = createXPath();
try {
if (source instanceof InputSource) {
return xPath.evaluate(expression, (InputSource) source, returnType);
} else {
return xPath.evaluate(expression, source, returnType);
}
} catch (XPathExpressionException e) {
throw new UtilException(e);
}
} | java | public static Object getByXPath(String expression, Object source, QName returnType) {
final XPath xPath = createXPath();
try {
if (source instanceof InputSource) {
return xPath.evaluate(expression, (InputSource) source, returnType);
} else {
return xPath.evaluate(expression, source, returnType);
}
} catch (XPathExpressionException e) {
throw new UtilException(e);
}
} | [
"public",
"static",
"Object",
"getByXPath",
"(",
"String",
"expression",
",",
"Object",
"source",
",",
"QName",
"returnType",
")",
"{",
"final",
"XPath",
"xPath",
"=",
"createXPath",
"(",
")",
";",
"try",
"{",
"if",
"(",
"source",
"instanceof",
"InputSource"... | 通过XPath方式读取XML节点等信息<br>
Xpath相关文章:https://www.ibm.com/developerworks/cn/xml/x-javaxpathapi.html
@param expression XPath表达式
@param source 资源,可以是Docunent、Node节点等
@param returnType 返回类型,{@link javax.xml.xpath.XPathConstants}
@return 匹配返回类型的值
@since 3.2.0 | [
"通过XPath方式读取XML节点等信息<br",
">",
"Xpath相关文章:https",
":",
"//",
"www",
".",
"ibm",
".",
"com",
"/",
"developerworks",
"/",
"cn",
"/",
"xml",
"/",
"x",
"-",
"javaxpathapi",
".",
"html"
] | train | https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/util/XmlUtil.java#L612-L623 |
phax/ph-commons | ph-commons/src/main/java/com/helger/commons/collection/ArrayHelper.java | ArrayHelper.getConcatenated | @Nonnull
@ReturnsMutableCopy
public static <ELEMENTTYPE> ELEMENTTYPE [] getConcatenated (@Nullable final ELEMENTTYPE aHead,
@Nullable final ELEMENTTYPE [] aTailArray,
@Nonnull final Class <ELEMENTTYPE> aClass)
{
if (isEmpty (aTailArray))
return newArraySingleElement (aHead, aClass);
// Start concatenating
final ELEMENTTYPE [] ret = newArray (aClass, 1 + aTailArray.length);
ret[0] = aHead;
System.arraycopy (aTailArray, 0, ret, 1, aTailArray.length);
return ret;
} | java | @Nonnull
@ReturnsMutableCopy
public static <ELEMENTTYPE> ELEMENTTYPE [] getConcatenated (@Nullable final ELEMENTTYPE aHead,
@Nullable final ELEMENTTYPE [] aTailArray,
@Nonnull final Class <ELEMENTTYPE> aClass)
{
if (isEmpty (aTailArray))
return newArraySingleElement (aHead, aClass);
// Start concatenating
final ELEMENTTYPE [] ret = newArray (aClass, 1 + aTailArray.length);
ret[0] = aHead;
System.arraycopy (aTailArray, 0, ret, 1, aTailArray.length);
return ret;
} | [
"@",
"Nonnull",
"@",
"ReturnsMutableCopy",
"public",
"static",
"<",
"ELEMENTTYPE",
">",
"ELEMENTTYPE",
"[",
"]",
"getConcatenated",
"(",
"@",
"Nullable",
"final",
"ELEMENTTYPE",
"aHead",
",",
"@",
"Nullable",
"final",
"ELEMENTTYPE",
"[",
"]",
"aTailArray",
",",
... | Get a new array that combines the passed head and the array. The head
element will be the first element of the created array.
@param <ELEMENTTYPE>
Array element type
@param aHead
The first element of the result array. If this element is
<code>null</code> it will be inserted as such into the array!
@param aTailArray
The tail array. May be <code>null</code>.
@param aClass
The element class. Must be present, because in case both elements
are <code>null</code> there would be no way to create a new array.
May not be <code>null</code>.
@return <code>null</code> if both array parameters are <code>null</code> -
a non-<code>null</code> array with all elements in the correct
order otherwise. | [
"Get",
"a",
"new",
"array",
"that",
"combines",
"the",
"passed",
"head",
"and",
"the",
"array",
".",
"The",
"head",
"element",
"will",
"be",
"the",
"first",
"element",
"of",
"the",
"created",
"array",
"."
] | train | https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-commons/src/main/java/com/helger/commons/collection/ArrayHelper.java#L1961-L1975 |
k3po/k3po | specification/socks5/src/main/java/org/kaazing/specification/socks5/internal/Functions.java | Functions.verifyMIC | @Function
public static boolean verifyMIC(GSSContext context, MessageProp prop, byte[] message, byte[] mic) {
try {
context.verifyMIC(mic, 0, mic.length,
message, 0, message.length,
prop);
return true;
} catch (GSSException ex) {
throw new RuntimeException("Exception verifying mic", ex);
}
} | java | @Function
public static boolean verifyMIC(GSSContext context, MessageProp prop, byte[] message, byte[] mic) {
try {
context.verifyMIC(mic, 0, mic.length,
message, 0, message.length,
prop);
return true;
} catch (GSSException ex) {
throw new RuntimeException("Exception verifying mic", ex);
}
} | [
"@",
"Function",
"public",
"static",
"boolean",
"verifyMIC",
"(",
"GSSContext",
"context",
",",
"MessageProp",
"prop",
",",
"byte",
"[",
"]",
"message",
",",
"byte",
"[",
"]",
"mic",
")",
"{",
"try",
"{",
"context",
".",
"verifyMIC",
"(",
"mic",
",",
"... | Verify a message integrity check sent by a peer. If the MIC correctly identifies the
message then the peer knows that the remote peer correctly received the message.
@param context GSSContext for which a connection has been established to the remote peer
@param prop the MessageProp that was used to wrap the original message
@param message the bytes of the original message
@param mic the bytes received from the remote peer that represent the MIC (like a checksum)
@return a boolean whether or not the MIC was correctly verified | [
"Verify",
"a",
"message",
"integrity",
"check",
"sent",
"by",
"a",
"peer",
".",
"If",
"the",
"MIC",
"correctly",
"identifies",
"the",
"message",
"then",
"the",
"peer",
"knows",
"that",
"the",
"remote",
"peer",
"correctly",
"received",
"the",
"message",
"."
] | train | https://github.com/k3po/k3po/blob/3ca4fd31ab4a397893aa640c62ada0e485c8bbd4/specification/socks5/src/main/java/org/kaazing/specification/socks5/internal/Functions.java#L157-L168 |
apache/groovy | src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java | StaticTypeCheckingVisitor.checkOrMarkInnerFieldAccess | private String checkOrMarkInnerFieldAccess(Expression source, FieldNode fn, boolean lhsOfAssignment, String delegationData) {
if (fn == null || fn.isStatic()) return delegationData;
ClassNode enclosingClassNode = typeCheckingContext.getEnclosingClassNode();
ClassNode declaringClass = fn.getDeclaringClass();
// private handled elsewhere
if ((fn.isPublic() || fn.isProtected()) &&
(declaringClass != enclosingClassNode || typeCheckingContext.getEnclosingClosure() != null) &&
declaringClass.getModule() == enclosingClassNode.getModule() && !lhsOfAssignment && enclosingClassNode.isDerivedFrom(declaringClass)) {
if (source instanceof PropertyExpression) {
PropertyExpression pe = (PropertyExpression) source;
// this and attributes handled elsewhere
if ("this".equals(pe.getPropertyAsString()) || source instanceof AttributeExpression) return delegationData;
pe.getObjectExpression().putNodeMetaData(StaticTypesMarker.IMPLICIT_RECEIVER, "owner");
}
return "owner";
}
return delegationData;
} | java | private String checkOrMarkInnerFieldAccess(Expression source, FieldNode fn, boolean lhsOfAssignment, String delegationData) {
if (fn == null || fn.isStatic()) return delegationData;
ClassNode enclosingClassNode = typeCheckingContext.getEnclosingClassNode();
ClassNode declaringClass = fn.getDeclaringClass();
// private handled elsewhere
if ((fn.isPublic() || fn.isProtected()) &&
(declaringClass != enclosingClassNode || typeCheckingContext.getEnclosingClosure() != null) &&
declaringClass.getModule() == enclosingClassNode.getModule() && !lhsOfAssignment && enclosingClassNode.isDerivedFrom(declaringClass)) {
if (source instanceof PropertyExpression) {
PropertyExpression pe = (PropertyExpression) source;
// this and attributes handled elsewhere
if ("this".equals(pe.getPropertyAsString()) || source instanceof AttributeExpression) return delegationData;
pe.getObjectExpression().putNodeMetaData(StaticTypesMarker.IMPLICIT_RECEIVER, "owner");
}
return "owner";
}
return delegationData;
} | [
"private",
"String",
"checkOrMarkInnerFieldAccess",
"(",
"Expression",
"source",
",",
"FieldNode",
"fn",
",",
"boolean",
"lhsOfAssignment",
",",
"String",
"delegationData",
")",
"{",
"if",
"(",
"fn",
"==",
"null",
"||",
"fn",
".",
"isStatic",
"(",
")",
")",
... | Given a field node, checks if we are accessing or setting a public or protected field from an inner class. | [
"Given",
"a",
"field",
"node",
"checks",
"if",
"we",
"are",
"accessing",
"or",
"setting",
"a",
"public",
"or",
"protected",
"field",
"from",
"an",
"inner",
"class",
"."
] | train | https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java#L531-L548 |
looly/hutool | hutool-core/src/main/java/cn/hutool/core/lang/Assert.java | Assert.notNull | public static <T> T notNull(T object, String errorMsgTemplate, Object... params) throws IllegalArgumentException {
if (object == null) {
throw new IllegalArgumentException(StrUtil.format(errorMsgTemplate, params));
}
return object;
} | java | public static <T> T notNull(T object, String errorMsgTemplate, Object... params) throws IllegalArgumentException {
if (object == null) {
throw new IllegalArgumentException(StrUtil.format(errorMsgTemplate, params));
}
return object;
} | [
"public",
"static",
"<",
"T",
">",
"T",
"notNull",
"(",
"T",
"object",
",",
"String",
"errorMsgTemplate",
",",
"Object",
"...",
"params",
")",
"throws",
"IllegalArgumentException",
"{",
"if",
"(",
"object",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalA... | 断言对象是否不为{@code null} ,如果为{@code null} 抛出{@link NullPointerException} 异常 Assert that an object is not {@code null} .
<pre class="code">
Assert.notNull(clazz, "The class must not be null");
</pre>
@param <T> 被检查对象泛型类型
@param object 被检查对象
@param errorMsgTemplate 错误消息模板,变量使用{}表示
@param params 参数
@return 被检查后的对象
@throws IllegalArgumentException if the object is {@code null} | [
"断言对象是否不为",
"{",
"@code",
"null",
"}",
",如果为",
"{",
"@code",
"null",
"}",
"抛出",
"{",
"@link",
"NullPointerException",
"}",
"异常",
"Assert",
"that",
"an",
"object",
"is",
"not",
"{",
"@code",
"null",
"}",
"."
] | train | https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/lang/Assert.java#L130-L135 |
google/closure-templates | java/src/com/google/template/soy/jbcsrc/TemplateFactoryCompiler.java | TemplateFactoryCompiler.generateCreateMethod | private void generateCreateMethod(ClassVisitor cv, TypeInfo factoryType) {
final Label start = new Label();
final Label end = new Label();
final LocalVariable thisVar = createThisVar(factoryType, start, end);
final LocalVariable paramsVar = createLocal("params", 1, SOY_RECORD_TYPE, start, end);
final LocalVariable ijVar = createLocal("ij", 2, SOY_RECORD_TYPE, start, end);
final Statement returnTemplate =
Statement.returnExpression(template.constructor().construct(paramsVar, ijVar));
new Statement() {
@Override
protected void doGen(CodeBuilder ga) {
ga.mark(start);
returnTemplate.gen(ga);
ga.mark(end);
thisVar.tableEntry(ga);
paramsVar.tableEntry(ga);
ijVar.tableEntry(ga);
}
}.writeMethod(Opcodes.ACC_PUBLIC, CREATE_METHOD, cv);
} | java | private void generateCreateMethod(ClassVisitor cv, TypeInfo factoryType) {
final Label start = new Label();
final Label end = new Label();
final LocalVariable thisVar = createThisVar(factoryType, start, end);
final LocalVariable paramsVar = createLocal("params", 1, SOY_RECORD_TYPE, start, end);
final LocalVariable ijVar = createLocal("ij", 2, SOY_RECORD_TYPE, start, end);
final Statement returnTemplate =
Statement.returnExpression(template.constructor().construct(paramsVar, ijVar));
new Statement() {
@Override
protected void doGen(CodeBuilder ga) {
ga.mark(start);
returnTemplate.gen(ga);
ga.mark(end);
thisVar.tableEntry(ga);
paramsVar.tableEntry(ga);
ijVar.tableEntry(ga);
}
}.writeMethod(Opcodes.ACC_PUBLIC, CREATE_METHOD, cv);
} | [
"private",
"void",
"generateCreateMethod",
"(",
"ClassVisitor",
"cv",
",",
"TypeInfo",
"factoryType",
")",
"{",
"final",
"Label",
"start",
"=",
"new",
"Label",
"(",
")",
";",
"final",
"Label",
"end",
"=",
"new",
"Label",
"(",
")",
";",
"final",
"LocalVaria... | Writes the {@link CompiledTemplate.Factory#create} method, which directly delegates to the
constructor of the {@link #template}. | [
"Writes",
"the",
"{"
] | train | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jbcsrc/TemplateFactoryCompiler.java#L130-L149 |
apache/incubator-heron | heron/spi/src/java/org/apache/heron/spi/packing/PackingPlan.java | PackingPlan.getMaxContainerResources | public Resource getMaxContainerResources() {
double maxCpu = 0;
ByteAmount maxRam = ByteAmount.ZERO;
ByteAmount maxDisk = ByteAmount.ZERO;
for (ContainerPlan containerPlan : getContainers()) {
Resource containerResource =
containerPlan.getScheduledResource().or(containerPlan.getRequiredResource());
maxCpu = Math.max(maxCpu, containerResource.getCpu());
maxRam = maxRam.max(containerResource.getRam());
maxDisk = maxDisk.max(containerResource.getDisk());
}
return new Resource(maxCpu, maxRam, maxDisk);
} | java | public Resource getMaxContainerResources() {
double maxCpu = 0;
ByteAmount maxRam = ByteAmount.ZERO;
ByteAmount maxDisk = ByteAmount.ZERO;
for (ContainerPlan containerPlan : getContainers()) {
Resource containerResource =
containerPlan.getScheduledResource().or(containerPlan.getRequiredResource());
maxCpu = Math.max(maxCpu, containerResource.getCpu());
maxRam = maxRam.max(containerResource.getRam());
maxDisk = maxDisk.max(containerResource.getDisk());
}
return new Resource(maxCpu, maxRam, maxDisk);
} | [
"public",
"Resource",
"getMaxContainerResources",
"(",
")",
"{",
"double",
"maxCpu",
"=",
"0",
";",
"ByteAmount",
"maxRam",
"=",
"ByteAmount",
".",
"ZERO",
";",
"ByteAmount",
"maxDisk",
"=",
"ByteAmount",
".",
"ZERO",
";",
"for",
"(",
"ContainerPlan",
"contain... | Computes the maximum of all the resources required by the containers in the packing plan. If
the PackingPlan has already been scheduled, the scheduled resources will be used over the
required resources.
@return maximum Resources found in all containers. | [
"Computes",
"the",
"maximum",
"of",
"all",
"the",
"resources",
"required",
"by",
"the",
"containers",
"in",
"the",
"packing",
"plan",
".",
"If",
"the",
"PackingPlan",
"has",
"already",
"been",
"scheduled",
"the",
"scheduled",
"resources",
"will",
"be",
"used",... | train | https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/spi/src/java/org/apache/heron/spi/packing/PackingPlan.java#L53-L66 |
netheosgithub/pcs_api | java/src/main/java/net/netheos/pcsapi/providers/cloudme/CloudMe.java | CloudMe.getApiRequestInvoker | private RequestInvoker<CResponse> getApiRequestInvoker( HttpRequestBase request, CPath path )
{
return new RequestInvoker<CResponse>( new HttpRequestor( request, path, sessionManager ),
API_RESPONSE_VALIDATOR );
} | java | private RequestInvoker<CResponse> getApiRequestInvoker( HttpRequestBase request, CPath path )
{
return new RequestInvoker<CResponse>( new HttpRequestor( request, path, sessionManager ),
API_RESPONSE_VALIDATOR );
} | [
"private",
"RequestInvoker",
"<",
"CResponse",
">",
"getApiRequestInvoker",
"(",
"HttpRequestBase",
"request",
",",
"CPath",
"path",
")",
"{",
"return",
"new",
"RequestInvoker",
"<",
"CResponse",
">",
"(",
"new",
"HttpRequestor",
"(",
"request",
",",
"path",
","... | An invoker that checks response content type = XML : to be used by all API requests
@param request API request
@return a request invoker specific for API requests | [
"An",
"invoker",
"that",
"checks",
"response",
"content",
"type",
"=",
"XML",
":",
"to",
"be",
"used",
"by",
"all",
"API",
"requests"
] | train | https://github.com/netheosgithub/pcs_api/blob/20691e52e144014f99ca75cb7dedc7ba0c18586c/java/src/main/java/net/netheos/pcsapi/providers/cloudme/CloudMe.java#L117-L121 |
zerodhatech/javakiteconnect | kiteconnect/src/com/zerodhatech/models/User.java | User.parseResponse | public User parseResponse(JSONObject response) throws JSONException {
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {
@Override
public Date deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
try {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return format.parse(jsonElement.getAsString());
} catch (ParseException e) {
return null;
}
}
});
Gson gson = gsonBuilder.setDateFormat("yyyy-MM-dd HH:mm:ss").create();
User user = gson.fromJson(String.valueOf(response.get("data")), User.class);
user = parseArray(user, response.getJSONObject("data"));
return user;
} | java | public User parseResponse(JSONObject response) throws JSONException {
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {
@Override
public Date deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
try {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return format.parse(jsonElement.getAsString());
} catch (ParseException e) {
return null;
}
}
});
Gson gson = gsonBuilder.setDateFormat("yyyy-MM-dd HH:mm:ss").create();
User user = gson.fromJson(String.valueOf(response.get("data")), User.class);
user = parseArray(user, response.getJSONObject("data"));
return user;
} | [
"public",
"User",
"parseResponse",
"(",
"JSONObject",
"response",
")",
"throws",
"JSONException",
"{",
"GsonBuilder",
"gsonBuilder",
"=",
"new",
"GsonBuilder",
"(",
")",
";",
"gsonBuilder",
".",
"registerTypeAdapter",
"(",
"Date",
".",
"class",
",",
"new",
"Json... | Parses user details response from server.
@param response is the json response from server.
@throws JSONException is thrown when there is error while parsing response.
@return User is the parsed data. | [
"Parses",
"user",
"details",
"response",
"from",
"server",
"."
] | train | https://github.com/zerodhatech/javakiteconnect/blob/4a3f15ff2c8a1b3b6ec61799f8bb047e4dfeb92d/kiteconnect/src/com/zerodhatech/models/User.java#L52-L70 |
googleapis/google-cloud-java | google-cloud-clients/google-cloud-compute/src/main/java/com/google/cloud/compute/deprecated/SnapshotInfo.java | SnapshotInfo.newBuilder | public static Builder newBuilder(SnapshotId snapshotId, DiskId source) {
return new BuilderImpl().setSnapshotId(snapshotId).setSourceDisk(source);
} | java | public static Builder newBuilder(SnapshotId snapshotId, DiskId source) {
return new BuilderImpl().setSnapshotId(snapshotId).setSourceDisk(source);
} | [
"public",
"static",
"Builder",
"newBuilder",
"(",
"SnapshotId",
"snapshotId",
",",
"DiskId",
"source",
")",
"{",
"return",
"new",
"BuilderImpl",
"(",
")",
".",
"setSnapshotId",
"(",
"snapshotId",
")",
".",
"setSourceDisk",
"(",
"source",
")",
";",
"}"
] | Returns a builder for a {@code SnapshotInfo} object given the snapshot identity and a source
disk identity. | [
"Returns",
"a",
"builder",
"for",
"a",
"{"
] | train | https://github.com/googleapis/google-cloud-java/blob/d2f0bc64a53049040fe9c9d338b12fab3dd1ad6a/google-cloud-clients/google-cloud-compute/src/main/java/com/google/cloud/compute/deprecated/SnapshotInfo.java#L444-L446 |
eclipse/hawkbit | hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/MaintenanceScheduleHelper.java | MaintenanceScheduleHelper.validateMaintenanceSchedule | public static void validateMaintenanceSchedule(final String cronSchedule, final String duration,
final String timezone) {
if (allNotEmpty(cronSchedule, duration, timezone)) {
validateCronSchedule(cronSchedule);
validateDuration(duration);
// check if there is a window currently active or available in
// future.
if (!getNextMaintenanceWindow(cronSchedule, duration, timezone).isPresent()) {
throw new InvalidMaintenanceScheduleException(
"No valid maintenance window available after current time");
}
} else if (atLeastOneNotEmpty(cronSchedule, duration, timezone)) {
throw new InvalidMaintenanceScheduleException(
"All of schedule, duration and timezone should either be null or non empty.");
}
} | java | public static void validateMaintenanceSchedule(final String cronSchedule, final String duration,
final String timezone) {
if (allNotEmpty(cronSchedule, duration, timezone)) {
validateCronSchedule(cronSchedule);
validateDuration(duration);
// check if there is a window currently active or available in
// future.
if (!getNextMaintenanceWindow(cronSchedule, duration, timezone).isPresent()) {
throw new InvalidMaintenanceScheduleException(
"No valid maintenance window available after current time");
}
} else if (atLeastOneNotEmpty(cronSchedule, duration, timezone)) {
throw new InvalidMaintenanceScheduleException(
"All of schedule, duration and timezone should either be null or non empty.");
}
} | [
"public",
"static",
"void",
"validateMaintenanceSchedule",
"(",
"final",
"String",
"cronSchedule",
",",
"final",
"String",
"duration",
",",
"final",
"String",
"timezone",
")",
"{",
"if",
"(",
"allNotEmpty",
"(",
"cronSchedule",
",",
"duration",
",",
"timezone",
... | Check if the maintenance schedule definition is valid in terms of
validity of cron expression, duration and availability of at least one
valid maintenance window. Further a maintenance schedule is valid if
either all the parameters: schedule, duration and time zone are valid or
are null.
@param cronSchedule
is a cron expression with 6 mandatory fields and 1 last
optional field: "second minute hour dayofmonth month weekday
year".
@param duration
in HH:mm:ss format specifying the duration of a maintenance
window, for example 00:30:00 for 30 minutes.
@param timezone
is the time zone specified as +/-hh:mm offset from UTC. For
example +02:00 for CET summer time and +00:00 for UTC. The
start time of a maintenance window calculated based on the
cron expression is relative to this time zone.
@throws InvalidMaintenanceScheduleException
if the defined schedule fails the validity criteria. | [
"Check",
"if",
"the",
"maintenance",
"schedule",
"definition",
"is",
"valid",
"in",
"terms",
"of",
"validity",
"of",
"cron",
"expression",
"duration",
"and",
"availability",
"of",
"at",
"least",
"one",
"valid",
"maintenance",
"window",
".",
"Further",
"a",
"ma... | train | https://github.com/eclipse/hawkbit/blob/9884452ad42f3b4827461606d8a9215c8625a7fe/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/MaintenanceScheduleHelper.java#L119-L134 |
astrapi69/jaulp-wicket | jaulp-wicket-components/src/main/java/de/alpharogroup/wicket/components/deregistration/DeregistrationPanel.java | DeregistrationPanel.newMotivation | protected LabeledTextAreaPanel<String, DeregistrationModelBean> newMotivation(final String id,
final IModel<DeregistrationModelBean> model)
{
final IModel<String> labelModel = ResourceModelFactory.newResourceModel(
ResourceBundleKey.builder().key("sem.main.feedback.deregistration.user.label")
.defaultValue("Please confirm the deregistration")
.parameters(ListExtensions.toObjectArray(getDomainName())).build(),
this);
final IModel<String> placeholderModel = ResourceModelFactory.newResourceModel(
"global.enter.your.deregistration.motivation.label", this,
"Enter here your deregistration motivation.");
final LabeledTextAreaPanel<String, DeregistrationModelBean> description = new LabeledTextAreaPanel<String, DeregistrationModelBean>(
id, model, labelModel)
{
/** The Constant serialVersionUID. */
private static final long serialVersionUID = 1L;
/**
* {@inheritDoc}
*/
@Override
protected TextArea<String> newTextArea(final String id,
final IModel<DeregistrationModelBean> model)
{
final TextArea<String> textArea = super.newTextArea(id, model);
if (placeholderModel != null)
{
textArea.add(new AttributeAppender("placeholder", placeholderModel));
}
return textArea;
}
};
return description;
} | java | protected LabeledTextAreaPanel<String, DeregistrationModelBean> newMotivation(final String id,
final IModel<DeregistrationModelBean> model)
{
final IModel<String> labelModel = ResourceModelFactory.newResourceModel(
ResourceBundleKey.builder().key("sem.main.feedback.deregistration.user.label")
.defaultValue("Please confirm the deregistration")
.parameters(ListExtensions.toObjectArray(getDomainName())).build(),
this);
final IModel<String> placeholderModel = ResourceModelFactory.newResourceModel(
"global.enter.your.deregistration.motivation.label", this,
"Enter here your deregistration motivation.");
final LabeledTextAreaPanel<String, DeregistrationModelBean> description = new LabeledTextAreaPanel<String, DeregistrationModelBean>(
id, model, labelModel)
{
/** The Constant serialVersionUID. */
private static final long serialVersionUID = 1L;
/**
* {@inheritDoc}
*/
@Override
protected TextArea<String> newTextArea(final String id,
final IModel<DeregistrationModelBean> model)
{
final TextArea<String> textArea = super.newTextArea(id, model);
if (placeholderModel != null)
{
textArea.add(new AttributeAppender("placeholder", placeholderModel));
}
return textArea;
}
};
return description;
} | [
"protected",
"LabeledTextAreaPanel",
"<",
"String",
",",
"DeregistrationModelBean",
">",
"newMotivation",
"(",
"final",
"String",
"id",
",",
"final",
"IModel",
"<",
"DeregistrationModelBean",
">",
"model",
")",
"{",
"final",
"IModel",
"<",
"String",
">",
"labelMod... | Factory method for creating the LabeledTextAreaPanel. This method is invoked in the
constructor from the derived classes and can be overridden so users can provide their own
version of a Form.
@param id
the id
@param model
the model
@return the form | [
"Factory",
"method",
"for",
"creating",
"the",
"LabeledTextAreaPanel",
".",
"This",
"method",
"is",
"invoked",
"in",
"the",
"constructor",
"from",
"the",
"derived",
"classes",
"and",
"can",
"be",
"overridden",
"so",
"users",
"can",
"provide",
"their",
"own",
"... | train | https://github.com/astrapi69/jaulp-wicket/blob/85d74368d00abd9bb97659b5794e38c0f8a013d4/jaulp-wicket-components/src/main/java/de/alpharogroup/wicket/components/deregistration/DeregistrationPanel.java#L202-L235 |
HeidelTime/heideltime | src/de/unihd/dbs/uima/annotator/heideltime/HeidelTime.java | HeidelTime.checkPosConstraint | public boolean checkPosConstraint(Sentence s, String posConstraint, MatchResult m, JCas jcas) {
Pattern paConstraint = Pattern.compile("group\\(([0-9]+)\\):(.*?):");
for (MatchResult mr : Toolbox.findMatches(paConstraint,posConstraint)) {
int groupNumber = Integer.parseInt(mr.group(1));
int tokenBegin = s.getBegin() + m.start(groupNumber);
int tokenEnd = s.getBegin() + m.end(groupNumber);
String pos = mr.group(2);
String pos_as_is = getPosFromMatchResult(tokenBegin, tokenEnd ,s, jcas);
if (pos_as_is.matches(pos)) {
Logger.printDetail("POS CONSTRAINT IS VALID: pos should be "+pos+" and is "+pos_as_is);
} else {
return false;
}
}
return true;
} | java | public boolean checkPosConstraint(Sentence s, String posConstraint, MatchResult m, JCas jcas) {
Pattern paConstraint = Pattern.compile("group\\(([0-9]+)\\):(.*?):");
for (MatchResult mr : Toolbox.findMatches(paConstraint,posConstraint)) {
int groupNumber = Integer.parseInt(mr.group(1));
int tokenBegin = s.getBegin() + m.start(groupNumber);
int tokenEnd = s.getBegin() + m.end(groupNumber);
String pos = mr.group(2);
String pos_as_is = getPosFromMatchResult(tokenBegin, tokenEnd ,s, jcas);
if (pos_as_is.matches(pos)) {
Logger.printDetail("POS CONSTRAINT IS VALID: pos should be "+pos+" and is "+pos_as_is);
} else {
return false;
}
}
return true;
} | [
"public",
"boolean",
"checkPosConstraint",
"(",
"Sentence",
"s",
",",
"String",
"posConstraint",
",",
"MatchResult",
"m",
",",
"JCas",
"jcas",
")",
"{",
"Pattern",
"paConstraint",
"=",
"Pattern",
".",
"compile",
"(",
"\"group\\\\(([0-9]+)\\\\):(.*?):\"",
")",
";",... | Check whether the part of speech constraint defined in a rule is satisfied.
@param s
@param posConstraint
@param m
@param jcas
@return | [
"Check",
"whether",
"the",
"part",
"of",
"speech",
"constraint",
"defined",
"in",
"a",
"rule",
"is",
"satisfied",
"."
] | train | https://github.com/HeidelTime/heideltime/blob/4ef5002eb5ecfeb818086ff7e394e792ee360335/src/de/unihd/dbs/uima/annotator/heideltime/HeidelTime.java#L2297-L2312 |
structurizr/java | structurizr-core/src/com/structurizr/documentation/Arc42DocumentationTemplate.java | Arc42DocumentationTemplate.addRisksAndTechnicalDebtSection | public Section addRisksAndTechnicalDebtSection(SoftwareSystem softwareSystem, File... files) throws IOException {
return addSection(softwareSystem, "Risks and Technical Debt", files);
} | java | public Section addRisksAndTechnicalDebtSection(SoftwareSystem softwareSystem, File... files) throws IOException {
return addSection(softwareSystem, "Risks and Technical Debt", files);
} | [
"public",
"Section",
"addRisksAndTechnicalDebtSection",
"(",
"SoftwareSystem",
"softwareSystem",
",",
"File",
"...",
"files",
")",
"throws",
"IOException",
"{",
"return",
"addSection",
"(",
"softwareSystem",
",",
"\"Risks and Technical Debt\"",
",",
"files",
")",
";",
... | Adds a "Risks and Technical Debt" section relating to a {@link SoftwareSystem} from one or more files.
@param softwareSystem the {@link SoftwareSystem} the documentation content relates to
@param files one or more File objects that point to the documentation content
@return a documentation {@link Section}
@throws IOException if there is an error reading the files | [
"Adds",
"a",
"Risks",
"and",
"Technical",
"Debt",
"section",
"relating",
"to",
"a",
"{",
"@link",
"SoftwareSystem",
"}",
"from",
"one",
"or",
"more",
"files",
"."
] | train | https://github.com/structurizr/java/blob/4b204f077877a24bcac363f5ecf0e129a0f9f4c5/structurizr-core/src/com/structurizr/documentation/Arc42DocumentationTemplate.java#L289-L291 |
spring-projects/spring-hateoas | src/main/java/org/springframework/hateoas/server/core/LinkBuilderSupport.java | LinkBuilderSupport.withFreshBuilder | protected <S> S withFreshBuilder(Function<UriComponentsBuilder, S> function) {
Assert.notNull(function, "Function must not be null!");
return function.apply(builder.cloneBuilder());
} | java | protected <S> S withFreshBuilder(Function<UriComponentsBuilder, S> function) {
Assert.notNull(function, "Function must not be null!");
return function.apply(builder.cloneBuilder());
} | [
"protected",
"<",
"S",
">",
"S",
"withFreshBuilder",
"(",
"Function",
"<",
"UriComponentsBuilder",
",",
"S",
">",
"function",
")",
"{",
"Assert",
".",
"notNull",
"(",
"function",
",",
"\"Function must not be null!\"",
")",
";",
"return",
"function",
".",
"appl... | Executes the given {@link Function} using a freshly cloned {@link UriComponentsBuilder}.
@param function must not be {@literal null}.
@return | [
"Executes",
"the",
"given",
"{",
"@link",
"Function",
"}",
"using",
"a",
"freshly",
"cloned",
"{",
"@link",
"UriComponentsBuilder",
"}",
"."
] | train | https://github.com/spring-projects/spring-hateoas/blob/70ebff9309f086cd8d6a97daf67e0dc215c87d9c/src/main/java/org/springframework/hateoas/server/core/LinkBuilderSupport.java#L177-L182 |
sailthru/sailthru-java-client | src/main/com/sailthru/client/SailthruClient.java | SailthruClient.getInstance | public static synchronized SailthruClient getInstance(String apiKey, String apiSecret) {
if (_instance == null) {
_instance = new SailthruClient(apiKey, apiSecret, DEFAULT_API_URL);
}
return _instance;
} | java | public static synchronized SailthruClient getInstance(String apiKey, String apiSecret) {
if (_instance == null) {
_instance = new SailthruClient(apiKey, apiSecret, DEFAULT_API_URL);
}
return _instance;
} | [
"public",
"static",
"synchronized",
"SailthruClient",
"getInstance",
"(",
"String",
"apiKey",
",",
"String",
"apiSecret",
")",
"{",
"if",
"(",
"_instance",
"==",
"null",
")",
"{",
"_instance",
"=",
"new",
"SailthruClient",
"(",
"apiKey",
",",
"apiSecret",
",",... | Synchronized singleton instance method using default URL string
@param apiKey Sailthru API key string
@param apiSecret Sailthru API secret string
@return singleton instance of SailthruClient
@deprecated | [
"Synchronized",
"singleton",
"instance",
"method",
"using",
"default",
"URL",
"string"
] | train | https://github.com/sailthru/sailthru-java-client/blob/62b491f6a39b41b836bfc021779200d29b6d2069/src/main/com/sailthru/client/SailthruClient.java#L56-L61 |
voldemort/voldemort | src/java/voldemort/server/protocol/admin/FetchStreamRequestHandler.java | FetchStreamRequestHandler.sendMessage | protected void sendMessage(DataOutputStream outputStream, Message message) throws IOException {
long startNs = System.nanoTime();
ProtoUtils.writeMessage(outputStream, message);
if(streamStats != null) {
streamStats.reportNetworkTime(operation,
Utils.elapsedTimeNs(startNs, System.nanoTime()));
}
} | java | protected void sendMessage(DataOutputStream outputStream, Message message) throws IOException {
long startNs = System.nanoTime();
ProtoUtils.writeMessage(outputStream, message);
if(streamStats != null) {
streamStats.reportNetworkTime(operation,
Utils.elapsedTimeNs(startNs, System.nanoTime()));
}
} | [
"protected",
"void",
"sendMessage",
"(",
"DataOutputStream",
"outputStream",
",",
"Message",
"message",
")",
"throws",
"IOException",
"{",
"long",
"startNs",
"=",
"System",
".",
"nanoTime",
"(",
")",
";",
"ProtoUtils",
".",
"writeMessage",
"(",
"outputStream",
"... | Helper method to send message on outputStream and account for network
time stats.
@param outputStream
@param message
@throws IOException | [
"Helper",
"method",
"to",
"send",
"message",
"on",
"outputStream",
"and",
"account",
"for",
"network",
"time",
"stats",
"."
] | train | https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/server/protocol/admin/FetchStreamRequestHandler.java#L206-L213 |
james-hu/jabb-core | src/main/java/net/sf/jabb/util/prop/PropertiesLoader.java | PropertiesLoader.getPropertyFromSystemOrEnv | static public String getPropertyFromSystemOrEnv(String lowerCamelCaseName, String defaultValue){
String upperCaseName = lowerCamelCaseName;
try{
upperCaseName = CaseFormat.LOWER_CAMEL.converterTo(CaseFormat.UPPER_UNDERSCORE).convert(lowerCamelCaseName);
}catch(Exception e){ // could there be any error during the conversion?
// ignore
}
String tmp;
String result = defaultValue;
tmp = System.getenv().get(lowerCamelCaseName);
if (tmp == null){
tmp = System.getenv().get(upperCaseName);
if (tmp == null){
// no change
}else{
result = tmp;
}
}else{
result = tmp;
}
result = System.getProperty(upperCaseName, result);
result = System.getProperty(lowerCamelCaseName, result);
return result;
} | java | static public String getPropertyFromSystemOrEnv(String lowerCamelCaseName, String defaultValue){
String upperCaseName = lowerCamelCaseName;
try{
upperCaseName = CaseFormat.LOWER_CAMEL.converterTo(CaseFormat.UPPER_UNDERSCORE).convert(lowerCamelCaseName);
}catch(Exception e){ // could there be any error during the conversion?
// ignore
}
String tmp;
String result = defaultValue;
tmp = System.getenv().get(lowerCamelCaseName);
if (tmp == null){
tmp = System.getenv().get(upperCaseName);
if (tmp == null){
// no change
}else{
result = tmp;
}
}else{
result = tmp;
}
result = System.getProperty(upperCaseName, result);
result = System.getProperty(lowerCamelCaseName, result);
return result;
} | [
"static",
"public",
"String",
"getPropertyFromSystemOrEnv",
"(",
"String",
"lowerCamelCaseName",
",",
"String",
"defaultValue",
")",
"{",
"String",
"upperCaseName",
"=",
"lowerCamelCaseName",
";",
"try",
"{",
"upperCaseName",
"=",
"CaseFormat",
".",
"LOWER_CAMEL",
"."... | Try to get property value in the following order:
<ol>
<li>JVM system property with the same name</li>
<li>JVM system property with the converted upper underscore name (e.g. converting nameOfTheProperty to NAME_OF_THE_PROPERTY)</li>
<li>OS environment variable with the same name</li>
<li>OS environment variable with the converted upper underscore name (e.g. converting nameOfTheProperty to NAME_OF_THE_PROPERTY)</li>
<li>the default value specified</li>
</ol>
@param lowerCamelCaseName name of the property in lower camel case (e.g. nameOfTheProperty)
@param defaultValue default value to be returned if the property cannot be found
@return the value of the property found, or the default value | [
"Try",
"to",
"get",
"property",
"value",
"in",
"the",
"following",
"order",
":",
"<ol",
">",
"<li",
">",
"JVM",
"system",
"property",
"with",
"the",
"same",
"name<",
"/",
"li",
">",
"<li",
">",
"JVM",
"system",
"property",
"with",
"the",
"converted",
"... | train | https://github.com/james-hu/jabb-core/blob/bceed441595c5e5195a7418795f03b69fa7b61e4/src/main/java/net/sf/jabb/util/prop/PropertiesLoader.java#L86-L113 |
ManfredTremmel/gwt-commons-lang3 | src/main/java/org/apache/commons/lang3/Validate.java | Validate.noNullElements | @GwtIncompatible("incompatible method")
public static <T extends Iterable<?>> T noNullElements(final T iterable) {
return noNullElements(iterable, DEFAULT_NO_NULL_ELEMENTS_COLLECTION_EX_MESSAGE);
} | java | @GwtIncompatible("incompatible method")
public static <T extends Iterable<?>> T noNullElements(final T iterable) {
return noNullElements(iterable, DEFAULT_NO_NULL_ELEMENTS_COLLECTION_EX_MESSAGE);
} | [
"@",
"GwtIncompatible",
"(",
"\"incompatible method\"",
")",
"public",
"static",
"<",
"T",
"extends",
"Iterable",
"<",
"?",
">",
">",
"T",
"noNullElements",
"(",
"final",
"T",
"iterable",
")",
"{",
"return",
"noNullElements",
"(",
"iterable",
",",
"DEFAULT_NO_... | <p>Validate that the specified argument iterable is neither
{@code null} nor contains any elements that are {@code null};
otherwise throwing an exception.
<pre>Validate.noNullElements(myCollection);</pre>
<p>If the iterable is {@code null}, then the message in the exception
is "The validated object is null".</p>
<p>If the array has a {@code null} element, then the message in the
exception is "The validated iterable contains null element at index:
" followed by the index.</p>
@param <T> the iterable type
@param iterable the iterable to check, validated not null by this method
@return the validated iterable (never {@code null} method for chaining)
@throws NullPointerException if the array is {@code null}
@throws IllegalArgumentException if an element is {@code null}
@see #noNullElements(Iterable, String, Object...) | [
"<p",
">",
"Validate",
"that",
"the",
"specified",
"argument",
"iterable",
"is",
"neither",
"{",
"@code",
"null",
"}",
"nor",
"contains",
"any",
"elements",
"that",
"are",
"{",
"@code",
"null",
"}",
";",
"otherwise",
"throwing",
"an",
"exception",
"."
] | train | https://github.com/ManfredTremmel/gwt-commons-lang3/blob/9e2dfbbda3668cfa5d935fe76479d1426c294504/src/main/java/org/apache/commons/lang3/Validate.java#L608-L611 |
ModeShape/modeshape | modeshape-jcr/src/main/java/org/modeshape/jcr/query/optimize/CopyCriteria.java | CopyCriteria.getColumnsReferencedBy | public static Set<Column> getColumnsReferencedBy( Visitable visitable ) {
if (visitable == null) return Collections.emptySet();
final Set<Column> symbols = new HashSet<Column>();
// Walk the entire structure, so only supply a StrategyVisitor (that does no navigation) ...
Visitors.visitAll(visitable, new AbstractVisitor() {
protected void addColumnFor( SelectorName selectorName,
String property ) {
symbols.add(new Column(selectorName, property, property));
}
@Override
public void visit( Column column ) {
symbols.add(column);
}
@Override
public void visit( EquiJoinCondition joinCondition ) {
addColumnFor(joinCondition.selector1Name(), joinCondition.getProperty1Name());
addColumnFor(joinCondition.selector2Name(), joinCondition.getProperty2Name());
}
@Override
public void visit( PropertyExistence prop ) {
addColumnFor(prop.selectorName(), prop.getPropertyName());
}
@Override
public void visit( PropertyValue prop ) {
addColumnFor(prop.selectorName(), prop.getPropertyName());
}
@Override
public void visit( ReferenceValue ref ) {
String propertyName = ref.getPropertyName();
if (propertyName != null) {
addColumnFor(ref.selectorName(), propertyName);
}
}
});
return symbols;
} | java | public static Set<Column> getColumnsReferencedBy( Visitable visitable ) {
if (visitable == null) return Collections.emptySet();
final Set<Column> symbols = new HashSet<Column>();
// Walk the entire structure, so only supply a StrategyVisitor (that does no navigation) ...
Visitors.visitAll(visitable, new AbstractVisitor() {
protected void addColumnFor( SelectorName selectorName,
String property ) {
symbols.add(new Column(selectorName, property, property));
}
@Override
public void visit( Column column ) {
symbols.add(column);
}
@Override
public void visit( EquiJoinCondition joinCondition ) {
addColumnFor(joinCondition.selector1Name(), joinCondition.getProperty1Name());
addColumnFor(joinCondition.selector2Name(), joinCondition.getProperty2Name());
}
@Override
public void visit( PropertyExistence prop ) {
addColumnFor(prop.selectorName(), prop.getPropertyName());
}
@Override
public void visit( PropertyValue prop ) {
addColumnFor(prop.selectorName(), prop.getPropertyName());
}
@Override
public void visit( ReferenceValue ref ) {
String propertyName = ref.getPropertyName();
if (propertyName != null) {
addColumnFor(ref.selectorName(), propertyName);
}
}
});
return symbols;
} | [
"public",
"static",
"Set",
"<",
"Column",
">",
"getColumnsReferencedBy",
"(",
"Visitable",
"visitable",
")",
"{",
"if",
"(",
"visitable",
"==",
"null",
")",
"return",
"Collections",
".",
"emptySet",
"(",
")",
";",
"final",
"Set",
"<",
"Column",
">",
"symbo... | Get the set of Column objects that represent those columns referenced by the visitable object.
@param visitable the object to be visited
@return the set of Column objects, with column names that always are the string-form of the {@link Column#getPropertyName()
property name}; never null | [
"Get",
"the",
"set",
"of",
"Column",
"objects",
"that",
"represent",
"those",
"columns",
"referenced",
"by",
"the",
"visitable",
"object",
"."
] | train | https://github.com/ModeShape/modeshape/blob/794cfdabb67a90f24629c4fff0424a6125f8f95b/modeshape-jcr/src/main/java/org/modeshape/jcr/query/optimize/CopyCriteria.java#L173-L213 |
liyiorg/weixin-popular | src/main/java/weixin/popular/util/XMLConverUtil.java | XMLConverUtil.convertToObject | public static <T> T convertToObject(Class<T> clazz, InputStream inputStream) {
return convertToObject(clazz, new InputStreamReader(inputStream));
} | java | public static <T> T convertToObject(Class<T> clazz, InputStream inputStream) {
return convertToObject(clazz, new InputStreamReader(inputStream));
} | [
"public",
"static",
"<",
"T",
">",
"T",
"convertToObject",
"(",
"Class",
"<",
"T",
">",
"clazz",
",",
"InputStream",
"inputStream",
")",
"{",
"return",
"convertToObject",
"(",
"clazz",
",",
"new",
"InputStreamReader",
"(",
"inputStream",
")",
")",
";",
"}"... | XML to Object
@param <T>
T
@param clazz
clazz
@param inputStream
inputStream
@return T | [
"XML",
"to",
"Object"
] | train | https://github.com/liyiorg/weixin-popular/blob/c64255292d41463bdb671938feaabf42a335d82c/src/main/java/weixin/popular/util/XMLConverUtil.java#L77-L79 |
Azure/azure-sdk-for-java | keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/implementation/KeyVaultClientBaseImpl.java | KeyVaultClientBaseImpl.encryptAsync | public ServiceFuture<KeyOperationResult> encryptAsync(String vaultBaseUrl, String keyName, String keyVersion, JsonWebKeyEncryptionAlgorithm algorithm, byte[] value, final ServiceCallback<KeyOperationResult> serviceCallback) {
return ServiceFuture.fromResponse(encryptWithServiceResponseAsync(vaultBaseUrl, keyName, keyVersion, algorithm, value), serviceCallback);
} | java | public ServiceFuture<KeyOperationResult> encryptAsync(String vaultBaseUrl, String keyName, String keyVersion, JsonWebKeyEncryptionAlgorithm algorithm, byte[] value, final ServiceCallback<KeyOperationResult> serviceCallback) {
return ServiceFuture.fromResponse(encryptWithServiceResponseAsync(vaultBaseUrl, keyName, keyVersion, algorithm, value), serviceCallback);
} | [
"public",
"ServiceFuture",
"<",
"KeyOperationResult",
">",
"encryptAsync",
"(",
"String",
"vaultBaseUrl",
",",
"String",
"keyName",
",",
"String",
"keyVersion",
",",
"JsonWebKeyEncryptionAlgorithm",
"algorithm",
",",
"byte",
"[",
"]",
"value",
",",
"final",
"Service... | Encrypts an arbitrary sequence of bytes using an encryption key that is stored in a key vault.
The ENCRYPT operation encrypts an arbitrary sequence of bytes using an encryption key that is stored in Azure Key Vault. Note that the ENCRYPT operation only supports a single block of data, the size of which is dependent on the target key and the encryption algorithm to be used. The ENCRYPT operation is only strictly necessary for symmetric keys stored in Azure Key Vault since protection with an asymmetric key can be performed using public portion of the key. This operation is supported for asymmetric keys as a convenience for callers that have a key-reference but do not have access to the public key material. This operation requires the keys/encypt permission.
@param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net.
@param keyName The name of the key.
@param keyVersion The version of the key.
@param algorithm algorithm identifier. Possible values include: 'RSA-OAEP', 'RSA-OAEP-256', 'RSA1_5'
@param value the Base64Url value
@param serviceCallback the async ServiceCallback to handle successful and failed responses.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the {@link ServiceFuture} object | [
"Encrypts",
"an",
"arbitrary",
"sequence",
"of",
"bytes",
"using",
"an",
"encryption",
"key",
"that",
"is",
"stored",
"in",
"a",
"key",
"vault",
".",
"The",
"ENCRYPT",
"operation",
"encrypts",
"an",
"arbitrary",
"sequence",
"of",
"bytes",
"using",
"an",
"enc... | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/implementation/KeyVaultClientBaseImpl.java#L2163-L2165 |
broadinstitute/barclay | src/main/java/org/broadinstitute/barclay/utils/Utils.java | Utils.dupString | public static String dupString(char c, int nCopies) {
char[] chars = new char[nCopies];
Arrays.fill(chars, c);
return new String(chars);
} | java | public static String dupString(char c, int nCopies) {
char[] chars = new char[nCopies];
Arrays.fill(chars, c);
return new String(chars);
} | [
"public",
"static",
"String",
"dupString",
"(",
"char",
"c",
",",
"int",
"nCopies",
")",
"{",
"char",
"[",
"]",
"chars",
"=",
"new",
"char",
"[",
"nCopies",
"]",
";",
"Arrays",
".",
"fill",
"(",
"chars",
",",
"c",
")",
";",
"return",
"new",
"String... | Create a new string thats a n duplicate copies of c
@param c the char to duplicate
@param nCopies how many copies?
@return a string | [
"Create",
"a",
"new",
"string",
"thats",
"a",
"n",
"duplicate",
"copies",
"of",
"c"
] | train | https://github.com/broadinstitute/barclay/blob/7e56d725766b0da3baff23e79a31c3d01c3589c2/src/main/java/org/broadinstitute/barclay/utils/Utils.java#L127-L131 |
UrielCh/ovh-java-sdk | ovh-java-sdk-xdsl/src/main/java/net/minidev/ovh/api/ApiOvhXdsl.java | ApiOvhXdsl.serviceName_modem_blocIp_POST | public OvhTask serviceName_modem_blocIp_POST(String serviceName, OvhServiceStatusEnum status) throws IOException {
String qPath = "/xdsl/{serviceName}/modem/blocIp";
StringBuilder sb = path(qPath, serviceName);
HashMap<String, Object>o = new HashMap<String, Object>();
addBody(o, "status", status);
String resp = exec(qPath, "POST", sb.toString(), o);
return convertTo(resp, OvhTask.class);
} | java | public OvhTask serviceName_modem_blocIp_POST(String serviceName, OvhServiceStatusEnum status) throws IOException {
String qPath = "/xdsl/{serviceName}/modem/blocIp";
StringBuilder sb = path(qPath, serviceName);
HashMap<String, Object>o = new HashMap<String, Object>();
addBody(o, "status", status);
String resp = exec(qPath, "POST", sb.toString(), o);
return convertTo(resp, OvhTask.class);
} | [
"public",
"OvhTask",
"serviceName_modem_blocIp_POST",
"(",
"String",
"serviceName",
",",
"OvhServiceStatusEnum",
"status",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/xdsl/{serviceName}/modem/blocIp\"",
";",
"StringBuilder",
"sb",
"=",
"path",
"(",
"q... | Change the status of the Bloc IP on modem
REST: POST /xdsl/{serviceName}/modem/blocIp
@param status [required] the new status of the bloc ip service
@param serviceName [required] The internal name of your XDSL offer | [
"Change",
"the",
"status",
"of",
"the",
"Bloc",
"IP",
"on",
"modem"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-xdsl/src/main/java/net/minidev/ovh/api/ApiOvhXdsl.java#L805-L812 |
Kickflip/kickflip-android-sdk | sdk/src/main/java/io/kickflip/sdk/av/Broadcaster.java | Broadcaster.queueOrSubmitUpload | private void queueOrSubmitUpload(String key, File file) {
if (mReadyToBroadcast) {
submitUpload(key, file);
} else {
if (VERBOSE) Log.i(TAG, "queueing " + key + " until S3 Credentials available");
queueUpload(key, file);
}
} | java | private void queueOrSubmitUpload(String key, File file) {
if (mReadyToBroadcast) {
submitUpload(key, file);
} else {
if (VERBOSE) Log.i(TAG, "queueing " + key + " until S3 Credentials available");
queueUpload(key, file);
}
} | [
"private",
"void",
"queueOrSubmitUpload",
"(",
"String",
"key",
",",
"File",
"file",
")",
"{",
"if",
"(",
"mReadyToBroadcast",
")",
"{",
"submitUpload",
"(",
"key",
",",
"file",
")",
";",
"}",
"else",
"{",
"if",
"(",
"VERBOSE",
")",
"Log",
".",
"i",
... | Handle an upload, either submitting to the S3 client
or queueing for submission once credentials are ready
@param key destination key
@param file local file | [
"Handle",
"an",
"upload",
"either",
"submitting",
"to",
"the",
"S3",
"client",
"or",
"queueing",
"for",
"submission",
"once",
"credentials",
"are",
"ready"
] | train | https://github.com/Kickflip/kickflip-android-sdk/blob/af3aae5f1128d7376e67aefe11a3a1a3844be734/sdk/src/main/java/io/kickflip/sdk/av/Broadcaster.java#L456-L463 |
haifengl/smile | core/src/main/java/smile/association/TotalSupportTree.java | TotalSupportTree.getFrequentItemsets | private long getFrequentItemsets(PrintStream out, List<ItemSet> list, int[] itemset, int size, Node node) {
ItemSet set = new ItemSet(itemset, node.support);
if (out != null) {
out.println(set);
}
if (list != null) {
list.add(set);
}
long n = 1;
if (node.children != null) {
for (int i = 0; i < size; i++) {
Node child = node.children[i];
if (child != null && child.support >= minSupport) {
int[] newItemset = FPGrowth.insert(itemset, child.id);
n += getFrequentItemsets(out, list, newItemset, i, child);
}
}
}
return n;
} | java | private long getFrequentItemsets(PrintStream out, List<ItemSet> list, int[] itemset, int size, Node node) {
ItemSet set = new ItemSet(itemset, node.support);
if (out != null) {
out.println(set);
}
if (list != null) {
list.add(set);
}
long n = 1;
if (node.children != null) {
for (int i = 0; i < size; i++) {
Node child = node.children[i];
if (child != null && child.support >= minSupport) {
int[] newItemset = FPGrowth.insert(itemset, child.id);
n += getFrequentItemsets(out, list, newItemset, i, child);
}
}
}
return n;
} | [
"private",
"long",
"getFrequentItemsets",
"(",
"PrintStream",
"out",
",",
"List",
"<",
"ItemSet",
">",
"list",
",",
"int",
"[",
"]",
"itemset",
",",
"int",
"size",
",",
"Node",
"node",
")",
"{",
"ItemSet",
"set",
"=",
"new",
"ItemSet",
"(",
"itemset",
... | Returns the set of frequent item sets.
@param out a print stream for output of frequent item sets.
@param list a container to store frequent item sets on output.
@param node the path from root to this node matches the given item set.
@param itemset the frequent item set generated so far.
@param size the length/size of the current array level in the T-tree.
@return the number of discovered frequent item sets | [
"Returns",
"the",
"set",
"of",
"frequent",
"item",
"sets",
"."
] | train | https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/core/src/main/java/smile/association/TotalSupportTree.java#L216-L238 |
google/j2objc | jre_emul/android/platform/libcore/ojluni/src/main/java/sun/security/jca/ProviderList.java | ProviderList.getServices | @Deprecated
public List<Service> getServices(String type, List<String> algorithms) {
List<ServiceId> ids = new ArrayList<>();
for (String alg : algorithms) {
ids.add(new ServiceId(type, alg));
}
return getServices(ids);
} | java | @Deprecated
public List<Service> getServices(String type, List<String> algorithms) {
List<ServiceId> ids = new ArrayList<>();
for (String alg : algorithms) {
ids.add(new ServiceId(type, alg));
}
return getServices(ids);
} | [
"@",
"Deprecated",
"public",
"List",
"<",
"Service",
">",
"getServices",
"(",
"String",
"type",
",",
"List",
"<",
"String",
">",
"algorithms",
")",
"{",
"List",
"<",
"ServiceId",
">",
"ids",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"for",
"(",
"... | This method exists for compatibility with JCE only. It will be removed
once JCE has been changed to use the replacement method.
@deprecated use getServices(List<ServiceId>) instead | [
"This",
"method",
"exists",
"for",
"compatibility",
"with",
"JCE",
"only",
".",
"It",
"will",
"be",
"removed",
"once",
"JCE",
"has",
"been",
"changed",
"to",
"use",
"the",
"replacement",
"method",
"."
] | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/sun/security/jca/ProviderList.java#L364-L371 |
Azure/azure-sdk-for-java | sql/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sql/v2017_03_01_preview/implementation/JobTargetExecutionsInner.java | JobTargetExecutionsInner.listByStepWithServiceResponseAsync | public Observable<ServiceResponse<Page<JobExecutionInner>>> listByStepWithServiceResponseAsync(final String resourceGroupName, final String serverName, final String jobAgentName, final String jobName, final UUID jobExecutionId, final String stepName) {
return listByStepSinglePageAsync(resourceGroupName, serverName, jobAgentName, jobName, jobExecutionId, stepName)
.concatMap(new Func1<ServiceResponse<Page<JobExecutionInner>>, Observable<ServiceResponse<Page<JobExecutionInner>>>>() {
@Override
public Observable<ServiceResponse<Page<JobExecutionInner>>> call(ServiceResponse<Page<JobExecutionInner>> page) {
String nextPageLink = page.body().nextPageLink();
if (nextPageLink == null) {
return Observable.just(page);
}
return Observable.just(page).concatWith(listByStepNextWithServiceResponseAsync(nextPageLink));
}
});
} | java | public Observable<ServiceResponse<Page<JobExecutionInner>>> listByStepWithServiceResponseAsync(final String resourceGroupName, final String serverName, final String jobAgentName, final String jobName, final UUID jobExecutionId, final String stepName) {
return listByStepSinglePageAsync(resourceGroupName, serverName, jobAgentName, jobName, jobExecutionId, stepName)
.concatMap(new Func1<ServiceResponse<Page<JobExecutionInner>>, Observable<ServiceResponse<Page<JobExecutionInner>>>>() {
@Override
public Observable<ServiceResponse<Page<JobExecutionInner>>> call(ServiceResponse<Page<JobExecutionInner>> page) {
String nextPageLink = page.body().nextPageLink();
if (nextPageLink == null) {
return Observable.just(page);
}
return Observable.just(page).concatWith(listByStepNextWithServiceResponseAsync(nextPageLink));
}
});
} | [
"public",
"Observable",
"<",
"ServiceResponse",
"<",
"Page",
"<",
"JobExecutionInner",
">",
">",
">",
"listByStepWithServiceResponseAsync",
"(",
"final",
"String",
"resourceGroupName",
",",
"final",
"String",
"serverName",
",",
"final",
"String",
"jobAgentName",
",",
... | Lists the target executions of a job step execution.
@param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal.
@param serverName The name of the server.
@param jobAgentName The name of the job agent.
@param jobName The name of the job to get.
@param jobExecutionId The id of the job execution
@param stepName The name of the step.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the PagedList<JobExecutionInner> object | [
"Lists",
"the",
"target",
"executions",
"of",
"a",
"job",
"step",
"execution",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/sql/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sql/v2017_03_01_preview/implementation/JobTargetExecutionsInner.java#L496-L508 |
square/jna-gmp | jnagmp/src/main/java/com/squareup/jnagmp/Gmp.java | Gmp.modPowSecure | public static BigInteger modPowSecure(BigInteger base, BigInteger exponent, BigInteger modulus) {
if (modulus.signum() <= 0) {
throw new ArithmeticException("modulus must be positive");
}
if (!modulus.testBit(0)) {
throw new IllegalArgumentException("modulus must be odd");
}
return INSTANCE.get().modPowSecureImpl(base, exponent, modulus);
} | java | public static BigInteger modPowSecure(BigInteger base, BigInteger exponent, BigInteger modulus) {
if (modulus.signum() <= 0) {
throw new ArithmeticException("modulus must be positive");
}
if (!modulus.testBit(0)) {
throw new IllegalArgumentException("modulus must be odd");
}
return INSTANCE.get().modPowSecureImpl(base, exponent, modulus);
} | [
"public",
"static",
"BigInteger",
"modPowSecure",
"(",
"BigInteger",
"base",
",",
"BigInteger",
"exponent",
",",
"BigInteger",
"modulus",
")",
"{",
"if",
"(",
"modulus",
".",
"signum",
"(",
")",
"<=",
"0",
")",
"{",
"throw",
"new",
"ArithmeticException",
"("... | Calculate (base ^ exponent) % modulus; slower, hardened against timing attacks.
<p> NOTE: this methods REQUIRES modulus to be odd, due to a crash-bug in libgmp. This is not a
problem for RSA where the modulus is always odd.</p>
@param base the base, must be positive
@param exponent the exponent
@param modulus the modulus
@return the (base ^ exponent) % modulus
@throws ArithmeticException if modulus is non-positive, or the exponent is negative and the
base cannot be inverted
@throws IllegalArgumentException if modulus is even | [
"Calculate",
"(",
"base",
"^",
"exponent",
")",
"%",
"modulus",
";",
"slower",
"hardened",
"against",
"timing",
"attacks",
"."
] | train | https://github.com/square/jna-gmp/blob/192d26d97d6773bc3c68ccfa97450f4257d54838/jnagmp/src/main/java/com/squareup/jnagmp/Gmp.java#L132-L140 |
diegocarloslima/ByakuGallery | ByakuGallery/src/com/diegocarloslima/byakugallery/lib/TouchImageView.java | TouchImageView.computeFocus | private static float computeFocus(float viewSize, float drawableSize, float currentTranslation, float focusCoordinate) {
if(currentTranslation > 0 && focusCoordinate < currentTranslation) {
return currentTranslation;
} else if(currentTranslation < viewSize - drawableSize && focusCoordinate > currentTranslation + drawableSize) {
return drawableSize + currentTranslation;
}
return focusCoordinate;
} | java | private static float computeFocus(float viewSize, float drawableSize, float currentTranslation, float focusCoordinate) {
if(currentTranslation > 0 && focusCoordinate < currentTranslation) {
return currentTranslation;
} else if(currentTranslation < viewSize - drawableSize && focusCoordinate > currentTranslation + drawableSize) {
return drawableSize + currentTranslation;
}
return focusCoordinate;
} | [
"private",
"static",
"float",
"computeFocus",
"(",
"float",
"viewSize",
",",
"float",
"drawableSize",
",",
"float",
"currentTranslation",
",",
"float",
"focusCoordinate",
")",
"{",
"if",
"(",
"currentTranslation",
">",
"0",
"&&",
"focusCoordinate",
"<",
"currentTr... | If our focal point is outside the image, we will project it to our image bounds | [
"If",
"our",
"focal",
"point",
"is",
"outside",
"the",
"image",
"we",
"will",
"project",
"it",
"to",
"our",
"image",
"bounds"
] | train | https://github.com/diegocarloslima/ByakuGallery/blob/a0472e8c9f79184b6b83351da06a5544e4dc1be4/ByakuGallery/src/com/diegocarloslima/byakugallery/lib/TouchImageView.java#L386-L394 |
google/error-prone | core/src/main/java/com/google/errorprone/bugpatterns/UnnecessaryBoxedVariable.java | UnnecessaryBoxedVariable.localVariableMatches | private static boolean localVariableMatches(VariableTree tree, VisitorState state) {
ExpressionTree expression = tree.getInitializer();
if (expression == null) {
Tree leaf = state.getPath().getParentPath().getLeaf();
if (!(leaf instanceof EnhancedForLoopTree)) {
return true;
}
EnhancedForLoopTree node = (EnhancedForLoopTree) leaf;
Type expressionType = ASTHelpers.getType(node.getExpression());
if (expressionType == null) {
return false;
}
Type elemtype = state.getTypes().elemtype(expressionType);
// Be conservative - if elemtype is null, treat it as if it is a loop over a wrapped type.
return elemtype != null && elemtype.isPrimitive();
}
Type initializerType = ASTHelpers.getType(expression);
if (initializerType == null) {
return false;
}
if (initializerType.isPrimitive()) {
return true;
}
// Don't count X.valueOf(...) as a boxed usage, since it can be replaced with X.parseX.
return VALUE_OF_MATCHER.matches(expression, state);
} | java | private static boolean localVariableMatches(VariableTree tree, VisitorState state) {
ExpressionTree expression = tree.getInitializer();
if (expression == null) {
Tree leaf = state.getPath().getParentPath().getLeaf();
if (!(leaf instanceof EnhancedForLoopTree)) {
return true;
}
EnhancedForLoopTree node = (EnhancedForLoopTree) leaf;
Type expressionType = ASTHelpers.getType(node.getExpression());
if (expressionType == null) {
return false;
}
Type elemtype = state.getTypes().elemtype(expressionType);
// Be conservative - if elemtype is null, treat it as if it is a loop over a wrapped type.
return elemtype != null && elemtype.isPrimitive();
}
Type initializerType = ASTHelpers.getType(expression);
if (initializerType == null) {
return false;
}
if (initializerType.isPrimitive()) {
return true;
}
// Don't count X.valueOf(...) as a boxed usage, since it can be replaced with X.parseX.
return VALUE_OF_MATCHER.matches(expression, state);
} | [
"private",
"static",
"boolean",
"localVariableMatches",
"(",
"VariableTree",
"tree",
",",
"VisitorState",
"state",
")",
"{",
"ExpressionTree",
"expression",
"=",
"tree",
".",
"getInitializer",
"(",
")",
";",
"if",
"(",
"expression",
"==",
"null",
")",
"{",
"Tr... | Check to see if the local variable should be considered for replacement, i.e.
<ul>
<li>A variable without an initializer
<li>Enhanced for loop variables can be replaced if they are loops over primitive arrays
<li>A variable initialized with a primitive value (which is then auto-boxed)
<li>A variable initialized with an invocation of {@code Boxed.valueOf}, since that can be
replaced with {@code Boxed.parseBoxed}.
</ul> | [
"Check",
"to",
"see",
"if",
"the",
"local",
"variable",
"should",
"be",
"considered",
"for",
"replacement",
"i",
".",
"e",
"."
] | train | https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/core/src/main/java/com/google/errorprone/bugpatterns/UnnecessaryBoxedVariable.java#L177-L202 |
geomajas/geomajas-project-client-gwt | client/src/main/java/org/geomajas/gwt/client/widget/MapWidget.java | MapWidget.setNavigationAddonEnabled | public void setNavigationAddonEnabled(boolean enabled) {
navigationAddonEnabled = enabled;
final String panId = "panBTNCollection";
final String zoomId = "zoomAddon";
final String zoomRectId = "zoomRectAddon";
if (enabled) {
if (!getMapAddons().containsKey(panId)) {
PanButtonCollection panButtons = new PanButtonCollection(panId, this);
panButtons.setHorizontalMargin(5);
panButtons.setVerticalMargin(5);
registerMapAddon(panButtons);
}
if (!getMapAddons().containsKey(zoomId)) {
ZoomAddon zoomAddon = new ZoomAddon(zoomId, this);
zoomAddon.setHorizontalMargin(20);
zoomAddon.setVerticalMargin(65);
registerMapAddon(zoomAddon);
}
if (!getMapAddons().containsKey(zoomRectId)) {
ZoomToRectangleAddon zoomToRectangleAddon = new ZoomToRectangleAddon(zoomRectId, this);
zoomToRectangleAddon.setHorizontalMargin(20);
zoomToRectangleAddon.setVerticalMargin(135);
registerMapAddon(zoomToRectangleAddon);
}
} else {
unregisterMapAddon(addons.get(panId));
unregisterMapAddon(addons.get(zoomId));
unregisterMapAddon(addons.get(zoomRectId));
}
} | java | public void setNavigationAddonEnabled(boolean enabled) {
navigationAddonEnabled = enabled;
final String panId = "panBTNCollection";
final String zoomId = "zoomAddon";
final String zoomRectId = "zoomRectAddon";
if (enabled) {
if (!getMapAddons().containsKey(panId)) {
PanButtonCollection panButtons = new PanButtonCollection(panId, this);
panButtons.setHorizontalMargin(5);
panButtons.setVerticalMargin(5);
registerMapAddon(panButtons);
}
if (!getMapAddons().containsKey(zoomId)) {
ZoomAddon zoomAddon = new ZoomAddon(zoomId, this);
zoomAddon.setHorizontalMargin(20);
zoomAddon.setVerticalMargin(65);
registerMapAddon(zoomAddon);
}
if (!getMapAddons().containsKey(zoomRectId)) {
ZoomToRectangleAddon zoomToRectangleAddon = new ZoomToRectangleAddon(zoomRectId, this);
zoomToRectangleAddon.setHorizontalMargin(20);
zoomToRectangleAddon.setVerticalMargin(135);
registerMapAddon(zoomToRectangleAddon);
}
} else {
unregisterMapAddon(addons.get(panId));
unregisterMapAddon(addons.get(zoomId));
unregisterMapAddon(addons.get(zoomRectId));
}
} | [
"public",
"void",
"setNavigationAddonEnabled",
"(",
"boolean",
"enabled",
")",
"{",
"navigationAddonEnabled",
"=",
"enabled",
";",
"final",
"String",
"panId",
"=",
"\"panBTNCollection\"",
";",
"final",
"String",
"zoomId",
"=",
"\"zoomAddon\"",
";",
"final",
"String"... | Enables or disables the panning buttons. This setting has immediate effect on the map.
@param enabled
enabled status | [
"Enables",
"or",
"disables",
"the",
"panning",
"buttons",
".",
"This",
"setting",
"has",
"immediate",
"effect",
"on",
"the",
"map",
"."
] | train | https://github.com/geomajas/geomajas-project-client-gwt/blob/1c1adc48deb192ed825265eebcc74d70bbf45670/client/src/main/java/org/geomajas/gwt/client/widget/MapWidget.java#L761-L793 |
johnkil/Android-AppMsg | library/src/com/devspark/appmsg/AppMsg.java | AppMsg.getLayoutParams | public LayoutParams getLayoutParams() {
if (mLayoutParams == null) {
mLayoutParams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
}
return mLayoutParams;
} | java | public LayoutParams getLayoutParams() {
if (mLayoutParams == null) {
mLayoutParams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
}
return mLayoutParams;
} | [
"public",
"LayoutParams",
"getLayoutParams",
"(",
")",
"{",
"if",
"(",
"mLayoutParams",
"==",
"null",
")",
"{",
"mLayoutParams",
"=",
"new",
"LayoutParams",
"(",
"LayoutParams",
".",
"MATCH_PARENT",
",",
"LayoutParams",
".",
"WRAP_CONTENT",
")",
";",
"}",
"ret... | Gets the crouton's layout parameters, constructing a default if necessary.
@return the layout parameters | [
"Gets",
"the",
"crouton",
"s",
"layout",
"parameters",
"constructing",
"a",
"default",
"if",
"necessary",
"."
] | train | https://github.com/johnkil/Android-AppMsg/blob/e7fdd7870530a24e6d825278ee0863be0521e8b8/library/src/com/devspark/appmsg/AppMsg.java#L549-L554 |
exoplatform/jcr | exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/quota/ChangesListener.java | ChangesListener.addPathsWithUnknownChangedSize | private void addPathsWithUnknownChangedSize(ChangesItem changesItem, ItemState state)
{
if (!state.isPersisted() && (state.isDeleted() || state.isRenamed()))
{
String itemPath = getPath(state.getData().getQPath());
for (String trackedPath : quotaPersister.getAllTrackedNodes(rName, wsName))
{
if (itemPath.startsWith(trackedPath))
{
changesItem.addPathWithUnknownChangedSize(itemPath);
}
}
}
} | java | private void addPathsWithUnknownChangedSize(ChangesItem changesItem, ItemState state)
{
if (!state.isPersisted() && (state.isDeleted() || state.isRenamed()))
{
String itemPath = getPath(state.getData().getQPath());
for (String trackedPath : quotaPersister.getAllTrackedNodes(rName, wsName))
{
if (itemPath.startsWith(trackedPath))
{
changesItem.addPathWithUnknownChangedSize(itemPath);
}
}
}
} | [
"private",
"void",
"addPathsWithUnknownChangedSize",
"(",
"ChangesItem",
"changesItem",
",",
"ItemState",
"state",
")",
"{",
"if",
"(",
"!",
"state",
".",
"isPersisted",
"(",
")",
"&&",
"(",
"state",
".",
"isDeleted",
"(",
")",
"||",
"state",
".",
"isRenamed... | Checks if changes were made but changed size is unknown. If so, determinate
for which nodes data size should be recalculated at all and put those paths into
respective collection. | [
"Checks",
"if",
"changes",
"were",
"made",
"but",
"changed",
"size",
"is",
"unknown",
".",
"If",
"so",
"determinate",
"for",
"which",
"nodes",
"data",
"size",
"should",
"be",
"recalculated",
"at",
"all",
"and",
"put",
"those",
"paths",
"into",
"respective",
... | train | https://github.com/exoplatform/jcr/blob/3e7f9ee1b5683640d73a4316fb4b0ad5eac5b8a2/exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/quota/ChangesListener.java#L188-L202 |
apache/fluo-recipes | modules/spark/src/main/java/org/apache/fluo/recipes/spark/FluoSparkHelper.java | FluoSparkHelper.bulkImportRcvToFluo | public void bulkImportRcvToFluo(JavaPairRDD<RowColumn, Bytes> data, BulkImportOptions opts) {
data = partitionForAccumulo(data, fluoConfig.getAccumuloTable(), opts);
JavaPairRDD<Key, Value> kvData = data.flatMapToPair(tuple -> {
List<Tuple2<Key, Value>> output = new LinkedList<>();
RowColumn rc = tuple._1();
FluoKeyValueGenerator fkvg = new FluoKeyValueGenerator();
fkvg.setRow(rc.getRow()).setColumn(rc.getColumn()).setValue(tuple._2().toArray());
for (FluoKeyValue kv : fkvg.getKeyValues()) {
output.add(new Tuple2<>(kv.getKey(), kv.getValue()));
}
return output;
});
bulkImportKvToAccumulo(kvData, fluoConfig.getAccumuloTable(), opts);
} | java | public void bulkImportRcvToFluo(JavaPairRDD<RowColumn, Bytes> data, BulkImportOptions opts) {
data = partitionForAccumulo(data, fluoConfig.getAccumuloTable(), opts);
JavaPairRDD<Key, Value> kvData = data.flatMapToPair(tuple -> {
List<Tuple2<Key, Value>> output = new LinkedList<>();
RowColumn rc = tuple._1();
FluoKeyValueGenerator fkvg = new FluoKeyValueGenerator();
fkvg.setRow(rc.getRow()).setColumn(rc.getColumn()).setValue(tuple._2().toArray());
for (FluoKeyValue kv : fkvg.getKeyValues()) {
output.add(new Tuple2<>(kv.getKey(), kv.getValue()));
}
return output;
});
bulkImportKvToAccumulo(kvData, fluoConfig.getAccumuloTable(), opts);
} | [
"public",
"void",
"bulkImportRcvToFluo",
"(",
"JavaPairRDD",
"<",
"RowColumn",
",",
"Bytes",
">",
"data",
",",
"BulkImportOptions",
"opts",
")",
"{",
"data",
"=",
"partitionForAccumulo",
"(",
"data",
",",
"fluoConfig",
".",
"getAccumuloTable",
"(",
")",
",",
"... | Bulk import RowColumn/Value data into Fluo table (obtained from Fluo configuration). This
method will repartition RDD using the current split points of the Fluo table, creating one
partition per tablet in the table. This is done so that one RFile is created per tablet for
bulk import.
@param data RowColumn/Value data to import
@param opts Bulk import options | [
"Bulk",
"import",
"RowColumn",
"/",
"Value",
"data",
"into",
"Fluo",
"table",
"(",
"obtained",
"from",
"Fluo",
"configuration",
")",
".",
"This",
"method",
"will",
"repartition",
"RDD",
"using",
"the",
"current",
"split",
"points",
"of",
"the",
"Fluo",
"tabl... | train | https://github.com/apache/fluo-recipes/blob/24c11234c9654b16d999437ff49ddc3db86665f8/modules/spark/src/main/java/org/apache/fluo/recipes/spark/FluoSparkHelper.java#L149-L165 |
astrapi69/jaulp-wicket | jaulp-wicket-base/src/main/java/de/alpharogroup/wicket/base/util/application/ApplicationExtensions.java | ApplicationExtensions.setRootRequestMapper | public static IRequestMapper setRootRequestMapper(final Application application,
final int httpPort, final int httpsPort)
{
final IRequestMapper httpsMapper = new HttpsMapper(application.getRootRequestMapper(),
new HttpsConfig(httpPort, httpsPort));
application.setRootRequestMapper(httpsMapper);
return httpsMapper;
} | java | public static IRequestMapper setRootRequestMapper(final Application application,
final int httpPort, final int httpsPort)
{
final IRequestMapper httpsMapper = new HttpsMapper(application.getRootRequestMapper(),
new HttpsConfig(httpPort, httpsPort));
application.setRootRequestMapper(httpsMapper);
return httpsMapper;
} | [
"public",
"static",
"IRequestMapper",
"setRootRequestMapper",
"(",
"final",
"Application",
"application",
",",
"final",
"int",
"httpPort",
",",
"final",
"int",
"httpsPort",
")",
"{",
"final",
"IRequestMapper",
"httpsMapper",
"=",
"new",
"HttpsMapper",
"(",
"applicat... | Sets the root request mapper for the given application from the given httpPort and httpsPort.
@param application
the application
@param httpPort
the http port
@param httpsPort
the https port
@return the i request mapper | [
"Sets",
"the",
"root",
"request",
"mapper",
"for",
"the",
"given",
"application",
"from",
"the",
"given",
"httpPort",
"and",
"httpsPort",
"."
] | train | https://github.com/astrapi69/jaulp-wicket/blob/85d74368d00abd9bb97659b5794e38c0f8a013d4/jaulp-wicket-base/src/main/java/de/alpharogroup/wicket/base/util/application/ApplicationExtensions.java#L519-L526 |
rterp/GMapsFX | GMapsFX/src/main/java/com/lynden/gmapsfx/service/elevation/ElevationService.java | ElevationService.getElevationForLocations | public void getElevationForLocations(LocationElevationRequest req, ElevationServiceCallback callback) {
this.callback = callback;
JSObject doc = (JSObject) getJSObject().eval("document");
doc.setMember(getVariableName(), this);
StringBuilder r = new StringBuilder(getVariableName())
.append(".")
.append("getElevationForLocations(")
.append(req.getVariableName())
.append(", ")
.append("function(results, status) {alert('rec:'+status);\ndocument.")
.append(getVariableName())
.append(".processResponse(results, status);});");
LOG.trace("ElevationService direct call: " + r.toString());
getJSObject().eval(r.toString());
} | java | public void getElevationForLocations(LocationElevationRequest req, ElevationServiceCallback callback) {
this.callback = callback;
JSObject doc = (JSObject) getJSObject().eval("document");
doc.setMember(getVariableName(), this);
StringBuilder r = new StringBuilder(getVariableName())
.append(".")
.append("getElevationForLocations(")
.append(req.getVariableName())
.append(", ")
.append("function(results, status) {alert('rec:'+status);\ndocument.")
.append(getVariableName())
.append(".processResponse(results, status);});");
LOG.trace("ElevationService direct call: " + r.toString());
getJSObject().eval(r.toString());
} | [
"public",
"void",
"getElevationForLocations",
"(",
"LocationElevationRequest",
"req",
",",
"ElevationServiceCallback",
"callback",
")",
"{",
"this",
".",
"callback",
"=",
"callback",
";",
"JSObject",
"doc",
"=",
"(",
"JSObject",
")",
"getJSObject",
"(",
")",
".",
... | Create a request for elevations for multiple locations.
@param req
@param callback | [
"Create",
"a",
"request",
"for",
"elevations",
"for",
"multiple",
"locations",
"."
] | train | https://github.com/rterp/GMapsFX/blob/4623d3f768e8ad78fc50ee32dd204d236e01059f/GMapsFX/src/main/java/com/lynden/gmapsfx/service/elevation/ElevationService.java#L36-L56 |
facebookarchive/hadoop-20 | src/contrib/corona/src/java/org/apache/hadoop/mapred/CoronaJobInProgress.java | CoronaJobInProgress.getCounters | @SuppressWarnings("deprecation")
public Counters getCounters() {
synchronized (lockObject) {
Counters result = new Counters();
result.incrAllCounters(getJobCounters());
incrementTaskCountersUnprotected(result, maps);
return incrementTaskCountersUnprotected(result, reduces);
}
} | java | @SuppressWarnings("deprecation")
public Counters getCounters() {
synchronized (lockObject) {
Counters result = new Counters();
result.incrAllCounters(getJobCounters());
incrementTaskCountersUnprotected(result, maps);
return incrementTaskCountersUnprotected(result, reduces);
}
} | [
"@",
"SuppressWarnings",
"(",
"\"deprecation\"",
")",
"public",
"Counters",
"getCounters",
"(",
")",
"{",
"synchronized",
"(",
"lockObject",
")",
"{",
"Counters",
"result",
"=",
"new",
"Counters",
"(",
")",
";",
"result",
".",
"incrAllCounters",
"(",
"getJobCo... | Returns the total job counters, by adding together the job,
the map and the reduce counters. | [
"Returns",
"the",
"total",
"job",
"counters",
"by",
"adding",
"together",
"the",
"job",
"the",
"map",
"and",
"the",
"reduce",
"counters",
"."
] | train | https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/contrib/corona/src/java/org/apache/hadoop/mapred/CoronaJobInProgress.java#L2413-L2422 |
albfernandez/itext2 | src/main/java/com/lowagie/text/pdf/PdfCopyForms.java | PdfCopyForms.addDocument | public void addDocument(PdfReader reader, String ranges) throws DocumentException, IOException {
fc.addDocument(reader, SequenceList.expand(ranges, reader.getNumberOfPages()));
} | java | public void addDocument(PdfReader reader, String ranges) throws DocumentException, IOException {
fc.addDocument(reader, SequenceList.expand(ranges, reader.getNumberOfPages()));
} | [
"public",
"void",
"addDocument",
"(",
"PdfReader",
"reader",
",",
"String",
"ranges",
")",
"throws",
"DocumentException",
",",
"IOException",
"{",
"fc",
".",
"addDocument",
"(",
"reader",
",",
"SequenceList",
".",
"expand",
"(",
"ranges",
",",
"reader",
".",
... | Concatenates a PDF document selecting the pages to keep. The pages are described as
ranges. The page ordering can be changed but
no page repetitions are allowed.
@param reader the PDF document
@param ranges the comma separated ranges as described in {@link SequenceList}
@throws DocumentException on error | [
"Concatenates",
"a",
"PDF",
"document",
"selecting",
"the",
"pages",
"to",
"keep",
".",
"The",
"pages",
"are",
"described",
"as",
"ranges",
".",
"The",
"page",
"ordering",
"can",
"be",
"changed",
"but",
"no",
"page",
"repetitions",
"are",
"allowed",
"."
] | train | https://github.com/albfernandez/itext2/blob/438fc1899367fd13dfdfa8dfdca9a3c1a7783b84/src/main/java/com/lowagie/text/pdf/PdfCopyForms.java#L112-L114 |
google/closure-templates | java/src/com/google/template/soy/SoyFileSet.java | SoyFileSet.compileToTofu | public SoyTofu compileToTofu(Map<String, Supplier<Object>> pluginInstances) {
resetErrorReporter();
ServerCompilationPrimitives primitives = compileForServerRendering();
throwIfErrorsPresent();
SoyTofu tofu = doCompileToTofu(primitives, pluginInstances);
reportWarnings();
return tofu;
} | java | public SoyTofu compileToTofu(Map<String, Supplier<Object>> pluginInstances) {
resetErrorReporter();
ServerCompilationPrimitives primitives = compileForServerRendering();
throwIfErrorsPresent();
SoyTofu tofu = doCompileToTofu(primitives, pluginInstances);
reportWarnings();
return tofu;
} | [
"public",
"SoyTofu",
"compileToTofu",
"(",
"Map",
"<",
"String",
",",
"Supplier",
"<",
"Object",
">",
">",
"pluginInstances",
")",
"{",
"resetErrorReporter",
"(",
")",
";",
"ServerCompilationPrimitives",
"primitives",
"=",
"compileForServerRendering",
"(",
")",
";... | Compiles this Soy file set into a Java object (type {@code SoyTofu}) capable of rendering the
compiled templates.
@return The resulting {@code SoyTofu} object.
@throws SoyCompilationException If compilation fails. | [
"Compiles",
"this",
"Soy",
"file",
"set",
"into",
"a",
"Java",
"object",
"(",
"type",
"{",
"@code",
"SoyTofu",
"}",
")",
"capable",
"of",
"rendering",
"the",
"compiled",
"templates",
"."
] | train | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/SoyFileSet.java#L741-L749 |
apptentive/apptentive-android | apptentive/src/main/java/com/apptentive/android/sdk/util/Util.java | Util.getCompatDrawable | public static Drawable getCompatDrawable(Context c, int drawableRes) {
Drawable d = null;
try {
d = ContextCompat.getDrawable(c, drawableRes);
} catch (Exception ex) {
logException(ex);
}
return d;
} | java | public static Drawable getCompatDrawable(Context c, int drawableRes) {
Drawable d = null;
try {
d = ContextCompat.getDrawable(c, drawableRes);
} catch (Exception ex) {
logException(ex);
}
return d;
} | [
"public",
"static",
"Drawable",
"getCompatDrawable",
"(",
"Context",
"c",
",",
"int",
"drawableRes",
")",
"{",
"Drawable",
"d",
"=",
"null",
";",
"try",
"{",
"d",
"=",
"ContextCompat",
".",
"getDrawable",
"(",
"c",
",",
"drawableRes",
")",
";",
"}",
"cat... | helper method to get the drawable by its resource id, specific to the correct android version
@param c
@param drawableRes
@return | [
"helper",
"method",
"to",
"get",
"the",
"drawable",
"by",
"its",
"resource",
"id",
"specific",
"to",
"the",
"correct",
"android",
"version"
] | train | https://github.com/apptentive/apptentive-android/blob/887c08d7bd5ae6488a90366dfb58f58938861a93/apptentive/src/main/java/com/apptentive/android/sdk/util/Util.java#L386-L394 |
BrunoEberhard/minimal-j | src/main/java/org/minimalj/util/IdUtils.java | IdUtils.setId | public static void setId(Object object, Object id) {
try {
Field idField = getIdField(object.getClass());
if (idField != null) {
idField.set(object, id);
}
} catch (IllegalAccessException | IllegalArgumentException e) {
throw new LoggingRuntimeException(e, logger, "setting Id failed");
}
} | java | public static void setId(Object object, Object id) {
try {
Field idField = getIdField(object.getClass());
if (idField != null) {
idField.set(object, id);
}
} catch (IllegalAccessException | IllegalArgumentException e) {
throw new LoggingRuntimeException(e, logger, "setting Id failed");
}
} | [
"public",
"static",
"void",
"setId",
"(",
"Object",
"object",
",",
"Object",
"id",
")",
"{",
"try",
"{",
"Field",
"idField",
"=",
"getIdField",
"(",
"object",
".",
"getClass",
"(",
")",
")",
";",
"if",
"(",
"idField",
"!=",
"null",
")",
"{",
"idField... | Set the value of the <code>id</code> in the given object
@param object object containing a public <code>id</code> field. Must not be <code>null</code>
@param id the new value. Can be <code>null</code>. | [
"Set",
"the",
"value",
"of",
"the",
"<code",
">",
"id<",
"/",
"code",
">",
"in",
"the",
"given",
"object"
] | train | https://github.com/BrunoEberhard/minimal-j/blob/f7c5461b2b47a10b383aee1e2f1f150f6773703b/src/main/java/org/minimalj/util/IdUtils.java#L105-L114 |
apache/groovy | subprojects/groovy-swing/src/main/java/org/codehaus/groovy/runtime/SwingGroovyMethods.java | SwingGroovyMethods.leftShift | public static ButtonGroup leftShift(ButtonGroup self, AbstractButton b) {
self.add(b);
return self;
} | java | public static ButtonGroup leftShift(ButtonGroup self, AbstractButton b) {
self.add(b);
return self;
} | [
"public",
"static",
"ButtonGroup",
"leftShift",
"(",
"ButtonGroup",
"self",
",",
"AbstractButton",
"b",
")",
"{",
"self",
".",
"add",
"(",
"b",
")",
";",
"return",
"self",
";",
"}"
] | Overloads the left shift operator to provide an easy way to add
buttons to a ButtonGroup.
@param self a ButtonGroup
@param b an AbstractButton to be added to the buttonGroup.
@return same buttonGroup, after the value was added to it.
@since 1.6.4 | [
"Overloads",
"the",
"left",
"shift",
"operator",
"to",
"provide",
"an",
"easy",
"way",
"to",
"add",
"buttons",
"to",
"a",
"ButtonGroup",
"."
] | train | https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/subprojects/groovy-swing/src/main/java/org/codehaus/groovy/runtime/SwingGroovyMethods.java#L141-L144 |
appium/java-client | src/main/java/io/appium/java_client/imagecomparison/ComparisonResult.java | ComparisonResult.mapToRect | public static Rectangle mapToRect(Map<String, Object> map) {
return new Rectangle(toSeleniumCoordinate(map.get("x")),
toSeleniumCoordinate(map.get("y")),
toSeleniumCoordinate(map.get("height")),
toSeleniumCoordinate(map.get("width")));
} | java | public static Rectangle mapToRect(Map<String, Object> map) {
return new Rectangle(toSeleniumCoordinate(map.get("x")),
toSeleniumCoordinate(map.get("y")),
toSeleniumCoordinate(map.get("height")),
toSeleniumCoordinate(map.get("width")));
} | [
"public",
"static",
"Rectangle",
"mapToRect",
"(",
"Map",
"<",
"String",
",",
"Object",
">",
"map",
")",
"{",
"return",
"new",
"Rectangle",
"(",
"toSeleniumCoordinate",
"(",
"map",
".",
"get",
"(",
"\"x\"",
")",
")",
",",
"toSeleniumCoordinate",
"(",
"map"... | Transforms a map into {@link Rectangle} object.
@param map the source map.
@return {@link Rectangle} object | [
"Transforms",
"a",
"map",
"into",
"{",
"@link",
"Rectangle",
"}",
"object",
"."
] | train | https://github.com/appium/java-client/blob/5a17759b05d6fda8ef425b3ab6e766c73ed2e8df/src/main/java/io/appium/java_client/imagecomparison/ComparisonResult.java#L102-L107 |
google/j2objc | jre_emul/android/platform/libcore/ojluni/src/main/java/sun/security/provider/certpath/DistributionPointFetcher.java | DistributionPointFetcher.getFullNames | private static GeneralNames getFullNames(X500Name issuer, RDN rdn)
throws IOException
{
List<RDN> rdns = new ArrayList<>(issuer.rdns());
rdns.add(rdn);
X500Name fullName = new X500Name(rdns.toArray(new RDN[0]));
GeneralNames fullNames = new GeneralNames();
fullNames.add(new GeneralName(fullName));
return fullNames;
} | java | private static GeneralNames getFullNames(X500Name issuer, RDN rdn)
throws IOException
{
List<RDN> rdns = new ArrayList<>(issuer.rdns());
rdns.add(rdn);
X500Name fullName = new X500Name(rdns.toArray(new RDN[0]));
GeneralNames fullNames = new GeneralNames();
fullNames.add(new GeneralName(fullName));
return fullNames;
} | [
"private",
"static",
"GeneralNames",
"getFullNames",
"(",
"X500Name",
"issuer",
",",
"RDN",
"rdn",
")",
"throws",
"IOException",
"{",
"List",
"<",
"RDN",
">",
"rdns",
"=",
"new",
"ArrayList",
"<>",
"(",
"issuer",
".",
"rdns",
"(",
")",
")",
";",
"rdns",
... | Append relative name to the issuer name and return a new
GeneralNames object. | [
"Append",
"relative",
"name",
"to",
"the",
"issuer",
"name",
"and",
"return",
"a",
"new",
"GeneralNames",
"object",
"."
] | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/sun/security/provider/certpath/DistributionPointFetcher.java#L708-L717 |
zxing/zxing | core/src/main/java/com/google/zxing/datamatrix/encoder/HighLevelEncoder.java | HighLevelEncoder.determineConsecutiveDigitCount | public static int determineConsecutiveDigitCount(CharSequence msg, int startpos) {
int count = 0;
int len = msg.length();
int idx = startpos;
if (idx < len) {
char ch = msg.charAt(idx);
while (isDigit(ch) && idx < len) {
count++;
idx++;
if (idx < len) {
ch = msg.charAt(idx);
}
}
}
return count;
} | java | public static int determineConsecutiveDigitCount(CharSequence msg, int startpos) {
int count = 0;
int len = msg.length();
int idx = startpos;
if (idx < len) {
char ch = msg.charAt(idx);
while (isDigit(ch) && idx < len) {
count++;
idx++;
if (idx < len) {
ch = msg.charAt(idx);
}
}
}
return count;
} | [
"public",
"static",
"int",
"determineConsecutiveDigitCount",
"(",
"CharSequence",
"msg",
",",
"int",
"startpos",
")",
"{",
"int",
"count",
"=",
"0",
";",
"int",
"len",
"=",
"msg",
".",
"length",
"(",
")",
";",
"int",
"idx",
"=",
"startpos",
";",
"if",
... | Determines the number of consecutive characters that are encodable using numeric compaction.
@param msg the message
@param startpos the start position within the message
@return the requested character count | [
"Determines",
"the",
"number",
"of",
"consecutive",
"characters",
"that",
"are",
"encodable",
"using",
"numeric",
"compaction",
"."
] | train | https://github.com/zxing/zxing/blob/653ac2a3beb11481eff82e7d5f2bab8a745f7fac/core/src/main/java/com/google/zxing/datamatrix/encoder/HighLevelEncoder.java#L426-L441 |
avianey/facebook-api-android-maven | facebook/src/main/java/com/facebook/Request.java | Request.newUploadPhotoRequest | public static Request newUploadPhotoRequest(Session session, File file,
Callback callback) throws FileNotFoundException {
ParcelFileDescriptor descriptor = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY);
Bundle parameters = new Bundle(1);
parameters.putParcelable(PICTURE_PARAM, descriptor);
return new Request(session, MY_PHOTOS, parameters, HttpMethod.POST, callback);
} | java | public static Request newUploadPhotoRequest(Session session, File file,
Callback callback) throws FileNotFoundException {
ParcelFileDescriptor descriptor = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY);
Bundle parameters = new Bundle(1);
parameters.putParcelable(PICTURE_PARAM, descriptor);
return new Request(session, MY_PHOTOS, parameters, HttpMethod.POST, callback);
} | [
"public",
"static",
"Request",
"newUploadPhotoRequest",
"(",
"Session",
"session",
",",
"File",
"file",
",",
"Callback",
"callback",
")",
"throws",
"FileNotFoundException",
"{",
"ParcelFileDescriptor",
"descriptor",
"=",
"ParcelFileDescriptor",
".",
"open",
"(",
"file... | Creates a new Request configured to upload a photo to the user's default photo album. The photo
will be read from the specified stream.
@param session the Session to use, or null; if non-null, the session must be in an opened state
@param file the file containing the photo to upload
@param callback a callback that will be called when the request is completed to handle success or error conditions
@return a Request that is ready to execute | [
"Creates",
"a",
"new",
"Request",
"configured",
"to",
"upload",
"a",
"photo",
"to",
"the",
"user",
"s",
"default",
"photo",
"album",
".",
"The",
"photo",
"will",
"be",
"read",
"from",
"the",
"specified",
"stream",
"."
] | train | https://github.com/avianey/facebook-api-android-maven/blob/ae6c7aa7ae45739ee19f18c1983e05f7e35b9ede/facebook/src/main/java/com/facebook/Request.java#L335-L342 |
lessthanoptimal/BoofCV | main/boofcv-types/src/main/java/boofcv/struct/PackedSetsPoint2D_I32.java | PackedSetsPoint2D_I32.getSet | public void getSet(int which , FastQueue<Point2D_I32> list ) {
list.reset();
BlockIndexLength set = sets.get(which);
for (int i = 0; i < set.length; i++) {
int index = set.start + i*2;
int blockIndex = set.block + index/blockLength;
index %= blockLength;
int block[] = blocks.get( blockIndex );
list.grow().set( block[index] , block[index+1] );
}
} | java | public void getSet(int which , FastQueue<Point2D_I32> list ) {
list.reset();
BlockIndexLength set = sets.get(which);
for (int i = 0; i < set.length; i++) {
int index = set.start + i*2;
int blockIndex = set.block + index/blockLength;
index %= blockLength;
int block[] = blocks.get( blockIndex );
list.grow().set( block[index] , block[index+1] );
}
} | [
"public",
"void",
"getSet",
"(",
"int",
"which",
",",
"FastQueue",
"<",
"Point2D_I32",
">",
"list",
")",
"{",
"list",
".",
"reset",
"(",
")",
";",
"BlockIndexLength",
"set",
"=",
"sets",
".",
"get",
"(",
"which",
")",
";",
"for",
"(",
"int",
"i",
"... | Copies all the points in the set into the specified list
@param which (Input) which point set
@param list (Output) Storage for points | [
"Copies",
"all",
"the",
"points",
"in",
"the",
"set",
"into",
"the",
"specified",
"list"
] | train | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-types/src/main/java/boofcv/struct/PackedSetsPoint2D_I32.java#L160-L173 |
zxing/zxing | core/src/main/java/com/google/zxing/qrcode/encoder/MaskUtil.java | MaskUtil.getDataMaskBit | static boolean getDataMaskBit(int maskPattern, int x, int y) {
int intermediate;
int temp;
switch (maskPattern) {
case 0:
intermediate = (y + x) & 0x1;
break;
case 1:
intermediate = y & 0x1;
break;
case 2:
intermediate = x % 3;
break;
case 3:
intermediate = (y + x) % 3;
break;
case 4:
intermediate = ((y / 2) + (x / 3)) & 0x1;
break;
case 5:
temp = y * x;
intermediate = (temp & 0x1) + (temp % 3);
break;
case 6:
temp = y * x;
intermediate = ((temp & 0x1) + (temp % 3)) & 0x1;
break;
case 7:
temp = y * x;
intermediate = ((temp % 3) + ((y + x) & 0x1)) & 0x1;
break;
default:
throw new IllegalArgumentException("Invalid mask pattern: " + maskPattern);
}
return intermediate == 0;
} | java | static boolean getDataMaskBit(int maskPattern, int x, int y) {
int intermediate;
int temp;
switch (maskPattern) {
case 0:
intermediate = (y + x) & 0x1;
break;
case 1:
intermediate = y & 0x1;
break;
case 2:
intermediate = x % 3;
break;
case 3:
intermediate = (y + x) % 3;
break;
case 4:
intermediate = ((y / 2) + (x / 3)) & 0x1;
break;
case 5:
temp = y * x;
intermediate = (temp & 0x1) + (temp % 3);
break;
case 6:
temp = y * x;
intermediate = ((temp & 0x1) + (temp % 3)) & 0x1;
break;
case 7:
temp = y * x;
intermediate = ((temp % 3) + ((y + x) & 0x1)) & 0x1;
break;
default:
throw new IllegalArgumentException("Invalid mask pattern: " + maskPattern);
}
return intermediate == 0;
} | [
"static",
"boolean",
"getDataMaskBit",
"(",
"int",
"maskPattern",
",",
"int",
"x",
",",
"int",
"y",
")",
"{",
"int",
"intermediate",
";",
"int",
"temp",
";",
"switch",
"(",
"maskPattern",
")",
"{",
"case",
"0",
":",
"intermediate",
"=",
"(",
"y",
"+",
... | Return the mask bit for "getMaskPattern" at "x" and "y". See 8.8 of JISX0510:2004 for mask
pattern conditions. | [
"Return",
"the",
"mask",
"bit",
"for",
"getMaskPattern",
"at",
"x",
"and",
"y",
".",
"See",
"8",
".",
"8",
"of",
"JISX0510",
":",
"2004",
"for",
"mask",
"pattern",
"conditions",
"."
] | train | https://github.com/zxing/zxing/blob/653ac2a3beb11481eff82e7d5f2bab8a745f7fac/core/src/main/java/com/google/zxing/qrcode/encoder/MaskUtil.java#L154-L189 |
SpartaTech/sparta-spring-web-utils | src/main/java/org/sparta/springwebutils/property/PropertiesLoaderBuilder.java | PropertiesLoaderBuilder.loadPropertiesByPrefix | public PropertiesLoaderBuilder loadPropertiesByPrefix(String prefix, boolean removePrefix) {
for (PropertySource<?> propertySource : env.getPropertySources()) {
if (propertySource instanceof MapPropertySource) {
MapPropertySource mapPropSource = (MapPropertySource) propertySource;
for (String propName : mapPropSource.getPropertyNames()) {
if (propName.startsWith(prefix) && !props.containsKey(propName)) {
String adjustedName = propName;
if (removePrefix) {
adjustedName = propName.substring(prefix.length(), propName.length());
}
props.put(adjustedName, env.getProperty(propName));
}
}
}
}
return this;
} | java | public PropertiesLoaderBuilder loadPropertiesByPrefix(String prefix, boolean removePrefix) {
for (PropertySource<?> propertySource : env.getPropertySources()) {
if (propertySource instanceof MapPropertySource) {
MapPropertySource mapPropSource = (MapPropertySource) propertySource;
for (String propName : mapPropSource.getPropertyNames()) {
if (propName.startsWith(prefix) && !props.containsKey(propName)) {
String adjustedName = propName;
if (removePrefix) {
adjustedName = propName.substring(prefix.length(), propName.length());
}
props.put(adjustedName, env.getProperty(propName));
}
}
}
}
return this;
} | [
"public",
"PropertiesLoaderBuilder",
"loadPropertiesByPrefix",
"(",
"String",
"prefix",
",",
"boolean",
"removePrefix",
")",
"{",
"for",
"(",
"PropertySource",
"<",
"?",
">",
"propertySource",
":",
"env",
".",
"getPropertySources",
"(",
")",
")",
"{",
"if",
"(",... | Loads all properties found for a given prefix.
@param prefix prefix to find the properties
@param removePrefix if true - removes the prefix from the destination prop, false - copy with the same name
@return PropertyLoaderBuilder to continue the builder chain | [
"Loads",
"all",
"properties",
"found",
"for",
"a",
"given",
"prefix",
"."
] | train | https://github.com/SpartaTech/sparta-spring-web-utils/blob/f5382474d46a6048d58707fc64e7936277e8b2ce/src/main/java/org/sparta/springwebutils/property/PropertiesLoaderBuilder.java#L80-L96 |
threerings/nenya | core/src/main/java/com/threerings/miso/client/MisoScenePanel.java | MisoScenePanel.centerOnTile | public void centerOnTile (int tx, int ty)
{
Rectangle trect = MisoUtil.getTilePolygon(_metrics, tx, ty).getBounds();
int nx = trect.x + trect.width/2 - _vbounds.width/2;
int ny = trect.y + trect.height/2 - _vbounds.height/2;
// Log.info("Centering on t:" + StringUtil.coordsToString(tx, ty) +
// " b:" + StringUtil.toString(trect) +
// " vb: " + StringUtil.toString(_vbounds) +
// ", n:" + StringUtil.coordsToString(nx, ny) + ".");
setViewLocation(nx, ny);
} | java | public void centerOnTile (int tx, int ty)
{
Rectangle trect = MisoUtil.getTilePolygon(_metrics, tx, ty).getBounds();
int nx = trect.x + trect.width/2 - _vbounds.width/2;
int ny = trect.y + trect.height/2 - _vbounds.height/2;
// Log.info("Centering on t:" + StringUtil.coordsToString(tx, ty) +
// " b:" + StringUtil.toString(trect) +
// " vb: " + StringUtil.toString(_vbounds) +
// ", n:" + StringUtil.coordsToString(nx, ny) + ".");
setViewLocation(nx, ny);
} | [
"public",
"void",
"centerOnTile",
"(",
"int",
"tx",
",",
"int",
"ty",
")",
"{",
"Rectangle",
"trect",
"=",
"MisoUtil",
".",
"getTilePolygon",
"(",
"_metrics",
",",
"tx",
",",
"ty",
")",
".",
"getBounds",
"(",
")",
";",
"int",
"nx",
"=",
"trect",
".",... | Moves the scene such that the specified tile is in the center. | [
"Moves",
"the",
"scene",
"such",
"that",
"the",
"specified",
"tile",
"is",
"in",
"the",
"center",
"."
] | train | https://github.com/threerings/nenya/blob/3165a012fd859009db3367f87bd2a5b820cc760a/core/src/main/java/com/threerings/miso/client/MisoScenePanel.java#L169-L179 |
Azure/azure-sdk-for-java | cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/implementation/ComputerVisionImpl.java | ComputerVisionImpl.tagImageWithServiceResponseAsync | public Observable<ServiceResponse<TagResult>> tagImageWithServiceResponseAsync(String url, TagImageOptionalParameter tagImageOptionalParameter) {
if (this.client.endpoint() == null) {
throw new IllegalArgumentException("Parameter this.client.endpoint() is required and cannot be null.");
}
if (url == null) {
throw new IllegalArgumentException("Parameter url is required and cannot be null.");
}
final String language = tagImageOptionalParameter != null ? tagImageOptionalParameter.language() : null;
return tagImageWithServiceResponseAsync(url, language);
} | java | public Observable<ServiceResponse<TagResult>> tagImageWithServiceResponseAsync(String url, TagImageOptionalParameter tagImageOptionalParameter) {
if (this.client.endpoint() == null) {
throw new IllegalArgumentException("Parameter this.client.endpoint() is required and cannot be null.");
}
if (url == null) {
throw new IllegalArgumentException("Parameter url is required and cannot be null.");
}
final String language = tagImageOptionalParameter != null ? tagImageOptionalParameter.language() : null;
return tagImageWithServiceResponseAsync(url, language);
} | [
"public",
"Observable",
"<",
"ServiceResponse",
"<",
"TagResult",
">",
">",
"tagImageWithServiceResponseAsync",
"(",
"String",
"url",
",",
"TagImageOptionalParameter",
"tagImageOptionalParameter",
")",
"{",
"if",
"(",
"this",
".",
"client",
".",
"endpoint",
"(",
")"... | This operation generates a list of words, or tags, that are relevant to the content of the supplied image. The Computer Vision API can return tags based on objects, living beings, scenery or actions found in images. Unlike categories, tags are not organized according to a hierarchical classification system, but correspond to image content. Tags may contain hints to avoid ambiguity or provide context, for example the tag 'cello' may be accompanied by the hint 'musical instrument'. All tags are in English.
@param url Publicly reachable URL of an image
@param tagImageOptionalParameter the object representing the optional parameters to be set before calling this API
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the TagResult object | [
"This",
"operation",
"generates",
"a",
"list",
"of",
"words",
"or",
"tags",
"that",
"are",
"relevant",
"to",
"the",
"content",
"of",
"the",
"supplied",
"image",
".",
"The",
"Computer",
"Vision",
"API",
"can",
"return",
"tags",
"based",
"on",
"objects",
"li... | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/implementation/ComputerVisionImpl.java#L1626-L1636 |
ksclarke/freelib-utils | src/main/java/info/freelibrary/util/StringUtils.java | StringUtils.parseIntRange | public static int[] parseIntRange(final String aIntRange) {
final String[] range = aIntRange.split(RANGE_DELIMETER);
final int[] ints;
if (range.length == 1) {
ints = new int[range.length];
ints[0] = Integer.parseInt(aIntRange);
} else {
final int start = Integer.parseInt(range[0]);
final int end = Integer.parseInt(range[1]);
if (end >= start) {
int position = 0;
final int size = end - start;
ints = new int[size + 1]; // because we're zero-based
for (int index = start; index <= end; index++) {
ints[position++] = index;
}
} else {
throw new NumberFormatException(LOGGER.getI18n(MessageCodes.UTIL_045, start, RANGE_DELIMETER, end));
}
}
return ints;
} | java | public static int[] parseIntRange(final String aIntRange) {
final String[] range = aIntRange.split(RANGE_DELIMETER);
final int[] ints;
if (range.length == 1) {
ints = new int[range.length];
ints[0] = Integer.parseInt(aIntRange);
} else {
final int start = Integer.parseInt(range[0]);
final int end = Integer.parseInt(range[1]);
if (end >= start) {
int position = 0;
final int size = end - start;
ints = new int[size + 1]; // because we're zero-based
for (int index = start; index <= end; index++) {
ints[position++] = index;
}
} else {
throw new NumberFormatException(LOGGER.getI18n(MessageCodes.UTIL_045, start, RANGE_DELIMETER, end));
}
}
return ints;
} | [
"public",
"static",
"int",
"[",
"]",
"parseIntRange",
"(",
"final",
"String",
"aIntRange",
")",
"{",
"final",
"String",
"[",
"]",
"range",
"=",
"aIntRange",
".",
"split",
"(",
"RANGE_DELIMETER",
")",
";",
"final",
"int",
"[",
"]",
"ints",
";",
"if",
"(... | Parses strings with an integer range (e.g., 2-5) and returns an expanded integer array {2, 3, 4, 5} with those
values.
@param aIntRange A string representation of a range of integers
@return An int array with the expanded values of the string representation | [
"Parses",
"strings",
"with",
"an",
"integer",
"range",
"(",
"e",
".",
"g",
".",
"2",
"-",
"5",
")",
"and",
"returns",
"an",
"expanded",
"integer",
"array",
"{",
"2",
"3",
"4",
"5",
"}",
"with",
"those",
"values",
"."
] | train | https://github.com/ksclarke/freelib-utils/blob/54e822ae4c11b3d74793fd82a1a535ffafffaf45/src/main/java/info/freelibrary/util/StringUtils.java#L502-L527 |
Terradue/jcatalogue-client | apis/src/main/java/com/terradue/jcatalogue/repository/Proxy.java | Proxy.setPort | public Proxy setPort( int port )
{
if ( this.port == port )
{
return this;
}
return new Proxy( type, host, port, auth );
} | java | public Proxy setPort( int port )
{
if ( this.port == port )
{
return this;
}
return new Proxy( type, host, port, auth );
} | [
"public",
"Proxy",
"setPort",
"(",
"int",
"port",
")",
"{",
"if",
"(",
"this",
".",
"port",
"==",
"port",
")",
"{",
"return",
"this",
";",
"}",
"return",
"new",
"Proxy",
"(",
"type",
",",
"host",
",",
"port",
",",
"auth",
")",
";",
"}"
] | Sets the port number for the proxy.
@param port The port number for the proxy.
@return The new proxy, never {@code null}. | [
"Sets",
"the",
"port",
"number",
"for",
"the",
"proxy",
"."
] | train | https://github.com/Terradue/jcatalogue-client/blob/1f24c4da952d8ad2373c4fa97eed48b0b8a88d21/apis/src/main/java/com/terradue/jcatalogue/repository/Proxy.java#L129-L136 |
respoke/respoke-sdk-android | respokeSDK/src/main/java/com/digium/respokesdk/RespokeEndpoint.java | RespokeEndpoint.startDirectConnection | public RespokeDirectConnection startDirectConnection() {
// The constructor will call the setDirectConnection method on this endpoint instance with a reference to the new RespokeDirectConnection object
RespokeCall call = new RespokeCall(signalingChannel, this, true);
call.startCall(null, null, false);
return directConnection();
} | java | public RespokeDirectConnection startDirectConnection() {
// The constructor will call the setDirectConnection method on this endpoint instance with a reference to the new RespokeDirectConnection object
RespokeCall call = new RespokeCall(signalingChannel, this, true);
call.startCall(null, null, false);
return directConnection();
} | [
"public",
"RespokeDirectConnection",
"startDirectConnection",
"(",
")",
"{",
"// The constructor will call the setDirectConnection method on this endpoint instance with a reference to the new RespokeDirectConnection object",
"RespokeCall",
"call",
"=",
"new",
"RespokeCall",
"(",
"signaling... | Create a new DirectConnection. This method creates a new Call as well, attaching this DirectConnection to
it for the purposes of creating a peer-to-peer link for sending data such as messages to the other endpoint.
Information sent through a DirectConnection is not handled by the cloud infrastructure.
@return The DirectConnection which can be used to send data and messages directly to the other endpoint. | [
"Create",
"a",
"new",
"DirectConnection",
".",
"This",
"method",
"creates",
"a",
"new",
"Call",
"as",
"well",
"attaching",
"this",
"DirectConnection",
"to",
"it",
"for",
"the",
"purposes",
"of",
"creating",
"a",
"peer",
"-",
"to",
"-",
"peer",
"link",
"for... | train | https://github.com/respoke/respoke-sdk-android/blob/34a15f0558d29b1f1bc8481bbc5c505e855e05ef/respokeSDK/src/main/java/com/digium/respokesdk/RespokeEndpoint.java#L357-L363 |
google/j2objc | jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/impl/coll/CollationDataBuilder.java | CollationDataBuilder.copyFrom | void copyFrom(CollationDataBuilder src, CEModifier modifier) {
if(!isMutable()) {
throw new IllegalStateException("attempt to copyFrom() after build()");
}
CopyHelper helper = new CopyHelper(src, this, modifier);
Iterator<Trie2.Range> trieIterator = src.trie.iterator();
Trie2.Range range;
while(trieIterator.hasNext() && !(range = trieIterator.next()).leadSurrogate) {
enumRangeForCopy(range.startCodePoint, range.endCodePoint, range.value, helper);
}
// Update the contextChars and the unsafeBackwardSet while copying,
// in case a character had conditional mappings in the source builder
// and they were removed later.
modified |= src.modified;
} | java | void copyFrom(CollationDataBuilder src, CEModifier modifier) {
if(!isMutable()) {
throw new IllegalStateException("attempt to copyFrom() after build()");
}
CopyHelper helper = new CopyHelper(src, this, modifier);
Iterator<Trie2.Range> trieIterator = src.trie.iterator();
Trie2.Range range;
while(trieIterator.hasNext() && !(range = trieIterator.next()).leadSurrogate) {
enumRangeForCopy(range.startCodePoint, range.endCodePoint, range.value, helper);
}
// Update the contextChars and the unsafeBackwardSet while copying,
// in case a character had conditional mappings in the source builder
// and they were removed later.
modified |= src.modified;
} | [
"void",
"copyFrom",
"(",
"CollationDataBuilder",
"src",
",",
"CEModifier",
"modifier",
")",
"{",
"if",
"(",
"!",
"isMutable",
"(",
")",
")",
"{",
"throw",
"new",
"IllegalStateException",
"(",
"\"attempt to copyFrom() after build()\"",
")",
";",
"}",
"CopyHelper",
... | Copies all mappings from the src builder, with modifications.
This builder here must not be built yet, and should be empty. | [
"Copies",
"all",
"mappings",
"from",
"the",
"src",
"builder",
"with",
"modifications",
".",
"This",
"builder",
"here",
"must",
"not",
"be",
"built",
"yet",
"and",
"should",
"be",
"empty",
"."
] | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/impl/coll/CollationDataBuilder.java#L255-L269 |
Impetus/Kundera | src/jpa-engine/core/src/main/java/com/impetus/kundera/graph/GraphGenerator.java | GraphGenerator.onPreChecks | private <E> Object onPreChecks(E entity, PersistenceDelegator delegator)
{
// pre validation.
// check if entity is Null or with Invalid meta data!
Object id = null;
EntityMetadata entityMetadata = KunderaMetadataManager.getEntityMetadata(delegator.getKunderaMetadata(),
entity.getClass());
id = PropertyAccessorHelper.getId(entity, entityMetadata);
// set id, in case of auto generation and still not set.
if (ObjectGraphUtils.onAutoGenerateId((Field) entityMetadata.getIdAttribute().getJavaMember(), id))
{
id = new IdGenerator().generateAndSetId(entity, entityMetadata, delegator, delegator.getKunderaMetadata());
}
// check if id is set or not.
new PrimaryKeyNullCheck<Object>().validate(id);
validator.validate(entity, delegator.getKunderaMetadata());
// }
return id;
} | java | private <E> Object onPreChecks(E entity, PersistenceDelegator delegator)
{
// pre validation.
// check if entity is Null or with Invalid meta data!
Object id = null;
EntityMetadata entityMetadata = KunderaMetadataManager.getEntityMetadata(delegator.getKunderaMetadata(),
entity.getClass());
id = PropertyAccessorHelper.getId(entity, entityMetadata);
// set id, in case of auto generation and still not set.
if (ObjectGraphUtils.onAutoGenerateId((Field) entityMetadata.getIdAttribute().getJavaMember(), id))
{
id = new IdGenerator().generateAndSetId(entity, entityMetadata, delegator, delegator.getKunderaMetadata());
}
// check if id is set or not.
new PrimaryKeyNullCheck<Object>().validate(id);
validator.validate(entity, delegator.getKunderaMetadata());
// }
return id;
} | [
"private",
"<",
"E",
">",
"Object",
"onPreChecks",
"(",
"E",
"entity",
",",
"PersistenceDelegator",
"delegator",
")",
"{",
"// pre validation.",
"// check if entity is Null or with Invalid meta data!",
"Object",
"id",
"=",
"null",
";",
"EntityMetadata",
"entityMetadata",
... | On pre checks before generating graph. performed checks: <li>Check if
entity is valid.</li> <li>generated and set id in case
{@link GeneratedValue} is present and not set.</li> <li>Check if primary
key is not null.</li>
@param entity
entity
@param client
client
@return entity id | [
"On",
"pre",
"checks",
"before",
"generating",
"graph",
".",
"performed",
"checks",
":",
"<li",
">",
"Check",
"if",
"entity",
"is",
"valid",
".",
"<",
"/",
"li",
">",
"<li",
">",
"generated",
"and",
"set",
"id",
"in",
"case",
"{",
"@link",
"GeneratedVa... | train | https://github.com/Impetus/Kundera/blob/268958ab1ec09d14ec4d9184f0c8ded7a9158908/src/jpa-engine/core/src/main/java/com/impetus/kundera/graph/GraphGenerator.java#L215-L240 |
google/truth | extensions/java8/src/main/java/com/google/common/truth/IntStreamSubject.java | IntStreamSubject.containsAnyOf | @SuppressWarnings("GoodTime") // false positive; b/122617528
public void containsAnyOf(int first, int second, int... rest) {
check().that(actualList).containsAnyOf(first, second, box(rest));
} | java | @SuppressWarnings("GoodTime") // false positive; b/122617528
public void containsAnyOf(int first, int second, int... rest) {
check().that(actualList).containsAnyOf(first, second, box(rest));
} | [
"@",
"SuppressWarnings",
"(",
"\"GoodTime\"",
")",
"// false positive; b/122617528",
"public",
"void",
"containsAnyOf",
"(",
"int",
"first",
",",
"int",
"second",
",",
"int",
"...",
"rest",
")",
"{",
"check",
"(",
")",
".",
"that",
"(",
"actualList",
")",
".... | Fails if the subject does not contain at least one of the given elements. | [
"Fails",
"if",
"the",
"subject",
"does",
"not",
"contain",
"at",
"least",
"one",
"of",
"the",
"given",
"elements",
"."
] | train | https://github.com/google/truth/blob/60eceffd2e8c3297655d33ed87d965cf5af51108/extensions/java8/src/main/java/com/google/common/truth/IntStreamSubject.java#L98-L101 |
sarl/sarl | main/coreplugins/io.sarl.lang.ui/src/io/sarl/lang/ui/extralanguage/preferences/ExtraLanguagePreferenceAccess.java | ExtraLanguagePreferenceAccess.ifSpecificConfiguration | public IProject ifSpecificConfiguration(String preferenceContainerID, IProject project) {
if (project != null && hasProjectSpecificOptions(preferenceContainerID, project)) {
return project;
}
return null;
} | java | public IProject ifSpecificConfiguration(String preferenceContainerID, IProject project) {
if (project != null && hasProjectSpecificOptions(preferenceContainerID, project)) {
return project;
}
return null;
} | [
"public",
"IProject",
"ifSpecificConfiguration",
"(",
"String",
"preferenceContainerID",
",",
"IProject",
"project",
")",
"{",
"if",
"(",
"project",
"!=",
"null",
"&&",
"hasProjectSpecificOptions",
"(",
"preferenceContainerID",
",",
"project",
")",
")",
"{",
"return... | Filter the project according to the specific configuration.
<p>If the given project has a specific configuration, it is replied.
Otherwise, {@code null} is replied.
@param preferenceContainerID the identifier of the generator's preference container.
@param project the context. If {@code null}, the global context is assumed.
@return the unmodifiable preference store. | [
"Filter",
"the",
"project",
"according",
"to",
"the",
"specific",
"configuration",
"."
] | train | https://github.com/sarl/sarl/blob/ca00ff994598c730339972def4e19a60e0b8cace/main/coreplugins/io.sarl.lang.ui/src/io/sarl/lang/ui/extralanguage/preferences/ExtraLanguagePreferenceAccess.java#L247-L252 |
javalite/activejdbc | activejdbc/src/main/java/org/javalite/activejdbc/Model.java | Model.setBigDecimal | public <T extends Model> T setBigDecimal(String attributeName, Object value) {
Converter<Object, BigDecimal> converter = modelRegistryLocal.converterForValue(
attributeName, value, BigDecimal.class);
return setRaw(attributeName, converter != null ? converter.convert(value) : Convert.toBigDecimal(value));
} | java | public <T extends Model> T setBigDecimal(String attributeName, Object value) {
Converter<Object, BigDecimal> converter = modelRegistryLocal.converterForValue(
attributeName, value, BigDecimal.class);
return setRaw(attributeName, converter != null ? converter.convert(value) : Convert.toBigDecimal(value));
} | [
"public",
"<",
"T",
"extends",
"Model",
">",
"T",
"setBigDecimal",
"(",
"String",
"attributeName",
",",
"Object",
"value",
")",
"{",
"Converter",
"<",
"Object",
",",
"BigDecimal",
">",
"converter",
"=",
"modelRegistryLocal",
".",
"converterForValue",
"(",
"att... | Sets attribute value as <code>java.math.BigDecimal</code>.
If there is a {@link Converter} registered for the attribute that converts from Class <code>S</code> to Class
<code>java.math.BigDecimal</code>, given the value is an instance of <code>S</code>, then it will be used,
otherwise performs a conversion using {@link Convert#toBigDecimal(Object)}.
@param attributeName name of attribute.
@param value value
@return reference to this model. | [
"Sets",
"attribute",
"value",
"as",
"<code",
">",
"java",
".",
"math",
".",
"BigDecimal<",
"/",
"code",
">",
".",
"If",
"there",
"is",
"a",
"{",
"@link",
"Converter",
"}",
"registered",
"for",
"the",
"attribute",
"that",
"converts",
"from",
"Class",
"<co... | train | https://github.com/javalite/activejdbc/blob/ffcf5457cace19622a8f71e856cbbbe9e7dd5fcc/activejdbc/src/main/java/org/javalite/activejdbc/Model.java#L1725-L1729 |
ttddyy/datasource-proxy | src/main/java/net/ttddyy/dsproxy/support/ProxyDataSourceBuilder.java | ProxyDataSourceBuilder.logSlowQueryBySlf4j | public ProxyDataSourceBuilder logSlowQueryBySlf4j(long thresholdTime, TimeUnit timeUnit, SLF4JLogLevel logLevel, String loggerName) {
this.createSlf4jSlowQueryListener = true;
this.slowQueryThreshold = thresholdTime;
this.slowQueryTimeUnit = timeUnit;
this.slf4jSlowQueryLogLevel = logLevel;
this.slf4jSlowQueryLoggerName = loggerName;
return this;
} | java | public ProxyDataSourceBuilder logSlowQueryBySlf4j(long thresholdTime, TimeUnit timeUnit, SLF4JLogLevel logLevel, String loggerName) {
this.createSlf4jSlowQueryListener = true;
this.slowQueryThreshold = thresholdTime;
this.slowQueryTimeUnit = timeUnit;
this.slf4jSlowQueryLogLevel = logLevel;
this.slf4jSlowQueryLoggerName = loggerName;
return this;
} | [
"public",
"ProxyDataSourceBuilder",
"logSlowQueryBySlf4j",
"(",
"long",
"thresholdTime",
",",
"TimeUnit",
"timeUnit",
",",
"SLF4JLogLevel",
"logLevel",
",",
"String",
"loggerName",
")",
"{",
"this",
".",
"createSlf4jSlowQueryListener",
"=",
"true",
";",
"this",
".",
... | Register {@link SLF4JSlowQueryListener}.
@param thresholdTime slow query threshold time
@param timeUnit slow query threshold time unit
@param logLevel log level for slf4j
@param loggerName slf4j logger name
@return builder
@since 1.4.1 | [
"Register",
"{",
"@link",
"SLF4JSlowQueryListener",
"}",
"."
] | train | https://github.com/ttddyy/datasource-proxy/blob/62163ccf9a569a99aa3ad9f9151a32567447a62e/src/main/java/net/ttddyy/dsproxy/support/ProxyDataSourceBuilder.java#L375-L382 |
minio/minio-java | api/src/main/java/io/minio/MinioClient.java | MinioClient.setTimeout | public void setTimeout(long connectTimeout, long writeTimeout, long readTimeout) {
this.httpClient = this.httpClient.newBuilder()
.connectTimeout(connectTimeout, TimeUnit.MILLISECONDS)
.writeTimeout(writeTimeout, TimeUnit.MILLISECONDS)
.readTimeout(readTimeout, TimeUnit.MILLISECONDS)
.build();
} | java | public void setTimeout(long connectTimeout, long writeTimeout, long readTimeout) {
this.httpClient = this.httpClient.newBuilder()
.connectTimeout(connectTimeout, TimeUnit.MILLISECONDS)
.writeTimeout(writeTimeout, TimeUnit.MILLISECONDS)
.readTimeout(readTimeout, TimeUnit.MILLISECONDS)
.build();
} | [
"public",
"void",
"setTimeout",
"(",
"long",
"connectTimeout",
",",
"long",
"writeTimeout",
",",
"long",
"readTimeout",
")",
"{",
"this",
".",
"httpClient",
"=",
"this",
".",
"httpClient",
".",
"newBuilder",
"(",
")",
".",
"connectTimeout",
"(",
"connectTimeou... | Sets HTTP connect, write and read timeouts. A value of 0 means no timeout, otherwise values must be between 1 and
Integer.MAX_VALUE when converted to milliseconds.
</p><b>Example:</b><br>
<pre>{@code minioClient.setTimeout(TimeUnit.SECONDS.toMillis(10), TimeUnit.SECONDS.toMillis(10),
TimeUnit.SECONDS.toMillis(30)); }</pre>
@param connectTimeout HTTP connect timeout in milliseconds.
@param writeTimeout HTTP write timeout in milliseconds.
@param readTimeout HTTP read timeout in milliseconds. | [
"Sets",
"HTTP",
"connect",
"write",
"and",
"read",
"timeouts",
".",
"A",
"value",
"of",
"0",
"means",
"no",
"timeout",
"otherwise",
"values",
"must",
"be",
"between",
"1",
"and",
"Integer",
".",
"MAX_VALUE",
"when",
"converted",
"to",
"milliseconds",
"."
] | train | https://github.com/minio/minio-java/blob/b2028f56403c89ce2d5900ae813bc1314c87bc7f/api/src/main/java/io/minio/MinioClient.java#L796-L802 |
jenkinsci/artifactory-plugin | src/main/java/org/jfrog/hudson/ArtifactoryServer.java | ArtifactoryServer.createArtifactoryClient | public ArtifactoryBuildInfoClient createArtifactoryClient(String userName, String password,
ProxyConfiguration proxyConfiguration) {
return createArtifactoryClient(userName, password, proxyConfiguration, new NullLog());
} | java | public ArtifactoryBuildInfoClient createArtifactoryClient(String userName, String password,
ProxyConfiguration proxyConfiguration) {
return createArtifactoryClient(userName, password, proxyConfiguration, new NullLog());
} | [
"public",
"ArtifactoryBuildInfoClient",
"createArtifactoryClient",
"(",
"String",
"userName",
",",
"String",
"password",
",",
"ProxyConfiguration",
"proxyConfiguration",
")",
"{",
"return",
"createArtifactoryClient",
"(",
"userName",
",",
"password",
",",
"proxyConfiguratio... | This method might run on slaves, this is why we provide it with a proxy from the master config | [
"This",
"method",
"might",
"run",
"on",
"slaves",
"this",
"is",
"why",
"we",
"provide",
"it",
"with",
"a",
"proxy",
"from",
"the",
"master",
"config"
] | train | https://github.com/jenkinsci/artifactory-plugin/blob/f5fcfff6a5a50be5374813e49d1fe3aaf6422333/src/main/java/org/jfrog/hudson/ArtifactoryServer.java#L281-L284 |
datumbox/datumbox-framework | datumbox-framework-core/src/main/java/com/datumbox/framework/core/statistics/distributions/DiscreteDistributions.java | DiscreteDistributions.poissonCdf | public static double poissonCdf(int k, double lamda) {
if(k<0 || lamda<0) {
throw new IllegalArgumentException("All the parameters must be positive.");
}
/*
//Slow!
$probabilitySum=0;
for($i=0;$i<=$k;++$i) {
$probabilitySum+=self::poisson($i,$lamda);
}
*/
//Faster solution as described at: http://www.math.ucla.edu/~tom/distributions/poisson.html?
double probabilitySum = 1.0 - ContinuousDistributions.gammaCdf(lamda,k+1);
return probabilitySum;
} | java | public static double poissonCdf(int k, double lamda) {
if(k<0 || lamda<0) {
throw new IllegalArgumentException("All the parameters must be positive.");
}
/*
//Slow!
$probabilitySum=0;
for($i=0;$i<=$k;++$i) {
$probabilitySum+=self::poisson($i,$lamda);
}
*/
//Faster solution as described at: http://www.math.ucla.edu/~tom/distributions/poisson.html?
double probabilitySum = 1.0 - ContinuousDistributions.gammaCdf(lamda,k+1);
return probabilitySum;
} | [
"public",
"static",
"double",
"poissonCdf",
"(",
"int",
"k",
",",
"double",
"lamda",
")",
"{",
"if",
"(",
"k",
"<",
"0",
"||",
"lamda",
"<",
"0",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"All the parameters must be positive.\"",
")",
";",... | Returns the cumulative probability of poisson
@param k
@param lamda
@return | [
"Returns",
"the",
"cumulative",
"probability",
"of",
"poisson"
] | train | https://github.com/datumbox/datumbox-framework/blob/909dff0476e80834f05ecdde0624dd2390e9b0ca/datumbox-framework-core/src/main/java/com/datumbox/framework/core/statistics/distributions/DiscreteDistributions.java#L408-L425 |
Alluxio/alluxio | logserver/src/main/java/alluxio/logserver/AlluxioLog4jSocketNode.java | AlluxioLog4jSocketNode.configureHierarchy | private LoggerRepository configureHierarchy(String processType)
throws IOException {
String inetAddressStr = mSocket.getInetAddress().getHostAddress();
Properties properties = new Properties();
File configFile;
try {
configFile = new File(new URI(System.getProperty("log4j.configuration")));
} catch (URISyntaxException e) {
// Alluxio log server cannot derive a valid path to log4j.properties. Since this
// properties file is global, we should throw an exception.
throw new RuntimeException("Cannot derive a valid URI to log4j.properties file.", e);
}
try (FileInputStream inputStream = new FileInputStream(configFile)) {
properties.load(inputStream);
}
// Assign Level.TRACE to level so that log server prints whatever log messages received from
// log clients. If the log server receives a LoggingEvent, it assumes that the remote
// log client has the intention of writing this LoggingEvent to logs. It does not make
// much sense for the log client to send the message over the network and wants the
// messsage to be discarded by the log server.
// With this assumption, since TRACE is the lowest logging level, we do not have to compare
// the level of the event and the level of the logger when the log server receives
// LoggingEvents.
Level level = Level.TRACE;
Hierarchy clientHierarchy = new Hierarchy(new RootLogger(level));
// Startup script should guarantee that mBaseLogsDir already exists.
String logDirectoryPath =
PathUtils.concatPath(mBaseLogsDir, processType.toLowerCase());
File logDirectory = new File(logDirectoryPath);
if (!logDirectory.exists()) {
logDirectory.mkdir();
}
String logFilePath = PathUtils.concatPath(logDirectoryPath, inetAddressStr + ".log");
properties.setProperty(ROOT_LOGGER_PROPERTY_KEY,
level.toString() + "," + AlluxioLogServerProcess.LOGSERVER_CLIENT_LOGGER_APPENDER_NAME);
properties.setProperty(ROOT_LOGGER_APPENDER_FILE_PROPERTY_KEY, logFilePath);
new PropertyConfigurator().doConfigure(properties, clientHierarchy);
return clientHierarchy;
} | java | private LoggerRepository configureHierarchy(String processType)
throws IOException {
String inetAddressStr = mSocket.getInetAddress().getHostAddress();
Properties properties = new Properties();
File configFile;
try {
configFile = new File(new URI(System.getProperty("log4j.configuration")));
} catch (URISyntaxException e) {
// Alluxio log server cannot derive a valid path to log4j.properties. Since this
// properties file is global, we should throw an exception.
throw new RuntimeException("Cannot derive a valid URI to log4j.properties file.", e);
}
try (FileInputStream inputStream = new FileInputStream(configFile)) {
properties.load(inputStream);
}
// Assign Level.TRACE to level so that log server prints whatever log messages received from
// log clients. If the log server receives a LoggingEvent, it assumes that the remote
// log client has the intention of writing this LoggingEvent to logs. It does not make
// much sense for the log client to send the message over the network and wants the
// messsage to be discarded by the log server.
// With this assumption, since TRACE is the lowest logging level, we do not have to compare
// the level of the event and the level of the logger when the log server receives
// LoggingEvents.
Level level = Level.TRACE;
Hierarchy clientHierarchy = new Hierarchy(new RootLogger(level));
// Startup script should guarantee that mBaseLogsDir already exists.
String logDirectoryPath =
PathUtils.concatPath(mBaseLogsDir, processType.toLowerCase());
File logDirectory = new File(logDirectoryPath);
if (!logDirectory.exists()) {
logDirectory.mkdir();
}
String logFilePath = PathUtils.concatPath(logDirectoryPath, inetAddressStr + ".log");
properties.setProperty(ROOT_LOGGER_PROPERTY_KEY,
level.toString() + "," + AlluxioLogServerProcess.LOGSERVER_CLIENT_LOGGER_APPENDER_NAME);
properties.setProperty(ROOT_LOGGER_APPENDER_FILE_PROPERTY_KEY, logFilePath);
new PropertyConfigurator().doConfigure(properties, clientHierarchy);
return clientHierarchy;
} | [
"private",
"LoggerRepository",
"configureHierarchy",
"(",
"String",
"processType",
")",
"throws",
"IOException",
"{",
"String",
"inetAddressStr",
"=",
"mSocket",
".",
"getInetAddress",
"(",
")",
".",
"getHostAddress",
"(",
")",
";",
"Properties",
"properties",
"=",
... | Configure a {@link Hierarchy} instance used to retrive logger by name and maintain the logger
hierarchy. {@link AlluxioLog4jSocketNode} instance can retrieve the logger to log incoming
{@link org.apache.log4j.spi.LoggingEvent}s.
@param processType type of the process sending this {@link LoggingEvent}
@return a {@link Hierarchy} instance to retrieve logger
@throws IOException if fails to create an {@link FileInputStream} to read log4j.properties | [
"Configure",
"a",
"{",
"@link",
"Hierarchy",
"}",
"instance",
"used",
"to",
"retrive",
"logger",
"by",
"name",
"and",
"maintain",
"the",
"logger",
"hierarchy",
".",
"{",
"@link",
"AlluxioLog4jSocketNode",
"}",
"instance",
"can",
"retrieve",
"the",
"logger",
"t... | train | https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/logserver/src/main/java/alluxio/logserver/AlluxioLog4jSocketNode.java#L110-L148 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.