proj_name
stringclasses 131
values | relative_path
stringlengths 30
228
| class_name
stringlengths 1
68
| func_name
stringlengths 1
48
| masked_class
stringlengths 78
9.82k
| func_body
stringlengths 46
9.61k
| len_input
int64 29
2.01k
| len_output
int64 14
1.94k
| total
int64 55
2.05k
| relevant_context
stringlengths 0
38.4k
|
|---|---|---|---|---|---|---|---|---|---|
jtablesaw_tablesaw
|
tablesaw/core/src/main/java/tech/tablesaw/columns/numbers/FloatColumnType.java
|
FloatColumnType
|
instance
|
class FloatColumnType extends AbstractColumnType {
public static final int BYTE_SIZE = 4;
/** Returns the default parser for {@link FloatColumn} */
public static final FloatParser DEFAULT_PARSER = new FloatParser(ColumnType.FLOAT);
private static FloatColumnType INSTANCE;
private FloatColumnType(int byteSize, String name, String printerFriendlyName) {
super(byteSize, name, printerFriendlyName);
}
/** Returns the singleton instance of FloatColumnType */
public static FloatColumnType instance() {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override
public FloatColumn create(String name) {
return FloatColumn.create(name);
}
/** {@inheritDoc} */
@Override
public FloatParser customParser(ReadOptions options) {
return new FloatParser(this, options);
}
/** Returns true if the given value is the missing value indicator for this column type */
public static boolean valueIsMissing(float value) {
return Float.isNaN(value);
}
/** Returns the missing value indicator for this column type */
public static float missingValueIndicator() {
return Float.NaN;
}
}
|
if (INSTANCE == null) {
INSTANCE = new FloatColumnType(BYTE_SIZE, "FLOAT", "float");
}
return INSTANCE;
| 326
| 48
| 374
|
<methods>public int byteSize() ,public boolean equals(java.lang.Object) ,public java.lang.String getPrinterFriendlyName() ,public int hashCode() ,public java.lang.String name() ,public java.lang.String toString() <variables>private final non-sealed int byteSize,private final non-sealed java.lang.String name,private final non-sealed java.lang.String printerFriendlyName
|
jtablesaw_tablesaw
|
tablesaw/core/src/main/java/tech/tablesaw/columns/numbers/FloatParser.java
|
FloatParser
|
canParse
|
class FloatParser extends AbstractColumnParser<Float> {
public FloatParser(ColumnType columnType) {
super(columnType);
}
public FloatParser(FloatColumnType columnType, ReadOptions readOptions) {
super(columnType);
if (readOptions.missingValueIndicators().length > 0) {
missingValueStrings = Lists.newArrayList(readOptions.missingValueIndicators());
}
}
@Override
public boolean canParse(String s) {<FILL_FUNCTION_BODY>}
@Override
public Float parse(String s) {
return parseFloat(s);
}
@Override
public float parseFloat(String s) {
if (isMissing(s)) {
return FloatColumnType.missingValueIndicator();
}
return Float.parseFloat(AbstractColumnParser.remove(s, ','));
}
}
|
if (isMissing(s)) {
return true;
}
try {
Float.parseFloat(AbstractColumnParser.remove(s, ','));
return true;
} catch (NumberFormatException e) {
// it's all part of the plan
return false;
}
| 235
| 78
| 313
|
<methods>public void <init>(tech.tablesaw.api.ColumnType) ,public abstract boolean canParse(java.lang.String) ,public tech.tablesaw.api.ColumnType columnType() ,public boolean isMissing(java.lang.String) ,public abstract java.lang.Float parse(java.lang.String) ,public byte parseByte(java.lang.String) ,public double parseDouble(java.lang.String) ,public float parseFloat(java.lang.String) ,public int parseInt(java.lang.String) ,public long parseLong(java.lang.String) ,public short parseShort(java.lang.String) ,public void setMissingValueStrings(List<java.lang.String>) <variables>private final non-sealed tech.tablesaw.api.ColumnType columnType,protected List<java.lang.String> missingValueStrings
|
jtablesaw_tablesaw
|
tablesaw/core/src/main/java/tech/tablesaw/columns/numbers/IntColumnType.java
|
IntColumnType
|
instance
|
class IntColumnType extends AbstractColumnType {
/** The default parser for IntColumn */
public static final IntParser DEFAULT_PARSER = new IntParser(ColumnType.INTEGER);
private static final int BYTE_SIZE = 4;
private static IntColumnType INSTANCE;
private IntColumnType(int byteSize, String name, String printerFriendlyName) {
super(byteSize, name, printerFriendlyName);
}
/** Returns the singleton instance of IntColumnType */
public static IntColumnType instance() {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override
public IntColumn create(String name) {
return IntColumn.create(name);
}
/** {@inheritDoc} */
@Override
public IntParser customParser(ReadOptions options) {
return new IntParser(this, options);
}
/** Returns true if the given value is the missing value indicator for this column type */
public static boolean valueIsMissing(int value) {
return value == missingValueIndicator();
}
/** Returns the missing value indicator for this column type NOTE: */
public static int missingValueIndicator() {
return Integer.MIN_VALUE;
}
}
|
if (INSTANCE == null) {
INSTANCE = new IntColumnType(BYTE_SIZE, "INTEGER", "Integer");
}
return INSTANCE;
| 312
| 47
| 359
|
<methods>public int byteSize() ,public boolean equals(java.lang.Object) ,public java.lang.String getPrinterFriendlyName() ,public int hashCode() ,public java.lang.String name() ,public java.lang.String toString() <variables>private final non-sealed int byteSize,private final non-sealed java.lang.String name,private final non-sealed java.lang.String printerFriendlyName
|
jtablesaw_tablesaw
|
tablesaw/core/src/main/java/tech/tablesaw/columns/numbers/IntParser.java
|
IntParser
|
parseInt
|
class IntParser extends AbstractColumnParser<Integer> {
private final boolean ignoreZeroDecimal;
public IntParser(ColumnType columnType) {
super(columnType);
ignoreZeroDecimal = ReadOptions.DEFAULT_IGNORE_ZERO_DECIMAL;
}
public IntParser(IntColumnType columnType, ReadOptions readOptions) {
super(columnType);
if (readOptions.missingValueIndicators().length > 0) {
missingValueStrings = Lists.newArrayList(readOptions.missingValueIndicators());
}
ignoreZeroDecimal = readOptions.ignoreZeroDecimal();
}
@Override
public boolean canParse(String str) {
if (isMissing(str)) {
return true;
}
String s = str;
try {
if (ignoreZeroDecimal) {
s = StringUtils.removeZeroDecimal(s);
}
Integer.parseInt(AbstractColumnParser.remove(s, ','));
return true;
} catch (NumberFormatException e) {
// it's all part of the plan
return false;
}
}
@Override
public Integer parse(String s) {
return parseInt(s);
}
@Override
public double parseDouble(String s) {
return parseInt(s);
}
@Override
public int parseInt(String str) {<FILL_FUNCTION_BODY>}
}
|
if (isMissing(str)) {
return IntColumnType.missingValueIndicator();
}
String s = str;
if (ignoreZeroDecimal) {
s = StringUtils.removeZeroDecimal(s);
}
return Integer.parseInt(AbstractColumnParser.remove(s, ','));
| 370
| 82
| 452
|
<methods>public void <init>(tech.tablesaw.api.ColumnType) ,public abstract boolean canParse(java.lang.String) ,public tech.tablesaw.api.ColumnType columnType() ,public boolean isMissing(java.lang.String) ,public abstract java.lang.Integer parse(java.lang.String) ,public byte parseByte(java.lang.String) ,public double parseDouble(java.lang.String) ,public float parseFloat(java.lang.String) ,public int parseInt(java.lang.String) ,public long parseLong(java.lang.String) ,public short parseShort(java.lang.String) ,public void setMissingValueStrings(List<java.lang.String>) <variables>private final non-sealed tech.tablesaw.api.ColumnType columnType,protected List<java.lang.String> missingValueStrings
|
jtablesaw_tablesaw
|
tablesaw/core/src/main/java/tech/tablesaw/columns/numbers/LongColumnType.java
|
LongColumnType
|
instance
|
class LongColumnType extends AbstractColumnType {
/** The default parser for LongColumn */
public static final LongParser DEFAULT_PARSER = new LongParser(ColumnType.LONG);
private static final int BYTE_SIZE = 8;
private static LongColumnType INSTANCE;
private LongColumnType(int byteSize, String name, String printerFriendlyName) {
super(byteSize, name, printerFriendlyName);
}
/** Returns the singleton instance of LongColumnType */
public static LongColumnType instance() {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override
public LongColumn create(String name) {
return LongColumn.create(name);
}
/** Returns the default parser used to convert strings to long values */
public LongParser defaultParser() {
return DEFAULT_PARSER;
}
/** {@inheritDoc} */
@Override
public LongParser customParser(ReadOptions options) {
return new LongParser(this, options);
}
/** Returns true if the given value is the missing value indicator for this column type */
public static boolean valueIsMissing(long value) {
return value == missingValueIndicator();
}
/** Returns the missing value indicator for this column type NOTE: */
public static long missingValueIndicator() {
return Long.MIN_VALUE;
}
}
|
if (INSTANCE == null) {
INSTANCE = new LongColumnType(BYTE_SIZE, "LONG", "Long");
}
return INSTANCE;
| 347
| 46
| 393
|
<methods>public int byteSize() ,public boolean equals(java.lang.Object) ,public java.lang.String getPrinterFriendlyName() ,public int hashCode() ,public java.lang.String name() ,public java.lang.String toString() <variables>private final non-sealed int byteSize,private final non-sealed java.lang.String name,private final non-sealed java.lang.String printerFriendlyName
|
jtablesaw_tablesaw
|
tablesaw/core/src/main/java/tech/tablesaw/columns/numbers/LongParser.java
|
LongParser
|
parseLong
|
class LongParser extends AbstractColumnParser<Long> {
private final boolean ignoreZeroDecimal;
public LongParser(ColumnType columnType) {
super(columnType);
ignoreZeroDecimal = ReadOptions.DEFAULT_IGNORE_ZERO_DECIMAL;
}
public LongParser(LongColumnType columnType, ReadOptions readOptions) {
super(columnType);
if (readOptions.missingValueIndicators().length > 0) {
missingValueStrings = Lists.newArrayList(readOptions.missingValueIndicators());
}
ignoreZeroDecimal = readOptions.ignoreZeroDecimal();
}
@Override
public boolean canParse(String str) {
if (isMissing(str)) {
return true;
}
String s = str;
try {
if (ignoreZeroDecimal) {
s = StringUtils.removeZeroDecimal(s);
}
Long.parseLong(AbstractColumnParser.remove(s, ','));
return true;
} catch (NumberFormatException e) {
// it's all part of the plan
return false;
}
}
@Override
public Long parse(String s) {
return parseLong(s);
}
@Override
public double parseDouble(String str) {
return parseLong(str);
}
@Override
public long parseLong(String str) {<FILL_FUNCTION_BODY>}
}
|
if (isMissing(str)) {
return LongColumnType.missingValueIndicator();
}
String s = str;
if (ignoreZeroDecimal) {
s = StringUtils.removeZeroDecimal(s);
}
return Long.parseLong(AbstractColumnParser.remove(s, ','));
| 370
| 82
| 452
|
<methods>public void <init>(tech.tablesaw.api.ColumnType) ,public abstract boolean canParse(java.lang.String) ,public tech.tablesaw.api.ColumnType columnType() ,public boolean isMissing(java.lang.String) ,public abstract java.lang.Long parse(java.lang.String) ,public byte parseByte(java.lang.String) ,public double parseDouble(java.lang.String) ,public float parseFloat(java.lang.String) ,public int parseInt(java.lang.String) ,public long parseLong(java.lang.String) ,public short parseShort(java.lang.String) ,public void setMissingValueStrings(List<java.lang.String>) <variables>private final non-sealed tech.tablesaw.api.ColumnType columnType,protected List<java.lang.String> missingValueStrings
|
jtablesaw_tablesaw
|
tablesaw/core/src/main/java/tech/tablesaw/columns/numbers/NumberColumnFormatter.java
|
NumberColumnFormatter
|
currency
|
class NumberColumnFormatter extends ColumnFormatter {
private final NumberFormat format;
private ColumnType columnType;
public static NumberColumnFormatter percent(int fractionalDigits) {
NumberFormat format = NumberFormat.getPercentInstance();
format.setGroupingUsed(false);
format.setMinimumFractionDigits(fractionalDigits);
format.setMaximumFractionDigits(fractionalDigits);
return new NumberColumnFormatter(format);
}
/** Returns a formatter that prints floating point numbers with all precision */
public static NumberColumnFormatter floatingPointDefault() {
NumberFormat format =
new DecimalFormat("0", DecimalFormatSymbols.getInstance(Locale.getDefault()));
format.setMaximumFractionDigits(340);
format.setMaximumIntegerDigits(340);
format.setGroupingUsed(false);
return new NumberColumnFormatter(format);
}
/** Formats numbers using java default, so sometimes in scientific notation, sometimes not */
public static NumberColumnFormatter standard() {
return new NumberColumnFormatter();
}
public static NumberColumnFormatter ints() {
NumberFormat format = new DecimalFormat();
format.setGroupingUsed(false);
format.setMinimumFractionDigits(0);
format.setMaximumFractionDigits(0);
return new NumberColumnFormatter(format);
}
public static NumberColumnFormatter intsWithGrouping() {
NumberFormat format = new DecimalFormat();
format.setGroupingUsed(true);
format.setMinimumFractionDigits(0);
format.setMaximumFractionDigits(0);
return new NumberColumnFormatter(format);
}
public static NumberColumnFormatter fixedWithGrouping(int fractionalDigits) {
NumberFormat format = new DecimalFormat();
format.setGroupingUsed(true);
format.setMinimumFractionDigits(fractionalDigits);
format.setMaximumFractionDigits(fractionalDigits);
return new NumberColumnFormatter(format);
}
public static NumberColumnFormatter currency(String language, String country) {<FILL_FUNCTION_BODY>}
public NumberColumnFormatter() {
super("");
this.format = null;
}
public NumberColumnFormatter(NumberFormat format) {
super("");
this.format = format;
}
public NumberColumnFormatter(NumberFormat format, String missingString) {
super(missingString);
this.format = format;
}
public NumberColumnFormatter(String missingString) {
super(missingString);
this.format = null;
}
public void setColumnType(ColumnType columnType) {
this.columnType = columnType;
}
public NumberFormat getFormat() {
return format;
}
public String format(long value) {
if (isMissingValue(value)) {
return getMissingString();
}
if (format == null) {
return String.valueOf(value);
}
return format.format(value);
}
public String format(int value) {
if (isMissingValue(value)) {
return getMissingString();
}
if (format == null) {
return String.valueOf(value);
}
return format.format(value);
}
public String format(short value) {
if (isMissingValue(value)) {
return getMissingString();
}
if (format == null) {
return String.valueOf(value);
}
return format.format(value);
}
public String format(float value) {
if (isMissingValue(value)) {
return getMissingString();
}
if (format == null) {
return String.valueOf(value);
}
return format.format(value);
}
public String format(double value) {
if (isMissingValue(value)) {
return getMissingString();
}
if (format == null) {
return String.valueOf(value);
}
return format.format(value);
}
@Override
public String toString() {
return "NumberColumnFormatter{"
+ "format="
+ format
+ ", missingString='"
+ getMissingString()
+ '\''
+ '}';
}
private boolean isMissingValue(double value) {
if (columnType.equals(ColumnType.DOUBLE)) {
return DoubleColumnType.valueIsMissing(value);
} else {
throw new RuntimeException("Unhandled column type in NumberColumnFormatter: " + columnType);
}
}
private boolean isMissingValue(float value) {
if (columnType.equals(ColumnType.FLOAT)) {
return FloatColumnType.valueIsMissing(value);
} else {
throw new RuntimeException("Unhandled column type in NumberColumnFormatter: " + columnType);
}
}
private boolean isMissingValue(int value) {
if (columnType.equals(ColumnType.INTEGER)) {
return IntColumnType.valueIsMissing(value);
}
if (columnType.equals(ColumnType.SHORT)) {
return ShortColumnType.valueIsMissing(value);
} else {
throw new RuntimeException("Unhandled column type in NumberColumnFormatter: " + columnType);
}
}
private boolean isMissingValue(short value) {
if (columnType.equals(ColumnType.SHORT)) {
return ShortColumnType.valueIsMissing(value);
} else {
throw new RuntimeException("Unhandled column type in NumberColumnFormatter: " + columnType);
}
}
private boolean isMissingValue(long value) {
if (columnType.equals(ColumnType.LONG)) {
return LongColumnType.valueIsMissing(value);
} else {
throw new RuntimeException("Unhandled column type in NumberColumnFormatter: " + columnType);
}
}
}
|
NumberFormat format = NumberFormat.getCurrencyInstance(new Locale(language, country));
return new NumberColumnFormatter(format);
| 1,541
| 36
| 1,577
|
<methods>public java.lang.String getMissingString() <variables>private final non-sealed java.lang.String missingString
|
jtablesaw_tablesaw
|
tablesaw/core/src/main/java/tech/tablesaw/columns/numbers/NumberInterpolator.java
|
NumberInterpolator
|
linear
|
class NumberInterpolator<T extends Number> extends Interpolator<T> {
protected final NumericColumn<T> col;
/** Constructs an interpolator for the given column */
public NumberInterpolator(NumericColumn<T> col) {
super(col);
this.col = col;
}
/** Linearly interpolates missing values. */
public DoubleColumn linear() {<FILL_FUNCTION_BODY>}
}
|
DoubleColumn result = col.asDoubleColumn();
int last = -1;
for (int i = 0; i < col.size(); i++) {
if (!col.isMissing(i)) {
if (last >= 0 && last != i - 1) {
for (int j = last + 1; j < i; j++) {
result.set(
j,
col.getDouble(last)
+ (col.getDouble(i) - col.getDouble(last)) * (j - last) / (i - last));
}
}
last = i;
}
}
return result;
| 115
| 163
| 278
|
<methods>public void <init>(Column<T>) ,public Column<T> backfill() ,public Column<T> frontfill() <variables>protected final non-sealed Column<T> col
|
jtablesaw_tablesaw
|
tablesaw/core/src/main/java/tech/tablesaw/columns/numbers/ShortColumnType.java
|
ShortColumnType
|
instance
|
class ShortColumnType extends AbstractColumnType {
public static final ShortParser DEFAULT_PARSER = new ShortParser(ShortColumnType.INSTANCE);
private static final int BYTE_SIZE = 2;
private static ShortColumnType INSTANCE;
private ShortColumnType(int byteSize, String name, String printerFriendlyName) {
super(byteSize, name, printerFriendlyName);
}
public static ShortColumnType instance() {<FILL_FUNCTION_BODY>}
@Override
public ShortColumn create(String name) {
return ShortColumn.create(name);
}
@Override
public ShortParser customParser(ReadOptions options) {
return new ShortParser(this, options);
}
public static boolean valueIsMissing(int value) {
return value == missingValueIndicator();
}
public static short missingValueIndicator() {
return Short.MIN_VALUE;
}
}
|
if (INSTANCE == null) {
INSTANCE = new ShortColumnType(BYTE_SIZE, "SHORT", "Short");
}
return INSTANCE;
| 238
| 46
| 284
|
<methods>public int byteSize() ,public boolean equals(java.lang.Object) ,public java.lang.String getPrinterFriendlyName() ,public int hashCode() ,public java.lang.String name() ,public java.lang.String toString() <variables>private final non-sealed int byteSize,private final non-sealed java.lang.String name,private final non-sealed java.lang.String printerFriendlyName
|
jtablesaw_tablesaw
|
tablesaw/core/src/main/java/tech/tablesaw/columns/numbers/ShortParser.java
|
ShortParser
|
parseShort
|
class ShortParser extends AbstractColumnParser<Short> {
private final boolean ignoreZeroDecimal;
public ShortParser(ShortColumnType columnType) {
super(columnType);
ignoreZeroDecimal = ReadOptions.DEFAULT_IGNORE_ZERO_DECIMAL;
}
public ShortParser(ShortColumnType columnType, ReadOptions readOptions) {
super(columnType);
if (readOptions.missingValueIndicators().length > 0) {
missingValueStrings = Lists.newArrayList(readOptions.missingValueIndicators());
}
ignoreZeroDecimal = readOptions.ignoreZeroDecimal();
}
@Override
public boolean canParse(String str) {
if (isMissing(str)) {
return true;
}
String s = str;
try {
if (ignoreZeroDecimal) {
s = StringUtils.removeZeroDecimal(s);
}
Short.parseShort(AbstractColumnParser.remove(s, ','));
return true;
} catch (NumberFormatException e) {
// it's all part of the plan
return false;
}
}
@Override
public Short parse(String s) {
return parseShort(s);
}
@Override
public double parseDouble(String s) {
return parseInt(s);
}
@Override
public short parseShort(String str) {<FILL_FUNCTION_BODY>}
}
|
if (isMissing(str)) {
return ShortColumnType.missingValueIndicator();
}
String s = str;
if (ignoreZeroDecimal) {
s = StringUtils.removeZeroDecimal(s);
}
return Short.parseShort(AbstractColumnParser.remove(s, ','));
| 371
| 82
| 453
|
<methods>public void <init>(tech.tablesaw.api.ColumnType) ,public abstract boolean canParse(java.lang.String) ,public tech.tablesaw.api.ColumnType columnType() ,public boolean isMissing(java.lang.String) ,public abstract java.lang.Short parse(java.lang.String) ,public byte parseByte(java.lang.String) ,public double parseDouble(java.lang.String) ,public float parseFloat(java.lang.String) ,public int parseInt(java.lang.String) ,public long parseLong(java.lang.String) ,public short parseShort(java.lang.String) ,public void setMissingValueStrings(List<java.lang.String>) <variables>private final non-sealed tech.tablesaw.api.ColumnType columnType,protected List<java.lang.String> missingValueStrings
|
jtablesaw_tablesaw
|
tablesaw/core/src/main/java/tech/tablesaw/columns/numbers/Stats.java
|
Stats
|
getStats
|
class Stats {
private long n;
private double sum;
private double mean;
private double min;
private double max;
private double variance;
private double standardDeviation;
private double geometricMean;
private double quadraticMean;
private double secondMoment;
private double populationVariance;
private double sumOfLogs;
private double sumOfSquares;
private final String name;
/** Constructs a Stats object with the given name */
private Stats(String name) {
this.name = name;
}
/** Constructs a Stats object from the given column */
public static Stats create(final NumericColumn<?> values) {
SummaryStatistics summaryStatistics = new SummaryStatistics();
for (int i = 0; i < values.size(); i++) {
summaryStatistics.addValue(values.getDouble(i));
}
return getStats(values, summaryStatistics);
}
private static Stats getStats(NumericColumn<?> values, SummaryStatistics summaryStatistics) {<FILL_FUNCTION_BODY>}
/** Returns the range of values in the data */
public double range() {
return (max - min);
}
/** Returns the standard deviation of values in the data */
public double standardDeviation() {
return standardDeviation;
}
/** Returns the number of values in the data */
public long n() {
return n;
}
/** Returns the mean of values in the data */
public double mean() {
return mean;
}
/** Returns the smallest value */
public double min() {
return min;
}
/** Returns the largest value */
public double max() {
return max;
}
/** Returns the sum of the values */
public double sum() {
return sum;
}
/** Returns the sample variance of the values */
public double variance() {
return variance;
}
/** Returns the sum of squares of the values */
public double sumOfSquares() {
return sumOfSquares;
}
/** Returns the population variance of the values */
public double populationVariance() {
return populationVariance;
}
/** Returns the sum of the logs of the values */
public double sumOfLogs() {
return sumOfLogs;
}
/** Returns the geometric mean of the values */
public double geometricMean() {
return geometricMean;
}
/** Returns the quadratic mean of the values */
public double quadraticMean() {
return quadraticMean;
}
/** Returns the second moment of the values */
public double secondMoment() {
return secondMoment;
}
/** Returns the most common calculated statistics in tabular form */
public Table asTable() {
Table t = Table.create(name);
StringColumn measure = StringColumn.create("Measure");
DoubleColumn value = DoubleColumn.create("Value");
t.addColumns(measure);
t.addColumns(value);
measure.append("Count");
value.append(n);
measure.append("sum");
value.append(sum());
measure.append("Mean");
value.append(mean());
measure.append("Min");
value.append(min());
measure.append("Max");
value.append(max());
measure.append("Range");
value.append(range());
measure.append("Variance");
value.append(variance());
measure.append("Std. Dev");
value.append(standardDeviation());
return t;
}
/** Returns all the calculated statistics in tabular form */
public Table asTableComplete() {
Table t = asTable();
StringColumn measure = t.stringColumn("Measure");
DoubleColumn value = t.doubleColumn("Value");
measure.append("Sum of Squares");
value.append(sumOfSquares());
measure.append("Sum of Logs");
value.append(sumOfLogs());
measure.append("Population Variance");
value.append(populationVariance());
measure.append("Geometric Mean");
value.append(geometricMean());
measure.append("Quadratic Mean");
value.append(quadraticMean());
measure.append("Second Moment");
value.append(secondMoment());
return t;
}
}
|
Stats stats = new Stats("Column: " + values.name());
stats.min = summaryStatistics.getMin();
stats.max = summaryStatistics.getMax();
stats.n = summaryStatistics.getN();
stats.sum = summaryStatistics.getSum();
stats.variance = summaryStatistics.getVariance();
stats.populationVariance = summaryStatistics.getPopulationVariance();
stats.quadraticMean = summaryStatistics.getQuadraticMean();
stats.geometricMean = summaryStatistics.getGeometricMean();
stats.mean = summaryStatistics.getMean();
stats.standardDeviation = summaryStatistics.getStandardDeviation();
stats.sumOfLogs = summaryStatistics.getSumOfLogs();
stats.sumOfSquares = summaryStatistics.getSumsq();
stats.secondMoment = summaryStatistics.getSecondMoment();
return stats;
| 1,140
| 238
| 1,378
|
<no_super_class>
|
jtablesaw_tablesaw
|
tablesaw/core/src/main/java/tech/tablesaw/columns/numbers/fillers/DoubleRangeIterable.java
|
DoubleRangeIterable
|
intIterator
|
class DoubleRangeIterable implements Iterable<Double> {
private final double from, to, by;
private final boolean including;
private final int count;
private DoubleRangeIterable(
final double from,
final double to,
final boolean including,
final double by,
final int count) {
this.from = from;
this.to = to;
this.including = including;
this.by = by;
this.count = count;
}
private static DoubleRangeIterable range(
final double from, final double to, final double by, final int count) {
return new DoubleRangeIterable(from, to, false, by, count);
}
public static DoubleRangeIterable range(final double from, final double to, final double by) {
return range(from, to, by, -1);
}
public static DoubleRangeIterable range(final double from, final double to) {
return range(from, to, 1.0);
}
public static DoubleRangeIterable range(final double from, final double by, final int count) {
return range(from, Double.NaN, by, count);
}
public static DoubleRangeIterable range(final double from, final int count) {
return range(from, 1.0, count);
}
public DoubleIterator iterator() {
return new DoubleIterator() {
double next = from;
int num = 0;
@Override
public boolean hasNext() {
return (count < 0 || num < count)
&& (Double.isNaN(to)
|| Math.abs(next - from) < Math.abs(to - from)
|| (including && next == to));
}
@Override
public double nextDouble() {
final double current = next;
next += by;
num++;
return current;
}
};
}
public IntIterator intIterator() {<FILL_FUNCTION_BODY>}
}
|
return new IntIterator() {
int next = (int) from;
int num = 0;
@Override
public boolean hasNext() {
return (count < 0 || num < count)
&& (Double.isNaN(to)
|| Math.abs(next - from) < Math.abs(to - from)
|| (including && next == to));
}
@Override
public int nextInt() {
final int current = next;
next += by;
num++;
return current;
}
};
| 506
| 143
| 649
|
<no_super_class>
|
jtablesaw_tablesaw
|
tablesaw/core/src/main/java/tech/tablesaw/columns/strings/StringColumnFormatter.java
|
StringColumnFormatter
|
toString
|
class StringColumnFormatter extends ColumnFormatter {
private final Function<String, String> formatter;
public StringColumnFormatter() {
super("");
this.formatter = null;
}
public StringColumnFormatter(Function<String, String> formatFunction) {
super("");
this.formatter = formatFunction;
}
public StringColumnFormatter(Function<String, String> formatFunction, String missingString) {
super(missingString);
this.formatter = formatFunction;
}
public String format(String value) {
if (StringColumnType.missingValueIndicator().equals(value)) {
return getMissingString();
}
if (formatter == null) {
return value;
}
return formatter.apply(value);
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return "StringColumnFormatter{"
+ "format="
+ formatter
+ ", missingString='"
+ getMissingString()
+ '\''
+ '}';
| 233
| 50
| 283
|
<methods>public java.lang.String getMissingString() <variables>private final non-sealed java.lang.String missingString
|
jtablesaw_tablesaw
|
tablesaw/core/src/main/java/tech/tablesaw/columns/strings/StringColumnType.java
|
StringColumnType
|
instance
|
class StringColumnType extends AbstractColumnType {
public static final int BYTE_SIZE = 4;
public static final StringParser DEFAULT_PARSER = new StringParser(ColumnType.STRING);
private static StringColumnType INSTANCE;
private StringColumnType(int byteSize, String name, String printerFriendlyName) {
super(byteSize, name, printerFriendlyName);
}
public static StringColumnType instance() {<FILL_FUNCTION_BODY>}
public static boolean valueIsMissing(String string) {
return missingValueIndicator().equals(string);
}
@Override
public StringColumn create(String name) {
return StringColumn.create(name);
}
@Override
public StringParser customParser(ReadOptions options) {
return new StringParser(this, options);
}
public static String missingValueIndicator() {
return "";
}
}
|
if (INSTANCE == null) {
INSTANCE = new StringColumnType(BYTE_SIZE, "STRING", "String");
}
return INSTANCE;
| 232
| 45
| 277
|
<methods>public int byteSize() ,public boolean equals(java.lang.Object) ,public java.lang.String getPrinterFriendlyName() ,public int hashCode() ,public java.lang.String name() ,public java.lang.String toString() <variables>private final non-sealed int byteSize,private final non-sealed java.lang.String name,private final non-sealed java.lang.String printerFriendlyName
|
jtablesaw_tablesaw
|
tablesaw/core/src/main/java/tech/tablesaw/columns/temporal/fillers/TemporalRangeIterable.java
|
TemporalRangeIterable
|
iterator
|
class TemporalRangeIterable<T extends Temporal> implements Iterable<T> {
private final T from, to;
private final long by;
private final TemporalUnit byUnit;
private final boolean including;
private final int count;
private TemporalRangeIterable(
final T from,
final T to,
final boolean including,
final long by,
final TemporalUnit byUnit,
final int count) {
this.from = from;
this.to = to;
this.including = including;
this.by = by;
this.byUnit = byUnit;
this.count = count;
}
private static <T extends Temporal> TemporalRangeIterable<T> range(
final T from, final T to, final long by, final TemporalUnit byUnit, final int count) {
return new TemporalRangeIterable<>(from, to, false, by, byUnit, count);
}
public static <T extends Temporal> TemporalRangeIterable<T> range(
final T from, final T to, final long by, final TemporalUnit byUnit) {
return range(from, to, by, byUnit, -1);
}
public static <T extends Temporal> TemporalRangeIterable<T> range(
final T from, final long by, final TemporalUnit byUnit, final int count) {
return range(from, null, by, byUnit, count);
}
@Override
public Iterator<T> iterator() {<FILL_FUNCTION_BODY>}
}
|
return new Iterator<T>() {
T next = from;
int num = 0;
@Override
public boolean hasNext() {
return (count < 0 || num < count)
&& (to == null || next.until(to, byUnit) > 0 || (including && next.equals(to)));
}
@Override
@SuppressWarnings("unchecked")
public T next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
final T current = next;
next = (T) next.plus(by, byUnit);
num++;
return current;
}
};
| 409
| 171
| 580
|
<no_super_class>
|
jtablesaw_tablesaw
|
tablesaw/core/src/main/java/tech/tablesaw/columns/times/TimeColumnFormatter.java
|
TimeColumnFormatter
|
format
|
class TimeColumnFormatter extends TemporalColumnFormatter {
public TimeColumnFormatter(DateTimeFormatter format) {
super(format);
}
public TimeColumnFormatter() {
super();
}
public TimeColumnFormatter(DateTimeFormatter format, String missingValueString) {
super(format, missingValueString);
}
public String format(int value) {<FILL_FUNCTION_BODY>}
@Override
public String toString() {
return "TimeColumnFormatter{"
+ "format="
+ getFormat()
+ ", missingString='"
+ getMissingString()
+ '\''
+ '}';
}
}
|
DateTimeFormatter format = getFormat();
if (value == TimeColumnType.missingValueIndicator()) {
return getMissingString();
}
if (format == null) {
return toShortTimeString(value);
}
LocalTime time = asLocalTime(value);
if (time == null) {
return "";
}
return format.format(time);
| 177
| 100
| 277
|
<methods>public java.time.format.DateTimeFormatter getFormat() <variables>private final non-sealed java.time.format.DateTimeFormatter format
|
jtablesaw_tablesaw
|
tablesaw/core/src/main/java/tech/tablesaw/columns/times/TimeColumnType.java
|
TimeColumnType
|
instance
|
class TimeColumnType extends AbstractColumnType {
public static final int BYTE_SIZE = 4;
public static final TimeParser DEFAULT_PARSER = new TimeParser(ColumnType.LOCAL_TIME);
private static TimeColumnType INSTANCE;
private TimeColumnType(int byteSize, String name, String printerFriendlyName) {
super(byteSize, name, printerFriendlyName);
}
public static TimeColumnType instance() {<FILL_FUNCTION_BODY>}
public static boolean valueIsMissing(int i) {
return i == missingValueIndicator();
}
@Override
public TimeColumn create(String name) {
return TimeColumn.create(name);
}
@Override
public AbstractColumnParser<LocalTime> customParser(ReadOptions options) {
return new TimeParser(this, options);
}
public static int missingValueIndicator() {
return Integer.MIN_VALUE;
}
}
|
if (INSTANCE == null) {
INSTANCE = new TimeColumnType(BYTE_SIZE, "LOCAL_TIME", "Time");
}
return INSTANCE;
| 244
| 48
| 292
|
<methods>public int byteSize() ,public boolean equals(java.lang.Object) ,public java.lang.String getPrinterFriendlyName() ,public int hashCode() ,public java.lang.String name() ,public java.lang.String toString() <variables>private final non-sealed int byteSize,private final non-sealed java.lang.String name,private final non-sealed java.lang.String printerFriendlyName
|
jtablesaw_tablesaw
|
tablesaw/core/src/main/java/tech/tablesaw/columns/times/TimeParser.java
|
TimeParser
|
canParse
|
class TimeParser extends AbstractColumnParser<LocalTime> {
private static final DateTimeFormatter timef1 = DateTimeFormatter.ofPattern("HH:mm:ss.SSS");
private static final DateTimeFormatter timef2 = DateTimeParser.caseInsensitiveFormatter("hh:mm:ss a");
private static final DateTimeFormatter timef3 = DateTimeParser.caseInsensitiveFormatter("h:mm:ss a");
private static final DateTimeFormatter timef4 = DateTimeFormatter.ISO_LOCAL_TIME;
private static final DateTimeFormatter timef5 = DateTimeParser.caseInsensitiveFormatter("hh:mm a");
private static final DateTimeFormatter timef6 = DateTimeParser.caseInsensitiveFormatter("h:mm a");
// only for parsing:
private static final DateTimeFormatter timef7 = DateTimeFormatter.ofPattern("HHmm");
// A formatter that handles time formats defined above used for type detection.
// It is more conservative than the converter
private static final DateTimeFormatter TIME_DETECTION_FORMATTER =
new DateTimeFormatterBuilder()
.appendOptional(timef5)
.appendOptional(timef2)
.appendOptional(timef3)
.appendOptional(timef1)
.appendOptional(timef4)
.appendOptional(timef6)
.toFormatter();
// A formatter that handles time formats defined above
/**
* A formatter for parsing. Useful when the user has specified that a numeric-like column is
* really supposed to be a time See timef7 definition
*/
private static final DateTimeFormatter TIME_CONVERSION_FORMATTER =
new DateTimeFormatterBuilder()
.appendOptional(timef5)
.appendOptional(timef2)
.appendOptional(timef3)
.appendOptional(timef1)
.appendOptional(timef4)
.appendOptional(timef6)
.appendOptional(timef7)
.toFormatter();
private static final DateTimeFormatter DEFAULT_FORMATTER = TIME_DETECTION_FORMATTER;
private Locale locale = Locale.getDefault();
private DateTimeFormatter formatter = DEFAULT_FORMATTER;
private DateTimeFormatter parserFormatter = TIME_CONVERSION_FORMATTER;
public TimeParser(ColumnType columnType) {
super(columnType);
}
public TimeParser(ColumnType columnType, ReadOptions readOptions) {
super(columnType);
DateTimeFormatter readCsvFormatter = readOptions.timeFormatter();
if (readCsvFormatter != null) {
formatter = readCsvFormatter;
parserFormatter = readCsvFormatter;
}
if (readOptions.locale() != null) {
locale = readOptions.locale();
}
if (readOptions.missingValueIndicators().length > 0) {
missingValueStrings = Lists.newArrayList(readOptions.missingValueIndicators());
}
}
@Override
public boolean canParse(String s) {<FILL_FUNCTION_BODY>}
@Override
public LocalTime parse(String value) {
if (isMissing(value)) {
return null;
}
String paddedValue = Strings.padStart(value, 4, '0');
return LocalTime.parse(paddedValue, parserFormatter);
}
}
|
if (isMissing(s)) {
return true;
}
try {
LocalTime.parse(s, formatter.withLocale(locale));
return true;
} catch (DateTimeParseException e) {
// it's all part of the plan
return false;
}
| 843
| 78
| 921
|
<methods>public void <init>(tech.tablesaw.api.ColumnType) ,public abstract boolean canParse(java.lang.String) ,public tech.tablesaw.api.ColumnType columnType() ,public boolean isMissing(java.lang.String) ,public abstract java.time.LocalTime parse(java.lang.String) ,public byte parseByte(java.lang.String) ,public double parseDouble(java.lang.String) ,public float parseFloat(java.lang.String) ,public int parseInt(java.lang.String) ,public long parseLong(java.lang.String) ,public short parseShort(java.lang.String) ,public void setMissingValueStrings(List<java.lang.String>) <variables>private final non-sealed tech.tablesaw.api.ColumnType columnType,protected List<java.lang.String> missingValueStrings
|
jtablesaw_tablesaw
|
tablesaw/core/src/main/java/tech/tablesaw/conversion/TableConverter.java
|
TableConverter
|
floatMatrix
|
class TableConverter {
private final Relation table;
public TableConverter(Relation table) {
this.table = table;
}
public double[][] doubleMatrix() {
return doubleMatrix(table.numericColumns());
}
public double[][] doubleMatrix(int... columnIndicies) {
return doubleMatrix(table.numericColumns(columnIndicies));
}
public double[][] doubleMatrix(String... columnNames) {
return doubleMatrix(table.numericColumns(columnNames));
}
public float[][] floatMatrix() {
return floatMatrix(table.numericColumns());
}
public float[][] floatMatrix(int... columnIndicies) {
return floatMatrix(table.numericColumns(columnIndicies));
}
public float[][] floatMatrix(String... columnNames) {
return floatMatrix(table.numericColumns(columnNames));
}
public int[][] intMatrix() {
return intMatrix(table.numericColumns());
}
public int[][] intMatrix(int... columnIndicies) {
return intMatrix(table.numericColumns(columnIndicies));
}
public int[][] intMatrix(String... columnNames) {
return intMatrix(table.numericColumns(columnNames));
}
private static double[][] doubleMatrix(List<NumericColumn<?>> numberColumns) {
Preconditions.checkArgument(!numberColumns.isEmpty());
int obs = numberColumns.get(0).size();
double[][] allVals = new double[obs][numberColumns.size()];
for (int r = 0; r < obs; r++) {
for (int c = 0; c < numberColumns.size(); c++) {
allVals[r][c] = numberColumns.get(c).getDouble(r);
}
}
return allVals;
}
private static float[][] floatMatrix(List<NumericColumn<?>> numberColumns) {<FILL_FUNCTION_BODY>}
private static int[][] intMatrix(List<NumericColumn<?>> numberColumns) {
Preconditions.checkArgument(!numberColumns.isEmpty());
int obs = numberColumns.get(0).size();
int[][] allVals = new int[obs][numberColumns.size()];
for (int r = 0; r < obs; r++) {
for (int c = 0; c < numberColumns.size(); c++) {
allVals[r][c] = (int) numberColumns.get(c).getDouble(r);
}
}
return allVals;
}
}
|
Preconditions.checkArgument(!numberColumns.isEmpty());
int obs = numberColumns.get(0).size();
float[][] allVals = new float[obs][numberColumns.size()];
for (int r = 0; r < obs; r++) {
for (int c = 0; c < numberColumns.size(); c++) {
allVals[r][c] = (float) numberColumns.get(c).getDouble(r);
}
}
return allVals;
| 665
| 127
| 792
|
<no_super_class>
|
jtablesaw_tablesaw
|
tablesaw/core/src/main/java/tech/tablesaw/conversion/smile/SmileConverter.java
|
SmileConverter
|
toDataFrame
|
class SmileConverter {
private final Relation table;
public SmileConverter(Relation table) {
this.table = table;
}
public DataFrame toDataFrame() {
StructType schema =
DataTypes.struct(
table.columns().stream()
.map(col -> new StructField(col.name(), toSmileType(col.type())))
.collect(Collectors.toList()));
return toDataFrame(schema);
}
public DataFrame toDataFrame(StructType schema) {<FILL_FUNCTION_BODY>}
private DataType toSmileType(ColumnType type) {
if (type.equals(ColumnType.BOOLEAN)) {
return DataTypes.BooleanType;
} else if (type.equals(ColumnType.DOUBLE)) {
return DataTypes.DoubleType;
} else if (type.equals(ColumnType.FLOAT)) {
return DataTypes.FloatType;
} else if (type.equals(ColumnType.INSTANT)) {
return DataTypes.DateTimeType;
} else if (type.equals(ColumnType.INTEGER)) {
return DataTypes.IntegerType;
} else if (type.equals(ColumnType.LOCAL_DATE)) {
return DataTypes.DateType;
} else if (type.equals(ColumnType.LOCAL_DATE_TIME)) {
return DataTypes.DateTimeType;
} else if (type.equals(ColumnType.LOCAL_TIME)) {
return DataTypes.TimeType;
} else if (type.equals(ColumnType.LONG)) {
return DataTypes.LongType;
} else if (type.equals(ColumnType.SHORT)) {
return DataTypes.ShortType;
} else if (type.equals(ColumnType.STRING)) {
return DataTypes.StringType;
}
throw new IllegalStateException("Unsupported column type " + type);
}
}
|
List<Tuple> rows = new ArrayList<>();
int colCount = table.columnCount();
for (int rowIndex = 0; rowIndex < table.rowCount(); rowIndex++) {
Object[] row = new Object[colCount];
for (int colIndex = 0; colIndex < colCount; colIndex++) {
Column<?> col = table.column(colIndex);
if (!col.isMissing(rowIndex)) {
row[colIndex] =
col.type().equals(ColumnType.INSTANT)
? LocalDateTime.ofInstant(((InstantColumn) col).get(rowIndex), ZoneOffset.UTC)
: col.get(rowIndex);
}
}
rows.add(Tuple.of(row, schema));
}
return DataFrame.of(rows, schema.boxed(rows));
| 483
| 213
| 696
|
<no_super_class>
|
jtablesaw_tablesaw
|
tablesaw/core/src/main/java/tech/tablesaw/filtering/And.java
|
And
|
apply
|
class And implements Function<Table, Selection> {
private Function<Table, Selection>[] arguments;
@SafeVarargs
public And(Function<Table, Selection>... arguments) {
Preconditions.checkNotNull(arguments, "The arguments to And must be non-null");
Preconditions.checkArgument(
arguments.length > 0, "The arguments to And must be an array of length 1 or greater");
this.arguments = arguments;
}
@Override
public Selection apply(Table table) {<FILL_FUNCTION_BODY>}
}
|
Selection result = arguments[0].apply(table);
for (int i = 1; i < arguments.length; i++) {
result.and(arguments[i].apply(table));
}
return result;
| 143
| 58
| 201
|
<no_super_class>
|
jtablesaw_tablesaw
|
tablesaw/core/src/main/java/tech/tablesaw/filtering/Or.java
|
Or
|
apply
|
class Or implements Function<Table, Selection> {
private Function<Table, Selection>[] arguments;
@SafeVarargs
public Or(Function<Table, Selection>... arguments) {
Preconditions.checkNotNull(arguments, "The arguments to Or must be non-null");
Preconditions.checkArgument(
arguments.length > 0, "The arguments to Or must be an array of length 1 or greater");
this.arguments = arguments;
}
@Override
public Selection apply(Table table) {<FILL_FUNCTION_BODY>}
}
|
Selection result = arguments[0].apply(table);
for (int i = 1; i < arguments.length; i++) {
result.or(arguments[i].apply(table));
}
return result;
| 143
| 58
| 201
|
<no_super_class>
|
jtablesaw_tablesaw
|
tablesaw/core/src/main/java/tech/tablesaw/index/ByteIndex.java
|
ByteIndex
|
greaterThan
|
class ByteIndex implements Index {
private final Byte2ObjectAVLTreeMap<IntArrayList> index;
/** Constructs an index for the given column */
public ByteIndex(BooleanColumn column) {
Preconditions.checkArgument(
column.type().equals(ColumnType.BOOLEAN), "Byte indexing only allowed on BOOLEAN columns");
int sizeEstimate = Integer.min(1_000_000, column.size() / 100);
Byte2ObjectOpenHashMap<IntArrayList> tempMap = new Byte2ObjectOpenHashMap<>(sizeEstimate);
for (int i = 0; i < column.size(); i++) {
byte value = column.getByte(i);
IntArrayList recordIds = tempMap.get(value);
if (recordIds == null) {
recordIds = new IntArrayList();
recordIds.add(i);
tempMap.trim();
tempMap.put(value, recordIds);
} else {
recordIds.add(i);
}
}
index = new Byte2ObjectAVLTreeMap<>(tempMap);
}
private static void addAllToSelection(IntArrayList tableKeys, Selection selection) {
for (int i : tableKeys) {
selection.add(i);
}
}
/**
* Returns a bitmap containing row numbers of all cells matching the given int
*
* @param value This is a 'key' from the index perspective, meaning it is a value from the
* standpoint of the column
*/
public Selection get(byte value) {
Selection selection = new BitmapBackedSelection();
IntArrayList list = index.get(value);
if (list != null) {
addAllToSelection(list, selection);
}
return selection;
}
/** Returns a {@link Selection} of all values at least as large as the given value */
public Selection atLeast(byte value) {
Selection selection = new BitmapBackedSelection();
Byte2ObjectSortedMap<IntArrayList> tail = index.tailMap(value);
for (IntArrayList keys : tail.values()) {
addAllToSelection(keys, selection);
}
return selection;
}
/** Returns a {@link Selection} of all values greater than the given value */
public Selection greaterThan(byte value) {<FILL_FUNCTION_BODY>}
/** Returns a {@link Selection} of all values at most as large as the given value */
public Selection atMost(byte value) {
Selection selection = new BitmapBackedSelection();
Byte2ObjectSortedMap<IntArrayList> head =
index.headMap((byte) (value + 1)); // we add 1 to get values equal to the arg
for (IntArrayList keys : head.values()) {
addAllToSelection(keys, selection);
}
return selection;
}
/** Returns a {@link Selection} of all values less than the given value */
public Selection lessThan(byte value) {
Selection selection = new BitmapBackedSelection();
Byte2ObjectSortedMap<IntArrayList> head =
index.headMap(value); // we add 1 to get values equal to the arg
for (IntArrayList keys : head.values()) {
addAllToSelection(keys, selection);
}
return selection;
}
}
|
Selection selection = new BitmapBackedSelection();
Byte2ObjectSortedMap<IntArrayList> tail = index.tailMap((byte) (value + 1));
for (IntArrayList keys : tail.values()) {
addAllToSelection(keys, selection);
}
return selection;
| 842
| 74
| 916
|
<no_super_class>
|
jtablesaw_tablesaw
|
tablesaw/core/src/main/java/tech/tablesaw/index/DoubleIndex.java
|
DoubleIndex
|
atLeast
|
class DoubleIndex implements Index {
private final Double2ObjectAVLTreeMap<IntArrayList> index;
/** Constructs an index for the given column */
public DoubleIndex(DoubleColumn column) {
int sizeEstimate = Integer.min(1_000_000, column.size() / 100);
Double2ObjectOpenHashMap<IntArrayList> tempMap = new Double2ObjectOpenHashMap<>(sizeEstimate);
for (int i = 0; i < column.size(); i++) {
double value = column.getDouble(i);
IntArrayList recordIds = tempMap.get(value);
if (recordIds == null) {
recordIds = new IntArrayList();
recordIds.add(i);
tempMap.trim();
tempMap.put(value, recordIds);
} else {
recordIds.add(i);
}
}
index = new Double2ObjectAVLTreeMap<>(tempMap);
}
private static void addAllToSelection(IntArrayList tableKeys, Selection selection) {
for (int i : tableKeys) {
selection.add(i);
}
}
/**
* Returns a bitmap containing row numbers of all cells matching the given int
*
* @param value This is a 'key' from the index perspective, meaning it is a value from the
* standpoint of the column
*/
public Selection get(double value) {
Selection selection = new BitmapBackedSelection();
IntArrayList list = index.get(value);
if (list != null) {
addAllToSelection(list, selection);
}
return selection;
}
/** Returns a {@link Selection} of all values at least as large as the given value */
public Selection atLeast(double value) {<FILL_FUNCTION_BODY>}
/** Returns a {@link Selection} of all values greater than the given value */
public Selection greaterThan(double value) {
Selection selection = new BitmapBackedSelection();
Double2ObjectSortedMap<IntArrayList> tail = index.tailMap(value + 0.000001);
for (IntArrayList keys : tail.values()) {
addAllToSelection(keys, selection);
}
return selection;
}
/** Returns a {@link Selection} of all values at most as large as the given value */
public Selection atMost(double value) {
Selection selection = new BitmapBackedSelection();
Double2ObjectSortedMap<IntArrayList> head =
index.headMap(value + 0.000001); // we add 1 to get values equal
// to the arg
for (IntArrayList keys : head.values()) {
addAllToSelection(keys, selection);
}
return selection;
}
/** Returns a {@link Selection} of all values less than the given value */
public Selection lessThan(double value) {
Selection selection = new BitmapBackedSelection();
Double2ObjectSortedMap<IntArrayList> head = index.headMap(value);
for (IntArrayList keys : head.values()) {
addAllToSelection(keys, selection);
}
return selection;
}
}
|
Selection selection = new BitmapBackedSelection();
Double2ObjectSortedMap<IntArrayList> tail = index.tailMap(value);
for (IntArrayList keys : tail.values()) {
addAllToSelection(keys, selection);
}
return selection;
| 807
| 69
| 876
|
<no_super_class>
|
jtablesaw_tablesaw
|
tablesaw/core/src/main/java/tech/tablesaw/index/FloatIndex.java
|
FloatIndex
|
greaterThan
|
class FloatIndex implements Index {
private final Float2ObjectAVLTreeMap<IntArrayList> index;
/** Constructs an index for the given column */
public FloatIndex(FloatColumn column) {
int sizeEstimate = Integer.min(1_000_000, column.size() / 100);
Float2ObjectOpenHashMap<IntArrayList> tempMap = new Float2ObjectOpenHashMap<>(sizeEstimate);
for (int i = 0; i < column.size(); i++) {
float value = column.getFloat(i);
IntArrayList recordIds = tempMap.get(value);
if (recordIds == null) {
recordIds = new IntArrayList();
recordIds.add(i);
tempMap.trim();
tempMap.put(value, recordIds);
} else {
recordIds.add(i);
}
}
index = new Float2ObjectAVLTreeMap<>(tempMap);
}
private static void addAllToSelection(IntArrayList tableKeys, Selection selection) {
for (int i : tableKeys) {
selection.add(i);
}
}
/**
* Returns a bitmap containing row numbers of all cells matching the given int
*
* @param value This is a 'key' from the index perspective, meaning it is a value from the
* standpoint of the column
*/
public Selection get(float value) {
Selection selection = new BitmapBackedSelection();
IntArrayList list = index.get(value);
if (list != null) {
addAllToSelection(list, selection);
}
return selection;
}
/** Returns a {@link Selection} of all values at least as large as the given value */
public Selection atLeast(float value) {
Selection selection = new BitmapBackedSelection();
Float2ObjectSortedMap<IntArrayList> tail = index.tailMap(value);
for (IntArrayList keys : tail.values()) {
addAllToSelection(keys, selection);
}
return selection;
}
/** Returns a {@link Selection} of all values greater than the given value */
public Selection greaterThan(float value) {<FILL_FUNCTION_BODY>}
/** Returns a {@link Selection} of all values at most as large as the given value */
public Selection atMost(float value) {
Selection selection = new BitmapBackedSelection();
Float2ObjectSortedMap<IntArrayList> head =
index.headMap(value + 0.000001f); // we add 1 to get values equal
// to the arg
for (IntArrayList keys : head.values()) {
addAllToSelection(keys, selection);
}
return selection;
}
/** Returns a {@link Selection} of all values less than the given value */
public Selection lessThan(float value) {
Selection selection = new BitmapBackedSelection();
Float2ObjectSortedMap<IntArrayList> head = index.headMap(value);
for (IntArrayList keys : head.values()) {
addAllToSelection(keys, selection);
}
return selection;
}
}
|
Selection selection = new BitmapBackedSelection();
Float2ObjectSortedMap<IntArrayList> tail = index.tailMap(value + 0.000001f);
for (IntArrayList keys : tail.values()) {
addAllToSelection(keys, selection);
}
return selection;
| 808
| 80
| 888
|
<no_super_class>
|
jtablesaw_tablesaw
|
tablesaw/core/src/main/java/tech/tablesaw/index/IntIndex.java
|
IntIndex
|
atMost
|
class IntIndex implements Index {
private final Int2ObjectAVLTreeMap<IntArrayList> index;
/** Constructs an index for the given column */
public IntIndex(DateColumn column) {
int sizeEstimate = Integer.min(1_000_000, column.size() / 100);
Int2ObjectOpenHashMap<IntArrayList> tempMap = new Int2ObjectOpenHashMap<>(sizeEstimate);
for (int i = 0; i < column.size(); i++) {
int value = column.getIntInternal(i);
IntArrayList recordIds = tempMap.get(value);
if (recordIds == null) {
recordIds = new IntArrayList();
recordIds.add(i);
tempMap.trim();
tempMap.put(value, recordIds);
} else {
recordIds.add(i);
}
}
index = new Int2ObjectAVLTreeMap<>(tempMap);
}
/** Constructs an index for the given column */
public IntIndex(IntColumn column) {
Preconditions.checkArgument(
column.type().equals(ColumnType.INTEGER),
"Int indexing only allowed on INTEGER numeric columns");
int sizeEstimate = Integer.min(1_000_000, column.size() / 100);
Int2ObjectOpenHashMap<IntArrayList> tempMap = new Int2ObjectOpenHashMap<>(sizeEstimate);
for (int i = 0; i < column.size(); i++) {
int value = column.getInt(i);
IntArrayList recordIds = tempMap.get(value);
if (recordIds == null) {
recordIds = new IntArrayList();
recordIds.add(i);
tempMap.trim();
tempMap.put(value, recordIds);
} else {
recordIds.add(i);
}
}
index = new Int2ObjectAVLTreeMap<>(tempMap);
}
/** Constructs an index for the given column */
public IntIndex(TimeColumn column) {
int sizeEstimate = Integer.min(1_000_000, column.size() / 100);
Int2ObjectOpenHashMap<IntArrayList> tempMap = new Int2ObjectOpenHashMap<>(sizeEstimate);
for (int i = 0; i < column.size(); i++) {
int value = column.getIntInternal(i);
IntArrayList recordIds = tempMap.get(value);
if (recordIds == null) {
recordIds = new IntArrayList();
recordIds.add(i);
tempMap.trim();
tempMap.put(value, recordIds);
} else {
recordIds.add(i);
}
}
index = new Int2ObjectAVLTreeMap<>(tempMap);
}
private static void addAllToSelection(IntArrayList tableKeys, Selection selection) {
for (int i : tableKeys) {
selection.add(i);
}
}
/**
* Returns a bitmap {@link Selection} containing row numbers of all cells matching the given int
*
* @param value This is a 'key' from the index perspective, meaning it is a value from the
* standpoint of the column
*/
public Selection get(int value) {
Selection selection = new BitmapBackedSelection();
IntArrayList list = index.get(value);
if (list != null) {
addAllToSelection(list, selection);
}
return selection;
}
/** Returns the {@link Selection} of all values exactly equal to the given value */
public Selection get(LocalTime value) {
return get(PackedLocalTime.pack(value));
}
/** Returns the {@link Selection} of all values exactly equal to the given value */
public Selection get(LocalDate value) {
return get(PackedLocalDate.pack(value));
}
/** Returns a {@link Selection} of all values at least as large as the given value */
public Selection atLeast(int value) {
Selection selection = new BitmapBackedSelection();
Int2ObjectSortedMap<IntArrayList> tail = index.tailMap(value);
for (IntArrayList keys : tail.values()) {
addAllToSelection(keys, selection);
}
return selection;
}
/** Returns a {@link Selection} of all values at least as large as the given value */
public Selection atLeast(LocalTime value) {
return atLeast(PackedLocalTime.pack(value));
}
/** Returns a {@link Selection} of all values at least as large as the given value */
public Selection atLeast(LocalDate value) {
return atLeast(PackedLocalDate.pack(value));
}
/** Returns a {@link Selection} of all values greater than the given value */
public Selection greaterThan(int value) {
Selection selection = new BitmapBackedSelection();
Int2ObjectSortedMap<IntArrayList> tail = index.tailMap(value + 1);
for (IntArrayList keys : tail.values()) {
addAllToSelection(keys, selection);
}
return selection;
}
/** Returns a {@link Selection} of all values greater than the given value */
public Selection greaterThan(LocalTime value) {
return greaterThan(PackedLocalTime.pack(value));
}
/** Returns a {@link Selection} of all values greater than the given value */
public Selection greaterThan(LocalDate value) {
return greaterThan(PackedLocalDate.pack(value));
}
/** Returns a {@link Selection} of all values at most as large as the given value */
public Selection atMost(int value) {<FILL_FUNCTION_BODY>}
/** Returns a {@link Selection} of all values at most as large as the given value */
public Selection atMost(LocalTime value) {
return atMost(PackedLocalTime.pack(value));
}
/** Returns a {@link Selection} of all values at most as large as the given value */
public Selection atMost(LocalDate value) {
return atMost(PackedLocalDate.pack(value));
}
/** Returns a {@link Selection} of all values less than the given value */
public Selection lessThan(int value) {
Selection selection = new BitmapBackedSelection();
Int2ObjectSortedMap<IntArrayList> head =
index.headMap(value); // we add 1 to get values equal to the arg
for (IntArrayList keys : head.values()) {
addAllToSelection(keys, selection);
}
return selection;
}
/** Returns a {@link Selection} of all values less than the given value */
public Selection lessThan(LocalTime value) {
return lessThan(PackedLocalTime.pack(value));
}
/** Returns a {@link Selection} of all values less than the given value */
public Selection lessThan(LocalDate value) {
return lessThan(PackedLocalDate.pack(value));
}
}
|
Selection selection = new BitmapBackedSelection();
Int2ObjectSortedMap<IntArrayList> head =
index.headMap(value + 1); // we add 1 to get values equal to the arg
for (IntArrayList keys : head.values()) {
addAllToSelection(keys, selection);
}
return selection;
| 1,796
| 85
| 1,881
|
<no_super_class>
|
jtablesaw_tablesaw
|
tablesaw/core/src/main/java/tech/tablesaw/index/LongIndex.java
|
LongIndex
|
get
|
class LongIndex implements Index {
private final Long2ObjectAVLTreeMap<IntArrayList> index;
/** Constructs an index for the given column */
public LongIndex(TemporalColumn<?> column) {
int sizeEstimate = Integer.min(1_000_000, column.size() / 100);
Long2ObjectOpenHashMap<IntArrayList> tempMap = new Long2ObjectOpenHashMap<>(sizeEstimate);
for (int i = 0; i < column.size(); i++) {
long value = column.getLongInternal(i);
IntArrayList recordIds = tempMap.get(value);
if (recordIds == null) {
recordIds = new IntArrayList();
recordIds.add(i);
tempMap.trim();
tempMap.put(value, recordIds);
} else {
recordIds.add(i);
}
}
index = new Long2ObjectAVLTreeMap<>(tempMap);
}
/** Constructs an index for the given column */
public LongIndex(LongColumn column) {
int sizeEstimate = Integer.min(1_000_000, column.size() / 100);
Long2ObjectOpenHashMap<IntArrayList> tempMap = new Long2ObjectOpenHashMap<>(sizeEstimate);
for (int i = 0; i < column.size(); i++) {
long value = column.getLong(i);
IntArrayList recordIds = tempMap.get(value);
if (recordIds == null) {
recordIds = new IntArrayList();
recordIds.add(i);
tempMap.trim();
tempMap.put(value, recordIds);
} else {
recordIds.add(i);
}
}
index = new Long2ObjectAVLTreeMap<>(tempMap);
}
private static void addAllToSelection(IntArrayList tableKeys, Selection selection) {
for (int i : tableKeys) {
selection.add(i);
}
}
/**
* Returns a bitmap containing row numbers of all cells matching the given long
*
* @param value This is a 'key' from the index perspective, meaning it is a value from the
* standpoint of the column
*/
public Selection get(long value) {<FILL_FUNCTION_BODY>}
/** Returns the {@link Selection} of all values exactly equal to the given value */
public Selection get(Instant value) {
return get(PackedInstant.pack(value));
}
/** Returns the {@link Selection} of all values exactly equal to the given value */
public Selection get(LocalDateTime value) {
return get(PackedLocalDateTime.pack(value));
}
/** Returns a {@link Selection} of all values at least as large as the given value */
public Selection atLeast(long value) {
Selection selection = new BitmapBackedSelection();
Long2ObjectSortedMap<IntArrayList> tail = index.tailMap(value);
for (IntArrayList keys : tail.values()) {
addAllToSelection(keys, selection);
}
return selection;
}
/** Returns a {@link Selection} of all values at least as large as the given value */
public Selection atLeast(Instant value) {
return atLeast(PackedInstant.pack(value));
}
/** Returns a {@link Selection} of all values at least as large as the given value */
public Selection atLeast(LocalDateTime value) {
return atLeast(PackedLocalDateTime.pack(value));
}
/** Returns a {@link Selection} of all values greater than the given value */
public Selection greaterThan(long value) {
Selection selection = new BitmapBackedSelection();
Long2ObjectSortedMap<IntArrayList> tail = index.tailMap(value + 1);
for (IntArrayList keys : tail.values()) {
addAllToSelection(keys, selection);
}
return selection;
}
/** Returns a {@link Selection} of all values greater than the given value */
public Selection greaterThan(Instant value) {
return greaterThan(PackedInstant.pack(value));
}
/** Returns a {@link Selection} of all values greater than the given value */
public Selection greaterThan(LocalDateTime value) {
return greaterThan(PackedLocalDateTime.pack(value));
}
/** Returns a {@link Selection} of all values at most as large as the given value */
public Selection atMost(long value) {
Selection selection = new BitmapBackedSelection();
Long2ObjectSortedMap<IntArrayList> head =
index.headMap(value + 1); // we add 1 to get values equal to the arg
for (IntArrayList keys : head.values()) {
addAllToSelection(keys, selection);
}
return selection;
}
/** Returns a {@link Selection} of all values at most as large as the given value */
public Selection atMost(Instant value) {
return atMost(PackedInstant.pack(value));
}
/** Returns a {@link Selection} of all values at most as large as the given value */
public Selection atMost(LocalDateTime value) {
return atMost(PackedLocalDateTime.pack(value));
}
/** Returns a {@link Selection} of all values less than the given value */
public Selection lessThan(long value) {
Selection selection = new BitmapBackedSelection();
Long2ObjectSortedMap<IntArrayList> head =
index.headMap(value); // we add 1 to get values equal to the arg
for (IntArrayList keys : head.values()) {
addAllToSelection(keys, selection);
}
return selection;
}
/** Returns a {@link Selection} of all values less than the given value */
public Selection lessThan(Instant value) {
return lessThan(PackedInstant.pack(value));
}
/** Returns a {@link Selection} of all values less than the given value */
public Selection lessThan(LocalDateTime value) {
return lessThan(PackedLocalDateTime.pack(value));
}
}
|
Selection selection = new BitmapBackedSelection();
IntArrayList list = index.get(value);
if (list != null) {
addAllToSelection(list, selection);
}
return selection;
| 1,569
| 57
| 1,626
|
<no_super_class>
|
jtablesaw_tablesaw
|
tablesaw/core/src/main/java/tech/tablesaw/index/ShortIndex.java
|
ShortIndex
|
lessThan
|
class ShortIndex implements Index {
private final Short2ObjectAVLTreeMap<IntArrayList> index;
/** Constructs an index for the given column */
public ShortIndex(ShortColumn column) {
Preconditions.checkArgument(
column.type().equals(ShortColumnType.instance()),
"Short indexing only allowed on SHORT numeric columns");
int sizeEstimate = Integer.min(1_000_000, column.size() / 100);
Short2ObjectOpenHashMap<IntArrayList> tempMap = new Short2ObjectOpenHashMap<>(sizeEstimate);
for (int i = 0; i < column.size(); i++) {
short value = column.getShort(i);
IntArrayList recordIds = tempMap.get(value);
if (recordIds == null) {
recordIds = new IntArrayList();
recordIds.add(i);
tempMap.trim();
tempMap.put(value, recordIds);
} else {
recordIds.add(i);
}
}
index = new Short2ObjectAVLTreeMap<>(tempMap);
}
private static void addAllToSelection(IntArrayList tableKeys, Selection selection) {
for (int i : tableKeys) {
selection.add(i);
}
}
/**
* Returns a bitmap containing row numbers of all cells matching the given int
*
* @param value This is a 'key' from the index perspective, meaning it is a value from the
* standpoint of the column
*/
public Selection get(short value) {
Selection selection = new BitmapBackedSelection();
IntArrayList list = index.get(value);
if (list != null) {
addAllToSelection(list, selection);
}
return selection;
}
/** Returns a {@link Selection} of all values at least as large as the given value */
public Selection atLeast(short value) {
Selection selection = new BitmapBackedSelection();
Short2ObjectSortedMap<IntArrayList> tail = index.tailMap(value);
for (IntArrayList keys : tail.values()) {
addAllToSelection(keys, selection);
}
return selection;
}
/** Returns a {@link Selection} of all values greater than the given value */
public Selection greaterThan(short value) {
Selection selection = new BitmapBackedSelection();
Short2ObjectSortedMap<IntArrayList> tail = index.tailMap((short) (value + 1));
for (IntArrayList keys : tail.values()) {
addAllToSelection(keys, selection);
}
return selection;
}
/** Returns a {@link Selection} of all values at most as large as the given value */
public Selection atMost(short value) {
Selection selection = new BitmapBackedSelection();
Short2ObjectSortedMap<IntArrayList> head =
index.headMap((short) (value + 1)); // we add 1 to get values equal to the arg
for (IntArrayList keys : head.values()) {
addAllToSelection(keys, selection);
}
return selection;
}
/** Returns a {@link Selection} of all values less than the given value */
public Selection lessThan(short value) {<FILL_FUNCTION_BODY>}
}
|
Selection selection = new BitmapBackedSelection();
Short2ObjectSortedMap<IntArrayList> head =
index.headMap(value); // we add 1 to get values equal to the arg
for (IntArrayList keys : head.values()) {
addAllToSelection(keys, selection);
}
return selection;
| 833
| 83
| 916
|
<no_super_class>
|
jtablesaw_tablesaw
|
tablesaw/core/src/main/java/tech/tablesaw/index/StringIndex.java
|
StringIndex
|
get
|
class StringIndex implements Index {
private final Map<String, IntArrayList> index;
/** Creates an index on the given AbstractStringColumn */
public StringIndex(StringColumn column) {
int sizeEstimate = Integer.min(1_000_000, column.size() / 100);
Map<String, IntArrayList> tempMap = new HashMap<>(sizeEstimate);
for (int i = 0; i < column.size(); i++) {
String value = column.get(i);
IntArrayList recordIds = tempMap.get(value);
if (recordIds == null) {
recordIds = new IntArrayList();
recordIds.add(i);
tempMap.put(value, recordIds);
} else {
recordIds.add(i);
}
}
index = new HashMap<>(tempMap);
}
private static void addAllToSelection(IntArrayList tableKeys, Selection selection) {
for (int i : tableKeys) {
selection.add(i);
}
}
/**
* Returns a bitmap {@link Selection} containing row numbers of all cells matching the given int
*
* @param value This is a 'key' from the index perspective, meaning it is a value from the
* standpoint of the column
*/
public Selection get(String value) {<FILL_FUNCTION_BODY>}
}
|
Selection selection = new BitmapBackedSelection();
IntArrayList list = index.get(value);
if (list != null) {
addAllToSelection(list, selection);
}
return selection;
| 354
| 57
| 411
|
<no_super_class>
|
jtablesaw_tablesaw
|
tablesaw/core/src/main/java/tech/tablesaw/interpolation/Interpolator.java
|
Interpolator
|
frontfill
|
class Interpolator<T> {
/** The column being interpolated */
protected final Column<T> col;
/** Constructs an object for performing interpolation on the given column */
public Interpolator(Column<T> column) {
this.col = column;
}
/** Fills missing values with the next non-missing value */
public Column<T> backfill() {
Column<T> result = col.copy();
T lastVal = null;
for (int i = col.size() - 1; i >= 0; i--) {
if (col.isMissing(i)) {
if (lastVal != null) {
result.set(i, lastVal);
}
} else {
lastVal = col.get(i);
}
}
return result;
}
/** Fills missing values with the last non-missing value */
public Column<T> frontfill() {<FILL_FUNCTION_BODY>}
}
|
Column<T> result = col.copy();
T lastVal = null;
for (int i = 0; i < col.size(); i++) {
if (col.isMissing(i)) {
if (lastVal != null) {
result.set(i, lastVal);
}
} else {
lastVal = col.get(i);
}
}
return result;
| 251
| 106
| 357
|
<no_super_class>
|
jtablesaw_tablesaw
|
tablesaw/core/src/main/java/tech/tablesaw/io/AddCellToColumnException.java
|
AddCellToColumnException
|
dumpRow
|
class AddCellToColumnException extends RuntimeException {
private static final long serialVersionUID = 1L;
/** The index of the column that threw the Exception */
private final int columnIndex;
/** The number of the row that caused the exception to be thrown */
private final long rowNumber;
/** The column names stored as an array */
private final List<String> columnNames;
/** The original line that caused the Exception */
private final String[] line;
/**
* Creates a new instance of this Exception
*
* @param e The Exception that caused adding to fail
* @param columnIndex The index of the column that threw the Exception
* @param rowNumber The number of the row that caused the Exception to be thrown
* @param columnNames The column names stored as an array
* @param line The original line that caused the Exception
*/
public AddCellToColumnException(
Exception e, int columnIndex, long rowNumber, List<String> columnNames, String[] line) {
super(
"Error while adding cell from row "
+ rowNumber
+ " and column "
+ columnNames.get(columnIndex)
+ ""
+ "(position:"
+ columnIndex
+ "): "
+ e.getMessage(),
e);
this.columnIndex = columnIndex;
this.rowNumber = rowNumber;
this.columnNames = columnNames;
this.line = line;
}
/** Returns the index of the column that threw the Exception */
public int getColumnIndex() {
return columnIndex;
}
/** Returns the number of the row that caused the Exception to be thrown */
public long getRowNumber() {
return rowNumber;
}
/** Returns the column names array */
public List<String> getColumnNames() {
return columnNames;
}
/** Returns the name of the column that caused the Exception */
public String getColumnName() {
return columnNames.get(columnIndex);
}
/**
* Dumps to a PrintStream the information relative to the row that caused the problem
*
* @param out The PrintStream to output to
*/
public void dumpRow(PrintStream out) {<FILL_FUNCTION_BODY>}
}
|
for (int i = 0; i < columnNames.size(); i++) {
out.print("Column ");
out.print(i);
out.print(" ");
out.print(columnNames.get(columnIndex));
out.print(" : ");
try {
out.println(line[i]);
} catch (ArrayIndexOutOfBoundsException aioobe) {
out.println("Unable to get cell " + i + " of this line");
}
}
| 561
| 124
| 685
|
<methods>public void <init>() ,public void <init>(java.lang.String) ,public void <init>(java.lang.Throwable) ,public void <init>(java.lang.String, java.lang.Throwable) <variables>static final long serialVersionUID
|
jtablesaw_tablesaw
|
tablesaw/core/src/main/java/tech/tablesaw/io/DataFrameReader.java
|
DataFrameReader
|
string
|
class DataFrameReader {
private final ReaderRegistry registry;
public DataFrameReader(ReaderRegistry registry) {
this.registry = registry;
}
/**
* Reads the given URL into a table using default options Uses appropriate converter based on
* mime-type Use {@link #usingOptions(ReadOptions) usingOptions} to use non-default options
*/
public Table url(String url) {
try {
return url(new URL(url));
} catch (IOException e) {
throw new RuntimeIOException(e);
}
}
/**
* Reads the given URL into a table using default options Uses appropriate converter based on
* mime-type Use {@link #usingOptions(ReadOptions) usingOptions} to use non-default options
*/
public Table url(URL url) {
URLConnection connection = null;
try {
connection = url.openConnection();
} catch (IOException e) {
e.printStackTrace();
}
String contentType = connection.getContentType();
return url(url, getCharset(contentType), getMimeType(contentType));
}
private Table url(URL url, Charset charset, String mimeType) {
Optional<DataReader<?>> reader = registry.getReaderForMimeType(mimeType);
if (reader.isPresent()) {
return readUrl(url, charset, reader.get());
}
reader = registry.getReaderForExtension(getExtension(url));
if (reader.isPresent()) {
return readUrl(url, charset, reader.get());
}
throw new IllegalArgumentException("No reader registered for mime-type " + mimeType);
}
private Table readUrl(URL url, Charset charset, DataReader<?> reader) {
try {
return reader.read(new Source(url.openConnection().getInputStream(), charset));
} catch (IOException e) {
throw new RuntimeIOException(e);
}
}
private String getMimeType(String contentType) {
String[] pair = contentType.split(";");
return pair[0].trim();
}
private Charset getCharset(String contentType) {
String[] pair = contentType.split(";");
return pair.length == 1
? Charset.defaultCharset()
: Charset.forName(pair[1].split("=")[1].trim());
}
/**
* Best effort method to get the extension from a URL.
*
* @param url the url to pull the extension from.
* @return the extension.
*/
private String getExtension(URL url) {
return Files.getFileExtension(url.getPath());
}
/**
* Reads the given string contents into a table using default options Uses converter specified
* based on given file extension Use {@link #usingOptions(ReadOptions) usingOptions} to use
* non-default options
*/
public Table string(String s, String fileExtension) {<FILL_FUNCTION_BODY>}
/**
* Reads the given file into a table using default options Uses converter specified based on given
* file extension Use {@link #usingOptions(ReadOptions) usingOptions} to use non-default options
*/
public Table file(String file) {
return file(new File(file));
}
/**
* Reads the given file into a table using default options Uses converter specified based on given
* file extension Use {@link #usingOptions(ReadOptions) usingOptions} to use non-default options
*/
public Table file(File file) {
String extension = null;
try {
extension = Files.getFileExtension(file.getCanonicalPath());
Optional<DataReader<?>> reader = registry.getReaderForExtension(extension);
if (reader.isPresent()) {
return reader.get().read(new Source(file));
}
} catch (IOException e) {
throw new RuntimeIOException(e);
}
throw new IllegalArgumentException("No reader registered for extension " + extension);
}
public <T extends ReadOptions> Table usingOptions(T options) {
DataReader<T> reader = registry.getReaderForOptions(options);
return reader.read(options);
}
public Table usingOptions(ReadOptions.Builder builder) {
return usingOptions(builder.build());
}
public Table db(ResultSet resultSet) throws SQLException {
return SqlResultSetReader.read(resultSet);
}
public Table db(ResultSet resultSet, String tableName) throws SQLException {
Table table = SqlResultSetReader.read(resultSet);
table.setName(tableName);
return table;
}
// Legacy reader methods for backwards-compatibility
public Table csv(String file) {
return csv(CsvReadOptions.builder(file));
}
public Table csv(String contents, String tableName) {
try {
return csv(CsvReadOptions.builder(new StringReader(contents)).tableName(tableName));
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
public Table csv(File file) {
return csv(CsvReadOptions.builder(file));
}
public Table csv(InputStream stream) {
return csv(CsvReadOptions.builder(stream));
}
public Table csv(URL url) {
try {
return readUrl(url, getCharset(url.openConnection().getContentType()), new CsvReader());
} catch (IOException e) {
throw new RuntimeIOException(e);
}
}
public Table csv(InputStream stream, String name) {
return csv(CsvReadOptions.builder(stream).tableName(name));
}
public Table csv(Reader reader) {
return csv(CsvReadOptions.builder(reader));
}
public Table csv(CsvReadOptions.Builder options) {
return csv(options.build());
}
public Table csv(CsvReadOptions options) {
return new CsvReader().read(options);
}
}
|
Optional<DataReader<?>> reader = registry.getReaderForExtension(fileExtension);
if (!reader.isPresent()) {
throw new IllegalArgumentException("No reader registered for extension " + fileExtension);
}
return reader.get().read(Source.fromString(s));
| 1,540
| 70
| 1,610
|
<no_super_class>
|
jtablesaw_tablesaw
|
tablesaw/core/src/main/java/tech/tablesaw/io/DataFrameWriter.java
|
DataFrameWriter
|
toFile
|
class DataFrameWriter {
private final WriterRegistry registry;
private final Table table;
public DataFrameWriter(WriterRegistry registry, Table table) {
this.registry = registry;
this.table = table;
}
public void toFile(String file) {
toFile(new File(file));
}
public void toFile(File file) {<FILL_FUNCTION_BODY>}
public void toStream(OutputStream stream, String extension) {
DataWriter<?> dataWriter = registry.getWriterForExtension(extension);
dataWriter.write(table, new Destination(stream));
}
public void toWriter(Writer writer, String extension) {
DataWriter<?> dataWriter = registry.getWriterForExtension(extension);
dataWriter.write(table, new Destination(writer));
}
public <T extends WriteOptions> void usingOptions(T options) {
DataWriter<T> dataWriter = registry.getWriterForOptions(options);
dataWriter.write(table, options);
}
public String toString(String extension) {
StringWriter writer = new StringWriter();
DataWriter<?> dataWriter = registry.getWriterForExtension(extension);
dataWriter.write(table, new Destination(writer));
return writer.toString();
}
// legacy methods left for backwards compatibility
public void csv(String file) {
CsvWriteOptions options = CsvWriteOptions.builder(file).build();
new CsvWriter().write(table, options);
}
public void csv(File file) {
CsvWriteOptions options = CsvWriteOptions.builder(file).build();
new CsvWriter().write(table, options);
}
public void csv(CsvWriteOptions options) {
new CsvWriter().write(table, options);
}
public void csv(OutputStream stream) {
CsvWriteOptions options = CsvWriteOptions.builder(stream).build();
new CsvWriter().write(table, options);
}
public void csv(Writer writer) {
CsvWriteOptions options = CsvWriteOptions.builder(writer).build();
new CsvWriter().write(table, options);
}
}
|
String extension = null;
try {
extension = Files.getFileExtension(file.getCanonicalPath());
} catch (IOException e) {
throw new RuntimeIOException(e);
}
DataWriter<?> dataWriter = registry.getWriterForExtension(extension);
dataWriter.write(table, new Destination(file));
| 560
| 86
| 646
|
<no_super_class>
|
jtablesaw_tablesaw
|
tablesaw/core/src/main/java/tech/tablesaw/io/Destination.java
|
Destination
|
createWriter
|
class Destination {
protected final OutputStream stream;
protected final Writer writer;
public Destination(File file) {
try {
this.stream = new FileOutputStream(file);
} catch (FileNotFoundException e) {
throw new RuntimeIOException(e);
}
this.writer = null;
}
public Destination(Writer writer) {
this.stream = null;
this.writer = writer;
}
public Destination(OutputStream stream) {
this.stream = stream;
this.writer = null;
}
public OutputStream stream() {
return stream;
}
public Writer writer() {
return writer;
}
public Writer createWriter() {<FILL_FUNCTION_BODY>}
}
|
if (writer != null) {
return writer;
} else {
assert stream != null;
return new OutputStreamWriter(stream);
}
| 201
| 44
| 245
|
<no_super_class>
|
jtablesaw_tablesaw
|
tablesaw/core/src/main/java/tech/tablesaw/io/ReadOptions.java
|
Builder
|
columnTypesToDetect
|
class Builder {
protected final Source source;
protected String tableName = "";
protected List<ColumnType> columnTypesToDetect = DEFAULT_TYPES;
protected boolean sample = true;
protected String dateFormat;
protected DateTimeFormatter dateFormatter;
protected String timeFormat;
protected DateTimeFormatter timeFormatter;
protected String dateTimeFormat;
protected DateTimeFormatter dateTimeFormatter;
protected Locale locale = Locale.getDefault();
protected String[] missingValueIndicators = new String[0];
protected boolean minimizeColumnSizes = false;
protected boolean header = true;
protected int maxCharsPerColumn = 4096;
protected boolean ignoreZeroDecimal = DEFAULT_IGNORE_ZERO_DECIMAL;
protected boolean skipRowsWithInvalidColumnCount = DEFAULT_SKIP_ROWS_WITH_INVALID_COLUMN_COUNT;
private boolean allowDuplicateColumnNames = false;
protected ColumnType[] columnTypes;
protected Map<String, ColumnType> columnTypeMap = new HashMap<>();
protected Function<String, Optional<ColumnType>> columnTypeFunction;
protected Function<String, ColumnType> completeColumnTypeFunction;
protected Builder() {
source = null;
}
protected Builder(Source source) {
this.source = source;
}
protected Builder(File file) {
this.source = new Source(file);
this.tableName = file.getName();
}
protected Builder(URL url) throws IOException {
this.source = new Source(url.openStream());
this.tableName = url.toString();
}
protected Builder(InputStream stream) {
this.source = new Source(stream);
}
protected Builder(InputStreamReader reader) {
this.source = new Source(reader);
}
protected Builder(Reader reader) {
this.source = new Source(reader);
}
public Builder tableName(String tableName) {
this.tableName = tableName;
return this;
}
public Builder header(boolean hasHeader) {
this.header = hasHeader;
return this;
}
public Builder dateFormat(DateTimeFormatter dateFormat) {
this.dateFormatter = dateFormat;
return this;
}
public Builder allowDuplicateColumnNames(Boolean allow) {
this.allowDuplicateColumnNames = allow;
return this;
}
public Builder timeFormat(DateTimeFormatter dateFormat) {
this.timeFormatter = dateFormat;
return this;
}
public Builder dateTimeFormat(DateTimeFormatter dateFormat) {
this.dateTimeFormatter = dateFormat;
return this;
}
public Builder missingValueIndicator(String... missingValueIndicators) {
this.missingValueIndicators = missingValueIndicators;
return this;
}
public Builder maxCharsPerColumn(int maxCharsPerColumn) {
this.maxCharsPerColumn = maxCharsPerColumn;
return this;
}
/** Ignore zero value decimals in data values. Defaults to {@code true}. */
public Builder ignoreZeroDecimal(boolean ignoreZeroDecimal) {
this.ignoreZeroDecimal = ignoreZeroDecimal;
return this;
}
/** Skip the rows with invalid column count in data values. Defaluts to {@code false}. */
public Builder skipRowsWithInvalidColumnCount(boolean skipRowsWithInvalidColumnCount) {
this.skipRowsWithInvalidColumnCount = skipRowsWithInvalidColumnCount;
return this;
}
public Builder sample(boolean sample) {
this.sample = sample;
return this;
}
public Builder locale(Locale locale) {
this.locale = locale;
return this;
}
/** @see ColumnTypeDetector */
public Builder columnTypesToDetect(List<ColumnType> columnTypesToDetect) {<FILL_FUNCTION_BODY>}
/**
* Allow the {@link ColumnTypeDetector} to choose shorter column types such as float instead of
* double when the data will fit in a smaller type
*/
public Builder minimizeColumnSizes() {
this.columnTypesToDetect = EXTENDED_TYPES;
return this;
}
/**
* Provide column types for all columns skipping autodetect column type logic. The array must
* contain a ColumnType for each column in the table. An error will be thrown if they don't
* match up
*/
public Builder columnTypes(ColumnType[] columnTypes) {
if (columnTypeOptionsAlreadySet()) {
throw new IllegalStateException("columnTypes already set");
}
this.columnTypes = columnTypes;
return this;
}
/**
* Provide a function that determines ColumnType for all column names. To provide only for some
* use {@link #columnTypesPartial(Function)}
*
* <p>This method is generally more efficient because it skips column type detection
*/
public Builder columnTypes(Function<String, ColumnType> columnTypeFunction) {
if (columnTypeOptionsAlreadySet()) {
throw new IllegalStateException("columnTypes already set");
}
this.completeColumnTypeFunction = columnTypeFunction;
return this;
}
/**
* Provide a function that determines ColumnType for some column names. To provide for all
* column names use {@link #columnTypes(Function)} that generally is more efficient because it
* skips column type detection
*/
public Builder columnTypesPartial(Function<String, Optional<ColumnType>> columnTypeFunction) {
if (columnTypeOptionsAlreadySet()) {
throw new IllegalStateException("columnTypes already set");
}
this.columnTypeFunction = columnTypeFunction;
return this;
}
/**
* Provide a map that determines ColumnType for given column names. Types for not present column
* names will be autodetected. To provide type for all column names use {@link
* #columnTypes(Function)} that generally is more efficient because it skips column type
* detection
*/
public Builder columnTypesPartial(Map<String, ColumnType> columnTypeByName) {
if (columnTypeOptionsAlreadySet()) {
throw new IllegalStateException("columnTypes already set");
}
if (columnTypeByName != null) {
this.columnTypeMap = columnTypeByName;
}
return this;
}
private boolean columnTypeOptionsAlreadySet() {
return columnTypes != null
|| columnTypeFunction != null
|| completeColumnTypeFunction != null
|| !columnTypeMap.isEmpty();
}
public ReadOptions build() {
return new ReadOptions(this);
}
}
|
// Types need to be in certain order as more general types like string come last
// Otherwise everything will be parsed as a string
List<ColumnType> orderedTypes = new ArrayList<>();
for (ColumnType t : EXTENDED_TYPES) {
if (columnTypesToDetect.contains(t)) {
orderedTypes.add(t);
}
}
this.columnTypesToDetect = orderedTypes;
return this;
| 1,688
| 113
| 1,801
|
<no_super_class>
|
jtablesaw_tablesaw
|
tablesaw/core/src/main/java/tech/tablesaw/io/ReaderRegistry.java
|
ReaderRegistry
|
getReaderForOptions
|
class ReaderRegistry {
private final Map<String, DataReader<?>> optionTypesRegistry = new HashMap<>();
private final Map<String, DataReader<?>> extensionsRegistry = new HashMap<>();
private final Map<String, DataReader<?>> mimeTypesRegistry = new HashMap<>();
public void registerOptions(Class<? extends ReadOptions> optionsType, DataReader<?> reader) {
optionTypesRegistry.put(optionsType.getCanonicalName(), reader);
}
public void registerExtension(String extension, DataReader<?> reader) {
extensionsRegistry.put(extension, reader);
}
public void registerMimeType(String mimeType, DataReader<?> reader) {
mimeTypesRegistry.put(mimeType, reader);
}
@SuppressWarnings("unchecked")
public <T extends ReadOptions> DataReader<T> getReaderForOptions(T options) {<FILL_FUNCTION_BODY>}
public Optional<DataReader<?>> getReaderForExtension(String extension) {
return Optional.ofNullable(extensionsRegistry.get(extension));
}
public Optional<DataReader<?>> getReaderForMimeType(String mimeType) {
return Optional.ofNullable(mimeTypesRegistry.get(mimeType));
}
}
|
String clazz = options.getClass().getCanonicalName();
DataReader<T> reader = (DataReader<T>) optionTypesRegistry.get(clazz);
if (reader == null) {
throw new IllegalArgumentException("No reader registered for class " + clazz);
}
return reader;
| 329
| 78
| 407
|
<no_super_class>
|
jtablesaw_tablesaw
|
tablesaw/core/src/main/java/tech/tablesaw/io/Source.java
|
Source
|
getCharSet
|
class Source {
// we always have one of these (file, reader, or inputStream)
protected final File file;
protected final Reader reader;
protected final InputStream inputStream;
protected final Charset charset;
public Source(File file) {
this(file, getCharSet(file));
}
public Source(File file, Charset charset) {
this.file = file;
this.reader = null;
this.inputStream = null;
this.charset = charset;
}
public Source(InputStreamReader reader) {
this.file = null;
this.reader = reader;
this.inputStream = null;
this.charset = Charset.forName(reader.getEncoding());
}
public Source(Reader reader) {
this.file = null;
this.reader = reader;
this.inputStream = null;
this.charset = null;
}
public Source(InputStream inputStream) {
this(inputStream, Charset.defaultCharset());
}
public Source(InputStream inputStream, Charset charset) {
this.file = null;
this.reader = null;
this.inputStream = inputStream;
this.charset = charset;
}
public static Source fromString(String s) {
return new Source(new StringReader(s));
}
public static Source fromUrl(String url) throws IOException {
return new Source(new StringReader(loadUrl(url)));
}
public File file() {
return file;
}
public Reader reader() {
return reader;
}
public InputStream inputStream() {
return inputStream;
}
public Charset getCharset() {
return charset;
}
/**
* If cachedBytes are not null, returns a Reader created from the cachedBytes. Otherwise, returns
* a Reader from the underlying source.
*/
public Reader createReader(byte[] cachedBytes) throws IOException {
if (cachedBytes != null) {
return charset != null
? new InputStreamReader(new ByteArrayInputStream(cachedBytes), charset)
: new InputStreamReader(new ByteArrayInputStream(cachedBytes));
}
if (inputStream != null) {
return new InputStreamReader(inputStream, charset);
}
if (reader != null) {
return reader;
}
return new InputStreamReader(new FileInputStream(file), charset);
}
private static String loadUrl(String url) throws IOException {
try (Scanner scanner = new Scanner(new URL(url).openStream())) {
scanner.useDelimiter("\\A"); // start of a string
return scanner.hasNext() ? scanner.next() : "";
}
}
/**
* Returns the likely charset for the given file, if it can be determined. A confidence score is
* calculated. If the score is less than 60 (on a 1 to 100 interval) the system default charset is
* returned instead.
*
* @param file The file to be evaluated
* @return The likely charset, or the system default charset
*/
@VisibleForTesting
static Charset getCharSet(File file) {
long bufferSize = file.length() < 9999 ? file.length() : 9999;
byte[] buffer = new byte[(int) bufferSize];
try (InputStream initialStream = new FileInputStream(file)) {
int bytesRead = initialStream.read(buffer);
if (bytesRead < bufferSize) {
throw new IOException("Was not able to read expected number of bytes");
}
} catch (IOException e) {
throw new IllegalStateException(e);
}
return getCharSet(buffer);
}
/**
* Returns the likely charset for the given byte[], if it can be determined. A confidence score is
* calculated. If the score is less than 60 (on a 1 to 100 interval) the system default charset is
* returned instead.
*
* @param buffer The byte array to evaluate
* @return The likely charset, or the system default charset
*/
private static Charset getCharSet(byte[] buffer) {<FILL_FUNCTION_BODY>}
}
|
CharsetDetector detector = new CharsetDetector();
detector.setText(buffer);
CharsetMatch match = detector.detect();
if (match == null || match.getConfidence() < 60) {
return Charset.defaultCharset();
}
return Charset.forName(match.getName());
| 1,071
| 82
| 1,153
|
<no_super_class>
|
jtablesaw_tablesaw
|
tablesaw/core/src/main/java/tech/tablesaw/io/TableBuildingUtils.java
|
TableBuildingUtils
|
build
|
class TableBuildingUtils {
public static Table build(
List<String> columnNames, List<String[]> dataRows, ReadOptions options) {<FILL_FUNCTION_BODY>}
}
|
Table table = Table.create(options.tableName());
if (dataRows.isEmpty()) {
return table;
}
ColumnTypeDetector detector = new ColumnTypeDetector(options.columnTypesToDetect());
Iterator<String[]> iterator = dataRows.iterator();
ColumnType[] types = detector.detectColumnTypes(iterator, options);
// If there are columnTypes configured by the user use them
for (int i = 0; i < types.length; i++) {
boolean hasColumnName = i < columnNames.size();
Optional<ColumnType> configuredColumnType =
options.columnTypeReadOptions().columnType(i, hasColumnName ? columnNames.get(i) : null);
if (configuredColumnType.isPresent()) types[i] = configuredColumnType.get();
}
for (int i = 0; i < columnNames.size(); i++) {
table.addColumns(types[i].create(columnNames.get(i)));
}
for (int i = 0; i < dataRows.size(); i++) {
for (int j = 0; j < table.columnCount(); j++) {
table.column(j).appendCell(dataRows.get(i)[j]);
}
}
return table;
| 50
| 323
| 373
|
<no_super_class>
|
jtablesaw_tablesaw
|
tablesaw/core/src/main/java/tech/tablesaw/io/csv/CsvReader.java
|
CsvReader
|
detectColumnTypes
|
class CsvReader extends FileReader implements DataReader<CsvReadOptions> {
private static final CsvReader INSTANCE = new CsvReader();
static {
register(Table.defaultReaderRegistry);
}
public static void register(ReaderRegistry registry) {
registry.registerExtension("csv", INSTANCE);
registry.registerMimeType("text/csv", INSTANCE);
registry.registerOptions(CsvReadOptions.class, INSTANCE);
}
/** Constructs a CsvReader */
public CsvReader() {
super();
}
/**
* Determines column types if not provided by the user Reads all input into memory unless File was
* provided
*/
private Pair<Reader, ReadOptions.ColumnTypeReadOptions> getReaderAndColumnTypes(
Source source, CsvReadOptions options) throws IOException {
ReadOptions.ColumnTypeReadOptions columnTypeReadOptions = options.columnTypeReadOptions();
byte[] bytesCache = null;
boolean need2ParseFile =
!columnTypeReadOptions.hasColumnTypeForAllColumns()
&& (!options.header()
|| !columnTypeReadOptions.hasColumnTypeForAllColumnsIfHavingColumnNames());
if (need2ParseFile) {
Reader reader = source.createReader(null);
if (source.file() == null) {
String s = CharStreams.toString(reader);
bytesCache = source.getCharset() != null ? s.getBytes(source.getCharset()) : s.getBytes();
// create a new reader since we just exhausted the existing one
reader = source.createReader(bytesCache);
}
ColumnType[] detectedColumnTypes = detectColumnTypes(reader, options);
// If no columns where returned from detectColumnTypes leave initial options (that's the case
// for only header present)
if (detectedColumnTypes.length > 0) {
columnTypeReadOptions = ReadOptions.ColumnTypeReadOptions.of(detectedColumnTypes);
}
}
return Pair.create(source.createReader(bytesCache), columnTypeReadOptions);
}
public Table read(CsvReadOptions options) {
try {
return read(options, false);
} catch (IOException e) {
throw new RuntimeIOException(e);
}
}
private Table read(CsvReadOptions options, boolean headerOnly) throws IOException {
Pair<Reader, ReadOptions.ColumnTypeReadOptions> pair =
getReaderAndColumnTypes(options.source(), options);
Reader reader = pair.getKey();
ReadOptions.ColumnTypeReadOptions columnTypeReadOptions = pair.getValue();
AbstractParser<?> parser = csvParser(options);
try {
return parseRows(
options, headerOnly, reader, columnTypeReadOptions, parser, options.sampleSize());
} finally {
if (options.source().reader() == null) {
// if we get a reader back from options it means the client opened it, so let the client
// close it
// if it's null, we close it here.
parser.stopParsing();
reader.close();
}
}
}
/**
* Returns a string representation of the column types in file {@code csvFilename}, as determined
* by the type-detection algorithm
*
* <p>This method is intended to help analysts quickly fix any erroneous types, by printing out
* the types in a format such that they can be edited to correct any mistakes, and used in an
* array literal
*
* <p>For example:
*
* <p>LOCAL_DATE, // 0 date SHORT, // 1 approval STRING, // 2 who
*
* <p>Note that the types are array separated, and that the index position and the column name are
* printed such that they would be interpreted as comments if you paste the output into an array:
*
* <p>
*
* @throws IOException if file cannot be read
*/
public String printColumnTypes(CsvReadOptions options) throws IOException {
Table structure = read(options, true).structure();
return getTypeString(structure);
}
/**
* Estimates and returns the type for each column in the delimited text file {@code file}
*
* <p>The type is determined by checking a sample of the data in the file. Because only a sample
* of the data is checked, the types may be incorrect. If that is the case a Parse Exception will
* be thrown.
*
* <p>The method {@code printColumnTypes()} can be used to print a list of the detected columns
* that can be corrected and used to explicitly specify the correct column types.
*/
protected ColumnType[] detectColumnTypes(Reader reader, CsvReadOptions options) {<FILL_FUNCTION_BODY>}
private CsvParser csvParser(CsvReadOptions options) {
CsvParserSettings settings = new CsvParserSettings();
settings.setLineSeparatorDetectionEnabled(options.lineSeparatorDetectionEnabled());
settings.setFormat(csvFormat(options));
settings.setMaxCharsPerColumn(options.maxCharsPerColumn());
if (options.maxNumberOfColumns() != null) {
settings.setMaxColumns(options.maxNumberOfColumns());
}
return new CsvParser(settings);
}
private CsvFormat csvFormat(CsvReadOptions options) {
CsvFormat format = new CsvFormat();
if (options.quoteChar() != null) {
format.setQuote(options.quoteChar());
}
if (options.escapeChar() != null) {
format.setQuoteEscape(options.escapeChar());
}
if (options.separator() != null) {
format.setDelimiter(options.separator());
}
if (options.lineEnding() != null) {
format.setLineSeparator(options.lineEnding());
}
if (options.commentPrefix() != null) {
format.setComment(options.commentPrefix());
}
return format;
}
@Override
public Table read(Source source) {
return read(CsvReadOptions.builder(source).build());
}
}
|
boolean header = options.header();
CsvParser parser = csvParser(options);
try {
String[] columnNames = null;
if (header) {
parser.beginParsing(reader);
columnNames = getColumnNames(options, options.columnTypeReadOptions(), parser);
}
return getColumnTypes(reader, options, 0, parser, columnNames);
} finally {
parser.stopParsing();
// we don't close the reader since we didn't create it
}
| 1,558
| 133
| 1,691
|
<methods>public non-sealed void <init>() ,public java.lang.String[] getColumnNames(tech.tablesaw.io.ReadOptions, tech.tablesaw.io.ReadOptions.ColumnTypeReadOptions, AbstractParser<?>) ,public tech.tablesaw.api.ColumnType[] getColumnTypes(java.io.Reader, tech.tablesaw.io.ReadOptions, int, AbstractParser<?>, java.lang.String[]) <variables>private static final int UNLIMITED_SAMPLE_SIZE,private static Logger logger
|
jtablesaw_tablesaw
|
tablesaw/core/src/main/java/tech/tablesaw/io/csv/CsvWriter.java
|
CsvWriter
|
writeHeader
|
class CsvWriter implements DataWriter<CsvWriteOptions> {
private static final CsvWriter INSTANCE = new CsvWriter();
private static final String nullValue = "";
static {
register(Table.defaultWriterRegistry);
}
public static void register(WriterRegistry registry) {
registry.registerExtension("csv", INSTANCE);
registry.registerOptions(CsvWriteOptions.class, INSTANCE);
}
public void write(Table table, CsvWriteOptions options) {
CsvWriterSettings settings = createSettings(options);
com.univocity.parsers.csv.CsvWriter csvWriter = null;
// Creates a writer with the above settings;
try {
csvWriter =
new com.univocity.parsers.csv.CsvWriter(options.destination().createWriter(), settings);
writeHeader(table, options, csvWriter);
for (int r = 0; r < table.rowCount(); r++) {
String[] entries = new String[table.columnCount()];
for (int c = 0; c < table.columnCount(); c++) {
writeValues(table, options, r, entries, c);
}
csvWriter.writeRow(entries);
}
} finally {
if (csvWriter != null) {
csvWriter.flush();
if (options.autoClose()) csvWriter.close();
}
}
}
private void writeValues(Table table, CsvWriteOptions options, int r, String[] entries, int c) {
DateTimeFormatter dateFormatter = options.dateFormatter();
DateTimeFormatter dateTimeFormatter = options.dateTimeFormatter();
ColumnType columnType = table.column(c).type();
if (dateFormatter != null && columnType.equals(ColumnType.LOCAL_DATE)) {
DateColumn dc = (DateColumn) table.column(c);
entries[c] = options.dateFormatter().format(dc.get(r));
} else if (dateTimeFormatter != null && columnType.equals(ColumnType.LOCAL_DATE_TIME)) {
DateTimeColumn dc = (DateTimeColumn) table.column(c);
entries[c] = options.dateTimeFormatter().format(dc.get(r));
} else {
if (options.usePrintFormatters()) {
entries[c] = table.getString(r, c);
} else {
entries[c] = table.getUnformatted(r, c);
}
}
}
private void writeHeader(
Table table, CsvWriteOptions options, com.univocity.parsers.csv.CsvWriter csvWriter) {<FILL_FUNCTION_BODY>}
protected static CsvWriterSettings createSettings(CsvWriteOptions options) {
CsvWriterSettings settings = new CsvWriterSettings();
// Sets the character sequence to write for the values that are null.
settings.setNullValue(nullValue);
if (options.separator() != null) {
settings.getFormat().setDelimiter(options.separator());
}
if (options.quoteChar() != null) {
settings.getFormat().setQuote(options.quoteChar());
}
if (options.escapeChar() != null) {
settings.getFormat().setQuoteEscape(options.escapeChar());
}
if (options.lineEnd() != null) {
settings.getFormat().setLineSeparator(options.lineEnd());
}
settings.setIgnoreLeadingWhitespaces(options.ignoreLeadingWhitespaces());
settings.setIgnoreTrailingWhitespaces(options.ignoreTrailingWhitespaces());
// writes empty lines as well.
settings.setSkipEmptyLines(false);
settings.setQuoteAllFields(options.quoteAllFields());
return settings;
}
@Override
public void write(Table table, Destination dest) {
write(table, CsvWriteOptions.builder(dest).build());
}
}
|
if (options.header()) {
String[] header = new String[table.columnCount()];
for (int c = 0; c < table.columnCount(); c++) {
String name = table.column(c).name();
header[c] = options.columnNameMap().getOrDefault(name, name);
}
csvWriter.writeHeaders(header);
}
| 1,009
| 98
| 1,107
|
<no_super_class>
|
jtablesaw_tablesaw
|
tablesaw/core/src/main/java/tech/tablesaw/io/fixed/FixedWidthReader.java
|
FixedWidthReader
|
getReaderAndColumnTypes
|
class FixedWidthReader extends FileReader implements DataReader<FixedWidthReadOptions> {
private static final FixedWidthReader INSTANCE = new FixedWidthReader();
static {
register(Table.defaultReaderRegistry);
}
public static void register(ReaderRegistry registry) {
registry.registerOptions(FixedWidthReadOptions.class, INSTANCE);
}
/** Constructs a FixedWidthReader */
public FixedWidthReader() {
super();
}
/**
* Determines column types if not provided by the user Reads all input into memory unless File was
* provided
*/
private Pair<Reader, ReadOptions.ColumnTypeReadOptions> getReaderAndColumnTypes(
FixedWidthReadOptions options) {<FILL_FUNCTION_BODY>}
public Table read(FixedWidthReadOptions options) {
return read(options, false);
}
private Table read(FixedWidthReadOptions options, boolean headerOnly) {
Pair<Reader, ReadOptions.ColumnTypeReadOptions> pair = getReaderAndColumnTypes(options);
Reader reader = pair.getKey();
ReadOptions.ColumnTypeReadOptions columnTypeReadOptions = pair.getValue();
FixedWidthParser parser = fixedWidthParser(options);
try {
return parseRows(options, headerOnly, reader, columnTypeReadOptions, parser);
} finally {
if (options.source().reader() == null) {
// if we get a reader back from options it means the client opened it, so let the client
// close it
// if it's null, we close it here.
parser.stopParsing();
try {
reader.close();
} catch (IOException e) {
throw new RuntimeIOException(e);
}
}
}
}
/**
* Returns a string representation of the column types in file {@code fixed widthFilename}, as
* determined by the type-detection algorithm
*
* <p>This method is intended to help analysts quickly fix any erroneous types, by printing out
* the types in a format such that they can be edited to correct any mistakes, and used in an
* array literal
*
* <p>For example:
*
* <p>LOCAL_DATE, // 0 date SHORT, // 1 approval STRING, // 2 who
*
* <p>Note that the types are array separated, and that the index position and the column name are
* printed such that they would be interpreted as comments if you paste the output into an array:
*/
public String printColumnTypes(FixedWidthReadOptions options) {
Table structure = read(options, true).structure();
return getTypeString(structure);
}
/**
* Estimates and returns the type for each column in the delimited text file {@code file}
*
* <p>The type is determined by checking a sample of the data in the file. Because only a sample
* of the data is checked, the types may be incorrect. If that is the case a Parse Exception will
* be thrown.
*
* <p>The method {@code printColumnTypes()} can be used to print a list of the detected columns
* that can be corrected and used to explicitly specify the correct column types.
*/
public ColumnType[] detectColumnTypes(Reader reader, FixedWidthReadOptions options) {
boolean header = options.header();
int linesToSkip = header ? 1 : 0;
AbstractParser<?> parser = fixedWidthParser(options);
try {
String[] columnNames =
Optional.ofNullable(options.columnSpecs())
.flatMap(specs -> Optional.ofNullable(specs.getFieldNames()))
.map(
fieldNames ->
Arrays.stream(fieldNames)
.map(NormalizedString::toString)
.toArray(String[]::new))
.orElse(null);
return getColumnTypes(reader, options, linesToSkip, parser, columnNames);
} finally {
parser.stopParsing();
// we don't close the reader since we didn't create it
}
}
private FixedWidthParser fixedWidthParser(FixedWidthReadOptions options) {
FixedWidthParserSettings settings = new FixedWidthParserSettings();
if (options.columnSpecs() != null) {
settings = new FixedWidthParserSettings(options.columnSpecs());
}
settings.setFormat(fixedWidthFormat(options));
settings.setMaxCharsPerColumn(options.maxNumberOfColumns());
if (options.skipTrailingCharsUntilNewline()) {
settings.setSkipTrailingCharsUntilNewline(options.skipTrailingCharsUntilNewline());
}
if (options.maxNumberOfColumns() != null) {
settings.setMaxColumns(options.maxNumberOfColumns());
}
if (options.recordEndsOnNewline()) {
settings.setRecordEndsOnNewline(true);
}
return new FixedWidthParser(settings);
}
private FixedWidthFormat fixedWidthFormat(FixedWidthReadOptions options) {
FixedWidthFormat format = new FixedWidthFormat();
if (options.padding() != ' ') {
format.setPadding(options.padding());
}
if (options.lookupWildcard() != '?') {
format.setLookupWildcard(options.lookupWildcard());
}
if (options.lineEnding() != null) {
format.setLineSeparator(options.lineEnding());
}
return format;
}
@Override
public Table read(Source source) {
return read(FixedWidthReadOptions.builder(source).build());
}
}
|
ReadOptions.ColumnTypeReadOptions columnTypeReadOptions = options.columnTypeReadOptions();
byte[] bytesCache = null;
boolean hasColumnNames =
options.columnSpecs() != null
&& options.columnSpecs().getFieldNames() != null
&& options.columnSpecs().getFieldNames().length > 0;
try {
if (!options.columnTypeReadOptions().hasColumnTypeForAllColumns()
&& (!options.columnTypeReadOptions().hasColumnTypeForAllColumnsIfHavingColumnNames()
|| !hasColumnNames)) {
Reader reader = options.source().createReader(bytesCache);
if (options.source().file() == null) {
bytesCache = CharStreams.toString(reader).getBytes();
// create a new reader since we just exhausted the existing one
reader = options.source().createReader(bytesCache);
}
columnTypeReadOptions =
ReadOptions.ColumnTypeReadOptions.of(detectColumnTypes(reader, options));
}
} catch (IOException e) {
throw new RuntimeIOException(e);
}
try {
return Pair.create(options.source().createReader(bytesCache), columnTypeReadOptions);
} catch (IOException e) {
throw new RuntimeIOException(e);
}
| 1,412
| 317
| 1,729
|
<methods>public non-sealed void <init>() ,public java.lang.String[] getColumnNames(tech.tablesaw.io.ReadOptions, tech.tablesaw.io.ReadOptions.ColumnTypeReadOptions, AbstractParser<?>) ,public tech.tablesaw.api.ColumnType[] getColumnTypes(java.io.Reader, tech.tablesaw.io.ReadOptions, int, AbstractParser<?>, java.lang.String[]) <variables>private static final int UNLIMITED_SAMPLE_SIZE,private static Logger logger
|
jtablesaw_tablesaw
|
tablesaw/core/src/main/java/tech/tablesaw/io/fixed/FixedWidthWriter.java
|
FixedWidthWriter
|
write
|
class FixedWidthWriter implements DataWriter<FixedWidthWriteOptions> {
private static final FixedWidthWriter INSTANCE = new FixedWidthWriter();
static {
register(Table.defaultWriterRegistry);
}
public static void register(WriterRegistry registry) {
registry.registerOptions(FixedWidthWriteOptions.class, INSTANCE);
}
public void write(Table table, FixedWidthWriteOptions options) {<FILL_FUNCTION_BODY>}
protected FixedWidthFormat fixedWidthFormat(FixedWidthWriteOptions options) {
FixedWidthFormat format = new FixedWidthFormat();
if (options.padding() != ' ') {
format.setPadding(options.padding());
}
if (options.lookupWildcard() != '?') {
format.setLookupWildcard(options.lookupWildcard());
}
if (options.comment() != '#') {
format.setComment(options.comment());
}
if (options.lineSeparator() != null) {
format.setLineSeparator(options.lineSeparator());
}
if (options.lineSeparatorString() != null) {
format.setLineSeparator(options.lineSeparatorString());
}
if (options.normalizedNewline() != '\n') {
format.setNormalizedNewline(options.normalizedNewline());
}
return format;
}
protected FixedWidthWriterSettings fixedWidthWriterSettings(FixedWidthWriteOptions options) {
FixedWidthWriterSettings settings = new FixedWidthWriterSettings();
if (options.columnSpecs() != null) {
settings = new FixedWidthWriterSettings(options.columnSpecs());
}
if (options.autoConfigurationEnabled()) {
settings.setAutoConfigurationEnabled(options.autoConfigurationEnabled());
} else {
columnRowSettings(settings, options);
errorSettings(settings, options);
skipIgnoreSettings(settings, options);
}
return settings;
}
protected void columnRowSettings(
FixedWidthWriterSettings settings, FixedWidthWriteOptions options) {
if (options.defaultAlignmentForHeaders() != null) {
settings.setDefaultAlignmentForHeaders(options.defaultAlignmentForHeaders());
}
if (options.columnReorderingEnabled()) {
settings.setColumnReorderingEnabled(options.columnReorderingEnabled());
}
if (options.expandIncompleteRows()) {
settings.setExpandIncompleteRows(options.expandIncompleteRows());
}
if (!options.defaultPaddingForHeaders()) {
settings.setUseDefaultPaddingForHeaders(options.defaultPaddingForHeaders());
}
if (!options.writeLineSeparatorAfterRecord()) {
settings.setWriteLineSeparatorAfterRecord(options.writeLineSeparatorAfterRecord());
}
}
protected void errorSettings(FixedWidthWriterSettings settings, FixedWidthWriteOptions options) {
if (options.errorContentLength() <= -1) {
settings.setErrorContentLength(options.errorContentLength());
}
if (options.nullValue() != null) {
settings.setNullValue(options.nullValue());
}
if (options.emptyValue() != null) {
settings.setEmptyValue(options.emptyValue());
}
}
protected void skipIgnoreSettings(
FixedWidthWriterSettings settings, FixedWidthWriteOptions options) {
if (!options.ignoreTrailingWhitespaces()) {
settings.setIgnoreTrailingWhitespaces(options.ignoreTrailingWhitespaces());
}
if (!options.ignoreLeadingWhitespaces()) {
settings.setIgnoreLeadingWhitespaces(options.ignoreLeadingWhitespaces());
}
if (!options.skipBitsAsWhitespace()) {
settings.setSkipBitsAsWhitespace(options.skipBitsAsWhitespace());
}
if (!options.skipEmptyLines()) {
settings.setSkipEmptyLines(options.skipEmptyLines());
}
}
@Override
public void write(Table table, Destination dest) {
write(table, FixedWidthWriteOptions.builder(dest).build());
}
}
|
FixedWidthWriterSettings settings = fixedWidthWriterSettings(options);
settings.setFormat(fixedWidthFormat(options));
com.univocity.parsers.fixed.FixedWidthWriter fixedWidthWriter = null;
// Creates a writer with the above settings;
try {
Writer writer = options.destination().createWriter();
fixedWidthWriter = new com.univocity.parsers.fixed.FixedWidthWriter(writer, settings);
if (options.header()) {
String[] header = new String[table.columnCount()];
for (int c = 0; c < table.columnCount(); c++) {
header[c] = table.column(c).name();
}
fixedWidthWriter.writeHeaders(header);
}
for (int r = 0; r < table.rowCount(); r++) {
String[] entries = new String[table.columnCount()];
for (int c = 0; c < table.columnCount(); c++) {
table.get(r, c);
entries[c] = table.getUnformatted(r, c);
}
fixedWidthWriter.writeRow(entries);
}
} finally {
if (fixedWidthWriter != null) {
fixedWidthWriter.flush();
if (options.autoClose()) fixedWidthWriter.close();
}
}
| 1,036
| 335
| 1,371
|
<no_super_class>
|
jtablesaw_tablesaw
|
tablesaw/core/src/main/java/tech/tablesaw/io/jdbc/SqlResultSetReader.java
|
SqlResultSetReader
|
getColumnType
|
class SqlResultSetReader {
// Maps from supported SQL types to their Tablesaw equivalents'
private static final Map<Integer, ColumnType> SQL_TYPE_TO_TABLESAW_TYPE = initializeMap();
private static Map<Integer, ColumnType> initializeMap() {
return new HashMap<>(
new ImmutableMap.Builder<Integer, ColumnType>()
.put(Types.BOOLEAN, ColumnType.BOOLEAN)
.put(Types.BIT, ColumnType.BOOLEAN)
.put(Types.DECIMAL, ColumnType.DOUBLE)
.put(Types.DOUBLE, ColumnType.DOUBLE)
.put(Types.FLOAT, ColumnType.DOUBLE)
.put(Types.NUMERIC, ColumnType.DOUBLE)
.put(Types.REAL, ColumnType.FLOAT)
// Instant, LocalDateTime, OffsetDateTime and ZonedDateTime are often mapped to
// timestamp
.put(Types.TIMESTAMP, ColumnType.INSTANT)
.put(Types.INTEGER, ColumnType.INTEGER)
.put(Types.DATE, ColumnType.LOCAL_DATE)
.put(Types.TIME, ColumnType.LOCAL_TIME)
.put(Types.BIGINT, ColumnType.LONG)
.put(Types.SMALLINT, ColumnType.SHORT)
.put(Types.TINYINT, ColumnType.SHORT)
.put(Types.BINARY, ColumnType.STRING)
.put(Types.CHAR, ColumnType.STRING)
.put(Types.NCHAR, ColumnType.STRING)
.put(Types.NVARCHAR, ColumnType.STRING)
.put(Types.VARCHAR, ColumnType.STRING)
.put(Types.LONGVARCHAR, ColumnType.STRING)
.put(Types.LONGNVARCHAR, ColumnType.STRING)
.build());
}
/**
* Change or add a mapping between the given Jdbc type and column type. When reading from a
* database, the db column type is automatically assigned to the associated tablesaw column type
*
* @param jdbc an int representing a legal value from java.sql.types;
* @param columnType a tablesaw column type
*/
public static void mapJdbcTypeToColumnType(Integer jdbc, ColumnType columnType) {
SQL_TYPE_TO_TABLESAW_TYPE.put(jdbc, columnType);
}
/**
* Returns a new table with the given tableName, constructed from the given result set
*
* @throws SQLException if there is a problem detected in the database
*/
public static Table read(ResultSet resultSet) throws SQLException {
ResultSetMetaData metaData = resultSet.getMetaData();
Table table = Table.create();
// Setup the columns and add to the table
for (int i = 1; i <= metaData.getColumnCount(); i++) {
ColumnType type =
getColumnType(metaData.getColumnType(i), metaData.getScale(i), metaData.getPrecision(i));
Preconditions.checkState(
type != null,
"No column type found for %s as specified for column %s",
metaData.getColumnType(i),
metaData.getColumnName(i));
Column<?> newColumn = type.create(metaData.getColumnLabel(i));
table.addColumns(newColumn);
}
// Add the rows
while (resultSet.next()) {
for (int i = 1; i <= metaData.getColumnCount(); i++) {
Column<?> column =
table.column(i - 1); // subtract 1 because results sets originate at 1 not 0
if (column instanceof ShortColumn) {
appendToColumn(column, resultSet, resultSet.getShort(i));
} else if (column instanceof IntColumn) {
appendToColumn(column, resultSet, resultSet.getInt(i));
} else if (column instanceof LongColumn) {
appendToColumn(column, resultSet, resultSet.getLong(i));
} else if (column instanceof FloatColumn) {
appendToColumn(column, resultSet, resultSet.getFloat(i));
} else if (column instanceof DoubleColumn) {
appendToColumn(column, resultSet, resultSet.getDouble(i));
} else if (column instanceof BooleanColumn) {
appendToColumn(column, resultSet, resultSet.getBoolean(i));
} else {
column.appendObj(resultSet.getObject(i));
}
}
}
return table;
}
protected static void appendToColumn(Column<?> column, ResultSet resultSet, Object value)
throws SQLException {
if (resultSet.wasNull()) {
column.appendMissing();
} else {
column.appendObj(value);
}
}
protected static ColumnType getColumnType(int columnType, int scale, int precision) {<FILL_FUNCTION_BODY>}
}
|
ColumnType type = SQL_TYPE_TO_TABLESAW_TYPE.get(columnType);
// Try to improve on the initial type assigned to 'type' to minimize size/space of type needed.
// For all generic numeric columns inspect closer, checking the precision and
// scale to more accurately determine the appropriate java type to use.
if (columnType == Types.NUMERIC || columnType == Types.DECIMAL) {
// When scale is 0 then column is a type of integer
if (scale == 0) {
/* Mapping to java integer types based on integer precision defined:
Java type TypeMinVal TypeMaxVal p MaxIntVal
-----------------------------------------------------------------------------------------
byte, Byte: -128 127 NUMBER(2) 99
short, Short: -32768 32767 NUMBER(4) 9_999
int, Integer: -2147483648 2147483647 NUMBER(9) 999_999_999
long, Long: -9223372036854775808 9223372036854775807 NUMBER(18) 999_999_999_999_999_999
*/
if (precision > 0) {
if (precision <= 4) {
// Start with SHORT (since ColumnType.BYTE isn't supported yet)
// and find the smallest java integer type that fits
type = ColumnType.SHORT;
} else if (precision <= 9) {
type = ColumnType.INTEGER;
} else if (precision <= 18) {
type = ColumnType.LONG;
}
}
} else { // s is not zero, so a decimal value is expected. First try float, then double
if (scale <= 7) {
type = ColumnType.FLOAT;
} else if (scale <= 16) {
type = ColumnType.DOUBLE;
}
}
}
return type;
| 1,264
| 552
| 1,816
|
<no_super_class>
|
jtablesaw_tablesaw
|
tablesaw/core/src/main/java/tech/tablesaw/io/string/DataFramePrinter.java
|
DataFramePrinter
|
print
|
class DataFramePrinter {
private static final String TOO_SHORT_COLUMN_MARKER = "?";
private final int maxRows;
private final OutputStream stream;
/**
* Constructor
*
* @param maxRows the max rows to print
* @param stream the print stream to write to
*/
public DataFramePrinter(int maxRows, OutputStream stream) {
this.maxRows = maxRows;
this.stream = stream;
}
/**
* Returns the column widths required to print the header and data
*
* @param headers the headers to print
* @param data the data items to print
* @return the required column widths
*/
private static int[] getWidths(String[] headers, String[][] data) {
final int[] widths = new int[headers.length];
for (int j = 0; j < headers.length; j++) {
final String header = headers[j];
widths[j] = Math.max(widths[j], header != null ? header.length() : 0);
}
for (String[] rowValues : data) {
for (int j = 0; j < rowValues.length; j++) {
final String value = rowValues[j];
widths[j] = Math.max(widths[j], value != null ? value.length() : 0);
}
}
return widths;
}
/**
* Returns the header template given the widths specified
*
* @param widths the token widths
* @return the line format template
*/
private static String getHeaderTemplate(int[] widths, String[] headers) {
return IntStream.range(0, widths.length)
.mapToObj(
i -> {
final int width = widths[i];
final int length = headers[i].length();
final int leading = (width - length) / 2;
final int trailing = width - (length + leading);
final StringBuilder text = new StringBuilder();
whitespace(text, leading + 1);
text.append("%").append(i + 1).append("$s");
whitespace(text, trailing);
text.append(" |");
return text.toString();
})
.reduce((left, right) -> left + " " + right)
.orElse("");
}
/**
* Returns the data template given the widths specified
*
* @param widths the token widths
* @return the line format template
*/
private static String getDataTemplate(int[] widths) {
return IntStream.range(0, widths.length)
.mapToObj(i -> " %" + (i + 1) + "$" + widths[i] + "s |")
.reduce((left, right) -> left + " " + right)
.orElse("");
}
/**
* Returns a whitespace string of the length specified
*
* @param length the length for whitespace
*/
private static void whitespace(StringBuilder text, int length) {
IntStream.range(0, length).forEach(i -> text.append(" "));
}
/**
* Prints the specified DataFrame to the stream bound to this printer
*
* @param frame the DataFrame to print
*/
public void print(Relation frame) {<FILL_FUNCTION_BODY>}
private String tableName(Relation frame, int width) {
if (frame.name().length() > width) {
return frame.name();
}
int diff = width - frame.name().length();
String result = StringUtils.repeat(" ", diff / 2) + frame.name();
return result + StringUtils.repeat(" ", width - result.length());
}
/**
* Returns the header string tokens for the frame
*
* @param frame the frame to create header tokens
* @return the header tokens
*/
private String[] getHeaderTokens(Relation frame) {
final int colCount = frame.columnCount();
final String[] header = new String[colCount];
IntStream.range(0, colCount)
.forEach(
colIndex -> {
header[colIndex] = frame.column(colIndex).name();
});
return header;
}
private String getDataToken(Column<?> col, int i) {
return col.size() > i ? col.getString(i) : TOO_SHORT_COLUMN_MARKER;
}
/**
* Returns the 2-D array of data tokens from the frame specified
*
* @param frame the DataFrame from which to create 2D array of formatted tokens
* @return the array of data tokens
*/
private String[][] getDataTokens(Relation frame) {
if (frame.rowCount() == 0) return new String[0][0];
final int rowCount = Math.min(maxRows, frame.rowCount());
final boolean truncated = frame.rowCount() > maxRows;
final int colCount = frame.columnCount();
final String[][] data;
if (truncated) {
data = new String[rowCount + 1][colCount];
int i;
for (i = 0; i < Math.ceil((double) rowCount / 2); i++) {
for (int j = 0; j < colCount; j++) {
Column<?> col = frame.column(j);
data[i][j] = getDataToken(col, i);
}
}
for (int j = 0; j < colCount; j++) {
data[i][j] = "...";
}
for (++i; i <= rowCount; i++) {
for (int j = 0; j < colCount; j++) {
Column<?> col = frame.column(j);
data[i][j] = getDataToken(col, frame.rowCount() - maxRows + i - 1);
}
}
} else {
data = new String[rowCount][colCount];
for (int i = 0; i < rowCount; i++) {
for (int j = 0; j < colCount; j++) {
Column<?> col = frame.column(j);
String value = getDataToken(col, i);
data[i][j] = value == null ? "" : value;
}
}
}
return data;
}
}
|
try {
final String[] headers = getHeaderTokens(frame);
final String[][] data = getDataTokens(frame);
final int[] widths = getWidths(headers, data);
final String dataTemplate = getDataTemplate(widths);
final String headerTemplate = getHeaderTemplate(widths, headers);
final int totalWidth = IntStream.of(widths).map(w -> w + 5).sum() - 1;
final int totalHeight = data.length + 1;
int capacity = totalWidth * totalHeight;
if (capacity < 0) {
capacity = 0;
}
final StringBuilder text = new StringBuilder(capacity);
if (frame.name() != null) {
text.append(tableName(frame, totalWidth)).append(System.lineSeparator());
}
final String headerLine = String.format(headerTemplate, (Object[]) headers);
text.append(headerLine).append(System.lineSeparator());
for (int j = 0; j < totalWidth; j++) {
text.append("-");
}
for (String[] row : data) {
final String dataLine = String.format(dataTemplate, (Object[]) row);
text.append(System.lineSeparator());
text.append(dataLine);
}
final byte[] bytes = text.toString().getBytes();
this.stream.write(bytes);
this.stream.flush();
} catch (IOException ex) {
throw new IllegalStateException("Failed to print DataFrame", ex);
}
| 1,646
| 388
| 2,034
|
<no_super_class>
|
jtablesaw_tablesaw
|
tablesaw/core/src/main/java/tech/tablesaw/joining/ColumnIndexPair.java
|
ColumnIndexPair
|
toString
|
class ColumnIndexPair {
final ColumnType type;
final int left;
final int right;
public ColumnIndexPair(ColumnType type, int left, int right) {
this.type = type;
this.left = left;
this.right = right;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
final StringBuilder sb = new StringBuilder("ColumnIndexPair{");
sb.append("type=").append(type);
sb.append(", left=").append(left);
sb.append(", right=").append(right);
sb.append('}');
return sb.toString();
| 98
| 75
| 173
|
<no_super_class>
|
jtablesaw_tablesaw
|
tablesaw/core/src/main/java/tech/tablesaw/joining/RowComparatorChain.java
|
RowComparatorChain
|
equals
|
class RowComparatorChain implements Comparator<Row> {
private final List<Comparator<Row>> comparatorChain;
private BitSet orderingBits;
private boolean isLocked;
/** Constructs a comparator chain with the argument as the first node in the chain */
public RowComparatorChain(Comparator<Row> comparator) {
this(comparator, false);
}
private RowComparatorChain(Comparator<Row> comparator, boolean reverse) {
this.orderingBits = null;
this.isLocked = false;
this.comparatorChain = new ArrayList<>(1);
this.comparatorChain.add(comparator);
this.orderingBits = new BitSet(1);
if (reverse) {
this.orderingBits.set(0);
}
}
/** Appends the comparator to the end of the chain */
public void addComparator(Comparator<Row> comparator) {
this.comparatorChain.add(comparator);
}
/** Returns the number of comparators in the chain */
public int size() {
return this.comparatorChain.size();
}
private void checkChainIntegrity() {
if (this.comparatorChain.isEmpty()) {
throw new UnsupportedOperationException(
"ComparatorChains must contain at least one Comparator");
}
}
/**
* {@inheritDoc}
*
* @throws UnsupportedOperationException
*/
@Override
public int compare(Row o1, Row o2) throws UnsupportedOperationException {
if (!this.isLocked) {
this.checkChainIntegrity();
this.isLocked = true;
}
Iterator<Comparator<Row>> comparators = this.comparatorChain.iterator();
for (int comparatorIndex = 0; comparators.hasNext(); ++comparatorIndex) {
Comparator<Row> comparator = comparators.next();
int retval = comparator.compare(o1, o2);
if (retval != 0) {
if (this.orderingBits.get(comparatorIndex)) {
if (retval > 0) {
retval = -1;
} else {
retval = 1;
}
}
return retval;
}
}
return 0;
}
@Override
public int hashCode() {
int hash = 0;
if (null != this.comparatorChain) {
hash ^= this.comparatorChain.hashCode();
}
if (null != this.orderingBits) {
hash ^= this.orderingBits.hashCode();
}
return hash;
}
@Override
public boolean equals(Object object) {<FILL_FUNCTION_BODY>}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("RowComparatorChain{");
sb.append("comparatorChain=").append(comparatorChain);
sb.append('}');
return sb.toString();
}
}
|
if (this == object) {
return true;
} else if (null == object) {
return false;
} else if (!object.getClass().equals(this.getClass())) {
return false;
} else {
label48:
{
label32:
{
RowComparatorChain chain = (RowComparatorChain) object;
if (null == this.orderingBits) {
if (null != chain.orderingBits) {
break label32;
}
} else if (!this.orderingBits.equals(chain.orderingBits)) {
break label32;
}
if (null == this.comparatorChain) {
if (null == chain.comparatorChain) {
break label48;
}
} else if (this.comparatorChain.equals(chain.comparatorChain)) {
break label48;
}
}
return false;
}
return true;
}
| 811
| 261
| 1,072
|
<no_super_class>
|
jtablesaw_tablesaw
|
tablesaw/core/src/main/java/tech/tablesaw/joining/SortKey.java
|
SortKey
|
comparator
|
class SortKey implements Iterable<ColumnIndexPair> {
/** Describes how the tables are to be sorted */
private final ArrayList<ColumnIndexPair> sortOrder = new ArrayList<>();
private SortKey(ColumnIndexPair pair) {
next(pair);
}
/**
* Returns a new SortKey defining the first sort (for the first join column)
*
* @param pair The details of the sort, i.e. what type of column and the index of the columns in
* the respective tables.
*/
public static SortKey on(ColumnIndexPair pair) {
return new SortKey(pair);
}
/**
* Returns a new SortKey defining an additional sort clause
*
* @param pair The details of the sort, i.e. what type of column and the index of the columns in
* the respective tables.
*/
public SortKey next(ColumnIndexPair pair) {
sortOrder.add(pair);
return this;
}
/** Returns true if no order has been set */
public boolean isEmpty() {
return sortOrder.isEmpty();
}
/** Returns the number of columns used in this sort */
public int size() {
return sortOrder.size();
}
/**
* Returns a new SortKey for the given ColumnIndexPairs. A table being sorted on three columns,
* will have three pairs in the SortKey
*/
public static SortKey create(List<ColumnIndexPair> pairs) {
SortKey key = null;
for (ColumnIndexPair pair : pairs) {
if (key == null) { // key will be null the first time through
key = new SortKey(pair);
} else {
key.next(pair);
}
}
return key;
}
/**
* Returns a ComparatorChain consisting of one or more comparators as specified in the given
* SortKey
*/
static RowComparatorChain getChain(SortKey key) {
Iterator<ColumnIndexPair> entries = key.iterator();
ColumnIndexPair sort = entries.next();
Comparator<Row> comparator = comparator(sort);
RowComparatorChain chain = new RowComparatorChain(comparator);
while (entries.hasNext()) {
sort = entries.next();
chain.addComparator(comparator(sort));
}
return chain;
}
/** Returns a comparator for a given ColumnIndexPair */
private static Comparator<Row> comparator(ColumnIndexPair pair) {<FILL_FUNCTION_BODY>}
/** Returns the iterator for the SortKey */
@Override
public Iterator<ColumnIndexPair> iterator() {
return sortOrder.iterator();
}
@Override
public String toString() {
return MoreObjects.toStringHelper(this).add("order", sortOrder).toString();
}
}
|
if (pair.type.equals(ColumnType.INTEGER)) {
return (r11, r21) -> {
int b1 = r11.getInt(pair.left);
int b2 = r21.getInt(pair.right);
return Integer.compare(b1, b2);
};
} else if (pair.type.equals(ColumnType.LOCAL_DATE)) {
return (r11, r21) -> {
int b1 = r11.getPackedDate(pair.left);
int b2 = r21.getPackedDate(pair.right);
return Integer.compare(b1, b2);
};
} else if (pair.type.equals(ColumnType.LOCAL_TIME)) {
return (r11, r21) -> {
int b1 = r11.getPackedTime(pair.left);
int b2 = r21.getPackedTime(pair.right);
return Integer.compare(b1, b2);
};
} else if (pair.type.equals(ColumnType.LONG)) {
return (r11, r21) -> {
long b1 = r11.getLong(pair.left);
long b2 = r21.getLong(pair.right);
return Long.compare(b1, b2);
};
} else if (pair.type.equals(ColumnType.LOCAL_DATE_TIME)) {
return (r11, r21) -> {
long b1 = r11.getPackedDateTime(pair.left);
long b2 = r21.getPackedDateTime(pair.right);
return Long.compare(b1, b2);
};
} else if (pair.type.equals(ColumnType.INSTANT)) {
return (r11, r21) -> {
long b1 = r11.getPackedInstant(pair.left);
long b2 = r21.getPackedInstant(pair.right);
return Long.compare(b1, b2);
};
} else if (pair.type.equals(ColumnType.DOUBLE)) {
return (r11, r21) -> {
double b1 = r11.getDouble(pair.left);
double b2 = r21.getDouble(pair.right);
return Double.compare(b1, b2);
};
} else if (pair.type.equals(ColumnType.FLOAT)) {
return (r11, r21) -> {
float b1 = r11.getFloat(pair.left);
float b2 = r21.getFloat(pair.right);
return Float.compare(b1, b2);
};
} else if (pair.type.equals(ColumnType.BOOLEAN)) {
return (r11, r21) -> {
byte b1 = r11.getBooleanAsByte(pair.left);
byte b2 = r21.getBooleanAsByte(pair.right);
return Byte.compare(b1, b2);
};
} else if (pair.type.equals(ColumnType.STRING)) {
return (r11, r21) -> {
String b1 = r11.getString(pair.left);
String b2 = r21.getString(pair.right);
return b1.compareTo(b2);
};
}
throw new RuntimeException("Unhandled ColumnType in SortKey.");
| 727
| 892
| 1,619
|
<no_super_class>
|
jtablesaw_tablesaw
|
tablesaw/core/src/main/java/tech/tablesaw/selection/BitmapBackedSelection.java
|
BitmapBackedSelection
|
selectNRowsAtRandom
|
class BitmapBackedSelection implements Selection {
private static final Random random = new Random();
private final RoaringBitmap bitmap;
/**
* Returns a selection initialized from 0 to the given size, which cane be used for queries that
* exclude certain items, by first selecting the items to exclude, then flipping the bits.
*
* @param size The size The end point, exclusive
*/
public BitmapBackedSelection(int size) {
this.bitmap = new RoaringBitmap();
addRange(0, size);
}
/** Constructs a selection containing the elements in the given array */
public BitmapBackedSelection(int[] arr) {
this.bitmap = new RoaringBitmap();
add(arr);
}
/** Constructs a selection containing the elements in the given bitmap */
public BitmapBackedSelection(RoaringBitmap bitmap) {
this.bitmap = bitmap;
}
/** Constructs an empty Selection */
public BitmapBackedSelection() {
this.bitmap = new RoaringBitmap();
}
/** {@inheritDoc} */
@Override
public Selection removeRange(long start, long end) {
this.bitmap.remove(start, end);
return this;
}
/** {@inheritDoc} */
@Override
public Selection flip(int rangeStart, int rangeEnd) {
this.bitmap.flip((long) rangeStart, rangeEnd);
return this;
}
/** {@inheritDoc} */
@Override
public Selection add(int... ints) {
bitmap.add(ints);
return this;
}
@Override
public String toString() {
return "Selection of size: " + bitmap.getCardinality();
}
/** {@inheritDoc} */
@Override
public int size() {
return bitmap.getCardinality();
}
/** {@inheritDoc} */
@Override
public int[] toArray() {
return bitmap.toArray();
}
private RoaringBitmap toBitmap(Selection otherSelection) {
if (otherSelection instanceof BitmapBackedSelection) {
return ((BitmapBackedSelection) otherSelection).bitmap.clone();
}
RoaringBitmap bits = new RoaringBitmap();
for (int i : otherSelection) {
bits.add(i);
}
return bits;
}
/** Intersects the receiver and {@code otherSelection}, updating the receiver */
@Override
public Selection and(Selection otherSelection) {
bitmap.and(toBitmap(otherSelection));
return this;
}
/** Implements the union of the receiver and {@code otherSelection}, updating the receiver */
@Override
public Selection or(Selection otherSelection) {
bitmap.or(toBitmap(otherSelection));
return this;
}
/** {@inheritDoc} */
@Override
public Selection andNot(Selection otherSelection) {
bitmap.andNot(toBitmap(otherSelection));
return this;
}
/** {@inheritDoc} */
@Override
public boolean isEmpty() {
return size() == 0;
}
/** {@inheritDoc} */
@Override
public Selection clear() {
bitmap.clear();
return this;
}
/** {@inheritDoc} */
@Override
public boolean contains(int i) {
return bitmap.contains(i);
}
/**
* Adds to the current bitmap all integers in [rangeStart,rangeEnd)
*
* @param start inclusive beginning of range
* @param end exclusive ending of range
*/
@Override
public Selection addRange(int start, int end) {
bitmap.add((long) start, end);
return this;
}
/** {@inheritDoc} */
@Override
public int get(int i) {
return bitmap.select(i);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
BitmapBackedSelection integers = (BitmapBackedSelection) o;
return bitmap.equals(integers.bitmap);
}
@Override
public int hashCode() {
return bitmap.hashCode();
}
/** Returns a fastUtil intIterator that wraps a bitmap intIterator */
@Override
public IntIterator iterator() {
return new IntIterator() {
private final org.roaringbitmap.IntIterator iterator = bitmap.getIntIterator();
@Override
public int nextInt() {
return iterator.next();
}
@Override
public int skip(int k) {
throw new UnsupportedOperationException("Views do not support skipping in the iterator");
}
@Override
public boolean hasNext() {
return iterator.hasNext();
}
};
}
/** Returns a Selection containing all indexes in the array */
protected static Selection with(int... rows) {
BitmapBackedSelection selection = new BitmapBackedSelection();
for (int i : rows) {
selection.add(i);
}
return selection;
}
/** Returns a Selection containing all indexes in the array */
protected static Selection fromBitmap(RoaringBitmap bitmap) {
return new BitmapBackedSelection(bitmap);
}
/**
* Returns a Selection containing all indexes in the range start (inclusive) to end (exclusive),
*/
protected static Selection withRange(int start, int end) {
BitmapBackedSelection selection = new BitmapBackedSelection();
selection.addRange(start, end);
return selection;
}
/**
* Returns a Selection containing all values from totalRangeStart to totalRangeEnd, except for
* those in the range from excludedRangeStart to excludedRangeEnd. Start values are inclusive, end
* values exclusive.
*/
protected static Selection withoutRange(
int totalRangeStart, int totalRangeEnd, int excludedRangeStart, int excludedRangeEnd) {
Preconditions.checkArgument(excludedRangeStart >= totalRangeStart);
Preconditions.checkArgument(excludedRangeEnd <= totalRangeEnd);
Preconditions.checkArgument(totalRangeEnd >= totalRangeStart);
Preconditions.checkArgument(excludedRangeEnd >= excludedRangeStart);
Selection selection = Selection.withRange(totalRangeStart, totalRangeEnd);
Selection exclusion = Selection.withRange(excludedRangeStart, excludedRangeEnd);
selection.andNot(exclusion);
return selection;
}
/** Returns an randomly generated selection of size N where Max is the largest possible value */
protected static Selection selectNRowsAtRandom(int n, int max) {<FILL_FUNCTION_BODY>}
}
|
Selection selection = new BitmapBackedSelection();
if (n > max) {
throw new IllegalArgumentException(
"Illegal arguments: N (" + n + ") greater than Max (" + max + ")");
}
int[] rows = new int[n];
if (n == max) {
for (int k = 0; k < n; ++k) {
selection.add(k);
}
return selection;
}
BitSet bs = new BitSet(max);
int cardinality = 0;
while (cardinality < n) {
int v = random.nextInt(max);
if (!bs.get(v)) {
bs.set(v);
cardinality++;
}
}
int pos = 0;
for (int i = bs.nextSetBit(0); i >= 0; i = bs.nextSetBit(i + 1)) {
rows[pos++] = i;
}
for (int row : rows) {
selection.add(row);
}
return selection;
| 1,755
| 271
| 2,026
|
<no_super_class>
|
jtablesaw_tablesaw
|
tablesaw/core/src/main/java/tech/tablesaw/sorting/Sort.java
|
Sort
|
getOrder
|
class Sort implements Iterable<Map.Entry<String, Sort.Order>> {
private final LinkedHashMap<String, Order> sortOrder = new LinkedHashMap<>();
/**
* Constructs a Sort specifying the order (ascending or descending) to apply to the column with
* the given name
*/
public Sort(String columnName, Order order) {
next(columnName, order);
}
/**
* Returns a Sort specifying the order (ascending or descending) to apply to the column with the
* given name
*/
public static Sort on(String columnName, Order order) {
return new Sort(columnName, order);
}
/**
* Returns a Sort that concatenates a new sort on the given order (ascending or descending) and
* columnName onto the sort specified here. This method is used to construct complex sorts such
* as: Sort.on("foo", Order.ASCEND).next("bar", Order.DESCEND);
*/
public Sort next(String columnName, Order order) {
sortOrder.put(columnName, order);
return this;
}
/** Returns true if no order has been set */
public boolean isEmpty() {
return sortOrder.isEmpty();
}
/** Returns the number of columns used in this sort */
public int size() {
return sortOrder.size();
}
/**
* Create a Sort object from the given table and sort column names. Does not sort the table.
*
* @param table to sort. Used only to pull the table's schema. Does not modify the table.
* @param columnNames The columns to sort on. Can prefix column name with + for ascending, - for
* descending. Default to ascending if no prefix is added.
* @return a {@link #Sort} Object.
*/
public static Sort create(Table table, String... columnNames) {
Preconditions.checkArgument(columnNames.length > 0, "At least one sort column must provided.");
Sort key = null;
Set<String> names = table.columnNames().stream().map(String::toUpperCase).collect(toSet());
for (String columnName : columnNames) {
Sort.Order order = Sort.Order.ASCEND;
if (!names.contains(columnName.toUpperCase())) {
// the column name has been annotated with a prefix.
// get the prefix which could be - or +
String prefix = columnName.substring(0, 1);
Optional<Order> orderOptional = getOrder(prefix);
// Invalid prefix, column name exists on table.
if (!orderOptional.isPresent() && names.contains(columnName.substring(1).toUpperCase())) {
throw new IllegalStateException("Column prefix: " + prefix + " is unknown.");
}
// Valid prefix, column name does not exist on table.
if (orderOptional.isPresent() && !names.contains(columnName.substring(1).toUpperCase())) {
throw new IllegalStateException(
String.format(
"Column %s does not exist in table %s", columnName.substring(1), table.name()));
}
// Invalid prefix, column name does not exist on table.
if (!orderOptional.isPresent()) {
throw new IllegalStateException("Unrecognized Column: '" + columnName + "'");
}
// Valid Prefix, column name exists on table.
// remove - prefix so provided name matches actual column name
columnName = columnName.substring(1);
order = orderOptional.get();
}
if (key == null) { // key will be null the first time through
key = new Sort(columnName, order);
} else {
key.next(columnName, order);
}
}
return key;
}
private static Optional<Order> getOrder(String prefix) {<FILL_FUNCTION_BODY>}
/**
* Returns an iterator over elements of type {@code T}.
*
* @return an Iterator.
*/
@Override
public Iterator<Map.Entry<String, Order>> iterator() {
return sortOrder.entrySet().iterator();
}
@Override
public String toString() {
return MoreObjects.toStringHelper(this).add("order", sortOrder).toString();
}
public enum Order {
ASCEND,
DESCEND
}
}
|
switch (prefix) {
case "+":
return Optional.of(Order.ASCEND);
case "-":
return Optional.of(Order.DESCEND);
default:
return Optional.empty();
}
| 1,103
| 61
| 1,164
|
<no_super_class>
|
jtablesaw_tablesaw
|
tablesaw/core/src/main/java/tech/tablesaw/sorting/SortUtils.java
|
SortUtils
|
getChain
|
class SortUtils {
private SortUtils() {}
/** Returns a comparator chain for sorting according to the given key */
public static IntComparatorChain getChain(Table table, Sort key) {<FILL_FUNCTION_BODY>}
/**
* Returns a comparator for the column matching the specified name
*
* @param column The column to sort
* @param order Specifies whether the sort should be in ascending or descending order
*/
public static IntComparator rowComparator(Column<?> column, Sort.Order order) {
IntComparator rowComparator = column.rowComparator();
if (order == Sort.Order.DESCEND) {
return ReversingIntComparator.reverse(rowComparator);
} else {
return rowComparator;
}
}
/**
* Returns a comparator that can be used to sort the records in this table according to the given
* sort key
*/
public static IntComparator getComparator(Table table, Sort key) {
Iterator<Map.Entry<String, Sort.Order>> entries = key.iterator();
Map.Entry<String, Sort.Order> sort = entries.next();
Column<?> column = table.column(sort.getKey());
return SortUtils.rowComparator(column, sort.getValue());
}
}
|
Iterator<Map.Entry<String, Sort.Order>> entries = key.iterator();
Map.Entry<String, Sort.Order> sort = entries.next();
Column<?> column = table.column(sort.getKey());
IntComparator comparator = rowComparator(column, sort.getValue());
IntComparatorChain chain = new IntComparatorChain(comparator);
while (entries.hasNext()) {
sort = entries.next();
chain.addComparator(rowComparator(table.column(sort.getKey()), sort.getValue()));
}
return chain;
| 344
| 154
| 498
|
<no_super_class>
|
jtablesaw_tablesaw
|
tablesaw/core/src/main/java/tech/tablesaw/sorting/comparators/IntComparatorChain.java
|
IntComparatorChain
|
checkChainIntegrity
|
class IntComparatorChain implements IntComparator, Serializable {
private static final long serialVersionUID = 1L;
private final List<IntComparator> comparatorChain;
private BitSet orderingBits;
private boolean isLocked;
/** Constructs a comparator chain with the argument as the first node in the chain */
public IntComparatorChain(IntComparator comparator) {
this(comparator, false);
}
private IntComparatorChain(IntComparator comparator, boolean reverse) {
this.orderingBits = null;
this.isLocked = false;
this.comparatorChain = new ArrayList<>(1);
this.comparatorChain.add(comparator);
this.orderingBits = new BitSet(1);
if (reverse) {
this.orderingBits.set(0);
}
}
/** Appends the comparator to the end of the chain */
public void addComparator(IntComparator comparator) {
this.addComparator(comparator, false);
}
/**
* Add the comparator to the end of the chain, reversing the application order if {@code reverse}
* is equal to {@code true}
*/
private void addComparator(IntComparator comparator, boolean reverse) {
this.comparatorChain.add(comparator);
if (reverse) {
this.orderingBits.set(this.comparatorChain.size() - 1);
}
}
/** Returns the number of comparators in the chain */
public int size() {
return this.comparatorChain.size();
}
private void checkChainIntegrity() {<FILL_FUNCTION_BODY>}
/**
* {@inheritDoc}
*
* @throws UnsupportedOperationException
*/
@Override
public int compare(int o1, int o2) throws UnsupportedOperationException {
if (!this.isLocked) {
this.checkChainIntegrity();
this.isLocked = true;
}
Iterator<IntComparator> comparators = this.comparatorChain.iterator();
for (int comparatorIndex = 0; comparators.hasNext(); ++comparatorIndex) {
IntComparator comparator = comparators.next();
int retval = comparator.compare(o1, o2);
if (retval != 0) {
if (this.orderingBits.get(comparatorIndex)) {
if (retval > 0) {
retval = -1;
} else {
retval = 1;
}
}
return retval;
}
}
return 0;
}
@Override
public int hashCode() {
int hash = 0;
if (null != this.comparatorChain) {
hash ^= this.comparatorChain.hashCode();
}
if (null != this.orderingBits) {
hash ^= this.orderingBits.hashCode();
}
return hash;
}
@Override
public boolean equals(Object object) {
if (this == object) {
return true;
} else if (null == object) {
return false;
} else if (!object.getClass().equals(this.getClass())) {
return false;
} else {
label48:
{
label32:
{
IntComparatorChain chain = (IntComparatorChain) object;
if (null == this.orderingBits) {
if (null != chain.orderingBits) {
break label32;
}
} else if (!this.orderingBits.equals(chain.orderingBits)) {
break label32;
}
if (null == this.comparatorChain) {
if (null == chain.comparatorChain) {
break label48;
}
} else if (this.comparatorChain.equals(chain.comparatorChain)) {
break label48;
}
}
return false;
}
return true;
}
}
}
|
if (this.comparatorChain.isEmpty()) {
throw new UnsupportedOperationException(
"ComparatorChains must contain at least one Comparator");
}
| 1,077
| 46
| 1,123
|
<no_super_class>
|
jtablesaw_tablesaw
|
tablesaw/core/src/main/java/tech/tablesaw/table/RollingColumn.java
|
RollingColumn
|
calc
|
class RollingColumn {
/** The column providing the data for the rolling calculation */
protected final Column<?> column;
/** The size of the rolling window */
protected final int window;
/**
* Constructs a rolling column based on calculations on a sliding window of {@code window} rows of
* data from the given column
*/
public RollingColumn(Column<?> column, int window) {
this.column = column;
this.window = window;
}
/**
* Generates a name for the column based on the name of the original column and the function used
* in the calculation
*/
protected String generateNewColumnName(AggregateFunction<?, ?> function) {
return column.name() + " " + window + "-period" + " " + function.functionName();
}
/** Performs the calculation and returns a new column containing the results */
@SuppressWarnings({"unchecked"})
public <INCOL extends Column<?>, OUT> Column<?> calc(AggregateFunction<INCOL, OUT> function) {<FILL_FUNCTION_BODY>}
}
|
// TODO: the subset operation copies the array. creating a view would likely be more efficient
Column<?> result = function.returnType().create(generateNewColumnName(function));
for (int i = 0; i < window - 1; i++) {
result.appendMissing();
}
for (int origColIndex = 0; origColIndex < column.size() - window + 1; origColIndex++) {
Selection selection = new BitmapBackedSelection();
selection.addRange(origColIndex, origColIndex + window);
INCOL subsetCol = (INCOL) column.subset(selection.toArray());
OUT answer = function.summarize(subsetCol);
if (answer instanceof Number) {
Number number = (Number) answer;
((DoubleColumn) result).append(number.doubleValue());
} else {
result.appendObj(answer);
}
}
return result;
| 280
| 228
| 508
|
<no_super_class>
|
jtablesaw_tablesaw
|
tablesaw/core/src/main/java/tech/tablesaw/table/SelectionTableSliceGroup.java
|
SelectionTableSliceGroup
|
splitOnSelection
|
class SelectionTableSliceGroup extends TableSliceGroup {
/**
* Creates a TableSliceGroup where each slice contains {@code step} number of rows from the
* backing table
*
* @param original The original backing table that provides the data for the new slice group
* @param subTableNameTemplate The prefix of a name for each slice in the group. If the argument
* is "step" the name will take the form "step 1", "step 2", etc.
* @param step The number of rows per slice
* @return The new table
*/
public static SelectionTableSliceGroup create(
Table original, String subTableNameTemplate, int step) {
return new SelectionTableSliceGroup(original, subTableNameTemplate, step);
}
private SelectionTableSliceGroup(Table original, String subTableNameTemplate, int step) {
super(original);
List<Selection> selections = new ArrayList<>();
for (int i = 0; i < original.rowCount() - step; i += step) {
Selection selection = new BitmapBackedSelection();
selection.addRange(i, i + step);
selections.add(selection);
}
splitOnSelection(subTableNameTemplate, selections);
}
private void splitOnSelection(String nameTemplate, List<Selection> selections) {<FILL_FUNCTION_BODY>}
}
|
for (int i = 0; i < selections.size(); i++) {
TableSlice view = new TableSlice(getSourceTable(), selections.get(i));
String name = nameTemplate + ": " + i + 1;
view.setName(name);
getSlices().add(view);
}
| 348
| 85
| 433
|
<methods>public transient tech.tablesaw.api.Table aggregate(java.lang.String, AggregateFunction<?,?>[]) ,public tech.tablesaw.api.Table aggregate(ListMultimap<java.lang.String,AggregateFunction<?,?>>) ,public static java.lang.String aggregateColumnName(java.lang.String, java.lang.String) ,public List<tech.tablesaw.api.Table> asTableList() ,public tech.tablesaw.table.TableSlice get(int) ,public List<tech.tablesaw.table.TableSlice> getSlices() ,public tech.tablesaw.api.Table getSourceTable() ,public Iterator<tech.tablesaw.table.TableSlice> iterator() ,public int size() ,public static tech.tablesaw.api.Table summaryTableName(tech.tablesaw.api.Table) <variables>private static final Splitter SPLITTER,protected static final java.lang.String SPLIT_STRING,private tech.tablesaw.api.Table sourceTable,private final non-sealed java.lang.String[] splitColumnNames,private final List<tech.tablesaw.table.TableSlice> subTables
|
jtablesaw_tablesaw
|
tablesaw/core/src/main/java/tech/tablesaw/table/StandardTableSliceGroup.java
|
StandardTableSliceGroup
|
splitOn
|
class StandardTableSliceGroup extends TableSliceGroup {
/**
* Constructs a TableSliceGroup made by subdividing the original table by the given columns. A
* group subdividing on the two columns "Name" and "Place" will have a slice for every combination
* of name and place in the table
*/
private StandardTableSliceGroup(Table original, CategoricalColumn<?>... columns) {
super(original, splitColumnNames(columns));
setSourceTable(getSourceTable());
splitOn(getSplitColumnNames());
}
private static String[] splitColumnNames(CategoricalColumn<?>... columns) {
String[] splitColumnNames = new String[columns.length];
for (int i = 0; i < columns.length; i++) {
splitColumnNames[i] = columns[i].name();
}
return splitColumnNames;
}
/**
* Returns a viewGroup splitting the original table on the given columns. The named columns must
* be CategoricalColumns
*/
public static StandardTableSliceGroup create(Table original, String... columnsNames) {
List<CategoricalColumn<?>> columns = original.categoricalColumns(columnsNames);
return new StandardTableSliceGroup(original, columns.toArray(new CategoricalColumn<?>[0]));
}
/**
* Returns a viewGroup splitting the original table on the given columns. The named columns must
* be CategoricalColumns
*/
public static StandardTableSliceGroup create(Table original, CategoricalColumn<?>... columns) {
return new StandardTableSliceGroup(original, columns);
}
/**
* Splits the sourceTable table into sub-tables, grouping on the columns whose names are given in
* splitColumnNames
*/
private void splitOn(String... splitColumnNames) {<FILL_FUNCTION_BODY>}
private boolean containsTextColumn(List<Column<?>> splitColumns) {
return false;
// return splitColumns.stream().anyMatch(objects -> objects.type().equals(ColumnType.TEXT));
}
/** Wrapper class for a byte[] that implements equals and hashcode. */
private static class ByteArray {
final byte[] bytes;
ByteArray(byte[] bytes) {
this.bytes = bytes;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ByteArray byteArray = (ByteArray) o;
return Arrays.equals(bytes, byteArray.bytes);
}
@Override
public int hashCode() {
return Arrays.hashCode(bytes);
}
}
}
|
Map<ByteArray, Selection> selectionMap = new LinkedHashMap<>();
Map<ByteArray, String> sliceNameMap = new HashMap<>();
List<Column<?>> splitColumns = getSourceTable().columns(splitColumnNames);
if (containsTextColumn(splitColumns)) {
for (int i = 0; i < getSourceTable().rowCount(); i++) {
ByteArrayList byteArrayList = new ByteArrayList();
StringBuilder stringKey = new StringBuilder();
int count = 0;
for (Column<?> col : splitColumns) {
stringKey.append(col.getString(i));
if (count < splitColumns.size() - 1) {
stringKey.append(SPLIT_STRING);
}
byteArrayList.addElements(byteArrayList.size(), col.asBytes(i));
count++;
}
// Add to the matching selection.
ByteArray byteArray = new ByteArray(byteArrayList.toByteArray());
Selection selection = selectionMap.getOrDefault(byteArray, new BitmapBackedSelection());
selection.add(i);
selectionMap.put(byteArray, selection);
sliceNameMap.put(byteArray, stringKey.toString());
}
} else { // handle the case where split is on non-text-columns
int byteSize = getByteSize(splitColumns);
for (int i = 0; i < getSourceTable().rowCount(); i++) {
// TODO: instead of splitting on column type, have a function that returns the byte size?
StringBuilder stringKey = new StringBuilder();
ByteBuffer byteBuffer = ByteBuffer.allocate(byteSize);
int count = 0;
for (Column<?> col : splitColumns) {
stringKey.append(col.getString(i));
if (count < splitColumns.size() - 1) {
stringKey.append(SPLIT_STRING);
}
byteBuffer.put(col.asBytes(i));
count++;
}
// Add to the matching selection.
ByteArray byteArray = new ByteArray(byteBuffer.array());
Selection selection = selectionMap.getOrDefault(byteArray, new BitmapBackedSelection());
selection.add(i);
selectionMap.put(byteArray, selection);
sliceNameMap.put(byteArray, stringKey.toString());
}
}
// Construct slices for all the values in our maps
for (Entry<ByteArray, Selection> entry : selectionMap.entrySet()) {
TableSlice slice = new TableSlice(getSourceTable(), entry.getValue());
slice.setName(sliceNameMap.get(entry.getKey()));
addSlice(slice);
}
| 692
| 663
| 1,355
|
<methods>public transient tech.tablesaw.api.Table aggregate(java.lang.String, AggregateFunction<?,?>[]) ,public tech.tablesaw.api.Table aggregate(ListMultimap<java.lang.String,AggregateFunction<?,?>>) ,public static java.lang.String aggregateColumnName(java.lang.String, java.lang.String) ,public List<tech.tablesaw.api.Table> asTableList() ,public tech.tablesaw.table.TableSlice get(int) ,public List<tech.tablesaw.table.TableSlice> getSlices() ,public tech.tablesaw.api.Table getSourceTable() ,public Iterator<tech.tablesaw.table.TableSlice> iterator() ,public int size() ,public static tech.tablesaw.api.Table summaryTableName(tech.tablesaw.api.Table) <variables>private static final Splitter SPLITTER,protected static final java.lang.String SPLIT_STRING,private tech.tablesaw.api.Table sourceTable,private final non-sealed java.lang.String[] splitColumnNames,private final List<tech.tablesaw.table.TableSlice> subTables
|
jtablesaw_tablesaw
|
tablesaw/core/src/main/java/tech/tablesaw/table/TableSliceGroup.java
|
TableSliceGroup
|
splitGroupingColumn
|
class TableSliceGroup implements Iterable<TableSlice> {
/**
* A string that is used internally as a delimiter in creating a column name from all the grouping
* columns
*/
protected static final String SPLIT_STRING = "~~~";
/**
* A function that splits the group column name back into the original column names for the
* grouping columns
*/
private static final Splitter SPLITTER = Splitter.on(SPLIT_STRING);
/** The list of slices or views over the source table that I contain */
private final List<TableSlice> subTables = new ArrayList<>();
/** An array containing the names of the columns that the backing table was split on */
private final String[] splitColumnNames;
// The table that underlies all the manipulations performed here
private Table sourceTable;
/**
* Returns an instance for calculating a single summary for the given table, with no sub-groupings
*/
protected TableSliceGroup(Table original) {
sourceTable = original;
splitColumnNames = new String[0];
}
/**
* Returns an instance for calculating subgroups, one for each combination of the given
* groupColumnNames that appear in the source table
*/
protected TableSliceGroup(Table sourceTable, String[] groupColumnNames) {
this.sourceTable = sourceTable;
this.splitColumnNames = groupColumnNames;
}
/** Returns the names of the columns the backing table was split on. */
protected String[] getSplitColumnNames() {
return splitColumnNames;
}
/** Returns the sum of the sizes for the columns in the given {@link Column} list */
protected int getByteSize(List<Column<?>> columns) {
int byteSize = 0;
for (Column<?> c : columns) {
byteSize += c.byteSize();
}
return byteSize;
}
/** Add a slice to this group */
protected void addSlice(TableSlice slice) {
subTables.add(slice);
}
/** Returns the slices as a list */
public List<TableSlice> getSlices() {
return subTables;
}
/** Returns the ith slice in this group */
public TableSlice get(int i) {
return subTables.get(i);
}
/** Returns the table behind this slice group */
public Table getSourceTable() {
return sourceTable;
}
/** Returns the number of slices */
public int size() {
return subTables.size();
}
/**
* For a subtable that is grouped by the values in more than one column, split the grouping column
* into separate cols and return the revised view
*/
private Table splitGroupingColumn(Table groupTable) {<FILL_FUNCTION_BODY>}
/**
* Applies the given aggregation to the given column. The apply and combine steps of a
* split-apply-combine.
*/
public Table aggregate(String colName1, AggregateFunction<?, ?>... functions) {
ArrayListMultimap<String, AggregateFunction<?, ?>> columnFunctionMap =
ArrayListMultimap.create();
columnFunctionMap.putAll(colName1, Lists.newArrayList(functions));
return aggregate(columnFunctionMap);
}
/**
* Applies the given aggregations to the given columns. The apply and combine steps of a
* split-apply-combine.
*
* @param functions map from column name to aggregation to apply on that function
*/
@SuppressWarnings({"unchecked", "rawtypes"})
public Table aggregate(ListMultimap<String, AggregateFunction<?, ?>> functions) {
Table groupTable = summaryTableName(sourceTable);
StringColumn groupColumn = StringColumn.create("Group");
groupTable.addColumns(groupColumn);
boolean firstFunction = true;
for (Map.Entry<String, Collection<AggregateFunction<?, ?>>> entry :
functions.asMap().entrySet()) {
String columnName = entry.getKey();
for (AggregateFunction function : entry.getValue()) {
String colName = aggregateColumnName(columnName, function.functionName());
ColumnType type = function.returnType();
Column resultColumn = type.create(colName);
for (TableSlice subTable : getSlices()) {
Object result = function.summarize(subTable.column(columnName));
if (firstFunction) {
groupColumn.append(subTable.name());
}
if (function.returnType().equals(ColumnType.DOUBLE)) {
Number number = (Number) result;
resultColumn.append(number.doubleValue());
} else {
resultColumn.append(result);
}
}
groupTable.addColumns(resultColumn);
firstFunction = false;
}
}
return splitGroupingColumn(groupTable);
}
/** Returns the name of a summary table made by aggregating on the slices in this group */
public static Table summaryTableName(Table source) {
return Table.create(source.name() + " summary");
}
/**
* Returns an iterator over elements of type {@code T}.
*
* @return an Iterator.
*/
@Override
public Iterator<TableSlice> iterator() {
return subTables.iterator();
}
/**
* Returns a column name for aggregated data based on the given source column name and function
*/
public static String aggregateColumnName(String columnName, String functionName) {
return String.format("%s [%s]", functionName, columnName);
}
/**
* Returns a list of Tables created by reifying my list of slices (views) over the original table
*/
public List<Table> asTableList() {
List<Table> tableList = new ArrayList<>();
for (TableSlice view : this) {
tableList.add(view.asTable());
}
return tableList;
}
/** Sets the source table that backs this TableSliceGroup */
protected void setSourceTable(Table sourceTable) {
this.sourceTable = sourceTable;
}
}
|
if (splitColumnNames.length > 0) {
List<Column<?>> newColumns = new ArrayList<>();
List<Column<?>> columns = sourceTable.columns(splitColumnNames);
for (Column<?> column : columns) {
Column<?> newColumn = column.emptyCopy();
newColumns.add(newColumn);
}
// iterate through the rows in the table and split each of the grouping columns into multiple
// columns
for (int row = 0; row < groupTable.rowCount(); row++) {
List<String> strings = SPLITTER.splitToList(groupTable.stringColumn("Group").get(row));
for (int col = 0; col < newColumns.size(); col++) {
newColumns.get(col).appendCell(strings.get(col));
}
}
for (int col = 0; col < newColumns.size(); col++) {
Column<?> c = newColumns.get(col);
groupTable.insertColumn(col, c);
}
groupTable.removeColumns("Group");
}
return groupTable;
| 1,566
| 279
| 1,845
|
<no_super_class>
|
jtablesaw_tablesaw
|
tablesaw/core/src/main/java/tech/tablesaw/util/DoubleArrays.java
|
DoubleArrays
|
toN
|
class DoubleArrays {
/** Returns a double[] initialized with the values from 0 to n-1, inclusive; */
public static double[] toN(int n) {<FILL_FUNCTION_BODY>}
public static double[][] to2dArray(NumericColumn<?>... columns) {
Preconditions.checkArgument(columns.length >= 1);
int obs = columns[0].size();
double[][] allVals = new double[obs][columns.length];
for (int r = 0; r < obs; r++) {
for (int c = 0; c < columns.length; c++) {
allVals[r][c] = columns[c].getDouble(r);
}
}
return allVals;
}
public static double[][] to2dArray(List<NumericColumn<?>> columnList) {
return to2dArray(columnList.toArray(new NumericColumn<?>[0]));
}
public static double[][] to2dArray(TableSliceGroup views, int columnNumber) {
int viewCount = views.size();
double[][] allVals = new double[viewCount][];
for (int viewNumber = 0; viewNumber < viewCount; viewNumber++) {
TableSlice view = views.get(viewNumber);
allVals[viewNumber] = new double[view.rowCount()];
NumericColumn<?> numberColumn = view.numberColumn(columnNumber);
for (int r = 0; r < view.rowCount(); r++) {
allVals[viewNumber][r] = numberColumn.getDouble(r);
}
}
return allVals;
}
public static double[][] to2dArray(double[] x, double[] y) {
double[][] allVals = new double[x.length][2];
for (int i = 0; i < x.length; i++) {
allVals[i][0] = x[i];
allVals[i][1] = y[i];
}
return allVals;
}
public static double[][] to2dArray(NumericColumn<?> x, NumericColumn<?> y) {
double[][] allVals = new double[x.size()][2];
for (int i = 0; i < x.size(); i++) {
allVals[i][0] = x.getDouble(i);
allVals[i][1] = y.getDouble(i);
}
return allVals;
}
}
|
double[] result = new double[n];
for (int i = 0; i < n; i++) {
result[i] = i;
}
return result;
| 650
| 48
| 698
|
<no_super_class>
|
jtablesaw_tablesaw
|
tablesaw/docs-src/src/main/java/tech/tablesaw/docs/Main.java
|
Main
|
main
|
class Main {
public static void main(String[] args) throws IOException, InterruptedException {<FILL_FUNCTION_BODY>}
}
|
List<DocsSourceFile> docsClasses =
Arrays.asList(
// Register new docs classes here.
new Tutorial(),
new GettingStarted(),
// userguide
new CrossTabs());
for (DocsSourceFile docsClass : docsClasses) {
docsClass.run();
}
| 37
| 91
| 128
|
<no_super_class>
|
jtablesaw_tablesaw
|
tablesaw/docs-src/src/main/java/tech/tablesaw/docs/OutputWriter.java
|
OutputWriter
|
write
|
class OutputWriter {
private final Class<?> clazz;
public OutputWriter(Class<?> clazz) {
this.clazz = clazz;
try {
emptyFile();
} catch (IOException e) {
throw new RuntimeException(e.getMessage(), e);
}
}
/**
* Write the output of arbitrary java code to a file so it can be used in the documentation.
*
* @param object the object to write to the text file. Will call toString();
* @param tag the tag to mark the snippet with.
* @throws IOException
*/
public void write(Object object, String tag) throws IOException {<FILL_FUNCTION_BODY>}
private Path getPath() {
URL fullPath = clazz.getResource(clazz.getSimpleName() + ".class");
String path = fullPath.toString().split("classes")[1];
path = path.replace(".class", ".txt");
path = "./output" + path;
return Paths.get(path);
}
private void emptyFile() throws IOException {
if (Files.exists(getPath())) {
Files.delete(getPath());
}
if (!Files.exists(getPath().getParent())) {
Files.createDirectories(getPath().getParent());
}
Files.createFile(getPath());
}
/**
* Class to mock System.out.println()
*
* <p>This class is non-blocking and returns a String.
*/
public static class System {
public static final Printer out = new Printer();
public static class Printer {
private Printer() {};
public String println(Object obj) {
return obj.toString();
}
}
}
}
|
List<String> lines = new ArrayList<>();
lines.add("// @@ " + tag);
lines.addAll(Arrays.asList(object.toString().split(java.lang.System.lineSeparator())));
lines.add("// @@ " + tag);
lines.add(java.lang.System.lineSeparator());
Files.write(getPath(), lines, UTF_8, APPEND);
| 451
| 107
| 558
|
<no_super_class>
|
jtablesaw_tablesaw
|
tablesaw/docs-src/src/main/java/tech/tablesaw/docs/Tutorial.java
|
Tutorial
|
run
|
class Tutorial implements DocsSourceFile {
public static final OutputWriter outputWriter = new OutputWriter(Tutorial.class);
public void run() throws IOException {<FILL_FUNCTION_BODY>}
}
|
// @@ table_read
Table tornadoes = Table.read().csv("../data/tornadoes_1950-2014.csv");
// @@ table_read
outputWriter.write(
// @@ table_columns
tornadoes.columnNames()
// @@ table_columns
,
"table_columns");
outputWriter.write(
// @@ table_shape
tornadoes.shape()
// @@ table_shape
,
"table_shape");
outputWriter.write(
// @@ table_structure
tornadoes.structure().printAll()
// @@ table_structure
,
"table_structure");
// @@ print_table
System.out.println(tornadoes);
// @@ print_table
outputWriter.write(tornadoes, "print_table");
outputWriter.write(
// @@ filter_structure
tornadoes
.structure()
.where(tornadoes.structure().stringColumn("Column Type").isEqualTo("DOUBLE"))
// @@ filter_structure
,
"filter_structure");
outputWriter.write(
// @@ first_n
tornadoes.first(3)
// @@ first_n
,
"first_n");
// @@ date_col
StringColumn month = tornadoes.dateColumn("Date").month();
// @@ date_col
// @@ add_date_col
tornadoes.addColumns(month);
// @@ add_date_col
// @@ remove_col
tornadoes.removeColumns("State No");
// @@ remove_col
// @@ sort_on
tornadoes.sortOn("-Fatalities");
// @@ sort_on
outputWriter.write(
// @@ summary
tornadoes.column("Fatalities").summary().print()
// @@ summary
,
"summary");
// @@ filtering
Table result = tornadoes.where(tornadoes.intColumn("Fatalities").isGreaterThan(0));
result = tornadoes.where(result.dateColumn("Date").isInApril());
result =
tornadoes.where(
result
.intColumn("Width")
.isGreaterThan(300) // 300 yards
.or(result.doubleColumn("Length").isGreaterThan(10))); // 10 miles
result = result.selectColumns("State", "Date");
// @@ filtering
outputWriter.write(result.first(3), "filtering");
// @@ totals
Table injuriesByScale = tornadoes.summarize("Injuries", median).by("Scale").sortOn("Scale");
injuriesByScale.setName("Median injuries by Tornado Scale");
// @@ totals
outputWriter.write(injuriesByScale.first(10), "totals");
outputWriter.write(
// @@ crosstabs
CrossTab.counts(tornadoes, tornadoes.stringColumn("State"), tornadoes.intColumn("Scale"))
.first(10)
// @@ crosstabs
,
"crosstabs");
// Putting it all togeather.
// @@ all_together_where
Table summer =
tornadoes.where(
QuerySupport.or(
// In June
QuerySupport.and(
t -> t.dateColumn("Date").month().isEqualTo("JUNE"),
t -> t.dateColumn("Date").dayOfMonth().isGreaterThanOrEqualTo(21)),
// In July or August
t -> t.dateColumn("Date").month().isIn("JULY", "AUGUST"),
// In September
QuerySupport.or(
t -> t.dateColumn("Date").month().isEqualTo("SEPTEMBER"),
t -> t.dateColumn("Date").dayOfMonth().isLessThan(22))));
// @@ all_together_where
// @@ all_together_lag
summer = summer.sortAscendingOn("Date", "Time");
summer.addColumns(summer.dateColumn("Date").lag(1));
DateColumn summerDate = summer.dateColumn("Date");
DateColumn laggedDate = summer.dateColumn("Date lag(1)");
IntColumn delta = laggedDate.daysUntil(summerDate);
summer.addColumns(delta);
// @@ all_together_lag
// @@ all_together_summarize
Table summary = summer.summarize(delta, mean, count).by(summerDate.year());
// @@ all_together_summarize
outputWriter.write(summary.first(5), "all_together_summarize");
outputWriter.write(
// @@ all_together_single_col_summary
summary.nCol(1).mean()
// @@ all_together_single_col_summary
,
"all_together_single_col_summary");
// @@ write_csv
tornadoes.write().csv("rev_tornadoes_1950-2014.csv");
// @@ write_csv
| 56
| 1,350
| 1,406
|
<no_super_class>
|
jtablesaw_tablesaw
|
tablesaw/docs-src/src/main/java/tech/tablesaw/docs/userguide/CrossTabs.java
|
CrossTabs
|
run
|
class CrossTabs implements DocsSourceFile {
public static final OutputWriter outputWriter = new OutputWriter(CrossTabs.class);
@Override
public void run() throws IOException {<FILL_FUNCTION_BODY>}
}
|
// @@ intro_block
// preparation: load the data, and add a string column to hold the months in the date col
Table table = Table.read().csv("../data/bush.csv");
StringColumn month = table.dateColumn("date").month();
month.setName("month");
table.addColumns(month);
// perform the crossTab operation
Table counts = table.xTabCounts("month", "who");
System.out.println(counts);
// @@ intro_block
outputWriter.write(counts, "intro_block");
// @@ who_counts
Table whoCounts = table.xTabCounts("who");
// @@ who_counts
outputWriter.write(whoCounts, "who_counts");
// @@ who_percents
Table whoPercents = table.xTabPercents("who");
// @@ who_percents
// @@ who_percents_format
whoPercents
.columnsOfType(ColumnType.DOUBLE) // format to display as percents
.forEach(x -> ((NumberColumn) x).setPrintFormatter(NumberColumnFormatter.percent(0)));
// @@ who_percents_format
outputWriter.write(whoPercents, "who_percents_format");
// @@ table_percents
Table tablePercents = table.xTabTablePercents("month", "who");
tablePercents
.columnsOfType(ColumnType.DOUBLE)
.forEach(x -> ((NumberColumn) x).setPrintFormatter(NumberColumnFormatter.percent(1)));
// @@ table_percents
outputWriter.write(tablePercents, "table_percents");
// @@ column_percents
Table columnPercents = table.xTabColumnPercents("month", "who");
// @@ column_percents
columnPercents
.columnsOfType(ColumnType.DOUBLE)
.forEach(x -> ((NumberColumn) x).setPrintFormatter(NumberColumnFormatter.percent(0)));
outputWriter.write(columnPercents, "column_percents");
// @@ row_percents
Table rowPercents = table.xTabRowPercents("month", "who");
// @@ row_percents
rowPercents
.columnsOfType(ColumnType.DOUBLE)
.forEach(x -> ((NumberColumn) x).setPrintFormatter(NumberColumnFormatter.percent(0)));
outputWriter.write(rowPercents, "row_percents");
| 60
| 670
| 730
|
<no_super_class>
|
jtablesaw_tablesaw
|
tablesaw/html/src/main/java/tech/tablesaw/io/html/HtmlReader.java
|
HtmlReader
|
read
|
class HtmlReader implements DataReader<HtmlReadOptions> {
private static final HtmlReader INSTANCE = new HtmlReader();
static {
register(Table.defaultReaderRegistry);
}
public static void register(ReaderRegistry registry) {
registry.registerExtension("html", INSTANCE);
registry.registerMimeType("text/html", INSTANCE);
registry.registerOptions(HtmlReadOptions.class, INSTANCE);
}
@Override
public Table read(HtmlReadOptions options) {<FILL_FUNCTION_BODY>}
@Override
public Table read(Source source) {
return read(HtmlReadOptions.builder(source).build());
}
}
|
Document doc;
InputStream inputStream = options.source().inputStream();
try {
if (inputStream != null) {
// Reader must support mark, so can't use InputStreamReader
// Parse the InputStream directly
doc = Jsoup.parse(inputStream, null, "");
} else {
doc = Parser.htmlParser().parseInput(options.source().createReader(null), "");
}
} catch (IOException e) {
throw new RuntimeIOException(e);
}
Elements tables = doc.select("table");
int tableIndex = 0;
if (tables.size() != 1) {
if (options.tableIndex() != null) {
if (options.tableIndex() >= 0 && options.tableIndex() < tables.size()) {
tableIndex = options.tableIndex();
} else {
throw new IndexOutOfBoundsException(
"Table index outside bounds. The URL has " + tables.size() + " tables");
}
} else {
throw new IllegalStateException(
tables.size()
+ " tables found. When more than one html table is present on the page you must specify the index of the table to read from.");
}
}
Element htmlTable = tables.get(tableIndex);
List<String[]> rows = new ArrayList<>();
for (Element row : htmlTable.select("tr")) {
Elements headerCells = row.getElementsByTag("th");
Elements cells = row.getElementsByTag("td");
String[] nextLine =
Stream.concat(headerCells.stream(), cells.stream())
.map(Element::text)
.toArray(String[]::new);
rows.add(nextLine);
}
Table table = Table.create(options.tableName());
if (rows.isEmpty()) {
return table;
}
List<String> columnNames = new ArrayList<>();
if (options.header()) {
String[] headerRow = rows.remove(0);
for (int i = 0; i < headerRow.length; i++) {
columnNames.add(headerRow[i]);
}
} else {
for (int i = 0; i < rows.get(0).length; i++) {
columnNames.add("C" + i);
}
}
return TableBuildingUtils.build(columnNames, rows, options);
| 177
| 603
| 780
|
<no_super_class>
|
jtablesaw_tablesaw
|
tablesaw/html/src/main/java/tech/tablesaw/io/html/HtmlWriter.java
|
HtmlWriter
|
write
|
class HtmlWriter implements DataWriter<HtmlWriteOptions> {
private static final HtmlWriter INSTANCE = new HtmlWriter();
static {
register(Table.defaultWriterRegistry);
}
public static void register(WriterRegistry registry) {
registry.registerExtension("html", INSTANCE);
registry.registerOptions(HtmlWriteOptions.class, INSTANCE);
}
public void write(Table table, HtmlWriteOptions options) {<FILL_FUNCTION_BODY>}
/** Returns a string containing the html output of one table row */
private static Element row(
int row, Table table, ElementCreator elements, HtmlWriteOptions options) {
Element tr = elements.create("tr", null, row);
for (Column<?> col : table.columns()) {
if (options.escapeText()) {
tr.appendChild(
elements.create("td", col, row).appendText(String.valueOf(col.getString(row))));
} else {
tr.appendChild(
elements
.create("td", col, row)
.appendChild(new DataNode(String.valueOf(col.getString(row)))));
}
}
return tr;
}
private static Element header(List<Column<?>> cols, ElementCreator elements) {
Element thead = elements.create("thead");
Element tr = elements.create("tr");
thead.appendChild(tr);
for (Column<?> col : cols) {
tr.appendChild(elements.create("th", col, null).appendText(col.name()));
}
return thead;
}
@Override
public void write(Table table, Destination dest) {
write(table, HtmlWriteOptions.builder(dest).build());
}
}
|
ElementCreator elements = options.elementCreator();
Element html = elements.create("table");
html.appendChild(header(table.columns(), elements));
Element tbody = elements.create("tbody");
html.appendChild(tbody);
for (int row = 0; row < table.rowCount(); row++) {
tbody.appendChild(row(row, table, elements, options));
}
try (Writer writer = options.destination().createWriter()) {
writer.write(html.toString());
} catch (IOException e) {
throw new RuntimeIOException(e);
}
| 451
| 153
| 604
|
<no_super_class>
|
jtablesaw_tablesaw
|
tablesaw/json/src/main/java/tech/tablesaw/io/json/JsonReader.java
|
JsonReader
|
read
|
class JsonReader implements DataReader<JsonReadOptions> {
private static final JsonReader INSTANCE = new JsonReader();
private static final ObjectMapper mapper = new ObjectMapper();
static {
register(Table.defaultReaderRegistry);
}
public static void register(ReaderRegistry registry) {
registry.registerExtension("json", INSTANCE);
registry.registerMimeType("application/json", INSTANCE);
registry.registerOptions(JsonReadOptions.class, INSTANCE);
}
@Override
public Table read(JsonReadOptions options) {<FILL_FUNCTION_BODY>}
private Table convertArrayOfArrays(JsonNode jsonObj, ReadOptions options) {
JsonNode firstNode = jsonObj.get(0);
boolean firstRowAllStrings = true;
List<String> columnNames = new ArrayList<>();
for (JsonNode n : firstNode) {
if (!n.isTextual()) {
firstRowAllStrings = false;
}
}
boolean hasHeader = firstRowAllStrings;
for (int i = 0; i < firstNode.size(); i++) {
columnNames.add(hasHeader ? firstNode.get(i).textValue() : "Column " + i);
}
List<String[]> dataRows = new ArrayList<>();
for (int i = hasHeader ? 1 : 0; i < jsonObj.size(); i++) {
JsonNode arr = jsonObj.get(i);
String[] row = new String[arr.size()];
for (int j = 0; j < arr.size(); j++) {
row[j] = arr.get(j).asText();
}
dataRows.add(row);
}
return TableBuildingUtils.build(columnNames, dataRows, options);
}
private Table convertArrayOfObjects(JsonNode jsonObj, ReadOptions options) {
// flatten each object inside the array
StringBuilder result = new StringBuilder("[");
for (int i = 0; i < jsonObj.size(); i++) {
JsonNode rowObj = jsonObj.get(i);
String flattenedRow = null;
try {
flattenedRow = JsonFlattener.flatten(mapper.writeValueAsString(rowObj));
} catch (JsonProcessingException e) {
throw new RuntimeIOException(e);
}
if (i != 0) {
result.append(",");
}
result.append(flattenedRow);
}
String flattenedJsonString = result.append("]").toString();
JsonNode flattenedJsonObj = null;
try {
flattenedJsonObj = mapper.readTree(flattenedJsonString);
} catch (JsonProcessingException e) {
throw new RuntimeIOException(e);
}
Set<String> colNames = new LinkedHashSet<>();
for (JsonNode row : flattenedJsonObj) {
Iterator<String> fieldNames = row.fieldNames();
while (fieldNames.hasNext()) {
colNames.add(fieldNames.next());
}
}
List<String> columnNames = new ArrayList<>(colNames);
List<String[]> dataRows = new ArrayList<>();
for (JsonNode node : flattenedJsonObj) {
String[] arr = new String[columnNames.size()];
for (int i = 0; i < columnNames.size(); i++) {
if (node.has(columnNames.get(i))) {
arr[i] = node.get(columnNames.get(i)).asText();
} else {
arr[i] = null;
}
}
dataRows.add(arr);
}
return TableBuildingUtils.build(columnNames, dataRows, options);
}
@Override
public Table read(Source source) {
return read(JsonReadOptions.builder(source).build());
}
}
|
JsonNode jsonObj = null;
try {
jsonObj = mapper.readTree(options.source().createReader(null));
} catch (IOException e) {
throw new RuntimeIOException(e);
}
if (options.path() != null) {
jsonObj = jsonObj.at(options.path());
}
if (!jsonObj.isArray()) {
throw new IllegalStateException(
"Only reading a JSON array is currently supported. The array must hold an array or object for each row.");
}
if (jsonObj.size() == 0) {
return Table.create(options.tableName());
}
JsonNode firstNode = jsonObj.get(0);
if (firstNode.isArray()) {
return convertArrayOfArrays(jsonObj, options);
}
return convertArrayOfObjects(jsonObj, options);
| 984
| 217
| 1,201
|
<no_super_class>
|
jtablesaw_tablesaw
|
tablesaw/json/src/main/java/tech/tablesaw/io/json/JsonWriter.java
|
JsonWriter
|
write
|
class JsonWriter implements DataWriter<JsonWriteOptions> {
private static final JsonWriter INSTANCE = new JsonWriter();
private static final ObjectMapper mapper =
new ObjectMapper().registerModule(new JavaTimeModule());
static {
register(Table.defaultWriterRegistry);
}
public static void register(WriterRegistry registry) {
registry.registerExtension("json", INSTANCE);
registry.registerOptions(JsonWriteOptions.class, INSTANCE);
}
public void write(Table table, JsonWriteOptions options) {<FILL_FUNCTION_BODY>}
@Override
public void write(Table table, Destination dest) {
write(table, JsonWriteOptions.builder(dest).build());
}
}
|
ArrayNode output = mapper.createArrayNode();
if (options.asObjects()) {
for (int r = 0; r < table.rowCount(); r++) {
ObjectNode row = mapper.createObjectNode();
for (int c = 0; c < table.columnCount(); c++) {
row.set(table.column(c).name(), mapper.convertValue(table.get(r, c), JsonNode.class));
}
output.add(row);
}
} else {
if (options.header()) {
ArrayNode row = mapper.createArrayNode();
for (int c = 0; c < table.columnCount(); c++) {
row.add(mapper.convertValue(table.column(c).name(), JsonNode.class));
}
output.add(row);
}
for (int r = 0; r < table.rowCount(); r++) {
ArrayNode row = mapper.createArrayNode();
for (int c = 0; c < table.columnCount(); c++) {
row.add(mapper.convertValue(table.get(r, c), JsonNode.class));
}
output.add(row);
}
}
try (Writer writer = options.destination().createWriter()) {
String str = mapper.writeValueAsString(output);
writer.write(str);
} catch (IOException e) {
throw new RuntimeIOException(e);
}
| 185
| 367
| 552
|
<no_super_class>
|
jtablesaw_tablesaw
|
tablesaw/jsplot/src/main/java/tech/tablesaw/plotly/Plot.java
|
Plot
|
show
|
class Plot {
protected static final String DEFAULT_DIV_NAME = "target";
protected static final String DEFAULT_OUTPUT_FILE = "output.html";
protected static final String DEFAULT_OUTPUT_FILE_NAME = "output";
protected static final String DEFAULT_OUTPUT_FOLDER = "testoutput";
public static void show(Figure figure, String divName, File outputFile) {<FILL_FUNCTION_BODY>}
/**
* Opens the default browser on the given HTML page. This is a convenience method for anyone who
* wants total control over the HTML file containing one or more plots, but still wants to use the
* mechanism for opening the default browser on it.
*
* @param html An arbitrary HTML page, it doesn't even need plots
* @param outputFile The file where the page will be written
*/
public static void show(String html, File outputFile) {
try {
try (Writer writer =
new OutputStreamWriter(new FileOutputStream(outputFile), StandardCharsets.UTF_8)) {
writer.write(html);
}
new Browser().browse(outputFile);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
public static void show(Figure figure, String divName) {
show(figure, divName, defaultFile());
}
public static void show(Figure figure) {
show(figure, randomFile());
}
public static void show(Figure figure, File outputFile) {
show(figure, DEFAULT_DIV_NAME, outputFile);
}
protected static File defaultFile() {
Path path = Paths.get(DEFAULT_OUTPUT_FOLDER, DEFAULT_OUTPUT_FILE);
try {
Files.createDirectories(path.getParent());
} catch (IOException e) {
throw new UncheckedIOException(e);
}
return path.toFile();
}
protected static File randomFile() {
Path path = Paths.get(DEFAULT_OUTPUT_FOLDER, randomizedFileName());
try {
Files.createDirectories(path.getParent());
} catch (IOException e) {
throw new UncheckedIOException(e);
}
return path.toFile();
}
protected static String randomizedFileName() {
return DEFAULT_OUTPUT_FILE_NAME + UUID.randomUUID().toString() + ".html";
}
}
|
Page page = Page.pageBuilder(figure, divName).build();
String output = page.asJavascript();
try {
try (Writer writer =
new OutputStreamWriter(new FileOutputStream(outputFile), StandardCharsets.UTF_8)) {
writer.write(output);
}
new Browser().browse(outputFile);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
| 606
| 113
| 719
|
<no_super_class>
|
jtablesaw_tablesaw
|
tablesaw/jsplot/src/main/java/tech/tablesaw/plotly/Utils.java
|
Utils
|
dataAsString
|
class Utils {
private Utils() {}
public static String dataAsString(double[] data) {
return Arrays.toString(data);
}
/** @return un-escaped quote of argument */
public static String quote(String string) {
return "'" + string + "'";
}
/**
* Escapes string for Javascript, assuming but without surrounding it with doublequotes (") and
* saves to output to the given StringBuilder.
*/
private static void escape(String s, StringBuilder sb) {
JsonStringEncoder.getInstance().quoteAsString(s, sb);
}
/** @return a Javascript array of strings (escaped if needed) */
public static String dataAsString(Object[] data) {
StringBuilder builder = new StringBuilder("[");
for (int i = 0; i < data.length; i++) {
Object o = data[i];
builder.append("\"");
escape(String.valueOf(o), builder);
builder.append("\"");
if (i < data.length - 1) {
builder.append(",");
}
}
builder.append("]");
return builder.toString();
}
public static String dataAsString(double[][] data) {<FILL_FUNCTION_BODY>}
}
|
StringBuilder builder = new StringBuilder("[");
for (double[] row : data) {
builder.append("[");
for (double value : row) {
builder.append(value);
builder.append(",");
}
builder.append("],");
}
builder.append("]");
return builder.toString();
| 335
| 90
| 425
|
<no_super_class>
|
jtablesaw_tablesaw
|
tablesaw/jsplot/src/main/java/tech/tablesaw/plotly/api/AreaPlot.java
|
AreaPlot
|
create
|
class AreaPlot {
public static Figure create(
String title, Table table, String xCol, String yCol, String groupCol) {<FILL_FUNCTION_BODY>}
public static Figure create(String title, Table table, String xCol, String yCol) {
Layout layout = Layout.builder(title, xCol, yCol).build();
ScatterTrace trace =
ScatterTrace.builder(table.numberColumn(xCol), table.numberColumn(yCol))
.mode(ScatterTrace.Mode.LINE)
.fill(ScatterTrace.Fill.TO_NEXT_Y)
.build();
return new Figure(layout, trace);
}
}
|
TableSliceGroup tables = table.splitOn(table.categoricalColumn(groupCol));
Layout layout = Layout.builder(title, xCol, yCol).showLegend(true).build();
ScatterTrace[] traces = new ScatterTrace[tables.size()];
for (int i = 0; i < tables.size(); i++) {
List<Table> tableList = tables.asTableList();
traces[i] =
ScatterTrace.builder(
tableList.get(i).numberColumn(xCol), tableList.get(i).numberColumn(yCol))
.showLegend(true)
.name(tableList.get(i).name())
.mode(ScatterTrace.Mode.LINE)
.fill(ScatterTrace.Fill.TO_NEXT_Y)
.build();
}
return new Figure(layout, traces);
| 173
| 222
| 395
|
<no_super_class>
|
jtablesaw_tablesaw
|
tablesaw/jsplot/src/main/java/tech/tablesaw/plotly/api/BarPlot.java
|
BarPlot
|
create
|
class BarPlot {
protected static final int HEIGHT = 700;
protected static final int WIDTH = 900;
protected static Figure create(
Orientation orientation,
String title,
Table table,
String groupColName,
String numberColName) {
Layout layout = standardLayout(title).build();
BarTrace trace =
BarTrace.builder(table.categoricalColumn(groupColName), table.numberColumn(numberColName))
.orientation(orientation)
.build();
return new Figure(layout, trace);
}
protected static Figure create(
Orientation orientation,
String title,
Table table,
String groupColName,
Layout.BarMode barMode,
String... numberColNames) {<FILL_FUNCTION_BODY>}
private static Layout.LayoutBuilder standardLayout(String title) {
return Layout.builder().title(title).height(HEIGHT).width(WIDTH);
}
}
|
Layout layout = standardLayout(title).barMode(barMode).showLegend(true).build();
Trace[] traces = new Trace[numberColNames.length];
for (int i = 0; i < numberColNames.length; i++) {
String name = numberColNames[i];
BarTrace trace =
BarTrace.builder(table.categoricalColumn(groupColName), table.numberColumn(name))
.orientation(orientation)
.showLegend(true)
.name(name)
.build();
traces[i] = trace;
}
return new Figure(layout, traces);
| 254
| 162
| 416
|
<no_super_class>
|
jtablesaw_tablesaw
|
tablesaw/jsplot/src/main/java/tech/tablesaw/plotly/api/BoxPlot.java
|
BoxPlot
|
create
|
class BoxPlot {
private static final int HEIGHT = 600;
private static final int WIDTH = 800;
public static Figure create(
String title, Table table, String groupingColumn, String numericColumn) {<FILL_FUNCTION_BODY>}
}
|
Layout layout = Layout.builder().title(title).height(HEIGHT).width(WIDTH).build();
BoxTrace trace =
BoxTrace.builder(table.categoricalColumn(groupingColumn), table.nCol(numericColumn))
.build();
return new Figure(layout, trace);
| 73
| 79
| 152
|
<no_super_class>
|
jtablesaw_tablesaw
|
tablesaw/jsplot/src/main/java/tech/tablesaw/plotly/api/BubblePlot.java
|
BubblePlot
|
create
|
class BubblePlot {
public static Figure create(
String title, Table table, String xCol, String yCol, String sizeColumn, String groupCol) {<FILL_FUNCTION_BODY>}
/**
* create a bubble plot using more options including color/sizeMode/opacity
*
* @param title plot title
* @param xColumn non-nullable, column data for x-axis
* @param yColumn non-nullable, column data for y-axis
* @param sizeColumn nullable, indicate the bubble size
* @param color color for every data point
* @param sizeMode check {@link SizeMode}
* @param opacity display opacity
* @return bubble plot created from given parameters
*/
public static Figure create(
String title,
Column xColumn,
Column yColumn,
NumericColumn sizeColumn,
double[] color,
SizeMode sizeMode,
Double opacity) {
Layout layout = Layout.builder(title, xColumn.name(), yColumn.name()).build();
Marker marker = null;
MarkerBuilder builder = Marker.builder();
if (sizeColumn != null) {
builder.size(sizeColumn);
}
if (opacity != null) {
builder.opacity(opacity);
}
if (color != null) {
builder.color(color);
}
if (sizeMode != null) {
builder.sizeMode(sizeMode);
}
marker = builder.build();
ScatterTrace trace = ScatterTrace.builder(xColumn, yColumn).marker(marker).build();
return new Figure(layout, trace);
}
/**
* create a bubble plot using column names
*
* @param title plot title
* @param table source {@link Table} to fetch plot datap points
* @param xCol non-nullable, column name for x-axis
* @param yCol non-nullable, column name for y-axis
* @param sizeCol nullable, column name for bubble size
* @return bubble plot created from given parameters
*/
public static Figure create(String title, Table table, String xCol, String yCol, String sizeCol) {
NumericColumn xColumn = table.numberColumn(xCol);
NumericColumn yColumn = table.numberColumn(yCol);
NumericColumn sizeColumn = sizeCol == null ? null : table.numberColumn(sizeCol);
return create(title, xColumn, yColumn, sizeColumn, null, null, null);
}
public static Figure create(
String title, String xTitle, double[] xCol, String yTitle, double[] yCol) {
Layout layout = Layout.builder(title, xTitle, yTitle).build();
ScatterTrace trace = ScatterTrace.builder(xCol, yCol).build();
return new Figure(layout, trace);
}
}
|
TableSliceGroup tables = table.splitOn(table.categoricalColumn(groupCol));
Layout layout = Layout.builder(title, xCol, yCol).showLegend(true).build();
ScatterTrace[] traces = new ScatterTrace[tables.size()];
for (int i = 0; i < tables.size(); i++) {
List<Table> tableList = tables.asTableList();
Marker marker =
Marker.builder()
.size(tableList.get(i).numberColumn(sizeColumn))
// .opacity(.75)
.build();
traces[i] =
ScatterTrace.builder(
tableList.get(i).numberColumn(xCol), tableList.get(i).numberColumn(yCol))
.showLegend(true)
.marker(marker)
.name(tableList.get(i).name())
.build();
}
return new Figure(layout, traces);
| 726
| 248
| 974
|
<no_super_class>
|
jtablesaw_tablesaw
|
tablesaw/jsplot/src/main/java/tech/tablesaw/plotly/api/CandlestickPlot.java
|
CandlestickPlot
|
create
|
class CandlestickPlot {
private static final String PLOT_TYPE = "candlestick";
/** Returns Figure containing candlestick time series plot with a default layout */
public static Figure create(
String title,
Table table,
String xCol,
String openCol,
String highCol,
String lowCol,
String closeCol) {<FILL_FUNCTION_BODY>}
}
|
return PricePlot.create(title, table, xCol, openCol, highCol, lowCol, closeCol, PLOT_TYPE);
| 106
| 36
| 142
|
<no_super_class>
|
jtablesaw_tablesaw
|
tablesaw/jsplot/src/main/java/tech/tablesaw/plotly/api/ContourPlot.java
|
ContourPlot
|
create
|
class ContourPlot {
private ContourPlot() {
}
public static Figure create(String title, Table table, String categoryCol1, String categoryCol2) {<FILL_FUNCTION_BODY>}
}
|
Layout layout = Layout.builder(title).build();
Table counts = table.xTabCounts(categoryCol1, categoryCol2);
counts = counts.dropRows(counts.rowCount() - 1);
List<Column<?>> columns = counts.columns();
columns.remove(counts.columnCount() - 1);
Column<?> yColumn = columns.remove(0);
double[][] z = DoubleArrays.to2dArray(counts.numericColumns());
Object[] x = counts.columnNames().toArray();
Object[] y = yColumn.asObjectArray();
ContourTrace trace = ContourTrace.builder(x, y, z).build();
return new Figure(layout, trace);
| 59
| 185
| 244
|
<no_super_class>
|
jtablesaw_tablesaw
|
tablesaw/jsplot/src/main/java/tech/tablesaw/plotly/api/Heatmap.java
|
Heatmap
|
create
|
class Heatmap {
private Heatmap() {}
public static Figure create(String title, Table table, String categoryCol1, String categoryCol2) {<FILL_FUNCTION_BODY>}
}
|
Layout layout = Layout.builder(title).build();
Table counts = table.xTabCounts(categoryCol1, categoryCol2);
counts = counts.dropRows(counts.rowCount() - 1);
List<Column<?>> columns = counts.columns();
columns.remove(counts.columnCount() - 1);
Column<?> yColumn = columns.remove(0);
double[][] z = DoubleArrays.to2dArray(counts.numericColumns());
Object[] x = counts.columnNames().toArray();
Object[] y = yColumn.asObjectArray();
HeatmapTrace trace = HeatmapTrace.builder(x, y, z).build();
return new Figure(layout, trace);
| 52
| 185
| 237
|
<no_super_class>
|
jtablesaw_tablesaw
|
tablesaw/jsplot/src/main/java/tech/tablesaw/plotly/api/Histogram2D.java
|
Histogram2D
|
create
|
class Histogram2D {
public static Figure create(String title, Table table, String xCol, String yCol) {<FILL_FUNCTION_BODY>}
}
|
Histogram2DTrace trace =
Histogram2DTrace.builder(table.numberColumn(xCol), table.numberColumn(yCol)).build();
return new Figure(Layout.builder(title, xCol, yCol).build(), trace);
| 44
| 63
| 107
|
<no_super_class>
|
jtablesaw_tablesaw
|
tablesaw/jsplot/src/main/java/tech/tablesaw/plotly/api/LinePlot.java
|
LinePlot
|
create
|
class LinePlot {
public static Figure create(
String title, Table table, String xCol, String yCol, String groupCol) {<FILL_FUNCTION_BODY>}
public static Figure create(String title, Table table, String xCol, String yCol) {
Layout layout = Layout.builder(title, xCol, yCol).build();
ScatterTrace trace =
ScatterTrace.builder(table.numberColumn(xCol), table.numberColumn(yCol))
.mode(ScatterTrace.Mode.LINE)
.build();
return new Figure(layout, trace);
}
public static Figure create(
String title, String xTitle, double[] xCol, String yTitle, double[] yCol) {
Layout layout = Layout.builder(title, xTitle, yTitle).build();
ScatterTrace trace = ScatterTrace.builder(xCol, yCol).mode(ScatterTrace.Mode.LINE).build();
return new Figure(layout, trace);
}
}
|
TableSliceGroup tables = table.splitOn(table.categoricalColumn(groupCol));
Layout layout = Layout.builder(title, xCol, yCol).showLegend(true).build();
ScatterTrace[] traces = new ScatterTrace[tables.size()];
for (int i = 0; i < tables.size(); i++) {
List<Table> tableList = tables.asTableList();
traces[i] =
ScatterTrace.builder(
tableList.get(i).numberColumn(xCol), tableList.get(i).numberColumn(yCol))
.showLegend(true)
.name(tableList.get(i).name())
.mode(ScatterTrace.Mode.LINE)
.build();
}
return new Figure(layout, traces);
| 252
| 205
| 457
|
<no_super_class>
|
jtablesaw_tablesaw
|
tablesaw/jsplot/src/main/java/tech/tablesaw/plotly/api/OHLCPlot.java
|
OHLCPlot
|
create
|
class OHLCPlot {
private static final String PLOT_TYPE = "ohlc";
/** Returns Figure containing Open-High-Low-Close time series plot with a default layout */
public static Figure create(
String title,
Table table,
String xCol,
String openCol,
String highCol,
String lowCol,
String closeCol) {<FILL_FUNCTION_BODY>}
}
|
return PricePlot.create(title, table, xCol, openCol, highCol, lowCol, closeCol, PLOT_TYPE);
| 107
| 36
| 143
|
<no_super_class>
|
jtablesaw_tablesaw
|
tablesaw/jsplot/src/main/java/tech/tablesaw/plotly/api/PiePlot.java
|
PiePlot
|
create
|
class PiePlot {
public static Figure create(
String title, Table table, String groupColName, String numberColName) {<FILL_FUNCTION_BODY>}
}
|
Layout layout = Layout.builder(title).build();
PieTrace trace =
PieTrace.builder(table.column(groupColName), table.numberColumn(numberColName))
.showLegend(true)
.build();
return new Figure(layout, trace);
| 48
| 76
| 124
|
<no_super_class>
|
jtablesaw_tablesaw
|
tablesaw/jsplot/src/main/java/tech/tablesaw/plotly/api/PricePlot.java
|
PricePlot
|
create
|
class PricePlot {
public static Figure create(
String title,
Table table,
String xCol,
String openCol,
String highCol,
String lowCol,
String closeCol,
String plotType) {<FILL_FUNCTION_BODY>}
}
|
Layout layout = Layout.builder(title, xCol).build();
Column<?> x = table.column(xCol);
NumericColumn<?> open = table.numberColumn(openCol);
NumericColumn<?> high = table.numberColumn(highCol);
NumericColumn<?> low = table.numberColumn(lowCol);
NumericColumn<?> close = table.numberColumn(closeCol);
ScatterTrace trace;
if (ColumnType.LOCAL_DATE.equals(x.type())) {
trace =
ScatterTrace.builder(table.dateColumn(xCol), open, high, low, close)
.type(plotType)
.build();
} else if (ColumnType.LOCAL_DATE_TIME.equals(x.type())) {
trace =
ScatterTrace.builder(table.dateTimeColumn(xCol), open, high, low, close)
.type(plotType)
.build();
} else if (ColumnType.INSTANT.equals(x.type())) {
trace =
ScatterTrace.builder(table.instantColumn(xCol), open, high, low, close)
.type(plotType)
.build();
} else {
throw new IllegalArgumentException(
"Column containing data for the X-Axis must be of type INSTANT, LOCAL_DATE, or LOCAL_DATE_TIME");
}
return new Figure(layout, trace);
| 75
| 362
| 437
|
<no_super_class>
|
jtablesaw_tablesaw
|
tablesaw/jsplot/src/main/java/tech/tablesaw/plotly/api/QQPlot.java
|
QQPlot
|
interpolate
|
class QQPlot {
/**
* Returns a figure containing a QQ Plot describing the differences between the distribution of
* values in the columns of interest
*
* @param title A title for the plot
* @param table The table containing the columns of interest
* @param columnName1 The name of the first numeric column containing the data to plot
* @param columnName2 The name of the second numeric column containing the data to plot
* @return A quantile plot
*/
public static Figure create(String title, Table table, String columnName1, String columnName2) {
NumericColumn<?> xCol = table.nCol(columnName1);
NumericColumn<?> yCol = table.nCol(columnName2);
return create(title, xCol.name(), xCol.asDoubleArray(), yCol.name(), yCol.asDoubleArray());
}
/**
* Returns a figure containing a QQ Plot describing the differences between the distribution of
* values in the columns of interest
*
* @param title A title for the plot
* @param xTitle The name of the first numeric column containing the data to plot
* @param xData The data to plot on the x Axis
* @param yTitle The name of the second numeric column containing the data to plot
* @param yData The data to plot on the y Axis
* @return A quantile plot
*/
public static Figure create(
String title, String xTitle, double[] xData, String yTitle, double[] yData) {
Preconditions.checkArgument(xData.length != 0, "x Data array is empty");
Preconditions.checkArgument(yData.length != 0, "x Data array is empty");
if (xData.length != yData.length) {
double[] interpolatedData;
if (xData.length < yData.length) {
interpolatedData = interpolate(yData, xData.length);
yData = interpolatedData;
} else {
interpolatedData = interpolate(xData, yData.length);
xData = interpolatedData;
}
}
Arrays.sort(xData);
Arrays.sort(yData);
double min = Math.min(xData[0], yData[0]);
double max = Math.max(xData[xData.length - 1], yData[yData.length - 1]);
double[] line = {min, max};
// Draw the 45 degree line indicating equal distributions
ScatterTrace trace1 =
ScatterTrace.builder(line, line).mode(ScatterTrace.Mode.LINE).name("y = x").build();
// Draw the actual data points
ScatterTrace trace2 = ScatterTrace.builder(xData, yData).name("distributions").build();
Layout layout =
Layout.builder()
.title(title)
.xAxis(Axis.builder().title(xTitle).build())
.yAxis(Axis.builder().title(yTitle).build())
.height(700)
.width(900)
.build();
return new Figure(layout, trace1, trace2);
}
/**
* Returns a double array, whose values are quantiles from the given source, based on the given
* size. The idea is to produce size elements that represent the quantiles of source array
*
* @param source The array to whose quantiles are calculated
* @param size The size of the array to return
*/
private static double[] interpolate(double[] source, int size) {<FILL_FUNCTION_BODY>}
}
|
double[] interpolatedData = new double[size];
for (int i = 0; i < size; i++) {
double value = ((i + .5) / (double) size) * 100;
interpolatedData[i] = StatUtils.percentile(source, value);
}
return interpolatedData;
| 908
| 85
| 993
|
<no_super_class>
|
jtablesaw_tablesaw
|
tablesaw/jsplot/src/main/java/tech/tablesaw/plotly/api/QuantilePlot.java
|
QuantilePlot
|
create
|
class QuantilePlot {
/**
* Returns a figure containing a Quantile Plot describing the distribution of values in the column
* of interest
*
* @param title A title for the plot
* @param table The table containing the column of interest
* @param columnName The name of the numeric column containing the data to plot
* @return A quantile plot
*/
public static Figure create(String title, Table table, String columnName) {<FILL_FUNCTION_BODY>}
}
|
NumericColumn<?> xCol = table.nCol(columnName);
double[] x = new double[xCol.size()];
for (int i = 0; i < x.length; i++) {
x[i] = i / (float) x.length;
}
NumericColumn<?> copy = xCol.copy();
copy.sortAscending();
ScatterTrace trace = ScatterTrace.builder(x, copy.asDoubleArray()).build();
Layout layout = Layout.builder().title(title).build();
return new Figure(layout, trace);
| 126
| 156
| 282
|
<no_super_class>
|
jtablesaw_tablesaw
|
tablesaw/jsplot/src/main/java/tech/tablesaw/plotly/api/Scatter3DPlot.java
|
Scatter3DPlot
|
create
|
class Scatter3DPlot {
private static final int HEIGHT = 800;
private static final int WIDTH = 1000;
public static Figure create(
String title, Table table, String xCol, String yCol, String zCol, String groupCol) {
TableSliceGroup tables = table.splitOn(table.categoricalColumn(groupCol));
Layout layout = standardLayout(title, xCol, yCol, zCol, true);
Scatter3DTrace[] traces = new Scatter3DTrace[tables.size()];
for (int i = 0; i < tables.size(); i++) {
List<Table> tableList = tables.asTableList();
traces[i] =
Scatter3DTrace.builder(
tableList.get(i).numberColumn(xCol),
tableList.get(i).numberColumn(yCol),
tableList.get(i).numberColumn(zCol))
.showLegend(true)
.name(tableList.get(i).name())
.build();
}
return new Figure(layout, traces);
}
public static Figure create(String title, Table table, String xCol, String yCol, String zCol) {
Layout layout = standardLayout(title, xCol, yCol, zCol, false);
Scatter3DTrace trace =
Scatter3DTrace.builder(
table.numberColumn(xCol), table.numberColumn(yCol), table.numberColumn(zCol))
.build();
return new Figure(layout, trace);
}
public static Figure create(
String title,
Table table,
String xCol,
String yCol,
String zCol,
String sizeColumn,
String groupCol) {<FILL_FUNCTION_BODY>}
private static Layout standardLayout(
String title, String xCol, String yCol, String zCol, boolean showLegend) {
return Layout.builder()
.title(title)
.height(HEIGHT)
.width(WIDTH)
.showLegend(showLegend)
.scene(
Scene.sceneBuilder()
.xAxis(Axis.builder().title(xCol).build())
.yAxis(Axis.builder().title(yCol).build())
.zAxis(Axis.builder().title(zCol).build())
.build())
.build();
}
}
|
TableSliceGroup tables = table.splitOn(table.categoricalColumn(groupCol));
Layout layout = standardLayout(title, xCol, yCol, zCol, false);
Scatter3DTrace[] traces = new Scatter3DTrace[tables.size()];
for (int i = 0; i < tables.size(); i++) {
List<Table> tableList = tables.asTableList();
Marker marker =
Marker.builder()
.size(tableList.get(i).numberColumn(sizeColumn))
// .opacity(.75)
.build();
traces[i] =
Scatter3DTrace.builder(
tableList.get(i).numberColumn(xCol),
tableList.get(i).numberColumn(yCol),
tableList.get(i).numberColumn(zCol))
.marker(marker)
.showLegend(true)
.name(tableList.get(i).name())
.build();
}
return new Figure(layout, traces);
| 610
| 267
| 877
|
<no_super_class>
|
jtablesaw_tablesaw
|
tablesaw/jsplot/src/main/java/tech/tablesaw/plotly/api/ScatterPlot.java
|
ScatterPlot
|
create
|
class ScatterPlot {
private static final double OPACITY = .75;
public static Figure create(
String title, Table table, String xCol, String yCol, String groupCol) {
TableSliceGroup tables = table.splitOn(table.categoricalColumn(groupCol));
Layout layout = Layout.builder(title, xCol, yCol).showLegend(true).build();
ScatterTrace[] traces = new ScatterTrace[tables.size()];
Marker marker = Marker.builder().opacity(OPACITY).build();
for (int i = 0; i < tables.size(); i++) {
List<Table> tableList = tables.asTableList();
traces[i] =
ScatterTrace.builder(
tableList.get(i).numberColumn(xCol), tableList.get(i).numberColumn(yCol))
.showLegend(true)
.marker(marker)
.name(tableList.get(i).name())
.build();
}
return new Figure(layout, traces);
}
public static Figure create(String title, Table table, String xCol, String yCol) {<FILL_FUNCTION_BODY>}
public static Figure create(
String title, String xTitle, double[] xCol, String yTitle, double[] yCol) {
Layout layout = Layout.builder(title, xTitle, yTitle).build();
ScatterTrace trace = ScatterTrace.builder(xCol, yCol).build();
return new Figure(layout, trace);
}
}
|
Layout layout = Layout.builder(title, xCol, yCol).build();
ScatterTrace trace =
ScatterTrace.builder(table.numberColumn(xCol), table.numberColumn(yCol)).build();
return new Figure(layout, trace);
| 396
| 67
| 463
|
<no_super_class>
|
jtablesaw_tablesaw
|
tablesaw/jsplot/src/main/java/tech/tablesaw/plotly/api/TimeSeriesPlot.java
|
TimeSeriesPlot
|
create
|
class TimeSeriesPlot {
public static Figure create(
String title, Table table, String dateColX, String yCol, String groupCol) {
TableSliceGroup tables = table.splitOn(table.categoricalColumn(groupCol));
Layout layout = Layout.builder(title, dateColX, yCol).build();
ScatterTrace[] traces = new ScatterTrace[tables.size()];
for (int i = 0; i < tables.size(); i++) {
List<Table> tableList = tables.asTableList();
Table t = tableList.get(i).sortOn(dateColX);
traces[i] =
ScatterTrace.builder(t.dateColumn(dateColX), t.numberColumn(yCol))
.showLegend(true)
.name(tableList.get(i).name())
.mode(ScatterTrace.Mode.LINE)
.build();
}
return new Figure(layout, traces);
}
public static Figure create(String title, Table table, String dateColXName, String yColName) {
Layout layout = Layout.builder(title, dateColXName, yColName).build();
ScatterTrace trace =
ScatterTrace.builder(table.column(dateColXName), table.numberColumn(yColName))
.mode(ScatterTrace.Mode.LINE)
.build();
return new Figure(layout, trace);
}
public static Figure create(
String title, String xTitle, DateColumn xCol, String yTitle, NumericColumn<?> yCol) {
Layout layout = Layout.builder(title, xTitle, yTitle).build();
ScatterTrace trace = ScatterTrace.builder(xCol, yCol).mode(ScatterTrace.Mode.LINE).build();
return new Figure(layout, trace);
}
public static Figure create(
String title, String xTitle, DateTimeColumn xCol, String yTitle, NumericColumn<?> yCol) {
Layout layout = Layout.builder(title, xTitle, yTitle).build();
ScatterTrace trace = ScatterTrace.builder(xCol, yCol).mode(ScatterTrace.Mode.LINE).build();
return new Figure(layout, trace);
}
public static Figure create(
String title, String xTitle, InstantColumn xCol, String yTitle, NumericColumn<?> yCol) {<FILL_FUNCTION_BODY>}
/**
* Creates a time series where the x values are from a DateTimeColumn, rather than a DateColumn
*
* @param title The title of the plot
* @param table The table containing the source data
* @param dateTimeColumnName The name of a DateTimeColumn
* @param numberColumnName The name of a NumberColumn
* @return The figure to be displayed
*/
public static Figure createDateTimeSeries(
String title, Table table, String dateTimeColumnName, String numberColumnName) {
DateTimeColumn xCol = table.dateTimeColumn(dateTimeColumnName);
NumericColumn<?> yCol = table.numberColumn(numberColumnName);
Layout layout = Layout.builder(title, xCol.name(), yCol.name()).build();
ScatterTrace trace = ScatterTrace.builder(xCol, yCol).mode(ScatterTrace.Mode.LINE).build();
return new Figure(layout, trace);
}
}
|
Layout layout = Layout.builder(title, xTitle, yTitle).build();
ScatterTrace trace = ScatterTrace.builder(xCol, yCol).mode(ScatterTrace.Mode.LINE).build();
return new Figure(layout, trace);
| 850
| 65
| 915
|
<no_super_class>
|
jtablesaw_tablesaw
|
tablesaw/jsplot/src/main/java/tech/tablesaw/plotly/api/TukeyMeanDifferencePlot.java
|
TukeyMeanDifferencePlot
|
interpolate
|
class TukeyMeanDifferencePlot {
/**
* Returns a figure containing a Tukey Mean-Difference Plot describing the differences between the
* data in two columns of interest
*
* @param title A title for the plot
* @param measure The measure being compared on the plot (e.g "inches" or "height in inches"
* @param table The table containing the columns of interest
* @param columnName1 The name of the first numeric column containing the data to plot
* @param columnName2 The name of the second numeric column containing the data to plot
* @return A quantile plot
*/
public static Figure create(
String title, String measure, Table table, String columnName1, String columnName2) {
NumericColumn<?> xCol = table.nCol(columnName1);
NumericColumn<?> yCol = table.nCol(columnName2);
return create(title, measure, xCol.asDoubleArray(), yCol.asDoubleArray());
}
/**
* Returns a figure containing a QQ Plot describing the differences between the distribution of
* values in the columns of interest
*
* @param title A title for the plot
* @param measure The measure being compared on the plot (e.g "inches" or "height in inches"
* @param xData The data to plot on the x Axis
* @param yData The data to plot on the y Axis
* @return A quantile plot
*/
public static Figure create(String title, String measure, double[] xData, double[] yData) {
Preconditions.checkArgument(xData.length != 0, "x Data array is empty");
Preconditions.checkArgument(yData.length != 0, "x Data array is empty");
if (xData.length != yData.length) {
double[] interpolatedData;
if (xData.length < yData.length) {
interpolatedData = interpolate(yData, xData.length);
yData = interpolatedData;
} else {
interpolatedData = interpolate(xData, yData.length);
xData = interpolatedData;
}
}
Arrays.sort(xData);
Arrays.sort(yData);
double[] averagePoints = new double[xData.length];
double[] differencePoints = new double[xData.length];
for (int i = 0; i < xData.length; i++) {
averagePoints[i] = (xData[i] + yData[i]) / 2.0;
differencePoints[i] = (xData[i] - yData[i]);
}
double xMin = StatUtils.min(xData);
double xMax = StatUtils.max(xData);
double[] zeroLineX = {xMin, xMax};
double[] zeroLineY = {0, 0};
// Draw the line indicating equal distributions (this is zero in this plot)
ScatterTrace trace1 =
ScatterTrace.builder(zeroLineX, zeroLineY)
.mode(ScatterTrace.Mode.LINE)
.name("y = x")
.build();
// Draw the actual data points
ScatterTrace trace2 =
ScatterTrace.builder(averagePoints, differencePoints).name("mean x difference").build();
Layout layout =
Layout.builder()
.title(title)
.xAxis(Axis.builder().title("mean (" + measure + ")").build())
.yAxis(Axis.builder().title("difference (" + measure + ")").build())
.height(700)
.width(900)
.build();
return new Figure(layout, trace1, trace2);
}
/**
* Returns a double array, whose values are quantiles from the given source, based on the given
* size. The idea is to produce size elements that represent the quantiles of source array
*
* @param source The array to whose quantiles are calculated
* @param size The size of the array to return
*/
private static double[] interpolate(double[] source, int size) {<FILL_FUNCTION_BODY>}
}
|
double[] interpolatedData = new double[size];
for (int i = 0; i < size; i++) {
double value = ((i + .5) / (double) size) * 100;
interpolatedData[i] = StatUtils.percentile(source, value);
}
return interpolatedData;
| 1,046
| 85
| 1,131
|
<no_super_class>
|
jtablesaw_tablesaw
|
tablesaw/jsplot/src/main/java/tech/tablesaw/plotly/api/ViolinPlot.java
|
ViolinPlot
|
create
|
class ViolinPlot {
private static final int HEIGHT = 600;
private static final int WIDTH = 800;
public static Figure create(
String title, Table table, String groupingColumn, String numericColumn, boolean showBoxPlot, boolean showMeanLine) {<FILL_FUNCTION_BODY>}
}
|
Layout layout = Layout.builder().title(title).height(HEIGHT).width(WIDTH).build();
ViolinTrace trace =
ViolinTrace.builder(table.categoricalColumn(groupingColumn), table.nCol(numericColumn))
.boxPlot(showBoxPlot)
.meanLine(showMeanLine)
.build();
return new Figure(layout, trace);
| 87
| 105
| 192
|
<no_super_class>
|
jtablesaw_tablesaw
|
tablesaw/jsplot/src/main/java/tech/tablesaw/plotly/components/ColorBar.java
|
ColorBarBuilder
|
y
|
class ColorBarBuilder {
private ThicknessMode thicknessMode = DEFAULT_THICKNESS_MODE;
private double thickness = DEFAULT_THICKNESS; // (number greater than or equal to 0)
private LenMode lenMode = DEFAULT_LEN_MODE;
private double len = DEFAULT_LEN;
private double x = DEFAULT_X;
private int xPad = DEFAULT_X_PAD;
private int yPad = DEFAULT_Y_PAD;
private double y = DEFAULT_Y;
private Xanchor xAnchor = DEFAULT_X_ANCHOR;
private Yanchor yAnchor = DEFAULT_Y_ANCHOR;
private String outlineColor = DEFAULT_OUTLINE_COLOR;
private int outlineWidth = DEFAULT_OUTLINE_WIDTH;
private String borderColor = DEFAULT_BORDER_COLOR;
private int borderWidth = DEFAULT_BORDER_WIDTH;
private String bgColor = DEFAULT_BG_COLOR;
private TickSettings tickSettings;
/**
* Sets the thickness of the color bar, This measure excludes the size of the padding, ticks and
* labels.
*
* @param thickness a double greater than 0
* @return this ColorBar
*/
public ColorBarBuilder thickness(double thickness) {
Preconditions.checkArgument(thickness >= 0);
this.thickness = thickness;
return this;
}
/**
* Sets the length of the color bar, This measure excludes the size of the padding, ticks and
* labels.
*
* @param len a double greater than 0
* @return this ColorBar
*/
public ColorBarBuilder len(double len) {
Preconditions.checkArgument(len >= 0);
this.len = len;
return this;
}
/**
* Determines whether this color bar's length (i.e. the measure in the color variation
* direction) is set in units of plot "fraction" or in "pixels. Use `len` to set the value.
*/
public ColorBarBuilder lenMode(LenMode lenMode) {
this.lenMode = lenMode;
return this;
}
public ColorBarBuilder thicknessMode(ThicknessMode mode) {
this.thicknessMode = mode;
return this;
}
/**
* A number between or equal to -2and 3) default:1.02 Sets the x position of the color bar(in
* plot fraction).
*/
public ColorBarBuilder x(double x) {
Preconditions.checkArgument(x >= -2 && x <= 3);
this.x = x;
return this;
}
/**
* A number between or equal to -2and 3) default:0.5 Sets the y position of the color bar (in
* plot fraction).
*/
public ColorBarBuilder y(double y) {<FILL_FUNCTION_BODY>}
/**
* Sets this color bar's horizontal position anchor. This anchor binds the `x` position to the
* "left", "center" or "right" of the color bar.
*/
public ColorBarBuilder xAnchor(Xanchor xAnchor) {
this.xAnchor = xAnchor;
return this;
}
/**
* Sets this color bar's vertical position anchor This anchor binds the `y` position to the
* "top", "middle" or "bottom" of the color bar.
*/
public ColorBarBuilder yAnchor(Yanchor yAnchor) {
this.yAnchor = yAnchor;
return this;
}
/** Sets the amount of paddng (in px) along the y direction. */
public ColorBarBuilder yPad(int yPad) {
Preconditions.checkArgument(yPad >= 0);
this.yPad = yPad;
return this;
}
/** Sets the amount of padding(in px) along the x direction. */
public ColorBarBuilder xPad(int xPad) {
Preconditions.checkArgument(y >= 0);
this.xPad = xPad;
return this;
}
/** Sets the axis line color. */
public ColorBarBuilder outlineColor(String outlineColor) {
this.outlineColor = outlineColor;
return this;
}
/** Sets the color of the border enclosing this color bar. */
public ColorBarBuilder borderColor(String color) {
this.borderColor = color;
return this;
}
/** Sets the color of padded area. */
public ColorBarBuilder bgColor(String color) {
this.bgColor = color;
return this;
}
/** Sets the width (in px) or the border enclosing this color bar. */
public ColorBarBuilder borderWidth(int width) {
Preconditions.checkArgument(width >= 0);
this.borderWidth = width;
return this;
}
/** Sets the width (in px) of the axis line. */
public ColorBarBuilder outlineWidth(int width) {
Preconditions.checkArgument(width >= 0);
this.outlineWidth = width;
return this;
}
public ColorBarBuilder tickSettings(TickSettings tickSettings) {
this.tickSettings = tickSettings;
return this;
}
public ColorBar build() {
return new ColorBar(this);
}
}
|
Preconditions.checkArgument(y >= -2 && y <= 3);
this.y = y;
return this;
| 1,362
| 33
| 1,395
|
<methods>public non-sealed void <init>() ,public java.lang.String asJSON() ,public abstract java.lang.String asJavascript() ,public java.lang.String toString() <variables>private final PebbleEngine engine,protected static final ObjectMapper mapper
|
jtablesaw_tablesaw
|
tablesaw/jsplot/src/main/java/tech/tablesaw/plotly/components/Component.java
|
Component
|
asJSON
|
class Component {
protected static final ObjectMapper mapper = new ObjectMapper();
static {
mapper.enable(SerializationFeature.INDENT_OUTPUT);
mapper.setSerializationInclusion(Include.NON_NULL);
mapper.enable(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS);
}
private final PebbleEngine engine = TemplateUtils.getNewEngine();
protected PebbleEngine getEngine() {
return engine;
}
@Deprecated
public abstract String asJavascript();
@Deprecated
protected abstract Map<String, Object> getContext();
protected Map<String, Object> getJSONContext() {
return null;
}
public String asJSON() {<FILL_FUNCTION_BODY>}
protected String asJavascript(String filename) {
Writer writer = new StringWriter();
PebbleTemplate compiledTemplate;
try {
compiledTemplate = getEngine().getTemplate(filename);
compiledTemplate.evaluate(writer, getContext());
} catch (PebbleException e) {
throw new IllegalStateException(e);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
return writer.toString();
}
@Override
public String toString() {
return asJavascript();
}
}
|
StringWriter w = new StringWriter();
try {
mapper.writeValue(w, getJSONContext());
} catch (IOException ioe) {
throw new UncheckedIOException(ioe);
}
return w.toString();
| 349
| 63
| 412
|
<no_super_class>
|
jtablesaw_tablesaw
|
tablesaw/jsplot/src/main/java/tech/tablesaw/plotly/components/Config.java
|
Config
|
getContext
|
class Config extends Component {
private final Boolean displayModeBar;
private final Boolean responsive;
private final Boolean displayLogo;
private Config(Builder builder) {
this.displayModeBar = builder.displayModeBar;
this.responsive = builder.responsive;
this.displayLogo = builder.displayLogo;
}
public static Builder builder() {
return new Builder();
}
@Override
public String asJavascript() {
return "var config = " + asJSON();
}
@Override
protected Map<String, Object> getJSONContext() {
return getContext();
}
@Override
protected Map<String, Object> getContext() {<FILL_FUNCTION_BODY>}
public static class Builder {
Boolean displayModeBar;
Boolean responsive;
Boolean displayLogo;
private Builder() {}
public Builder displayModeBar(boolean displayModeBar) {
this.displayModeBar = displayModeBar;
return this;
}
public Builder responsive(boolean responsive) {
this.responsive = responsive;
return this;
}
public Builder displayLogo(boolean displayLogo) {
this.displayLogo = displayLogo;
return this;
}
public Config build() {
return new Config(this);
}
}
}
|
Map<String, Object> context = new HashMap<>();
context.put("displayModeBar", displayModeBar);
context.put("responsive", responsive);
context.put("displaylogo", displayLogo);
return context;
| 345
| 60
| 405
|
<methods>public non-sealed void <init>() ,public java.lang.String asJSON() ,public abstract java.lang.String asJavascript() ,public java.lang.String toString() <variables>private final PebbleEngine engine,protected static final ObjectMapper mapper
|
jtablesaw_tablesaw
|
tablesaw/jsplot/src/main/java/tech/tablesaw/plotly/components/Domain.java
|
Domain
|
getContext
|
class Domain extends Component {
private final Integer row;
private final Integer column;
private final double[] x;
private final double[] y;
private Domain(DomainBuilder builder) {
this.x = builder.x;
this.y = builder.y;
this.row = builder.row;
this.column = builder.column;
}
@Override
public String asJavascript() {
return asJSON();
}
@Override
protected Map<String, Object> getContext() {<FILL_FUNCTION_BODY>}
@Override
protected Map<String, Object> getJSONContext() {
return getContext();
}
public static DomainBuilder builder() {
return new DomainBuilder();
}
public static class DomainBuilder {
private Integer row;
private Integer column;
private double[] x;
private double[] y;
public DomainBuilder row(int row) {
this.row = row;
return this;
}
public DomainBuilder column(int column) {
this.column = column;
return this;
}
public DomainBuilder x(double[] x) {
this.x = x;
return this;
}
public DomainBuilder y(double[] y) {
this.y = y;
return this;
}
public Domain build() {
return new Domain(this);
}
}
}
|
Map<String, Object> context = new HashMap<>();
context.put("column", column);
context.put("row", row);
context.put("x", x);
context.put("y", y);
return context;
| 378
| 63
| 441
|
<methods>public non-sealed void <init>() ,public java.lang.String asJSON() ,public abstract java.lang.String asJavascript() ,public java.lang.String toString() <variables>private final PebbleEngine engine,protected static final ObjectMapper mapper
|
jtablesaw_tablesaw
|
tablesaw/jsplot/src/main/java/tech/tablesaw/plotly/components/Figure.java
|
Figure
|
buildContext
|
class Figure {
private Trace[] data;
private Layout layout;
private Config config;
private EventHandler[] eventHandlers;
private final Map<String, Object> context = new HashMap<>();
private final PebbleEngine engine = TemplateUtils.getNewEngine();
public Figure(FigureBuilder builder) {
this.data = builder.traces();
this.layout = builder.layout;
this.config = builder.config;
this.eventHandlers = builder.eventHandlers();
}
public Figure(Trace... traces) {
this((Layout) null, traces);
}
public Figure(Layout layout, Trace... traces) {
this(layout, (Config) null, traces);
}
public Figure(Layout layout, Config config, Trace... traces) {
this.data = traces;
this.layout = layout;
this.config = config;
this.eventHandlers = null;
}
public String divString(String divName) {
return String.format("<div id='%s' ></div>" + System.lineSeparator(), divName);
}
public Layout getLayout() {
return layout;
}
public void setLayout(Layout layout) {
this.layout = layout;
}
public Config getConfig() {
return config;
}
public void setConfig(Config config) {
this.config = config;
}
public EventHandler[] getEventHandlers() {
return eventHandlers;
}
public void setEventHandlers(EventHandler... handlers) {
eventHandlers = handlers;
}
public Trace[] getTraces() {
return data;
}
public void setTraces(Trace... data) {
this.data = data;
}
public String asJavascript(String divName) {
Writer writer = new StringWriter();
PebbleTemplate compiledTemplate;
buildContext(divName);
try {
compiledTemplate = engine.getTemplate("figure_template.html");
compiledTemplate.evaluate(writer, getContext());
} catch (PebbleException e) {
throw new IllegalStateException(e);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
return writer.toString();
}
protected void buildContext(String divName) {<FILL_FUNCTION_BODY>}
protected String plotFunction(String divName) {
StringBuilder builder = new StringBuilder();
builder.append("var data = [ ");
for (int i = 0; i < data.length; i++) {
builder.append("trace").append(i);
if (i < data.length - 1) {
builder.append(", ");
}
}
builder.append("];").append(System.lineSeparator());
builder.append("Plotly.newPlot(").append(divName).append(", ").append("data");
if (layout != null) {
builder.append(", ");
builder.append("layout");
}
if (config != null) {
builder.append(", ");
builder.append("config");
}
builder.append(");");
return builder.toString();
}
protected String eventHandlerFunction(String targetName, String divName) {
StringBuilder builder = new StringBuilder();
if (eventHandlers != null) {
builder.append(System.lineSeparator());
for (EventHandler eventHandler : eventHandlers) {
builder.append(eventHandler.asJavascript(targetName, divName));
}
builder.append(System.lineSeparator());
}
return builder.toString();
}
public Map<String, Object> getContext() {
return context;
}
public static FigureBuilder builder() {
return new FigureBuilder();
}
public static class FigureBuilder {
private Layout layout;
private Config config;
private List<Trace> traces = new ArrayList<>();
private List<EventHandler> eventHandlers = new ArrayList<>();
public FigureBuilder layout(Layout layout) {
this.layout = layout;
return this;
}
public FigureBuilder config(Config config) {
this.config = config;
return this;
}
public FigureBuilder addTraces(Trace... traces) {
this.traces.addAll(Arrays.asList(traces));
return this;
}
public FigureBuilder addEventHandlers(EventHandler... handlers) {
this.eventHandlers.addAll(Arrays.asList(handlers));
return this;
}
public Figure build() {
Preconditions.checkState(!traces.isEmpty(), "A figure must have at least one trace");
return new Figure(this);
}
private EventHandler[] eventHandlers() {
return eventHandlers.toArray(new EventHandler[0]);
}
private Trace[] traces() {
return traces.toArray(new Trace[0]);
}
}
}
|
String targetName = "target_" + divName;
context.put("divName", divName);
context.put("targetName", targetName);
StringBuilder builder = new StringBuilder();
if (layout != null) {
builder.append(layout.asJavascript());
}
if (config != null) {
builder.append(config.asJavascript());
}
builder.append(System.lineSeparator());
for (int i = 0; i < data.length; i++) {
Trace trace = data[i];
builder.append(trace.asJavascript(i));
builder.append(System.lineSeparator());
}
builder.append(System.lineSeparator());
String figure = builder.toString();
context.put("figure", figure);
context.put("plotFunction", plotFunction(targetName));
context.put("eventHandlerFunction", eventHandlerFunction(targetName, divName));
| 1,301
| 242
| 1,543
|
<no_super_class>
|
jtablesaw_tablesaw
|
tablesaw/jsplot/src/main/java/tech/tablesaw/plotly/components/Font.java
|
FontBuilder
|
equals
|
class FontBuilder {
private Family fontFamily = Family.OPEN_SANS;
private int size = 12; // number greater than or equal to 1
private String color = "#444";
private FontBuilder() {}
public FontBuilder size(int size) {
Preconditions.checkArgument(size >= 1);
this.size = size;
return this;
}
public FontBuilder color(String color) {
this.color = color;
return this;
}
public FontBuilder family(Family family) {
this.fontFamily = family;
return this;
}
public Font build() {
return new Font(this);
}
}
@Override
public boolean equals(Object o) {<FILL_FUNCTION_BODY>
|
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Font font = (Font) o;
return size == font.size && fontFamily == font.fontFamily && Objects.equals(color, font.color);
| 205
| 73
| 278
|
<methods>public non-sealed void <init>() ,public java.lang.String asJSON() ,public abstract java.lang.String asJavascript() ,public java.lang.String toString() <variables>private final PebbleEngine engine,protected static final ObjectMapper mapper
|
jtablesaw_tablesaw
|
tablesaw/jsplot/src/main/java/tech/tablesaw/plotly/components/Gradient.java
|
Gradient
|
getContext
|
class Gradient extends Component {
/** Defines the gradient type */
public enum Type {
RADIAL("radial"),
HORIZONTAL("horizontal"),
VERTICAL("vertical"),
NONE("none");
private final String value;
Type(String value) {
this.value = value;
}
@JsonValue
@Override
public String toString() {
return value;
}
}
private final Type type;
private final String[] color;
private Gradient(GradientBuilder builder) {
this.type = builder.type;
color = builder.color;
}
@Override
public String asJavascript() {
return asJSON();
}
@Override
protected Map<String, Object> getJSONContext() {
return getContext();
}
@Override
protected Map<String, Object> getContext() {<FILL_FUNCTION_BODY>}
public static GradientBuilder builder() {
return new GradientBuilder();
}
public static class GradientBuilder {
private Type type = Type.NONE;
private String[] color;
public GradientBuilder type(Type type) {
this.type = type;
return this;
}
/** Sets the marker color to a single value */
public GradientBuilder color(String color) {
this.color = new String[1];
this.color[0] = color;
return this;
}
/** Sets the marker color to an array of color values */
public GradientBuilder color(String[] color) {
this.color = color;
return this;
}
public Gradient build() {
return new Gradient(this);
}
}
}
|
Map<String, Object> context = new HashMap<>();
context.put("type", type);
if (color != null && color.length > 0) {
if (color.length > 1) {
context.put("color", color);
} else {
context.put("color", color[0]);
}
}
return context;
| 450
| 94
| 544
|
<methods>public non-sealed void <init>() ,public java.lang.String asJSON() ,public abstract java.lang.String asJavascript() ,public java.lang.String toString() <variables>private final PebbleEngine engine,protected static final ObjectMapper mapper
|
jtablesaw_tablesaw
|
tablesaw/jsplot/src/main/java/tech/tablesaw/plotly/components/HoverLabel.java
|
HoverLabel
|
getJSONContext
|
class HoverLabel extends Component {
/** Sets the background color of all hover labels on graph */
private final String bgColor;
/** Sets the border color of all hover labels on graph. */
private final String borderColor;
/** Sets the default hover label font used by all traces on the graph. */
private final Font font;
/**
* Sets the default length (in number of characters) of the trace name in the hover labels for all
* traces. -1 shows the whole name regardless of length. 0-3 shows the first 0-3 characters, and
* an integer >3 will show the whole name if it is less than that many characters, but if it is
* longer, will truncate to `namelength - 3` characters and add an ellipsis.
*/
private final int nameLength;
HoverLabel(HoverLabelBuilder builder) {
this.bgColor = builder.bgColor;
this.borderColor = builder.borderColor;
this.font = builder.font;
this.nameLength = builder.nameLength;
}
public static HoverLabelBuilder builder() {
return new HoverLabelBuilder();
}
@Override
public String asJavascript() {
return asJSON();
}
@Override
protected Map<String, Object> getJSONContext() {<FILL_FUNCTION_BODY>}
@Override
protected Map<String, Object> getContext() {
return getJSONContext();
}
public static class HoverLabelBuilder {
/** Sets the background color of all hover labels on graph */
private String bgColor = "";
/** Sets the border color of all hover labels on graph. */
private String borderColor = "";
/** Sets the default hover label font used by all traces on the graph. */
private Font font;
/**
* Sets the default length (in number of characters) of the trace name in the hover labels for
* all traces. -1 shows the whole name regardless of length. 0-3 shows the first 0-3 characters,
* and an integer >3 will show the whole name if it is less than that many characters, but if it
* is longer, will truncate to `namelength - 3` characters and add an ellipsis.
*/
private int nameLength = 15;
public HoverLabel build() {
return new HoverLabel(this);
}
public HoverLabelBuilder nameLength(int nameLength) {
this.nameLength = nameLength;
return this;
}
public HoverLabelBuilder font(Font font) {
this.font = font;
return this;
}
public HoverLabelBuilder borderColor(String borderColor) {
this.borderColor = borderColor;
return this;
}
public HoverLabelBuilder bgColor(String bgColor) {
this.bgColor = bgColor;
return this;
}
}
}
|
Map<String, Object> context = new HashMap<>();
context.put("bgcolor", bgColor);
context.put("bordercolor", borderColor);
context.put("namelength", nameLength);
context.put("font", font.getJSONContext());
return context;
| 738
| 74
| 812
|
<methods>public non-sealed void <init>() ,public java.lang.String asJSON() ,public abstract java.lang.String asJavascript() ,public java.lang.String toString() <variables>private final PebbleEngine engine,protected static final ObjectMapper mapper
|
jtablesaw_tablesaw
|
tablesaw/jsplot/src/main/java/tech/tablesaw/plotly/components/Line.java
|
LineBuilder
|
width
|
class LineBuilder {
private String color;
private double width = 2;
private double smoothing = 1;
private Shape shape = Shape.LINEAR;
private Dash dash = Dash.SOLID;
private boolean simplify = true;
/** Sets the line color */
public LineBuilder color(String color) {
this.color = color;
return this;
}
public LineBuilder width(double width) {<FILL_FUNCTION_BODY>}
/**
* Sets the smoothing parameter
*
* @param smoothing a value between 0 and 1.3, inclusive
*/
public LineBuilder smoothing(double smoothing) {
Preconditions.checkArgument(
smoothing >= 0 && smoothing <= 1.3,
"Smoothing parameter must be between 0 and 1.3, inclusive.");
this.smoothing = smoothing;
return this;
}
public LineBuilder dash(Dash dash) {
this.dash = dash;
return this;
}
/**
* Simplifies lines by removing nearly-collinear points. When transitioning lines, it may be
* desirable to disable this so that the number of points along the resulting SVG path is
* unaffected.
*
* @param b true if you want to simplify. True is the default
*/
public LineBuilder simplify(boolean b) {
this.simplify = b;
return this;
}
public LineBuilder shape(Shape shape) {
this.shape = shape;
return this;
}
public Line build() {
return new Line(this);
}
}
|
Preconditions.checkArgument(width >= 0, "Line width must be >= 0.");
this.width = width;
return this;
| 416
| 36
| 452
|
<methods>public non-sealed void <init>() ,public java.lang.String asJSON() ,public abstract java.lang.String asJavascript() ,public java.lang.String toString() <variables>private final PebbleEngine engine,protected static final ObjectMapper mapper
|
jtablesaw_tablesaw
|
tablesaw/jsplot/src/main/java/tech/tablesaw/plotly/components/Margin.java
|
Margin
|
getContext
|
class Margin extends Component {
/** The left margin, in px */
private final int left;
/** The right margin, in px */
private final int right;
/** The top margin, in px */
private final int top;
/** The bottom margin, in px */
private final int bottom;
/** The amount of padding between the plotting area and the axis lines, in px */
private final int pad;
private final boolean autoExpand;
public static MarginBuilder builder() {
return new MarginBuilder();
}
private Margin(MarginBuilder builder) {
this.left = builder.left;
this.right = builder.right;
this.top = builder.top;
this.bottom = builder.bottom;
this.pad = builder.pad;
this.autoExpand = builder.autoExpand;
}
@Override
public String asJavascript() {
return asJSON();
}
@Override
protected Map<String, Object> getContext() {<FILL_FUNCTION_BODY>}
@Override
protected Map<String, Object> getJSONContext() {
return getContext();
}
public static class MarginBuilder {
/** The left margin, in px */
private int left = 80;
/** The right margin, in px */
private int right = 80;
/** The top margin, in px */
private int top = 100;
/** The bottom margin, in px */
private int bottom = 80;
/** The amount of padding between the plotting area and the axis lines, in px */
private int pad = 0;
private boolean autoExpand = true;
private MarginBuilder() {}
public MarginBuilder top(int top) {
this.top = top;
return this;
}
public MarginBuilder bottom(int bottom) {
this.bottom = bottom;
return this;
}
public MarginBuilder left(int left) {
this.left = left;
return this;
}
public MarginBuilder right(int right) {
this.right = right;
return this;
}
public MarginBuilder padding(int padding) {
this.pad = padding;
return this;
}
public MarginBuilder autoExpand(boolean autoExpand) {
this.autoExpand = autoExpand;
return this;
}
public Margin build() {
return new Margin(this);
}
}
}
|
Map<String, Object> context = new HashMap<>();
context.put("t", top);
context.put("b", bottom);
context.put("r", right);
context.put("l", left);
context.put("pad", pad);
context.put("autoexpand", autoExpand);
return context;
| 658
| 86
| 744
|
<methods>public non-sealed void <init>() ,public java.lang.String asJSON() ,public abstract java.lang.String asJavascript() ,public java.lang.String toString() <variables>private final PebbleEngine engine,protected static final ObjectMapper mapper
|
jtablesaw_tablesaw
|
tablesaw/jsplot/src/main/java/tech/tablesaw/plotly/components/Marker.java
|
MarkerBuilder
|
size
|
class MarkerBuilder {
private double[] size = {6};
// Note, a marker can have a color, or color array, but not both
private String[] color;
private double[] colorArray;
private Gradient gradient;
private Palette colorScalePalette;
private boolean cAuto = DEFAULT_C_AUTO;
private double cMin;
private double cMax;
private Line line;
private boolean autoColorScale = DEFAULT_AUTO_COLOR_SCALE;
private boolean showScale = DEFAULT_SHOW_SCALE;
private boolean reverseScale = DEFAULT_REVERSE_SCALE;
private double opacity = DEFAULT_OPACITY;
private Symbol symbol;
private SizeMode sizeMode = DEFAULT_SIZE_MODE;
private ColorBar colorBar;
public MarkerBuilder size(double... size) {<FILL_FUNCTION_BODY>}
public MarkerBuilder size(NumericColumn<?> size) {
return size(size.asDoubleArray());
}
/**
* Has an effect only if `marker.color` is set to a numerical array and `cmin`, `cmax` are also
* set. In this case, it controls whether the range of colors in `colorscale` is mapped to the
* range of values in the `color` array (`cauto: True`), or the `cmin`/`cmax` values (`cauto:
* False`).
*
* <p>Defaults to `False` when `cmin`, `cmax` are set by the user.
*/
public MarkerBuilder cAuto(boolean b) {
this.cAuto = b;
return this;
}
/**
* Has an effect only if `marker.color` is set to a numerical array. Reverses the color mapping
* if True (`cmin` will correspond to the last color in the array and `cmax` will correspond to
* the first color).
*/
public MarkerBuilder reverseScale(boolean b) {
this.reverseScale = b;
return this;
}
/** Sets an outline around the marker */
public MarkerBuilder line(Line line) {
this.line = line;
return this;
}
/** Sets a gradient for the marker */
public MarkerBuilder gradient(Gradient gradient) {
this.gradient = gradient;
return this;
}
/** Sets the ColorBar to display the scale for the marker */
public MarkerBuilder colorBar(ColorBar colorBar) {
this.colorBar = colorBar;
return this;
}
/**
* Has an effect only if `marker.color` is set to a numerical array. Determines whether the
* colorscale is a default palette (`autocolorscale: True`) or the palette determined by
* `marker.colorscale`. In case `colorscale` is unspecified or `autocolorscale` is True, the
* default palette will be chosen according to whether numbers in the `color` array are all
* positive, all negative or mixed.
*
* <p>Defaults to true
*/
public MarkerBuilder autoColorScale(boolean b) {
this.autoColorScale = b;
return this;
}
/**
* Has an effect only if `marker.color` is set to a numerical array. Sets the lower and upper
* bound of the color domain. Values should be associated to the `marker.color` array index
*/
public MarkerBuilder cMinAndMax(double min, double max) {
this.cMin = min;
this.cMax = max;
return this;
}
/**
* Has an effect only if `marker.color` is set to a numerical array. Determines whether or not a
* colorbar is displayed.
*/
public MarkerBuilder showScale(boolean b) {
this.showScale = b;
return this;
}
/**
* Sets the colorscale and only has an effect if `marker.color` is set to a numerical array. The
* colorscale must be an array containing arrays mapping a normalized value to an rgb, rgba,
* hex, hsl, hsv, or named color string.
*
* <p>At minimum, a mapping for the lowest (0) and highest (1) values are required. For example,
* `[[0, 'rgb(0,0,255)', [1, 'rgb(255,0,0)']]`.
*
* <p>To control the bounds of the colorscale in color space, use `marker.cmin` and
* `marker.cmax`.
*/
public MarkerBuilder colorScale(Palette palette) {
this.colorScalePalette = palette;
return this;
}
/** Sets the opacity. Value must be between 0 and 1 inclusive */
public MarkerBuilder opacity(double opacity) {
Preconditions.checkArgument(opacity >= 0 && opacity <= 1);
this.opacity = opacity;
return this;
}
/** Sets the marker color to a single value */
public MarkerBuilder color(String color) {
this.color = new String[1];
this.color[0] = color;
this.colorArray = null;
return this;
}
/** Sets the marker color to an array of color values */
public MarkerBuilder color(String[] color) {
this.color = color;
this.colorArray = null;
return this;
}
/**
* Sets the marker color to an array of numeric values for use when a color scale is provided
*/
public MarkerBuilder color(double[] color) {
this.colorArray = color;
this.color = null;
return this;
}
/** Sets the symbol for the marker */
public MarkerBuilder symbol(Symbol symbol) {
this.symbol = symbol;
return this;
}
/**
* Sets the size mode for the marker
*
* <p>Has an effect only if `marker.size` is set to a numerical array. Sets the rule for which
* the data in `size` is converted to pixels, either as area or the diameter
*/
public MarkerBuilder sizeMode(SizeMode sizeMode) {
this.sizeMode = sizeMode;
return this;
}
public Marker build() {
return new Marker(this);
}
}
|
String errorMessage = "All sizes in size array must be greater than 0.";
for (double d : size) {
Preconditions.checkArgument(d > 0, errorMessage);
}
this.size = size;
return this;
| 1,624
| 64
| 1,688
|
<methods>public non-sealed void <init>() ,public java.lang.String asJSON() ,public abstract java.lang.String asJavascript() ,public java.lang.String toString() <variables>private final PebbleEngine engine,protected static final ObjectMapper mapper
|
jtablesaw_tablesaw
|
tablesaw/jsplot/src/main/java/tech/tablesaw/plotly/components/Page.java
|
Page
|
getContext
|
class Page extends Component {
private final Figure figure;
private final String divName;
private final String plotlyJsLocation;
private Page(PageBuilder builder) {
this.figure = builder.figure;
this.divName = builder.divName;
this.plotlyJsLocation = builder.plotlyJsLocation;
}
@Override
public String asJavascript() {
return asJavascript("page_template.html");
}
@Override
protected Map<String, Object> getContext() {<FILL_FUNCTION_BODY>}
public static PageBuilder pageBuilder(Figure figure, String divName) {
return new PageBuilder(figure, divName);
}
public static class PageBuilder {
private final Figure figure;
private final String divName;
private String plotlyJsLocation = null;
public PageBuilder(Figure figure, String divName) {
this.figure = figure;
this.divName = divName;
}
public Page build() {
return new Page(this);
}
public PageBuilder plotlyJsLocation(String location) {
this.plotlyJsLocation = location;
return this;
}
}
}
|
Map<String, Object> context = new HashMap<>();
context.put("figureScript", figure.asJavascript(divName));
context.put("targetDiv", figure.divString(divName));
context.put("figureTitle", figure.getLayout() != null ? figure.getLayout().getTitle() : null);
context.put("plotlyJsLocation", plotlyJsLocation);
return context;
| 317
| 106
| 423
|
<methods>public non-sealed void <init>() ,public java.lang.String asJSON() ,public abstract java.lang.String asJavascript() ,public java.lang.String toString() <variables>private final PebbleEngine engine,protected static final ObjectMapper mapper
|
jtablesaw_tablesaw
|
tablesaw/jsplot/src/main/java/tech/tablesaw/plotly/components/TemplateUtils.java
|
TemplateUtils
|
getNewEngine
|
class TemplateUtils {
private TemplateUtils() {}
private static Collection<String> templateLocations = new ArrayList<>();
public static void setTemplateLocations(String... locations) {
templateLocations = Arrays.asList(locations);
}
public static PebbleEngine getNewEngine() {<FILL_FUNCTION_BODY>}
}
|
PebbleEngine engine;
try {
Loader<?> loader = new ClasspathLoader();
if (templateLocations != null && !templateLocations.isEmpty()) {
List<Loader<?>> loaders = new ArrayList<>();
for (String templateLocation : templateLocations) {
FileLoader fileLoader = new FileLoader();
fileLoader.setPrefix(templateLocation);
loaders.add(fileLoader);
}
// add this one last, so it is shadowed
loaders.add(loader);
loader = new DelegatingLoader(loaders);
}
engine = new PebbleEngine.Builder().loader(loader).strictVariables(false).build();
} catch (PebbleException e) {
throw new IllegalStateException(e);
}
return engine;
| 92
| 203
| 295
|
<no_super_class>
|
jtablesaw_tablesaw
|
tablesaw/jsplot/src/main/java/tech/tablesaw/plotly/components/change/Change.java
|
Change
|
getJSONContext
|
class Change extends Component {
// private static final ChangeLine DEFAULT_CHANGE_LINE = new LineBuilder().build();
private final ChangeLine changeLine;
private final String fillColor;
@Override
public String asJavascript() {
return asJSON();
}
Change(ChangeBuilder builder) {
this.changeLine = builder.changeLine;
this.fillColor = builder.fillColor;
}
@Override
protected Map<String, Object> getJSONContext() {<FILL_FUNCTION_BODY>}
@Override
protected Map<String, Object> getContext() {
return getJSONContext();
}
public static class ChangeBuilder {
protected String fillColor;
protected ChangeLine changeLine;
public ChangeBuilder fillColor(String color) {
this.fillColor = color;
return this;
}
public ChangeBuilder changeLine(ChangeLine line) {
this.changeLine = line;
return this;
}
}
}
|
Map<String, Object> context = new HashMap<>();
if (changeLine != null) context.put("line", changeLine.getJSONContext());
if (fillColor != null) context.put("fillcolor", fillColor);
return context;
| 257
| 66
| 323
|
<methods>public non-sealed void <init>() ,public java.lang.String asJSON() ,public abstract java.lang.String asJavascript() ,public java.lang.String toString() <variables>private final PebbleEngine engine,protected static final ObjectMapper mapper
|
jtablesaw_tablesaw
|
tablesaw/jsplot/src/main/java/tech/tablesaw/plotly/components/change/ChangeLine.java
|
ChangeLine
|
getJSONContext
|
class ChangeLine extends Component {
private static final int DEFAULT_WIDTH = 2;
private static final String DEFAULT_COLOR = "#3D9970";
private final String color;
private final int width;
private ChangeLine(LineBuilder lineBuilder) {
color = lineBuilder.color;
width = lineBuilder.width;
}
@Override
public String asJavascript() {
return asJSON();
}
@Override
protected Map<String, Object> getJSONContext() {<FILL_FUNCTION_BODY>}
@Override
protected Map<String, Object> getContext() {
return getJSONContext();
}
public static LineBuilder builder() {
return new LineBuilder();
}
public static class LineBuilder {
private String color = DEFAULT_COLOR;
private int width = DEFAULT_WIDTH;
/** Sets the color of line bounding the box(es). */
public LineBuilder color(String color) {
this.color = color;
return this;
}
/**
* Sets the width (in px) of line bounding the box(es).
*
* @param width greater than or equal to 0
*/
public LineBuilder width(int width) {
Preconditions.checkArgument(width >= 0);
this.width = width;
return this;
}
public ChangeLine build() {
return new ChangeLine(this);
}
}
}
|
Map<String, Object> context = new HashMap<>();
if (!color.equals(DEFAULT_COLOR)) context.put("color", color);
if (width != DEFAULT_WIDTH) context.put("width", width);
return context;
| 374
| 63
| 437
|
<methods>public non-sealed void <init>() ,public java.lang.String asJSON() ,public abstract java.lang.String asJavascript() ,public java.lang.String toString() <variables>private final PebbleEngine engine,protected static final ObjectMapper mapper
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.