index
int64 0
36.5k
| proj_name
stringclasses 162
values | relative_path
stringlengths 30
228
| class_name
stringlengths 1
68
| func_name
stringlengths 1
51
| masked_class
stringlengths 68
9.82k
| func_body
stringlengths 46
9.61k
| len_func_body
int64 1
5.26k
| len_input
int64 27
2.01k
| len_output
int64 14
1.94k
| total
int64 55
2.05k
|
---|---|---|---|---|---|---|---|---|---|---|
36,420 | zxing_zxing | zxing/core/src/main/java/com/google/zxing/oned/rss/expanded/decoders/AbstractExpandedDecoder.java | AbstractExpandedDecoder | createDecoder | class AbstractExpandedDecoder {
private final BitArray information;
private final GeneralAppIdDecoder generalDecoder;
AbstractExpandedDecoder(BitArray information) {
this.information = information;
this.generalDecoder = new GeneralAppIdDecoder(information);
}
protected final BitArray getInformation() {
return information;
}
protected final GeneralAppIdDecoder getGeneralDecoder() {
return generalDecoder;
}
public abstract String parseInformation() throws NotFoundException, FormatException;
public static AbstractExpandedDecoder createDecoder(BitArray information) {<FILL_FUNCTION_BODY>}
} |
if (information.get(1)) {
return new AI01AndOtherAIs(information);
}
if (!information.get(2)) {
return new AnyAIDecoder(information);
}
int fourBitEncodationMethod = GeneralAppIdDecoder.extractNumericValueFromBitArray(information, 1, 4);
switch (fourBitEncodationMethod) {
case 4: return new AI013103decoder(information);
case 5: return new AI01320xDecoder(information);
}
int fiveBitEncodationMethod = GeneralAppIdDecoder.extractNumericValueFromBitArray(information, 1, 5);
switch (fiveBitEncodationMethod) {
case 12: return new AI01392xDecoder(information);
case 13: return new AI01393xDecoder(information);
}
int sevenBitEncodationMethod = GeneralAppIdDecoder.extractNumericValueFromBitArray(information, 1, 7);
switch (sevenBitEncodationMethod) {
case 56: return new AI013x0x1xDecoder(information, "310", "11");
case 57: return new AI013x0x1xDecoder(information, "320", "11");
case 58: return new AI013x0x1xDecoder(information, "310", "13");
case 59: return new AI013x0x1xDecoder(information, "320", "13");
case 60: return new AI013x0x1xDecoder(information, "310", "15");
case 61: return new AI013x0x1xDecoder(information, "320", "15");
case 62: return new AI013x0x1xDecoder(information, "310", "17");
case 63: return new AI013x0x1xDecoder(information, "320", "17");
}
throw new IllegalStateException("unknown decoder: " + information);
| 242 | 168 | 561 | 729 |
36,424 | zxing_zxing | zxing/core/src/main/java/com/google/zxing/pdf417/PDF417Reader.java | PDF417Reader | getMaxWidth | class PDF417Reader implements Reader, MultipleBarcodeReader {
private static final Result[] EMPTY_RESULT_ARRAY = new Result[0];
/**
* Locates and decodes a PDF417 code in an image.
*
* @return a String representing the content encoded by the PDF417 code
* @throws NotFoundException if a PDF417 code cannot be found,
* @throws FormatException if a PDF417 cannot be decoded
*/
@Override
public Result decode(BinaryBitmap image) throws NotFoundException, FormatException, ChecksumException {
return decode(image, null);
}
@Override
public Result decode(BinaryBitmap image, Map<DecodeHintType,?> hints) throws NotFoundException, FormatException,
ChecksumException {
Result[] result = decode(image, hints, false);
if (result.length == 0 || result[0] == null) {
throw NotFoundException.getNotFoundInstance();
}
return result[0];
}
@Override
public Result[] decodeMultiple(BinaryBitmap image) throws NotFoundException {
return decodeMultiple(image, null);
}
@Override
public Result[] decodeMultiple(BinaryBitmap image, Map<DecodeHintType,?> hints) throws NotFoundException {
try {
return decode(image, hints, true);
} catch (FormatException | ChecksumException ignored) {
throw NotFoundException.getNotFoundInstance();
}
}
private static Result[] decode(BinaryBitmap image, Map<DecodeHintType, ?> hints, boolean multiple)
throws NotFoundException, FormatException, ChecksumException {
List<Result> results = new ArrayList<>();
PDF417DetectorResult detectorResult = Detector.detect(image, hints, multiple);
for (ResultPoint[] points : detectorResult.getPoints()) {
DecoderResult decoderResult = PDF417ScanningDecoder.decode(detectorResult.getBits(), points[4], points[5],
points[6], points[7], getMinCodewordWidth(points), getMaxCodewordWidth(points));
Result result = new Result(decoderResult.getText(), decoderResult.getRawBytes(), points, BarcodeFormat.PDF_417);
result.putMetadata(ResultMetadataType.ERROR_CORRECTION_LEVEL, decoderResult.getECLevel());
result.putMetadata(ResultMetadataType.ERRORS_CORRECTED, decoderResult.getErrorsCorrected());
result.putMetadata(ResultMetadataType.ERASURES_CORRECTED, decoderResult.getErasures());
PDF417ResultMetadata pdf417ResultMetadata = (PDF417ResultMetadata) decoderResult.getOther();
if (pdf417ResultMetadata != null) {
result.putMetadata(ResultMetadataType.PDF417_EXTRA_METADATA, pdf417ResultMetadata);
}
result.putMetadata(ResultMetadataType.ORIENTATION, detectorResult.getRotation());
result.putMetadata(ResultMetadataType.SYMBOLOGY_IDENTIFIER, "]L" + decoderResult.getSymbologyModifier());
results.add(result);
}
return results.toArray(EMPTY_RESULT_ARRAY);
}
private static int getMaxWidth(ResultPoint p1, ResultPoint p2) {<FILL_FUNCTION_BODY>}
private static int getMinWidth(ResultPoint p1, ResultPoint p2) {
if (p1 == null || p2 == null) {
return Integer.MAX_VALUE;
}
return (int) Math.abs(p1.getX() - p2.getX());
}
private static int getMaxCodewordWidth(ResultPoint[] p) {
return Math.max(
Math.max(getMaxWidth(p[0], p[4]), getMaxWidth(p[6], p[2]) * PDF417Common.MODULES_IN_CODEWORD /
PDF417Common.MODULES_IN_STOP_PATTERN),
Math.max(getMaxWidth(p[1], p[5]), getMaxWidth(p[7], p[3]) * PDF417Common.MODULES_IN_CODEWORD /
PDF417Common.MODULES_IN_STOP_PATTERN));
}
private static int getMinCodewordWidth(ResultPoint[] p) {
return Math.min(
Math.min(getMinWidth(p[0], p[4]), getMinWidth(p[6], p[2]) * PDF417Common.MODULES_IN_CODEWORD /
PDF417Common.MODULES_IN_STOP_PATTERN),
Math.min(getMinWidth(p[1], p[5]), getMinWidth(p[7], p[3]) * PDF417Common.MODULES_IN_CODEWORD /
PDF417Common.MODULES_IN_STOP_PATTERN));
}
@Override
public void reset() {
// nothing needs to be reset
}
} |
if (p1 == null || p2 == null) {
return 0;
}
return (int) Math.abs(p1.getX() - p2.getX());
| 34 | 1,302 | 50 | 1,352 |
36,425 | zxing_zxing | zxing/core/src/main/java/com/google/zxing/pdf417/PDF417Writer.java | PDF417Writer | encode | class PDF417Writer implements Writer {
/**
* default white space (margin) around the code
*/
private static final int WHITE_SPACE = 30;
/**
* default error correction level
*/
private static final int DEFAULT_ERROR_CORRECTION_LEVEL = 2;
@Override
public BitMatrix encode(String contents,
BarcodeFormat format,
int width,
int height,
Map<EncodeHintType,?> hints) throws WriterException {<FILL_FUNCTION_BODY>}
@Override
public BitMatrix encode(String contents,
BarcodeFormat format,
int width,
int height) throws WriterException {
return encode(contents, format, width, height, null);
}
/**
* Takes encoder, accounts for width/height, and retrieves bit matrix
*/
private static BitMatrix bitMatrixFromEncoder(PDF417 encoder,
String contents,
int errorCorrectionLevel,
int width,
int height,
int margin,
boolean autoECI) throws WriterException {
encoder.generateBarcodeLogic(contents, errorCorrectionLevel, autoECI);
int aspectRatio = 4;
byte[][] originalScale = encoder.getBarcodeMatrix().getScaledMatrix(1, aspectRatio);
boolean rotated = false;
if ((height > width) != (originalScale[0].length < originalScale.length)) {
originalScale = rotateArray(originalScale);
rotated = true;
}
int scaleX = width / originalScale[0].length;
int scaleY = height / originalScale.length;
int scale = Math.min(scaleX, scaleY);
if (scale > 1) {
byte[][] scaledMatrix =
encoder.getBarcodeMatrix().getScaledMatrix(scale, scale * aspectRatio);
if (rotated) {
scaledMatrix = rotateArray(scaledMatrix);
}
return bitMatrixFromBitArray(scaledMatrix, margin);
}
return bitMatrixFromBitArray(originalScale, margin);
}
/**
* This takes an array holding the values of the PDF 417
*
* @param input a byte array of information with 0 is black, and 1 is white
* @param margin border around the barcode
* @return BitMatrix of the input
*/
private static BitMatrix bitMatrixFromBitArray(byte[][] input, int margin) {
// Creates the bit matrix with extra space for whitespace
BitMatrix output = new BitMatrix(input[0].length + 2 * margin, input.length + 2 * margin);
output.clear();
for (int y = 0, yOutput = output.getHeight() - margin - 1; y < input.length; y++, yOutput--) {
byte[] inputY = input[y];
for (int x = 0; x < input[0].length; x++) {
// Zero is white in the byte matrix
if (inputY[x] == 1) {
output.set(x + margin, yOutput);
}
}
}
return output;
}
/**
* Takes and rotates the it 90 degrees
*/
private static byte[][] rotateArray(byte[][] bitarray) {
byte[][] temp = new byte[bitarray[0].length][bitarray.length];
for (int ii = 0; ii < bitarray.length; ii++) {
// This makes the direction consistent on screen when rotating the
// screen;
int inverseii = bitarray.length - ii - 1;
for (int jj = 0; jj < bitarray[0].length; jj++) {
temp[jj][inverseii] = bitarray[ii][jj];
}
}
return temp;
}
} |
if (format != BarcodeFormat.PDF_417) {
throw new IllegalArgumentException("Can only encode PDF_417, but got " + format);
}
PDF417 encoder = new PDF417();
int margin = WHITE_SPACE;
int errorCorrectionLevel = DEFAULT_ERROR_CORRECTION_LEVEL;
boolean autoECI = false;
if (hints != null) {
if (hints.containsKey(EncodeHintType.PDF417_COMPACT)) {
encoder.setCompact(Boolean.parseBoolean(hints.get(EncodeHintType.PDF417_COMPACT).toString()));
}
if (hints.containsKey(EncodeHintType.PDF417_COMPACTION)) {
encoder.setCompaction(Compaction.valueOf(hints.get(EncodeHintType.PDF417_COMPACTION).toString()));
}
if (hints.containsKey(EncodeHintType.PDF417_DIMENSIONS)) {
Dimensions dimensions = (Dimensions) hints.get(EncodeHintType.PDF417_DIMENSIONS);
encoder.setDimensions(dimensions.getMaxCols(),
dimensions.getMinCols(),
dimensions.getMaxRows(),
dimensions.getMinRows());
}
if (hints.containsKey(EncodeHintType.MARGIN)) {
margin = Integer.parseInt(hints.get(EncodeHintType.MARGIN).toString());
}
if (hints.containsKey(EncodeHintType.ERROR_CORRECTION)) {
errorCorrectionLevel = Integer.parseInt(hints.get(EncodeHintType.ERROR_CORRECTION).toString());
}
if (hints.containsKey(EncodeHintType.CHARACTER_SET)) {
Charset encoding = Charset.forName(hints.get(EncodeHintType.CHARACTER_SET).toString());
encoder.setEncoding(encoding);
}
autoECI = hints.containsKey(EncodeHintType.PDF417_AUTO_ECI) &&
Boolean.parseBoolean(hints.get(EncodeHintType.PDF417_AUTO_ECI).toString());
}
return bitMatrixFromEncoder(encoder, contents, errorCorrectionLevel, width, height, margin, autoECI);
| 351 | 976 | 610 | 1,586 |
36,426 | zxing_zxing | zxing/core/src/main/java/com/google/zxing/pdf417/decoder/BarcodeValue.java | BarcodeValue | setValue | class BarcodeValue {
private final Map<Integer,Integer> values = new HashMap<>();
/**
* Add an occurrence of a value
*/
void setValue(int value) {<FILL_FUNCTION_BODY>}
/**
* Determines the maximum occurrence of a set value and returns all values which were set with this occurrence.
* @return an array of int, containing the values with the highest occurrence, or null, if no value was set
*/
int[] getValue() {
int maxConfidence = -1;
Collection<Integer> result = new ArrayList<>();
for (Entry<Integer,Integer> entry : values.entrySet()) {
if (entry.getValue() > maxConfidence) {
maxConfidence = entry.getValue();
result.clear();
result.add(entry.getKey());
} else if (entry.getValue() == maxConfidence) {
result.add(entry.getKey());
}
}
return PDF417Common.toIntArray(result);
}
Integer getConfidence(int value) {
return values.get(value);
}
} |
Integer confidence = values.get(value);
if (confidence == null) {
confidence = 0;
}
confidence++;
values.put(value, confidence);
| 39 | 285 | 48 | 333 |
36,427 | zxing_zxing | zxing/core/src/main/java/com/google/zxing/pdf417/decoder/BoundingBox.java | BoundingBox | addMissingRows | class BoundingBox {
private final BitMatrix image;
private final ResultPoint topLeft;
private final ResultPoint bottomLeft;
private final ResultPoint topRight;
private final ResultPoint bottomRight;
private final int minX;
private final int maxX;
private final int minY;
private final int maxY;
BoundingBox(BitMatrix image,
ResultPoint topLeft,
ResultPoint bottomLeft,
ResultPoint topRight,
ResultPoint bottomRight) throws NotFoundException {
boolean leftUnspecified = topLeft == null || bottomLeft == null;
boolean rightUnspecified = topRight == null || bottomRight == null;
if (leftUnspecified && rightUnspecified) {
throw NotFoundException.getNotFoundInstance();
}
if (leftUnspecified) {
topLeft = new ResultPoint(0, topRight.getY());
bottomLeft = new ResultPoint(0, bottomRight.getY());
} else if (rightUnspecified) {
topRight = new ResultPoint(image.getWidth() - 1, topLeft.getY());
bottomRight = new ResultPoint(image.getWidth() - 1, bottomLeft.getY());
}
this.image = image;
this.topLeft = topLeft;
this.bottomLeft = bottomLeft;
this.topRight = topRight;
this.bottomRight = bottomRight;
this.minX = (int) Math.min(topLeft.getX(), bottomLeft.getX());
this.maxX = (int) Math.max(topRight.getX(), bottomRight.getX());
this.minY = (int) Math.min(topLeft.getY(), topRight.getY());
this.maxY = (int) Math.max(bottomLeft.getY(), bottomRight.getY());
}
BoundingBox(BoundingBox boundingBox) {
this.image = boundingBox.image;
this.topLeft = boundingBox.topLeft;
this.bottomLeft = boundingBox.bottomLeft;
this.topRight = boundingBox.topRight;
this.bottomRight = boundingBox.bottomRight;
this.minX = boundingBox.minX;
this.maxX = boundingBox.maxX;
this.minY = boundingBox.minY;
this.maxY = boundingBox.maxY;
}
static BoundingBox merge(BoundingBox leftBox, BoundingBox rightBox) throws NotFoundException {
if (leftBox == null) {
return rightBox;
}
if (rightBox == null) {
return leftBox;
}
return new BoundingBox(leftBox.image, leftBox.topLeft, leftBox.bottomLeft, rightBox.topRight, rightBox.bottomRight);
}
BoundingBox addMissingRows(int missingStartRows, int missingEndRows, boolean isLeft) throws NotFoundException {<FILL_FUNCTION_BODY>}
int getMinX() {
return minX;
}
int getMaxX() {
return maxX;
}
int getMinY() {
return minY;
}
int getMaxY() {
return maxY;
}
ResultPoint getTopLeft() {
return topLeft;
}
ResultPoint getTopRight() {
return topRight;
}
ResultPoint getBottomLeft() {
return bottomLeft;
}
ResultPoint getBottomRight() {
return bottomRight;
}
} |
ResultPoint newTopLeft = topLeft;
ResultPoint newBottomLeft = bottomLeft;
ResultPoint newTopRight = topRight;
ResultPoint newBottomRight = bottomRight;
if (missingStartRows > 0) {
ResultPoint top = isLeft ? topLeft : topRight;
int newMinY = (int) top.getY() - missingStartRows;
if (newMinY < 0) {
newMinY = 0;
}
ResultPoint newTop = new ResultPoint(top.getX(), newMinY);
if (isLeft) {
newTopLeft = newTop;
} else {
newTopRight = newTop;
}
}
if (missingEndRows > 0) {
ResultPoint bottom = isLeft ? bottomLeft : bottomRight;
int newMaxY = (int) bottom.getY() + missingEndRows;
if (newMaxY >= image.getHeight()) {
newMaxY = image.getHeight() - 1;
}
ResultPoint newBottom = new ResultPoint(bottom.getX(), newMaxY);
if (isLeft) {
newBottomLeft = newBottom;
} else {
newBottomRight = newBottom;
}
}
return new BoundingBox(image, newTopLeft, newBottomLeft, newTopRight, newBottomRight);
| 275 | 892 | 338 | 1,230 |
36,428 | zxing_zxing | zxing/core/src/main/java/com/google/zxing/pdf417/decoder/Codeword.java | Codeword | isValidRowNumber | class Codeword {
private static final int BARCODE_ROW_UNKNOWN = -1;
private final int startX;
private final int endX;
private final int bucket;
private final int value;
private int rowNumber = BARCODE_ROW_UNKNOWN;
Codeword(int startX, int endX, int bucket, int value) {
this.startX = startX;
this.endX = endX;
this.bucket = bucket;
this.value = value;
}
boolean hasValidRowNumber() {
return isValidRowNumber(rowNumber);
}
boolean isValidRowNumber(int rowNumber) {<FILL_FUNCTION_BODY>}
void setRowNumberAsRowIndicatorColumn() {
rowNumber = (value / 30) * 3 + bucket / 3;
}
int getWidth() {
return endX - startX;
}
int getStartX() {
return startX;
}
int getEndX() {
return endX;
}
int getBucket() {
return bucket;
}
int getValue() {
return value;
}
int getRowNumber() {
return rowNumber;
}
void setRowNumber(int rowNumber) {
this.rowNumber = rowNumber;
}
@Override
public String toString() {
return rowNumber + "|" + value;
}
} |
return rowNumber != BARCODE_ROW_UNKNOWN && bucket == (rowNumber % 3) * 3;
| 18 | 389 | 34 | 423 |
36,431 | zxing_zxing | zxing/core/src/main/java/com/google/zxing/pdf417/decoder/DetectionResultColumn.java | DetectionResultColumn | getCodewordNearby | class DetectionResultColumn {
private static final int MAX_NEARBY_DISTANCE = 5;
private final BoundingBox boundingBox;
private final Codeword[] codewords;
DetectionResultColumn(BoundingBox boundingBox) {
this.boundingBox = new BoundingBox(boundingBox);
codewords = new Codeword[boundingBox.getMaxY() - boundingBox.getMinY() + 1];
}
final Codeword getCodewordNearby(int imageRow) {<FILL_FUNCTION_BODY>}
final int imageRowToCodewordIndex(int imageRow) {
return imageRow - boundingBox.getMinY();
}
final void setCodeword(int imageRow, Codeword codeword) {
codewords[imageRowToCodewordIndex(imageRow)] = codeword;
}
final Codeword getCodeword(int imageRow) {
return codewords[imageRowToCodewordIndex(imageRow)];
}
final BoundingBox getBoundingBox() {
return boundingBox;
}
final Codeword[] getCodewords() {
return codewords;
}
@Override
public String toString() {
try (Formatter formatter = new Formatter()) {
int row = 0;
for (Codeword codeword : codewords) {
if (codeword == null) {
formatter.format("%3d: | %n", row++);
continue;
}
formatter.format("%3d: %3d|%3d%n", row++, codeword.getRowNumber(), codeword.getValue());
}
return formatter.toString();
}
}
} |
Codeword codeword = getCodeword(imageRow);
if (codeword != null) {
return codeword;
}
for (int i = 1; i < MAX_NEARBY_DISTANCE; i++) {
int nearImageRow = imageRowToCodewordIndex(imageRow) - i;
if (nearImageRow >= 0) {
codeword = codewords[nearImageRow];
if (codeword != null) {
return codeword;
}
}
nearImageRow = imageRowToCodewordIndex(imageRow) + i;
if (nearImageRow < codewords.length) {
codeword = codewords[nearImageRow];
if (codeword != null) {
return codeword;
}
}
}
return null;
| 186 | 434 | 204 | 638 |
36,433 | zxing_zxing | zxing/core/src/main/java/com/google/zxing/pdf417/decoder/PDF417CodewordDecoder.java | PDF417CodewordDecoder | getClosestDecodedValue | class PDF417CodewordDecoder {
private static final float[][] RATIOS_TABLE =
new float[PDF417Common.SYMBOL_TABLE.length][PDF417Common.BARS_IN_MODULE];
static {
// Pre-computes the symbol ratio table.
for (int i = 0; i < PDF417Common.SYMBOL_TABLE.length; i++) {
int currentSymbol = PDF417Common.SYMBOL_TABLE[i];
int currentBit = currentSymbol & 0x1;
for (int j = 0; j < PDF417Common.BARS_IN_MODULE; j++) {
float size = 0.0f;
while ((currentSymbol & 0x1) == currentBit) {
size += 1.0f;
currentSymbol >>= 1;
}
currentBit = currentSymbol & 0x1;
RATIOS_TABLE[i][PDF417Common.BARS_IN_MODULE - j - 1] = size / PDF417Common.MODULES_IN_CODEWORD;
}
}
}
private PDF417CodewordDecoder() {
}
static int getDecodedValue(int[] moduleBitCount) {
int decodedValue = getDecodedCodewordValue(sampleBitCounts(moduleBitCount));
if (decodedValue != -1) {
return decodedValue;
}
return getClosestDecodedValue(moduleBitCount);
}
private static int[] sampleBitCounts(int[] moduleBitCount) {
float bitCountSum = MathUtils.sum(moduleBitCount);
int[] result = new int[PDF417Common.BARS_IN_MODULE];
int bitCountIndex = 0;
int sumPreviousBits = 0;
for (int i = 0; i < PDF417Common.MODULES_IN_CODEWORD; i++) {
float sampleIndex =
bitCountSum / (2 * PDF417Common.MODULES_IN_CODEWORD) +
(i * bitCountSum) / PDF417Common.MODULES_IN_CODEWORD;
if (sumPreviousBits + moduleBitCount[bitCountIndex] <= sampleIndex) {
sumPreviousBits += moduleBitCount[bitCountIndex];
bitCountIndex++;
}
result[bitCountIndex]++;
}
return result;
}
private static int getDecodedCodewordValue(int[] moduleBitCount) {
int decodedValue = getBitValue(moduleBitCount);
return PDF417Common.getCodeword(decodedValue) == -1 ? -1 : decodedValue;
}
private static int getBitValue(int[] moduleBitCount) {
long result = 0;
for (int i = 0; i < moduleBitCount.length; i++) {
for (int bit = 0; bit < moduleBitCount[i]; bit++) {
result = (result << 1) | (i % 2 == 0 ? 1 : 0);
}
}
return (int) result;
}
private static int getClosestDecodedValue(int[] moduleBitCount) {<FILL_FUNCTION_BODY>}
} |
int bitCountSum = MathUtils.sum(moduleBitCount);
float[] bitCountRatios = new float[PDF417Common.BARS_IN_MODULE];
if (bitCountSum > 1) {
for (int i = 0; i < bitCountRatios.length; i++) {
bitCountRatios[i] = moduleBitCount[i] / (float) bitCountSum;
}
}
float bestMatchError = Float.MAX_VALUE;
int bestMatch = -1;
for (int j = 0; j < RATIOS_TABLE.length; j++) {
float error = 0.0f;
float[] ratioTableRow = RATIOS_TABLE[j];
for (int k = 0; k < PDF417Common.BARS_IN_MODULE; k++) {
float diff = ratioTableRow[k] - bitCountRatios[k];
error += diff * diff;
if (error >= bestMatchError) {
break;
}
}
if (error < bestMatchError) {
bestMatchError = error;
bestMatch = PDF417Common.SYMBOL_TABLE[j];
}
}
return bestMatch;
| 230 | 818 | 309 | 1,127 |
36,435 | zxing_zxing | zxing/core/src/main/java/com/google/zxing/pdf417/decoder/ec/ErrorCorrection.java | ErrorCorrection | decode | class ErrorCorrection {
private final ModulusGF field;
public ErrorCorrection() {
this.field = ModulusGF.PDF417_GF;
}
/**
* @param received received codewords
* @param numECCodewords number of those codewords used for EC
* @param erasures location of erasures
* @return number of errors
* @throws ChecksumException if errors cannot be corrected, maybe because of too many errors
*/
public int decode(int[] received,
int numECCodewords,
int[] erasures) throws ChecksumException {<FILL_FUNCTION_BODY>}
private ModulusPoly[] runEuclideanAlgorithm(ModulusPoly a, ModulusPoly b, int R)
throws ChecksumException {
// Assume a's degree is >= b's
if (a.getDegree() < b.getDegree()) {
ModulusPoly temp = a;
a = b;
b = temp;
}
ModulusPoly rLast = a;
ModulusPoly r = b;
ModulusPoly tLast = field.getZero();
ModulusPoly t = field.getOne();
// Run Euclidean algorithm until r's degree is less than R/2
while (r.getDegree() >= R / 2) {
ModulusPoly rLastLast = rLast;
ModulusPoly tLastLast = tLast;
rLast = r;
tLast = t;
// Divide rLastLast by rLast, with quotient in q and remainder in r
if (rLast.isZero()) {
// Oops, Euclidean algorithm already terminated?
throw ChecksumException.getChecksumInstance();
}
r = rLastLast;
ModulusPoly q = field.getZero();
int denominatorLeadingTerm = rLast.getCoefficient(rLast.getDegree());
int dltInverse = field.inverse(denominatorLeadingTerm);
while (r.getDegree() >= rLast.getDegree() && !r.isZero()) {
int degreeDiff = r.getDegree() - rLast.getDegree();
int scale = field.multiply(r.getCoefficient(r.getDegree()), dltInverse);
q = q.add(field.buildMonomial(degreeDiff, scale));
r = r.subtract(rLast.multiplyByMonomial(degreeDiff, scale));
}
t = q.multiply(tLast).subtract(tLastLast).negative();
}
int sigmaTildeAtZero = t.getCoefficient(0);
if (sigmaTildeAtZero == 0) {
throw ChecksumException.getChecksumInstance();
}
int inverse = field.inverse(sigmaTildeAtZero);
ModulusPoly sigma = t.multiply(inverse);
ModulusPoly omega = r.multiply(inverse);
return new ModulusPoly[]{sigma, omega};
}
private int[] findErrorLocations(ModulusPoly errorLocator) throws ChecksumException {
// This is a direct application of Chien's search
int numErrors = errorLocator.getDegree();
int[] result = new int[numErrors];
int e = 0;
for (int i = 1; i < field.getSize() && e < numErrors; i++) {
if (errorLocator.evaluateAt(i) == 0) {
result[e] = field.inverse(i);
e++;
}
}
if (e != numErrors) {
throw ChecksumException.getChecksumInstance();
}
return result;
}
private int[] findErrorMagnitudes(ModulusPoly errorEvaluator,
ModulusPoly errorLocator,
int[] errorLocations) {
int errorLocatorDegree = errorLocator.getDegree();
if (errorLocatorDegree < 1) {
return new int[0];
}
int[] formalDerivativeCoefficients = new int[errorLocatorDegree];
for (int i = 1; i <= errorLocatorDegree; i++) {
formalDerivativeCoefficients[errorLocatorDegree - i] =
field.multiply(i, errorLocator.getCoefficient(i));
}
ModulusPoly formalDerivative = new ModulusPoly(field, formalDerivativeCoefficients);
// This is directly applying Forney's Formula
int s = errorLocations.length;
int[] result = new int[s];
for (int i = 0; i < s; i++) {
int xiInverse = field.inverse(errorLocations[i]);
int numerator = field.subtract(0, errorEvaluator.evaluateAt(xiInverse));
int denominator = field.inverse(formalDerivative.evaluateAt(xiInverse));
result[i] = field.multiply(numerator, denominator);
}
return result;
}
} |
ModulusPoly poly = new ModulusPoly(field, received);
int[] S = new int[numECCodewords];
boolean error = false;
for (int i = numECCodewords; i > 0; i--) {
int eval = poly.evaluateAt(field.exp(i));
S[numECCodewords - i] = eval;
if (eval != 0) {
error = true;
}
}
if (!error) {
return 0;
}
ModulusPoly knownErrors = field.getOne();
if (erasures != null) {
for (int erasure : erasures) {
int b = field.exp(received.length - 1 - erasure);
// Add (1 - bx) term:
ModulusPoly term = new ModulusPoly(field, new int[]{field.subtract(0, b), 1});
knownErrors = knownErrors.multiply(term);
}
}
ModulusPoly syndrome = new ModulusPoly(field, S);
//syndrome = syndrome.multiply(knownErrors);
ModulusPoly[] sigmaOmega =
runEuclideanAlgorithm(field.buildMonomial(numECCodewords, 1), syndrome, numECCodewords);
ModulusPoly sigma = sigmaOmega[0];
ModulusPoly omega = sigmaOmega[1];
//sigma = sigma.multiply(knownErrors);
int[] errorLocations = findErrorLocations(sigma);
int[] errorMagnitudes = findErrorMagnitudes(omega, sigma, errorLocations);
for (int i = 0; i < errorLocations.length; i++) {
int position = received.length - 1 - field.log(errorLocations[i]);
if (position < 0) {
throw ChecksumException.getChecksumInstance();
}
received[position] = field.subtract(received[position], errorMagnitudes[i]);
}
return errorLocations.length;
| 333 | 1,324 | 532 | 1,856 |
36,436 | zxing_zxing | zxing/core/src/main/java/com/google/zxing/pdf417/decoder/ec/ModulusGF.java | ModulusGF | log | class ModulusGF {
public static final ModulusGF PDF417_GF = new ModulusGF(PDF417Common.NUMBER_OF_CODEWORDS, 3);
private final int[] expTable;
private final int[] logTable;
private final ModulusPoly zero;
private final ModulusPoly one;
private final int modulus;
private ModulusGF(int modulus, int generator) {
this.modulus = modulus;
expTable = new int[modulus];
logTable = new int[modulus];
int x = 1;
for (int i = 0; i < modulus; i++) {
expTable[i] = x;
x = (x * generator) % modulus;
}
for (int i = 0; i < modulus - 1; i++) {
logTable[expTable[i]] = i;
}
// logTable[0] == 0 but this should never be used
zero = new ModulusPoly(this, new int[]{0});
one = new ModulusPoly(this, new int[]{1});
}
ModulusPoly getZero() {
return zero;
}
ModulusPoly getOne() {
return one;
}
ModulusPoly buildMonomial(int degree, int coefficient) {
if (degree < 0) {
throw new IllegalArgumentException();
}
if (coefficient == 0) {
return zero;
}
int[] coefficients = new int[degree + 1];
coefficients[0] = coefficient;
return new ModulusPoly(this, coefficients);
}
int add(int a, int b) {
return (a + b) % modulus;
}
int subtract(int a, int b) {
return (modulus + a - b) % modulus;
}
int exp(int a) {
return expTable[a];
}
int log(int a) {<FILL_FUNCTION_BODY>}
int inverse(int a) {
if (a == 0) {
throw new ArithmeticException();
}
return expTable[modulus - logTable[a] - 1];
}
int multiply(int a, int b) {
if (a == 0 || b == 0) {
return 0;
}
return expTable[(logTable[a] + logTable[b]) % (modulus - 1)];
}
int getSize() {
return modulus;
}
} |
if (a == 0) {
throw new IllegalArgumentException();
}
return logTable[a];
| 28 | 653 | 30 | 683 |
36,437 | zxing_zxing | zxing/core/src/main/java/com/google/zxing/pdf417/decoder/ec/ModulusPoly.java | ModulusPoly | negative | class ModulusPoly {
private final ModulusGF field;
private final int[] coefficients;
ModulusPoly(ModulusGF field, int[] coefficients) {
if (coefficients.length == 0) {
throw new IllegalArgumentException();
}
this.field = field;
int coefficientsLength = coefficients.length;
if (coefficientsLength > 1 && coefficients[0] == 0) {
// Leading term must be non-zero for anything except the constant polynomial "0"
int firstNonZero = 1;
while (firstNonZero < coefficientsLength && coefficients[firstNonZero] == 0) {
firstNonZero++;
}
if (firstNonZero == coefficientsLength) {
this.coefficients = new int[]{0};
} else {
this.coefficients = new int[coefficientsLength - firstNonZero];
System.arraycopy(coefficients,
firstNonZero,
this.coefficients,
0,
this.coefficients.length);
}
} else {
this.coefficients = coefficients;
}
}
int[] getCoefficients() {
return coefficients;
}
/**
* @return degree of this polynomial
*/
int getDegree() {
return coefficients.length - 1;
}
/**
* @return true iff this polynomial is the monomial "0"
*/
boolean isZero() {
return coefficients[0] == 0;
}
/**
* @return coefficient of x^degree term in this polynomial
*/
int getCoefficient(int degree) {
return coefficients[coefficients.length - 1 - degree];
}
/**
* @return evaluation of this polynomial at a given point
*/
int evaluateAt(int a) {
if (a == 0) {
// Just return the x^0 coefficient
return getCoefficient(0);
}
if (a == 1) {
// Just the sum of the coefficients
int result = 0;
for (int coefficient : coefficients) {
result = field.add(result, coefficient);
}
return result;
}
int result = coefficients[0];
int size = coefficients.length;
for (int i = 1; i < size; i++) {
result = field.add(field.multiply(a, result), coefficients[i]);
}
return result;
}
ModulusPoly add(ModulusPoly other) {
if (!field.equals(other.field)) {
throw new IllegalArgumentException("ModulusPolys do not have same ModulusGF field");
}
if (isZero()) {
return other;
}
if (other.isZero()) {
return this;
}
int[] smallerCoefficients = this.coefficients;
int[] largerCoefficients = other.coefficients;
if (smallerCoefficients.length > largerCoefficients.length) {
int[] temp = smallerCoefficients;
smallerCoefficients = largerCoefficients;
largerCoefficients = temp;
}
int[] sumDiff = new int[largerCoefficients.length];
int lengthDiff = largerCoefficients.length - smallerCoefficients.length;
// Copy high-order terms only found in higher-degree polynomial's coefficients
System.arraycopy(largerCoefficients, 0, sumDiff, 0, lengthDiff);
for (int i = lengthDiff; i < largerCoefficients.length; i++) {
sumDiff[i] = field.add(smallerCoefficients[i - lengthDiff], largerCoefficients[i]);
}
return new ModulusPoly(field, sumDiff);
}
ModulusPoly subtract(ModulusPoly other) {
if (!field.equals(other.field)) {
throw new IllegalArgumentException("ModulusPolys do not have same ModulusGF field");
}
if (other.isZero()) {
return this;
}
return add(other.negative());
}
ModulusPoly multiply(ModulusPoly other) {
if (!field.equals(other.field)) {
throw new IllegalArgumentException("ModulusPolys do not have same ModulusGF field");
}
if (isZero() || other.isZero()) {
return field.getZero();
}
int[] aCoefficients = this.coefficients;
int aLength = aCoefficients.length;
int[] bCoefficients = other.coefficients;
int bLength = bCoefficients.length;
int[] product = new int[aLength + bLength - 1];
for (int i = 0; i < aLength; i++) {
int aCoeff = aCoefficients[i];
for (int j = 0; j < bLength; j++) {
product[i + j] = field.add(product[i + j], field.multiply(aCoeff, bCoefficients[j]));
}
}
return new ModulusPoly(field, product);
}
ModulusPoly negative() {<FILL_FUNCTION_BODY>}
ModulusPoly multiply(int scalar) {
if (scalar == 0) {
return field.getZero();
}
if (scalar == 1) {
return this;
}
int size = coefficients.length;
int[] product = new int[size];
for (int i = 0; i < size; i++) {
product[i] = field.multiply(coefficients[i], scalar);
}
return new ModulusPoly(field, product);
}
ModulusPoly multiplyByMonomial(int degree, int coefficient) {
if (degree < 0) {
throw new IllegalArgumentException();
}
if (coefficient == 0) {
return field.getZero();
}
int size = coefficients.length;
int[] product = new int[size + degree];
for (int i = 0; i < size; i++) {
product[i] = field.multiply(coefficients[i], coefficient);
}
return new ModulusPoly(field, product);
}
@Override
public String toString() {
StringBuilder result = new StringBuilder(8 * getDegree());
for (int degree = getDegree(); degree >= 0; degree--) {
int coefficient = getCoefficient(degree);
if (coefficient != 0) {
if (coefficient < 0) {
result.append(" - ");
coefficient = -coefficient;
} else {
if (result.length() > 0) {
result.append(" + ");
}
}
if (degree == 0 || coefficient != 1) {
result.append(coefficient);
}
if (degree != 0) {
if (degree == 1) {
result.append('x');
} else {
result.append("x^");
result.append(degree);
}
}
}
}
return result.toString();
}
} |
int size = coefficients.length;
int[] negativeCoefficients = new int[size];
for (int i = 0; i < size; i++) {
negativeCoefficients[i] = field.subtract(0, coefficients[i]);
}
return new ModulusPoly(field, negativeCoefficients);
| 51 | 1,813 | 84 | 1,897 |
36,439 | zxing_zxing | zxing/core/src/main/java/com/google/zxing/pdf417/encoder/BarcodeMatrix.java | BarcodeMatrix | getScaledMatrix | class BarcodeMatrix {
private final BarcodeRow[] matrix;
private int currentRow;
private final int height;
private final int width;
/**
* @param height the height of the matrix (Rows)
* @param width the width of the matrix (Cols)
*/
BarcodeMatrix(int height, int width) {
matrix = new BarcodeRow[height];
//Initializes the array to the correct width
for (int i = 0, matrixLength = matrix.length; i < matrixLength; i++) {
matrix[i] = new BarcodeRow((width + 4) * 17 + 1);
}
this.width = width * 17;
this.height = height;
this.currentRow = -1;
}
void set(int x, int y, byte value) {
matrix[y].set(x, value);
}
void startRow() {
++currentRow;
}
BarcodeRow getCurrentRow() {
return matrix[currentRow];
}
public byte[][] getMatrix() {
return getScaledMatrix(1, 1);
}
public byte[][] getScaledMatrix(int xScale, int yScale) {<FILL_FUNCTION_BODY>}
} |
byte[][] matrixOut = new byte[height * yScale][width * xScale];
int yMax = height * yScale;
for (int i = 0; i < yMax; i++) {
matrixOut[yMax - i - 1] = matrix[i / yScale].getScaledRow(xScale);
}
return matrixOut;
| 60 | 332 | 91 | 423 |
36,440 | zxing_zxing | zxing/core/src/main/java/com/google/zxing/pdf417/encoder/BarcodeRow.java | BarcodeRow | getScaledRow | class BarcodeRow {
private final byte[] row;
//A tacker for position in the bar
private int currentLocation;
/**
* Creates a Barcode row of the width
*/
BarcodeRow(int width) {
this.row = new byte[width];
currentLocation = 0;
}
/**
* Sets a specific location in the bar
*
* @param x The location in the bar
* @param value Black if true, white if false;
*/
void set(int x, byte value) {
row[x] = value;
}
/**
* Sets a specific location in the bar
*
* @param x The location in the bar
* @param black Black if true, white if false;
*/
private void set(int x, boolean black) {
row[x] = (byte) (black ? 1 : 0);
}
/**
* @param black A boolean which is true if the bar black false if it is white
* @param width How many spots wide the bar is.
*/
void addBar(boolean black, int width) {
for (int ii = 0; ii < width; ii++) {
set(currentLocation++, black);
}
}
/**
* This function scales the row
*
* @param scale How much you want the image to be scaled, must be greater than or equal to 1.
* @return the scaled row
*/
byte[] getScaledRow(int scale) {<FILL_FUNCTION_BODY>}
} |
byte[] output = new byte[row.length * scale];
for (int i = 0; i < output.length; i++) {
output[i] = row[i / scale];
}
return output;
| 45 | 401 | 58 | 459 |
36,444 | zxing_zxing | zxing/core/src/main/java/com/google/zxing/qrcode/QRCodeReader.java | QRCodeReader | extractPureBits | class QRCodeReader implements Reader {
private static final ResultPoint[] NO_POINTS = new ResultPoint[0];
private final Decoder decoder = new Decoder();
protected final Decoder getDecoder() {
return decoder;
}
/**
* Locates and decodes a QR code in an image.
*
* @return a String representing the content encoded by the QR code
* @throws NotFoundException if a QR code cannot be found
* @throws FormatException if a QR code cannot be decoded
* @throws ChecksumException if error correction fails
*/
@Override
public Result decode(BinaryBitmap image) throws NotFoundException, ChecksumException, FormatException {
return decode(image, null);
}
@Override
public final Result decode(BinaryBitmap image, Map<DecodeHintType,?> hints)
throws NotFoundException, ChecksumException, FormatException {
DecoderResult decoderResult;
ResultPoint[] points;
if (hints != null && hints.containsKey(DecodeHintType.PURE_BARCODE)) {
BitMatrix bits = extractPureBits(image.getBlackMatrix());
decoderResult = decoder.decode(bits, hints);
points = NO_POINTS;
} else {
DetectorResult detectorResult = new Detector(image.getBlackMatrix()).detect(hints);
decoderResult = decoder.decode(detectorResult.getBits(), hints);
points = detectorResult.getPoints();
}
// If the code was mirrored: swap the bottom-left and the top-right points.
if (decoderResult.getOther() instanceof QRCodeDecoderMetaData) {
((QRCodeDecoderMetaData) decoderResult.getOther()).applyMirroredCorrection(points);
}
Result result = new Result(decoderResult.getText(), decoderResult.getRawBytes(), points, BarcodeFormat.QR_CODE);
List<byte[]> byteSegments = decoderResult.getByteSegments();
if (byteSegments != null) {
result.putMetadata(ResultMetadataType.BYTE_SEGMENTS, byteSegments);
}
String ecLevel = decoderResult.getECLevel();
if (ecLevel != null) {
result.putMetadata(ResultMetadataType.ERROR_CORRECTION_LEVEL, ecLevel);
}
if (decoderResult.hasStructuredAppend()) {
result.putMetadata(ResultMetadataType.STRUCTURED_APPEND_SEQUENCE,
decoderResult.getStructuredAppendSequenceNumber());
result.putMetadata(ResultMetadataType.STRUCTURED_APPEND_PARITY,
decoderResult.getStructuredAppendParity());
}
result.putMetadata(ResultMetadataType.ERRORS_CORRECTED, decoderResult.getErrorsCorrected());
result.putMetadata(ResultMetadataType.SYMBOLOGY_IDENTIFIER, "]Q" + decoderResult.getSymbologyModifier());
return result;
}
@Override
public void reset() {
// do nothing
}
/**
* This method detects a code in a "pure" image -- that is, pure monochrome image
* which contains only an unrotated, unskewed, image of a code, with some white border
* around it. This is a specialized method that works exceptionally fast in this special
* case.
*/
private static BitMatrix extractPureBits(BitMatrix image) throws NotFoundException {<FILL_FUNCTION_BODY>}
private static float moduleSize(int[] leftTopBlack, BitMatrix image) throws NotFoundException {
int height = image.getHeight();
int width = image.getWidth();
int x = leftTopBlack[0];
int y = leftTopBlack[1];
boolean inBlack = true;
int transitions = 0;
while (x < width && y < height) {
if (inBlack != image.get(x, y)) {
if (++transitions == 5) {
break;
}
inBlack = !inBlack;
}
x++;
y++;
}
if (x == width || y == height) {
throw NotFoundException.getNotFoundInstance();
}
return (x - leftTopBlack[0]) / 7.0f;
}
} |
int[] leftTopBlack = image.getTopLeftOnBit();
int[] rightBottomBlack = image.getBottomRightOnBit();
if (leftTopBlack == null || rightBottomBlack == null) {
throw NotFoundException.getNotFoundInstance();
}
float moduleSize = moduleSize(leftTopBlack, image);
int top = leftTopBlack[1];
int bottom = rightBottomBlack[1];
int left = leftTopBlack[0];
int right = rightBottomBlack[0];
// Sanity check!
if (left >= right || top >= bottom) {
throw NotFoundException.getNotFoundInstance();
}
if (bottom - top != right - left) {
// Special case, where bottom-right module wasn't black so we found something else in the last row
// Assume it's a square, so use height as the width
right = left + (bottom - top);
if (right >= image.getWidth()) {
// Abort if that would not make sense -- off image
throw NotFoundException.getNotFoundInstance();
}
}
int matrixWidth = Math.round((right - left + 1) / moduleSize);
int matrixHeight = Math.round((bottom - top + 1) / moduleSize);
if (matrixWidth <= 0 || matrixHeight <= 0) {
throw NotFoundException.getNotFoundInstance();
}
if (matrixHeight != matrixWidth) {
// Only possibly decode square regions
throw NotFoundException.getNotFoundInstance();
}
// Push in the "border" by half the module width so that we start
// sampling in the middle of the module. Just in case the image is a
// little off, this will help recover.
int nudge = (int) (moduleSize / 2.0f);
top += nudge;
left += nudge;
// But careful that this does not sample off the edge
// "right" is the farthest-right valid pixel location -- right+1 is not necessarily
// This is positive by how much the inner x loop below would be too large
int nudgedTooFarRight = left + (int) ((matrixWidth - 1) * moduleSize) - right;
if (nudgedTooFarRight > 0) {
if (nudgedTooFarRight > nudge) {
// Neither way fits; abort
throw NotFoundException.getNotFoundInstance();
}
left -= nudgedTooFarRight;
}
// See logic above
int nudgedTooFarDown = top + (int) ((matrixHeight - 1) * moduleSize) - bottom;
if (nudgedTooFarDown > 0) {
if (nudgedTooFarDown > nudge) {
// Neither way fits; abort
throw NotFoundException.getNotFoundInstance();
}
top -= nudgedTooFarDown;
}
// Now just read off the bits
BitMatrix bits = new BitMatrix(matrixWidth, matrixHeight);
for (int y = 0; y < matrixHeight; y++) {
int iOffset = top + (int) (y * moduleSize);
for (int x = 0; x < matrixWidth; x++) {
if (image.get(left + (int) (x * moduleSize), iOffset)) {
bits.set(x, y);
}
}
}
return bits;
| 673 | 1,112 | 853 | 1,965 |
36,445 | zxing_zxing | zxing/core/src/main/java/com/google/zxing/qrcode/QRCodeWriter.java | QRCodeWriter | renderResult | class QRCodeWriter implements Writer {
private static final int QUIET_ZONE_SIZE = 4;
@Override
public BitMatrix encode(String contents, BarcodeFormat format, int width, int height)
throws WriterException {
return encode(contents, format, width, height, null);
}
@Override
public BitMatrix encode(String contents,
BarcodeFormat format,
int width,
int height,
Map<EncodeHintType,?> hints) throws WriterException {
if (contents.isEmpty()) {
throw new IllegalArgumentException("Found empty contents");
}
if (format != BarcodeFormat.QR_CODE) {
throw new IllegalArgumentException("Can only encode QR_CODE, but got " + format);
}
if (width < 0 || height < 0) {
throw new IllegalArgumentException("Requested dimensions are too small: " + width + 'x' +
height);
}
ErrorCorrectionLevel errorCorrectionLevel = ErrorCorrectionLevel.L;
int quietZone = QUIET_ZONE_SIZE;
if (hints != null) {
if (hints.containsKey(EncodeHintType.ERROR_CORRECTION)) {
errorCorrectionLevel = ErrorCorrectionLevel.valueOf(hints.get(EncodeHintType.ERROR_CORRECTION).toString());
}
if (hints.containsKey(EncodeHintType.MARGIN)) {
quietZone = Integer.parseInt(hints.get(EncodeHintType.MARGIN).toString());
}
}
QRCode code = Encoder.encode(contents, errorCorrectionLevel, hints);
return renderResult(code, width, height, quietZone);
}
// Note that the input matrix uses 0 == white, 1 == black, while the output matrix uses
// 0 == black, 255 == white (i.e. an 8 bit greyscale bitmap).
private static BitMatrix renderResult(QRCode code, int width, int height, int quietZone) {<FILL_FUNCTION_BODY>}
} |
ByteMatrix input = code.getMatrix();
if (input == null) {
throw new IllegalStateException();
}
int inputWidth = input.getWidth();
int inputHeight = input.getHeight();
int qrWidth = inputWidth + (quietZone * 2);
int qrHeight = inputHeight + (quietZone * 2);
int outputWidth = Math.max(width, qrWidth);
int outputHeight = Math.max(height, qrHeight);
int multiple = Math.min(outputWidth / qrWidth, outputHeight / qrHeight);
// Padding includes both the quiet zone and the extra white pixels to accommodate the requested
// dimensions. For example, if input is 25x25 the QR will be 33x33 including the quiet zone.
// If the requested size is 200x160, the multiple will be 4, for a QR of 132x132. These will
// handle all the padding from 100x100 (the actual QR) up to 200x160.
int leftPadding = (outputWidth - (inputWidth * multiple)) / 2;
int topPadding = (outputHeight - (inputHeight * multiple)) / 2;
BitMatrix output = new BitMatrix(outputWidth, outputHeight);
for (int inputY = 0, outputY = topPadding; inputY < inputHeight; inputY++, outputY += multiple) {
// Write the contents of this row of the barcode
for (int inputX = 0, outputX = leftPadding; inputX < inputWidth; inputX++, outputX += multiple) {
if (input.get(inputX, inputY) == 1) {
output.setRegion(outputX, outputY, multiple, multiple);
}
}
}
return output;
| 310 | 535 | 461 | 996 |
36,447 | zxing_zxing | zxing/core/src/main/java/com/google/zxing/qrcode/decoder/DataBlock.java | DataBlock | getDataBlocks | class DataBlock {
private final int numDataCodewords;
private final byte[] codewords;
private DataBlock(int numDataCodewords, byte[] codewords) {
this.numDataCodewords = numDataCodewords;
this.codewords = codewords;
}
/**
* <p>When QR Codes use multiple data blocks, they are actually interleaved.
* That is, the first byte of data block 1 to n is written, then the second bytes, and so on. This
* method will separate the data into original blocks.</p>
*
* @param rawCodewords bytes as read directly from the QR Code
* @param version version of the QR Code
* @param ecLevel error-correction level of the QR Code
* @return DataBlocks containing original bytes, "de-interleaved" from representation in the
* QR Code
*/
static DataBlock[] getDataBlocks(byte[] rawCodewords,
Version version,
ErrorCorrectionLevel ecLevel) {<FILL_FUNCTION_BODY>}
int getNumDataCodewords() {
return numDataCodewords;
}
byte[] getCodewords() {
return codewords;
}
} |
if (rawCodewords.length != version.getTotalCodewords()) {
throw new IllegalArgumentException();
}
// Figure out the number and size of data blocks used by this version and
// error correction level
Version.ECBlocks ecBlocks = version.getECBlocksForLevel(ecLevel);
// First count the total number of data blocks
int totalBlocks = 0;
Version.ECB[] ecBlockArray = ecBlocks.getECBlocks();
for (Version.ECB ecBlock : ecBlockArray) {
totalBlocks += ecBlock.getCount();
}
// Now establish DataBlocks of the appropriate size and number of data codewords
DataBlock[] result = new DataBlock[totalBlocks];
int numResultBlocks = 0;
for (Version.ECB ecBlock : ecBlockArray) {
for (int i = 0; i < ecBlock.getCount(); i++) {
int numDataCodewords = ecBlock.getDataCodewords();
int numBlockCodewords = ecBlocks.getECCodewordsPerBlock() + numDataCodewords;
result[numResultBlocks++] = new DataBlock(numDataCodewords, new byte[numBlockCodewords]);
}
}
// All blocks have the same amount of data, except that the last n
// (where n may be 0) have 1 more byte. Figure out where these start.
int shorterBlocksTotalCodewords = result[0].codewords.length;
int longerBlocksStartAt = result.length - 1;
while (longerBlocksStartAt >= 0) {
int numCodewords = result[longerBlocksStartAt].codewords.length;
if (numCodewords == shorterBlocksTotalCodewords) {
break;
}
longerBlocksStartAt--;
}
longerBlocksStartAt++;
int shorterBlocksNumDataCodewords = shorterBlocksTotalCodewords - ecBlocks.getECCodewordsPerBlock();
// The last elements of result may be 1 element longer;
// first fill out as many elements as all of them have
int rawCodewordsOffset = 0;
for (int i = 0; i < shorterBlocksNumDataCodewords; i++) {
for (int j = 0; j < numResultBlocks; j++) {
result[j].codewords[i] = rawCodewords[rawCodewordsOffset++];
}
}
// Fill out the last data block in the longer ones
for (int j = longerBlocksStartAt; j < numResultBlocks; j++) {
result[j].codewords[shorterBlocksNumDataCodewords] = rawCodewords[rawCodewordsOffset++];
}
// Now add in error correction blocks
int max = result[0].codewords.length;
for (int i = shorterBlocksNumDataCodewords; i < max; i++) {
for (int j = 0; j < numResultBlocks; j++) {
int iOffset = j < longerBlocksStartAt ? i : i + 1;
result[j].codewords[iOffset] = rawCodewords[rawCodewordsOffset++];
}
}
return result;
| 531 | 313 | 795 | 1,108 |
36,449 | zxing_zxing | zxing/core/src/main/java/com/google/zxing/qrcode/decoder/Decoder.java | Decoder | decode | class Decoder {
private final ReedSolomonDecoder rsDecoder;
public Decoder() {
rsDecoder = new ReedSolomonDecoder(GenericGF.QR_CODE_FIELD_256);
}
public DecoderResult decode(boolean[][] image) throws ChecksumException, FormatException {
return decode(image, null);
}
/**
* <p>Convenience method that can decode a QR Code represented as a 2D array of booleans.
* "true" is taken to mean a black module.</p>
*
* @param image booleans representing white/black QR Code modules
* @param hints decoding hints that should be used to influence decoding
* @return text and bytes encoded within the QR Code
* @throws FormatException if the QR Code cannot be decoded
* @throws ChecksumException if error correction fails
*/
public DecoderResult decode(boolean[][] image, Map<DecodeHintType,?> hints)
throws ChecksumException, FormatException {
return decode(BitMatrix.parse(image), hints);
}
public DecoderResult decode(BitMatrix bits) throws ChecksumException, FormatException {
return decode(bits, null);
}
/**
* <p>Decodes a QR Code represented as a {@link BitMatrix}. A 1 or "true" is taken to mean a black module.</p>
*
* @param bits booleans representing white/black QR Code modules
* @param hints decoding hints that should be used to influence decoding
* @return text and bytes encoded within the QR Code
* @throws FormatException if the QR Code cannot be decoded
* @throws ChecksumException if error correction fails
*/
public DecoderResult decode(BitMatrix bits, Map<DecodeHintType,?> hints)
throws FormatException, ChecksumException {
// Construct a parser and read version, error-correction level
BitMatrixParser parser = new BitMatrixParser(bits);
FormatException fe = null;
ChecksumException ce = null;
try {
return decode(parser, hints);
} catch (FormatException e) {
fe = e;
} catch (ChecksumException e) {
ce = e;
}
try {
// Revert the bit matrix
parser.remask();
// Will be attempting a mirrored reading of the version and format info.
parser.setMirror(true);
// Preemptively read the version.
parser.readVersion();
// Preemptively read the format information.
parser.readFormatInformation();
/*
* Since we're here, this means we have successfully detected some kind
* of version and format information when mirrored. This is a good sign,
* that the QR code may be mirrored, and we should try once more with a
* mirrored content.
*/
// Prepare for a mirrored reading.
parser.mirror();
DecoderResult result = decode(parser, hints);
// Success! Notify the caller that the code was mirrored.
result.setOther(new QRCodeDecoderMetaData(true));
return result;
} catch (FormatException | ChecksumException e) {
// Throw the exception from the original reading
if (fe != null) {
throw fe;
}
throw ce; // If fe is null, this can't be
}
}
private DecoderResult decode(BitMatrixParser parser, Map<DecodeHintType,?> hints)
throws FormatException, ChecksumException {<FILL_FUNCTION_BODY>}
/**
* <p>Given data and error-correction codewords received, possibly corrupted by errors, attempts to
* correct the errors in-place using Reed-Solomon error correction.</p>
*
* @param codewordBytes data and error correction codewords
* @param numDataCodewords number of codewords that are data bytes
* @return the number of errors corrected
* @throws ChecksumException if error correction fails
*/
private int correctErrors(byte[] codewordBytes, int numDataCodewords) throws ChecksumException {
int numCodewords = codewordBytes.length;
// First read into an array of ints
int[] codewordsInts = new int[numCodewords];
for (int i = 0; i < numCodewords; i++) {
codewordsInts[i] = codewordBytes[i] & 0xFF;
}
int errorsCorrected = 0;
try {
errorsCorrected = rsDecoder.decodeWithECCount(codewordsInts, codewordBytes.length - numDataCodewords);
} catch (ReedSolomonException ignored) {
throw ChecksumException.getChecksumInstance();
}
// Copy back into array of bytes -- only need to worry about the bytes that were data
// We don't care about errors in the error-correction codewords
for (int i = 0; i < numDataCodewords; i++) {
codewordBytes[i] = (byte) codewordsInts[i];
}
return errorsCorrected;
}
} |
Version version = parser.readVersion();
ErrorCorrectionLevel ecLevel = parser.readFormatInformation().getErrorCorrectionLevel();
// Read codewords
byte[] codewords = parser.readCodewords();
// Separate into data blocks
DataBlock[] dataBlocks = DataBlock.getDataBlocks(codewords, version, ecLevel);
// Count total number of data bytes
int totalBytes = 0;
for (DataBlock dataBlock : dataBlocks) {
totalBytes += dataBlock.getNumDataCodewords();
}
byte[] resultBytes = new byte[totalBytes];
int resultOffset = 0;
// Error-correct and copy data blocks together into a stream of bytes
int errorsCorrected = 0;
for (DataBlock dataBlock : dataBlocks) {
byte[] codewordBytes = dataBlock.getCodewords();
int numDataCodewords = dataBlock.getNumDataCodewords();
errorsCorrected += correctErrors(codewordBytes, numDataCodewords);
for (int i = 0; i < numDataCodewords; i++) {
resultBytes[resultOffset++] = codewordBytes[i];
}
}
// Decode the contents of that stream of bytes
DecoderResult result = DecodedBitStreamParser.decode(resultBytes, version, ecLevel, hints);
result.setErrorsCorrected(errorsCorrected);
return result;
| 224 | 1,334 | 350 | 1,684 |
36,450 | zxing_zxing | zxing/core/src/main/java/com/google/zxing/qrcode/decoder/FormatInformation.java | FormatInformation | doDecodeFormatInformation | class FormatInformation {
private static final int FORMAT_INFO_MASK_QR = 0x5412;
/**
* See ISO 18004:2006, Annex C, Table C.1
*/
private static final int[][] FORMAT_INFO_DECODE_LOOKUP = {
{0x5412, 0x00},
{0x5125, 0x01},
{0x5E7C, 0x02},
{0x5B4B, 0x03},
{0x45F9, 0x04},
{0x40CE, 0x05},
{0x4F97, 0x06},
{0x4AA0, 0x07},
{0x77C4, 0x08},
{0x72F3, 0x09},
{0x7DAA, 0x0A},
{0x789D, 0x0B},
{0x662F, 0x0C},
{0x6318, 0x0D},
{0x6C41, 0x0E},
{0x6976, 0x0F},
{0x1689, 0x10},
{0x13BE, 0x11},
{0x1CE7, 0x12},
{0x19D0, 0x13},
{0x0762, 0x14},
{0x0255, 0x15},
{0x0D0C, 0x16},
{0x083B, 0x17},
{0x355F, 0x18},
{0x3068, 0x19},
{0x3F31, 0x1A},
{0x3A06, 0x1B},
{0x24B4, 0x1C},
{0x2183, 0x1D},
{0x2EDA, 0x1E},
{0x2BED, 0x1F},
};
private final ErrorCorrectionLevel errorCorrectionLevel;
private final byte dataMask;
private FormatInformation(int formatInfo) {
// Bits 3,4
errorCorrectionLevel = ErrorCorrectionLevel.forBits((formatInfo >> 3) & 0x03);
// Bottom 3 bits
dataMask = (byte) (formatInfo & 0x07);
}
static int numBitsDiffering(int a, int b) {
return Integer.bitCount(a ^ b);
}
/**
* @param maskedFormatInfo1 format info indicator, with mask still applied
* @param maskedFormatInfo2 second copy of same info; both are checked at the same time
* to establish best match
* @return information about the format it specifies, or {@code null}
* if doesn't seem to match any known pattern
*/
static FormatInformation decodeFormatInformation(int maskedFormatInfo1, int maskedFormatInfo2) {
FormatInformation formatInfo = doDecodeFormatInformation(maskedFormatInfo1, maskedFormatInfo2);
if (formatInfo != null) {
return formatInfo;
}
// Should return null, but, some QR codes apparently
// do not mask this info. Try again by actually masking the pattern
// first
return doDecodeFormatInformation(maskedFormatInfo1 ^ FORMAT_INFO_MASK_QR,
maskedFormatInfo2 ^ FORMAT_INFO_MASK_QR);
}
private static FormatInformation doDecodeFormatInformation(int maskedFormatInfo1, int maskedFormatInfo2) {<FILL_FUNCTION_BODY>}
ErrorCorrectionLevel getErrorCorrectionLevel() {
return errorCorrectionLevel;
}
byte getDataMask() {
return dataMask;
}
@Override
public int hashCode() {
return (errorCorrectionLevel.ordinal() << 3) | dataMask;
}
@Override
public boolean equals(Object o) {
if (!(o instanceof FormatInformation)) {
return false;
}
FormatInformation other = (FormatInformation) o;
return this.errorCorrectionLevel == other.errorCorrectionLevel &&
this.dataMask == other.dataMask;
}
} |
// Find the int in FORMAT_INFO_DECODE_LOOKUP with fewest bits differing
int bestDifference = Integer.MAX_VALUE;
int bestFormatInfo = 0;
for (int[] decodeInfo : FORMAT_INFO_DECODE_LOOKUP) {
int targetInfo = decodeInfo[0];
if (targetInfo == maskedFormatInfo1 || targetInfo == maskedFormatInfo2) {
// Found an exact match
return new FormatInformation(decodeInfo[1]);
}
int bitsDifference = numBitsDiffering(maskedFormatInfo1, targetInfo);
if (bitsDifference < bestDifference) {
bestFormatInfo = decodeInfo[1];
bestDifference = bitsDifference;
}
if (maskedFormatInfo1 != maskedFormatInfo2) {
// also try the other option
bitsDifference = numBitsDiffering(maskedFormatInfo2, targetInfo);
if (bitsDifference < bestDifference) {
bestFormatInfo = decodeInfo[1];
bestDifference = bitsDifference;
}
}
}
// Hamming distance of the 32 masked codes is 7, by construction, so <= 3 bits
// differing means we found a match
if (bestDifference <= 3) {
return new FormatInformation(bestFormatInfo);
}
return null;
| 278 | 1,168 | 347 | 1,515 |
36,451 | zxing_zxing | zxing/core/src/main/java/com/google/zxing/qrcode/decoder/QRCodeDecoderMetaData.java | QRCodeDecoderMetaData | applyMirroredCorrection | class QRCodeDecoderMetaData {
private final boolean mirrored;
QRCodeDecoderMetaData(boolean mirrored) {
this.mirrored = mirrored;
}
/**
* @return true if the QR Code was mirrored.
*/
public boolean isMirrored() {
return mirrored;
}
/**
* Apply the result points' order correction due to mirroring.
*
* @param points Array of points to apply mirror correction to.
*/
public void applyMirroredCorrection(ResultPoint[] points) {<FILL_FUNCTION_BODY>}
} |
if (!mirrored || points == null || points.length < 3) {
return;
}
ResultPoint bottomLeft = points[0];
points[0] = points[2];
points[2] = bottomLeft;
// No need to 'fix' top-left and alignment pattern.
| 58 | 170 | 77 | 247 |
36,453 | zxing_zxing | zxing/core/src/main/java/com/google/zxing/qrcode/detector/AlignmentPattern.java | AlignmentPattern | aboutEquals | class AlignmentPattern extends ResultPoint {
private final float estimatedModuleSize;
AlignmentPattern(float posX, float posY, float estimatedModuleSize) {
super(posX, posY);
this.estimatedModuleSize = estimatedModuleSize;
}
/**
* <p>Determines if this alignment pattern "about equals" an alignment pattern at the stated
* position and size -- meaning, it is at nearly the same center with nearly the same size.</p>
*/
boolean aboutEquals(float moduleSize, float i, float j) {<FILL_FUNCTION_BODY>}
/**
* Combines this object's current estimate of a finder pattern position and module size
* with a new estimate. It returns a new {@code FinderPattern} containing an average of the two.
*/
AlignmentPattern combineEstimate(float i, float j, float newModuleSize) {
float combinedX = (getX() + j) / 2.0f;
float combinedY = (getY() + i) / 2.0f;
float combinedModuleSize = (estimatedModuleSize + newModuleSize) / 2.0f;
return new AlignmentPattern(combinedX, combinedY, combinedModuleSize);
}
} |
if (Math.abs(i - getY()) <= moduleSize && Math.abs(j - getX()) <= moduleSize) {
float moduleSizeDiff = Math.abs(moduleSize - estimatedModuleSize);
return moduleSizeDiff <= 1.0f || moduleSizeDiff <= estimatedModuleSize;
}
return false;
| 52 | 312 | 80 | 392 |
36,456 | zxing_zxing | zxing/core/src/main/java/com/google/zxing/qrcode/detector/FinderPattern.java | FinderPattern | combineEstimate | class FinderPattern extends ResultPoint {
private final float estimatedModuleSize;
private final int count;
FinderPattern(float posX, float posY, float estimatedModuleSize) {
this(posX, posY, estimatedModuleSize, 1);
}
private FinderPattern(float posX, float posY, float estimatedModuleSize, int count) {
super(posX, posY);
this.estimatedModuleSize = estimatedModuleSize;
this.count = count;
}
public float getEstimatedModuleSize() {
return estimatedModuleSize;
}
public int getCount() {
return count;
}
/**
* <p>Determines if this finder pattern "about equals" a finder pattern at the stated
* position and size -- meaning, it is at nearly the same center with nearly the same size.</p>
*/
boolean aboutEquals(float moduleSize, float i, float j) {
if (Math.abs(i - getY()) <= moduleSize && Math.abs(j - getX()) <= moduleSize) {
float moduleSizeDiff = Math.abs(moduleSize - estimatedModuleSize);
return moduleSizeDiff <= 1.0f || moduleSizeDiff <= estimatedModuleSize;
}
return false;
}
/**
* Combines this object's current estimate of a finder pattern position and module size
* with a new estimate. It returns a new {@code FinderPattern} containing a weighted average
* based on count.
*/
FinderPattern combineEstimate(float i, float j, float newModuleSize) {<FILL_FUNCTION_BODY>}
} |
int combinedCount = count + 1;
float combinedX = (count * getX() + j) / combinedCount;
float combinedY = (count * getY() + i) / combinedCount;
float combinedModuleSize = (count * estimatedModuleSize + newModuleSize) / combinedCount;
return new FinderPattern(combinedX, combinedY, combinedModuleSize, combinedCount);
| 60 | 407 | 94 | 501 |
36,458 | zxing_zxing | zxing/core/src/main/java/com/google/zxing/qrcode/encoder/ByteMatrix.java | ByteMatrix | toString | class ByteMatrix {
private final byte[][] bytes;
private final int width;
private final int height;
public ByteMatrix(int width, int height) {
bytes = new byte[height][width];
this.width = width;
this.height = height;
}
public int getHeight() {
return height;
}
public int getWidth() {
return width;
}
public byte get(int x, int y) {
return bytes[y][x];
}
/**
* @return an internal representation as bytes, in row-major order. array[y][x] represents point (x,y)
*/
public byte[][] getArray() {
return bytes;
}
public void set(int x, int y, byte value) {
bytes[y][x] = value;
}
public void set(int x, int y, int value) {
bytes[y][x] = (byte) value;
}
public void set(int x, int y, boolean value) {
bytes[y][x] = (byte) (value ? 1 : 0);
}
public void clear(byte value) {
for (byte[] aByte : bytes) {
Arrays.fill(aByte, value);
}
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
} |
StringBuilder result = new StringBuilder(2 * width * height + 2);
for (int y = 0; y < height; ++y) {
byte[] bytesY = bytes[y];
for (int x = 0; x < width; ++x) {
switch (bytesY[x]) {
case 0:
result.append(" 0");
break;
case 1:
result.append(" 1");
break;
default:
result.append(" ");
break;
}
}
result.append('\n');
}
return result.toString();
| 201 | 363 | 155 | 518 |
36,462 | zxing_zxing | zxing/core/src/main/java/com/google/zxing/qrcode/encoder/MinimalEncoder.java | ResultNode | makePrintable | class ResultNode {
private final Mode mode;
private final int fromPosition;
private final int charsetEncoderIndex;
private final int characterLength;
ResultNode(Mode mode, int fromPosition, int charsetEncoderIndex, int characterLength) {
this.mode = mode;
this.fromPosition = fromPosition;
this.charsetEncoderIndex = charsetEncoderIndex;
this.characterLength = characterLength;
}
/**
* returns the size in bits
*/
private int getSize(Version version) {
int size = 4 + mode.getCharacterCountBits(version);
switch (mode) {
case KANJI:
size += 13 * characterLength;
break;
case ALPHANUMERIC:
size += (characterLength / 2) * 11;
size += (characterLength % 2) == 1 ? 6 : 0;
break;
case NUMERIC:
size += (characterLength / 3) * 10;
int rest = characterLength % 3;
size += rest == 1 ? 4 : rest == 2 ? 7 : 0;
break;
case BYTE:
size += 8 * getCharacterCountIndicator();
break;
case ECI:
size += 8; // the ECI assignment numbers for ISO-8859-x, UTF-8 and UTF-16 are all 8 bit long
}
return size;
}
/**
* returns the length in characters according to the specification (differs from getCharacterLength() in BYTE mode
* for multi byte encoded characters)
*/
private int getCharacterCountIndicator() {
return mode == Mode.BYTE ?
encoders.encode(stringToEncode.substring(fromPosition, fromPosition + characterLength),
charsetEncoderIndex).length : characterLength;
}
/**
* appends the bits
*/
private void getBits(BitArray bits) throws WriterException {
bits.appendBits(mode.getBits(), 4);
if (characterLength > 0) {
int length = getCharacterCountIndicator();
bits.appendBits(length, mode.getCharacterCountBits(version));
}
if (mode == Mode.ECI) {
bits.appendBits(encoders.getECIValue(charsetEncoderIndex), 8);
} else if (characterLength > 0) {
// append data
Encoder.appendBytes(stringToEncode.substring(fromPosition, fromPosition + characterLength), mode, bits,
encoders.getCharset(charsetEncoderIndex));
}
}
public String toString() {
StringBuilder result = new StringBuilder();
result.append(mode).append('(');
if (mode == Mode.ECI) {
result.append(encoders.getCharset(charsetEncoderIndex).displayName());
} else {
result.append(makePrintable(stringToEncode.substring(fromPosition, fromPosition + characterLength)));
}
result.append(')');
return result.toString();
}
private String makePrintable(String s) {<FILL_FUNCTION_BODY>}
} |
StringBuilder result = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) < 32 || s.charAt(i) > 126) {
result.append('.');
} else {
result.append(s.charAt(i));
}
}
return result.toString();
| 117 | 817 | 98 | 915 |
36,463 | zxing_zxing | zxing/core/src/main/java/com/google/zxing/qrcode/encoder/QRCode.java | QRCode | toString | class QRCode {
public static final int NUM_MASK_PATTERNS = 8;
private Mode mode;
private ErrorCorrectionLevel ecLevel;
private Version version;
private int maskPattern;
private ByteMatrix matrix;
public QRCode() {
maskPattern = -1;
}
/**
* @return the mode. Not relevant if {@link com.google.zxing.EncodeHintType#QR_COMPACT} is selected.
*/
public Mode getMode() {
return mode;
}
public ErrorCorrectionLevel getECLevel() {
return ecLevel;
}
public Version getVersion() {
return version;
}
public int getMaskPattern() {
return maskPattern;
}
public ByteMatrix getMatrix() {
return matrix;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
public void setMode(Mode value) {
mode = value;
}
public void setECLevel(ErrorCorrectionLevel value) {
ecLevel = value;
}
public void setVersion(Version version) {
this.version = version;
}
public void setMaskPattern(int value) {
maskPattern = value;
}
public void setMatrix(ByteMatrix value) {
matrix = value;
}
// Check if "mask_pattern" is valid.
public static boolean isValidMaskPattern(int maskPattern) {
return maskPattern >= 0 && maskPattern < NUM_MASK_PATTERNS;
}
} |
StringBuilder result = new StringBuilder(200);
result.append("<<\n");
result.append(" mode: ");
result.append(mode);
result.append("\n ecLevel: ");
result.append(ecLevel);
result.append("\n version: ");
result.append(version);
result.append("\n maskPattern: ");
result.append(maskPattern);
if (matrix == null) {
result.append("\n matrix: null\n");
} else {
result.append("\n matrix:\n");
result.append(matrix);
}
result.append(">>\n");
return result.toString();
| 103 | 415 | 168 | 583 |
36,464 | zxing_zxing | zxing/javase/src/main/java/com/google/zxing/client/j2se/BufferedImageLuminanceSource.java | BufferedImageLuminanceSource | crop | class BufferedImageLuminanceSource extends LuminanceSource {
private static final double MINUS_45_IN_RADIANS = -0.7853981633974483; // Math.toRadians(-45.0)
private final BufferedImage image;
private final int left;
private final int top;
public BufferedImageLuminanceSource(BufferedImage image) {
this(image, 0, 0, image.getWidth(), image.getHeight());
}
public BufferedImageLuminanceSource(BufferedImage image, int left, int top, int width, int height) {
super(width, height);
if (image.getType() == BufferedImage.TYPE_BYTE_GRAY) {
this.image = image;
} else {
int sourceWidth = image.getWidth();
int sourceHeight = image.getHeight();
if (left + width > sourceWidth || top + height > sourceHeight) {
throw new IllegalArgumentException("Crop rectangle does not fit within image data.");
}
this.image = new BufferedImage(sourceWidth, sourceHeight, BufferedImage.TYPE_BYTE_GRAY);
WritableRaster raster = this.image.getRaster();
int[] buffer = new int[width];
for (int y = top; y < top + height; y++) {
image.getRGB(left, y, width, 1, buffer, 0, sourceWidth);
for (int x = 0; x < width; x++) {
int pixel = buffer[x];
// The color of fully-transparent pixels is irrelevant. They are often, technically, fully-transparent
// black (0 alpha, and then 0 RGB). They are often used, of course as the "white" area in a
// barcode image. Force any such pixel to be white:
if ((pixel & 0xFF000000) == 0) {
// white, so we know its luminance is 255
buffer[x] = 0xFF;
} else {
// .299R + 0.587G + 0.114B (YUV/YIQ for PAL and NTSC),
// (306*R) >> 10 is approximately equal to R*0.299, and so on.
// 0x200 >> 10 is 0.5, it implements rounding.
buffer[x] =
(306 * ((pixel >> 16) & 0xFF) +
601 * ((pixel >> 8) & 0xFF) +
117 * (pixel & 0xFF) +
0x200) >> 10;
}
}
raster.setPixels(left, y, width, 1, buffer);
}
}
this.left = left;
this.top = top;
}
@Override
public byte[] getRow(int y, byte[] row) {
if (y < 0 || y >= getHeight()) {
throw new IllegalArgumentException("Requested row is outside the image: " + y);
}
int width = getWidth();
if (row == null || row.length < width) {
row = new byte[width];
}
// The underlying raster of image consists of bytes with the luminance values
image.getRaster().getDataElements(left, top + y, width, 1, row);
return row;
}
@Override
public byte[] getMatrix() {
int width = getWidth();
int height = getHeight();
int area = width * height;
byte[] matrix = new byte[area];
// The underlying raster of image consists of area bytes with the luminance values
image.getRaster().getDataElements(left, top, width, height, matrix);
return matrix;
}
@Override
public boolean isCropSupported() {
return true;
}
@Override
public LuminanceSource crop(int left, int top, int width, int height) {<FILL_FUNCTION_BODY>}
/**
* This is always true, since the image is a gray-scale image.
*
* @return true
*/
@Override
public boolean isRotateSupported() {
return true;
}
@Override
public LuminanceSource rotateCounterClockwise() {
int sourceWidth = image.getWidth();
int sourceHeight = image.getHeight();
// Rotate 90 degrees counterclockwise.
AffineTransform transform = new AffineTransform(0.0, -1.0, 1.0, 0.0, 0.0, sourceWidth);
// Note width/height are flipped since we are rotating 90 degrees.
BufferedImage rotatedImage = new BufferedImage(sourceHeight, sourceWidth, BufferedImage.TYPE_BYTE_GRAY);
// Draw the original image into rotated, via transformation
Graphics2D g = rotatedImage.createGraphics();
g.drawImage(image, transform, null);
g.dispose();
// Maintain the cropped region, but rotate it too.
int width = getWidth();
return new BufferedImageLuminanceSource(rotatedImage, top, sourceWidth - (left + width), getHeight(), width);
}
@Override
public LuminanceSource rotateCounterClockwise45() {
int width = getWidth();
int height = getHeight();
int oldCenterX = left + width / 2;
int oldCenterY = top + height / 2;
// Rotate 45 degrees counterclockwise.
AffineTransform transform = AffineTransform.getRotateInstance(MINUS_45_IN_RADIANS, oldCenterX, oldCenterY);
int sourceDimension = Math.max(image.getWidth(), image.getHeight());
BufferedImage rotatedImage = new BufferedImage(sourceDimension, sourceDimension, BufferedImage.TYPE_BYTE_GRAY);
// Draw the original image into rotated, via transformation
Graphics2D g = rotatedImage.createGraphics();
g.drawImage(image, transform, null);
g.dispose();
int halfDimension = Math.max(width, height) / 2;
int newLeft = Math.max(0, oldCenterX - halfDimension);
int newTop = Math.max(0, oldCenterY - halfDimension);
int newRight = Math.min(sourceDimension - 1, oldCenterX + halfDimension);
int newBottom = Math.min(sourceDimension - 1, oldCenterY + halfDimension);
return new BufferedImageLuminanceSource(rotatedImage, newLeft, newTop, newRight - newLeft, newBottom - newTop);
}
} |
return new BufferedImageLuminanceSource(image, this.left + left, this.top + top, width, height);
| 17 | 1,727 | 33 | 1,760 |
36,465 | zxing_zxing | zxing/javase/src/main/java/com/google/zxing/client/j2se/CommandLineEncoder.java | CommandLineEncoder | main | class CommandLineEncoder {
private CommandLineEncoder() {
}
public static void main(String[] args) throws Exception {<FILL_FUNCTION_BODY>}
} |
EncoderConfig config = new EncoderConfig();
JCommander jCommander = new JCommander(config);
jCommander.parse(args);
jCommander.setProgramName(CommandLineEncoder.class.getSimpleName());
if (config.help) {
jCommander.usage();
return;
}
String outFileString = config.outputFileBase;
if (EncoderConfig.DEFAULT_OUTPUT_FILE_BASE.equals(outFileString)) {
outFileString += '.' + config.imageFormat.toLowerCase(Locale.ENGLISH);
}
Map<EncodeHintType, Object> hints = new EnumMap<>(EncodeHintType.class);
if (config.errorCorrectionLevel != null) {
hints.put(EncodeHintType.ERROR_CORRECTION, config.errorCorrectionLevel);
}
BitMatrix matrix = new MultiFormatWriter().encode(
config.contents.get(0), config.barcodeFormat, config.width,
config.height, hints);
MatrixToImageWriter.writeToPath(matrix, config.imageFormat,
Paths.get(outFileString));
| 144 | 50 | 294 | 344 |
36,466 | zxing_zxing | zxing/javase/src/main/java/com/google/zxing/client/j2se/CommandLineRunner.java | CommandLineRunner | main | class CommandLineRunner {
private CommandLineRunner() {
}
public static void main(String[] args) throws Exception {<FILL_FUNCTION_BODY>}
private static List<URI> expand(Iterable<URI> inputs) throws IOException {
List<URI> expanded = new ArrayList<>();
for (URI input : inputs) {
if (isFileOrDir(input)) {
Path inputPath = Paths.get(input);
if (Files.isDirectory(inputPath)) {
try (DirectoryStream<Path> childPaths = Files.newDirectoryStream(inputPath)) {
for (Path childPath : childPaths) {
expanded.add(childPath.toUri());
}
}
} else {
expanded.add(input);
}
} else {
expanded.add(input);
}
}
for (int i = 0; i < expanded.size(); i++) {
URI input = expanded.get(i);
if (input.getScheme() == null) {
expanded.set(i, Paths.get(input.getRawPath()).toUri());
}
}
return expanded;
}
private static List<URI> retainValid(Iterable<URI> inputs, boolean recursive) {
List<URI> retained = new ArrayList<>();
for (URI input : inputs) {
boolean retain;
if (isFileOrDir(input)) {
Path inputPath = Paths.get(input);
retain =
!inputPath.getFileName().toString().startsWith(".") &&
(recursive || !Files.isDirectory(inputPath));
} else {
retain = true;
}
if (retain) {
retained.add(input);
}
}
return retained;
}
private static boolean isExpandable(Iterable<URI> inputs) {
for (URI input : inputs) {
if (isFileOrDir(input) && Files.isDirectory(Paths.get(input))) {
return true;
}
}
return false;
}
private static boolean isFileOrDir(URI uri) {
return "file".equals(uri.getScheme());
}
} |
DecoderConfig config = new DecoderConfig();
JCommander jCommander = new JCommander(config);
jCommander.parse(args);
jCommander.setProgramName(CommandLineRunner.class.getSimpleName());
if (config.help) {
jCommander.usage();
return;
}
List<URI> inputs = new ArrayList<>(config.inputPaths.size());
for (String inputPath : config.inputPaths) {
URI uri;
try {
uri = new URI(inputPath);
} catch (URISyntaxException use) {
// Assume it must be a file
if (!Files.exists(Paths.get(inputPath))) {
throw use;
}
uri = new URI("file", inputPath, null);
}
inputs.add(uri);
}
do {
inputs = retainValid(expand(inputs), config.recursive);
} while (config.recursive && isExpandable(inputs));
int numInputs = inputs.size();
if (numInputs == 0) {
jCommander.usage();
return;
}
Queue<URI> syncInputs = new ConcurrentLinkedQueue<>(inputs);
int numThreads = Math.min(numInputs, Runtime.getRuntime().availableProcessors());
int successful = 0;
if (numThreads > 1) {
ExecutorService executor = Executors.newFixedThreadPool(numThreads);
Collection<Future<Integer>> futures = new ArrayList<>(numThreads);
for (int x = 0; x < numThreads; x++) {
futures.add(executor.submit(new DecodeWorker(config, syncInputs)));
}
executor.shutdown();
for (Future<Integer> future : futures) {
successful += future.get();
}
} else {
successful += new DecodeWorker(config, syncInputs).call();
}
if (!config.brief && numInputs > 1) {
System.out.println("\nDecoded " + successful + " files out of " + numInputs +
" successfully (" + (successful * 100 / numInputs) + "%)\n");
}
| 416 | 560 | 572 | 1,132 |
36,468 | zxing_zxing | zxing/javase/src/main/java/com/google/zxing/client/j2se/DecoderConfig.java | DecoderConfig | buildHints | class DecoderConfig {
@Parameter(names = "--try_harder",
description = "Use the TRY_HARDER hint, default is normal mode")
boolean tryHarder;
@Parameter(names = "--pure_barcode",
description = "Input image is a pure monochrome barcode image, not a photo")
boolean pureBarcode;
@Parameter(names = "--products_only",
description = "Only decode the UPC and EAN families of barcodes")
boolean productsOnly;
@Parameter(names = "--dump_results",
description = "Write the decoded contents to input.txt")
boolean dumpResults;
@Parameter(names = "--dump_black_point",
description = "Compare black point algorithms with dump as input.mono.png")
boolean dumpBlackPoint;
@Parameter(names = "--multi",
description = "Scans image for multiple barcodes")
boolean multi;
@Parameter(names = "--brief",
description = "Only output one line per file, omitting the contents")
boolean brief;
@Parameter(names = "--raw",
description = "Output raw bitstream, before decoding symbols")
boolean outputRaw;
@Parameter(names = "--recursive",
description = "Descend into subdirectories")
boolean recursive;
@Parameter(names = "--crop",
description = " Only examine cropped region of input image(s)",
arity = 4,
validateWith = PositiveInteger.class)
List<Integer> crop;
@Parameter(names = "--possible_formats",
description = "Formats to decode, where format is any value in BarcodeFormat",
variableArity = true)
List<BarcodeFormat> possibleFormats;
@Parameter(names = "--help",
description = "Prints this help message",
help = true)
boolean help;
@Parameter(description = "(URIs to decode)", required = true, variableArity = true)
List<String> inputPaths;
Map<DecodeHintType,?> buildHints() {<FILL_FUNCTION_BODY>}
} |
List<BarcodeFormat> finalPossibleFormats = possibleFormats;
if (finalPossibleFormats == null || finalPossibleFormats.isEmpty()) {
finalPossibleFormats = new ArrayList<>(Arrays.asList(
BarcodeFormat.UPC_A,
BarcodeFormat.UPC_E,
BarcodeFormat.EAN_13,
BarcodeFormat.EAN_8,
BarcodeFormat.RSS_14,
BarcodeFormat.RSS_EXPANDED
));
if (!productsOnly) {
finalPossibleFormats.addAll(Arrays.asList(
BarcodeFormat.CODE_39,
BarcodeFormat.CODE_93,
BarcodeFormat.CODE_128,
BarcodeFormat.ITF,
BarcodeFormat.QR_CODE,
BarcodeFormat.DATA_MATRIX,
BarcodeFormat.AZTEC,
BarcodeFormat.PDF_417,
BarcodeFormat.CODABAR,
BarcodeFormat.MAXICODE
));
}
}
Map<DecodeHintType, Object> hints = new EnumMap<>(DecodeHintType.class);
hints.put(DecodeHintType.POSSIBLE_FORMATS, finalPossibleFormats);
if (tryHarder) {
hints.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
}
if (pureBarcode) {
hints.put(DecodeHintType.PURE_BARCODE, Boolean.TRUE);
}
return Collections.unmodifiableMap(hints);
| 302 | 556 | 435 | 991 |
36,469 | zxing_zxing | zxing/javase/src/main/java/com/google/zxing/client/j2se/GUIRunner.java | GUIRunner | getDecodeText | class GUIRunner extends JFrame {
private final JLabel imageLabel;
private final JTextComponent textArea;
private GUIRunner() {
imageLabel = new JLabel();
textArea = new JTextArea();
textArea.setEditable(false);
textArea.setMaximumSize(new Dimension(400, 200));
Container panel = new JPanel();
panel.setLayout(new FlowLayout());
panel.add(imageLabel);
panel.add(textArea);
setTitle("ZXing");
setSize(400, 400);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setContentPane(panel);
setLocationRelativeTo(null);
}
public static void main(String[] args) throws MalformedURLException {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
GUIRunner runner = new GUIRunner();
runner.setVisible(true);
runner.chooseImage();
}
});
}
private void chooseImage() {
JFileChooser fileChooser = new JFileChooser();
fileChooser.showOpenDialog(this);
Path file = fileChooser.getSelectedFile().toPath();
Icon imageIcon;
try {
imageIcon = new ImageIcon(file.toUri().toURL());
} catch (MalformedURLException muee) {
throw new IllegalArgumentException(muee);
}
setSize(imageIcon.getIconWidth(), imageIcon.getIconHeight() + 100);
imageLabel.setIcon(imageIcon);
String decodeText = getDecodeText(file);
textArea.setText(decodeText);
}
private static String getDecodeText(Path file) {<FILL_FUNCTION_BODY>}
} |
BufferedImage image;
try {
image = ImageReader.readImage(file.toUri());
} catch (IOException ioe) {
return ioe.toString();
}
LuminanceSource source = new BufferedImageLuminanceSource(image);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
Result result;
try {
result = new MultiFormatReader().decode(bitmap);
} catch (ReaderException re) {
return re.toString();
}
return String.valueOf(result.getText());
| 100 | 487 | 148 | 635 |
36,470 | zxing_zxing | zxing/javase/src/main/java/com/google/zxing/client/j2se/HtmlAssetTranslator.java | HtmlAssetTranslator | translateOneLanguage | class HtmlAssetTranslator {
private static final Pattern COMMA = Pattern.compile(",");
private HtmlAssetTranslator() {}
public static void main(String[] args) throws IOException {
if (args.length < 3) {
System.err.println("Usage: HtmlAssetTranslator android/assets/ " +
"(all|lang1[,lang2 ...]) (all|file1.html[ file2.html ...])");
return;
}
Path assetsDir = Paths.get(args[0]);
Collection<String> languagesToTranslate = parseLanguagesToTranslate(assetsDir, args[1]);
List<String> restOfArgs = Arrays.asList(args).subList(2, args.length);
Collection<String> fileNamesToTranslate = parseFileNamesToTranslate(assetsDir, restOfArgs);
for (String language : languagesToTranslate) {
translateOneLanguage(assetsDir, language, fileNamesToTranslate);
}
}
private static Collection<String> parseLanguagesToTranslate(Path assetsDir,
String languageArg) throws IOException {
if ("all".equals(languageArg)) {
Collection<String> languages = new ArrayList<>();
DirectoryStream.Filter<Path> fileFilter = entry -> {
String fileName = entry.getFileName().toString();
return Files.isDirectory(entry) && !Files.isSymbolicLink(entry) &&
fileName.startsWith("html-") && !"html-en".equals(fileName);
};
try (DirectoryStream<Path> dirs = Files.newDirectoryStream(assetsDir, fileFilter)) {
for (Path languageDir : dirs) {
languages.add(languageDir.getFileName().toString().substring(5));
}
}
return languages;
} else {
return Arrays.asList(COMMA.split(languageArg));
}
}
private static Collection<String> parseFileNamesToTranslate(Path assetsDir,
List<String> restOfArgs) throws IOException {
if ("all".equals(restOfArgs.get(0))) {
Collection<String> fileNamesToTranslate = new ArrayList<>();
Path htmlEnAssetDir = assetsDir.resolve("html-en");
try (DirectoryStream<Path> files = Files.newDirectoryStream(htmlEnAssetDir, "*.html")) {
for (Path file : files) {
fileNamesToTranslate.add(file.getFileName().toString());
}
}
return fileNamesToTranslate;
} else {
return restOfArgs;
}
}
private static void translateOneLanguage(Path assetsDir,
String language,
final Collection<String> filesToTranslate) throws IOException {<FILL_FUNCTION_BODY>}
private static void translateOneFile(String language,
Path targetHtmlDir,
Path sourceFile,
String translationTextTranslated) throws IOException {
Path destFile = targetHtmlDir.resolve(sourceFile.getFileName());
Document document;
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
DocumentBuilder builder = factory.newDocumentBuilder();
document = builder.parse(sourceFile.toFile());
} catch (ParserConfigurationException pce) {
throw new IllegalStateException(pce);
} catch (SAXException sae) {
throw new IOException(sae);
}
Element rootElement = document.getDocumentElement();
rootElement.normalize();
Queue<Node> nodes = new LinkedList<>();
nodes.add(rootElement);
while (!nodes.isEmpty()) {
Node node = nodes.poll();
if (shouldTranslate(node)) {
NodeList children = node.getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
nodes.add(children.item(i));
}
}
if (node.getNodeType() == Node.TEXT_NODE) {
String text = node.getTextContent();
if (!text.trim().isEmpty()) {
text = StringsResourceTranslator.translateString(text, language);
node.setTextContent(' ' + text + ' ');
}
}
}
Node translateText = document.createTextNode(translationTextTranslated);
Node paragraph = document.createElement("p");
paragraph.appendChild(translateText);
Node body = rootElement.getElementsByTagName("body").item(0);
body.appendChild(paragraph);
DOMImplementationRegistry registry;
try {
registry = DOMImplementationRegistry.newInstance();
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
throw new IllegalStateException(e);
}
DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS");
LSSerializer writer = impl.createLSSerializer();
String fileAsString = writer.writeToString(document);
// Replace default XML header with HTML DOCTYPE
fileAsString = fileAsString.replaceAll("<\\?xml[^>]+>", "<!DOCTYPE HTML>");
Files.write(destFile, Collections.singleton(fileAsString), StandardCharsets.UTF_8);
}
private static boolean shouldTranslate(Node node) {
// Ignore "notranslate" nodes
NamedNodeMap attributes = node.getAttributes();
if (attributes != null) {
Node classAttribute = attributes.getNamedItem("class");
if (classAttribute != null) {
String textContent = classAttribute.getTextContent();
if (textContent != null && textContent.contains("notranslate")) {
return false;
}
}
}
String nodeName = node.getNodeName();
if ("script".equalsIgnoreCase(nodeName)) {
return false;
}
// Ignore non-text snippets
String textContent = node.getTextContent();
if (textContent != null) {
for (int i = 0; i < textContent.length(); i++) {
if (Character.isLetter(textContent.charAt(i))) {
return true;
}
}
}
return false;
}
} |
Path targetHtmlDir = assetsDir.resolve("html-" + language);
Files.createDirectories(targetHtmlDir);
Path englishHtmlDir = assetsDir.resolve("html-en");
String translationTextTranslated =
StringsResourceTranslator.translateString("Translated by Google Translate.", language);
DirectoryStream.Filter<Path> filter = entry -> {
String name = entry.getFileName().toString();
return name.endsWith(".html") && (filesToTranslate.isEmpty() || filesToTranslate.contains(name));
};
try (DirectoryStream<Path> files = Files.newDirectoryStream(englishHtmlDir, filter)) {
for (Path sourceFile : files) {
translateOneFile(language, targetHtmlDir, sourceFile, translationTextTranslated);
}
}
| 116 | 1,588 | 201 | 1,789 |
36,471 | zxing_zxing | zxing/javase/src/main/java/com/google/zxing/client/j2se/ImageReader.java | ImageReader | readImage | class ImageReader {
private static final String BASE64TOKEN = "base64,";
private ImageReader() {
}
public static BufferedImage readImage(URI uri) throws IOException {<FILL_FUNCTION_BODY>}
public static BufferedImage readDataURIImage(URI uri) throws IOException {
String uriString = uri.getSchemeSpecificPart();
if (!uriString.startsWith("image/")) {
throw new IOException("Unsupported data URI MIME type");
}
int base64Start = uriString.indexOf(BASE64TOKEN);
if (base64Start < 0) {
throw new IOException("Unsupported data URI encoding");
}
String base64Data = uriString.substring(base64Start + BASE64TOKEN.length());
byte[] imageBytes = Base64.getDecoder().decode(base64Data);
return ImageIO.read(new ByteArrayInputStream(imageBytes));
}
} |
if ("data".equals(uri.getScheme())) {
return readDataURIImage(uri);
}
BufferedImage result;
try {
result = ImageIO.read(uri.toURL());
} catch (IllegalArgumentException iae) {
throw new IOException("Resource not found: " + uri, iae);
}
if (result == null) {
throw new IOException("Could not load " + uri);
}
return result;
| 94 | 256 | 120 | 376 |
36,472 | zxing_zxing | zxing/javase/src/main/java/com/google/zxing/client/j2se/MatrixToImageConfig.java | MatrixToImageConfig | getBufferedImageColorModel | class MatrixToImageConfig {
public static final int BLACK = 0xFF000000;
public static final int WHITE = 0xFFFFFFFF;
private final int onColor;
private final int offColor;
/**
* Creates a default config with on color {@link #BLACK} and off color {@link #WHITE}, generating normal
* black-on-white barcodes.
*/
public MatrixToImageConfig() {
this(BLACK, WHITE);
}
/**
* @param onColor pixel on color, specified as an ARGB value as an int
* @param offColor pixel off color, specified as an ARGB value as an int
*/
public MatrixToImageConfig(int onColor, int offColor) {
this.onColor = onColor;
this.offColor = offColor;
}
public int getPixelOnColor() {
return onColor;
}
public int getPixelOffColor() {
return offColor;
}
int getBufferedImageColorModel() {<FILL_FUNCTION_BODY>}
private static boolean hasTransparency(int argb) {
return (argb & 0xFF000000) != 0xFF000000;
}
} |
if (onColor == BLACK && offColor == WHITE) {
// Use faster BINARY if colors match default
return BufferedImage.TYPE_BYTE_BINARY;
}
if (hasTransparency(onColor) || hasTransparency(offColor)) {
// Use ARGB representation if colors specify non-opaque alpha
return BufferedImage.TYPE_INT_ARGB;
}
// Default otherwise to RGB representation with ignored alpha channel
return BufferedImage.TYPE_INT_RGB;
| 90 | 332 | 129 | 461 |
36,473 | zxing_zxing | zxing/javase/src/main/java/com/google/zxing/client/j2se/MatrixToImageWriter.java | MatrixToImageWriter | writeToStream | class MatrixToImageWriter {
private static final MatrixToImageConfig DEFAULT_CONFIG = new MatrixToImageConfig();
private MatrixToImageWriter() {}
/**
* Renders a {@link BitMatrix} as an image, where "false" bits are rendered
* as white, and "true" bits are rendered as black. Uses default configuration.
*
* @param matrix {@link BitMatrix} to write
* @return {@link BufferedImage} representation of the input
*/
public static BufferedImage toBufferedImage(BitMatrix matrix) {
return toBufferedImage(matrix, DEFAULT_CONFIG);
}
/**
* As {@link #toBufferedImage(BitMatrix)}, but allows customization of the output.
*
* @param matrix {@link BitMatrix} to write
* @param config output configuration
* @return {@link BufferedImage} representation of the input
*/
public static BufferedImage toBufferedImage(BitMatrix matrix, MatrixToImageConfig config) {
int width = matrix.getWidth();
int height = matrix.getHeight();
BufferedImage image = new BufferedImage(width, height, config.getBufferedImageColorModel());
int onColor = config.getPixelOnColor();
int offColor = config.getPixelOffColor();
int[] rowPixels = new int[width];
BitArray row = new BitArray(width);
for (int y = 0; y < height; y++) {
row = matrix.getRow(y, row);
for (int x = 0; x < width; x++) {
rowPixels[x] = row.get(x) ? onColor : offColor;
}
image.setRGB(0, y, width, 1, rowPixels, 0, width);
}
return image;
}
/**
* @param matrix {@link BitMatrix} to write
* @param format image format
* @param file file {@link File} to write image to
* @throws IOException if writes to the file fail
* @deprecated use {@link #writeToPath(BitMatrix, String, Path)}
*/
@Deprecated
public static void writeToFile(BitMatrix matrix, String format, File file) throws IOException {
writeToPath(matrix, format, file.toPath());
}
/**
* Writes a {@link BitMatrix} to a file with default configuration.
*
* @param matrix {@link BitMatrix} to write
* @param format image format
* @param file file {@link Path} to write image to
* @throws IOException if writes to the stream fail
* @see #toBufferedImage(BitMatrix)
*/
public static void writeToPath(BitMatrix matrix, String format, Path file) throws IOException {
writeToPath(matrix, format, file, DEFAULT_CONFIG);
}
/**
* @param matrix {@link BitMatrix} to write
* @param format image format
* @param file file {@link File} to write image to
* @param config output configuration
* @throws IOException if writes to the file fail
* @deprecated use {@link #writeToPath(BitMatrix, String, Path, MatrixToImageConfig)}
*/
@Deprecated
public static void writeToFile(BitMatrix matrix, String format, File file, MatrixToImageConfig config)
throws IOException {
writeToPath(matrix, format, file.toPath(), config);
}
/**
* As {@link #writeToPath(BitMatrix, String, Path)}, but allows customization of the output.
*
* @param matrix {@link BitMatrix} to write
* @param format image format
* @param file file {@link Path} to write image to
* @param config output configuration
* @throws IOException if writes to the file fail
*/
public static void writeToPath(BitMatrix matrix, String format, Path file, MatrixToImageConfig config)
throws IOException {
BufferedImage image = toBufferedImage(matrix, config);
if (!ImageIO.write(image, format, file.toFile())) {
throw new IOException("Could not write an image of format " + format + " to " + file);
}
}
/**
* Writes a {@link BitMatrix} to a stream with default configuration.
*
* @param matrix {@link BitMatrix} to write
* @param format image format
* @param stream {@link OutputStream} to write image to
* @throws IOException if writes to the stream fail
* @see #toBufferedImage(BitMatrix)
*/
public static void writeToStream(BitMatrix matrix, String format, OutputStream stream) throws IOException {
writeToStream(matrix, format, stream, DEFAULT_CONFIG);
}
/**
* As {@link #writeToStream(BitMatrix, String, OutputStream)}, but allows customization of the output.
*
* @param matrix {@link BitMatrix} to write
* @param format image format
* @param stream {@link OutputStream} to write image to
* @param config output configuration
* @throws IOException if writes to the stream fail
*/
public static void writeToStream(BitMatrix matrix, String format, OutputStream stream, MatrixToImageConfig config)
throws IOException {<FILL_FUNCTION_BODY>}
} |
BufferedImage image = toBufferedImage(matrix, config);
if (!ImageIO.write(image, format, stream)) {
throw new IOException("Could not write an image of format " + format);
}
| 42 | 1,307 | 56 | 1,363 |
36,475 | zxing_zxing | zxing/zxingorg/src/main/java/com/google/zxing/web/ChartServlet.java | ChartServlet | doParseParameters | class ChartServlet extends HttpServlet {
private static final int MAX_DIMENSION = 4096;
private static final Collection<Charset> SUPPORTED_OUTPUT_ENCODINGS = ImmutableSet.<Charset>builder()
.add(StandardCharsets.UTF_8).add(StandardCharsets.ISO_8859_1).add(Charset.forName("Shift_JIS")).build();
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
doEncode(request, response, false);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
doEncode(request, response, true);
}
private static void doEncode(HttpServletRequest request, HttpServletResponse response, boolean isPost)
throws IOException {
ChartServletRequestParameters parameters;
try {
parameters = doParseParameters(request, isPost);
} catch (IllegalArgumentException | NullPointerException e) {
response.sendError(HttpServletResponse.SC_BAD_REQUEST, e.toString());
return;
}
Map<EncodeHintType,Object> hints = new EnumMap<>(EncodeHintType.class);
hints.put(EncodeHintType.MARGIN, parameters.getMargin());
if (!StandardCharsets.ISO_8859_1.equals(parameters.getOutputEncoding())) {
// Only set if not QR code default
hints.put(EncodeHintType.CHARACTER_SET, parameters.getOutputEncoding().name());
}
hints.put(EncodeHintType.ERROR_CORRECTION, parameters.getEcLevel());
BitMatrix matrix;
try {
matrix = new QRCodeWriter().encode(parameters.getText(),
BarcodeFormat.QR_CODE,
parameters.getWidth(),
parameters.getHeight(),
hints);
} catch (WriterException we) {
response.sendError(HttpServletResponse.SC_BAD_REQUEST, we.toString());
return;
}
String requestURI = request.getRequestURI();
if (requestURI == null) {
response.sendError(HttpServletResponse.SC_BAD_REQUEST);
return;
}
int lastDot = requestURI.lastIndexOf('.');
String imageFormat;
if (lastDot > 0) {
imageFormat = requestURI.substring(lastDot + 1).toUpperCase(Locale.ROOT);
// Special-case jpg -> JPEG
if ("JPG".equals(imageFormat)) {
imageFormat = "JPEG";
}
} else {
imageFormat = "PNG";
}
String contentType;
switch (imageFormat) {
case "PNG":
contentType = "image/png";
break;
case "JPEG":
contentType = "image/jpeg";
break;
case "GIF":
contentType = "image/gif";
break;
default:
throw new IllegalArgumentException("Unknown format " + imageFormat);
}
ByteArrayOutputStream imageOut = new ByteArrayOutputStream(1024);
MatrixToImageWriter.writeToStream(matrix, imageFormat, imageOut);
byte[] imageData = imageOut.toByteArray();
response.setContentType(contentType);
response.setContentLength(imageData.length);
response.setHeader("Cache-Control", "public");
response.getOutputStream().write(imageData);
}
private static ChartServletRequestParameters doParseParameters(ServletRequest request, boolean readBody)
throws IOException {<FILL_FUNCTION_BODY>}
} |
String chartType = request.getParameter("cht");
Preconditions.checkArgument(chartType == null || "qr".equals(chartType), "Bad type");
String widthXHeight = request.getParameter("chs");
Preconditions.checkNotNull(widthXHeight, "No size");
int xIndex = widthXHeight.indexOf('x');
Preconditions.checkArgument(xIndex >= 0, "Bad size");
int width = Integer.parseInt(widthXHeight.substring(0, xIndex));
int height = Integer.parseInt(widthXHeight.substring(xIndex + 1));
Preconditions.checkArgument(width > 0 && height > 0, "Bad size");
Preconditions.checkArgument(width <= MAX_DIMENSION && height <= MAX_DIMENSION, "Bad size");
String outputEncodingName = request.getParameter("choe");
Charset outputEncoding;
if (outputEncodingName == null) {
outputEncoding = StandardCharsets.UTF_8;
} else {
outputEncoding = Charset.forName(outputEncodingName);
Preconditions.checkArgument(SUPPORTED_OUTPUT_ENCODINGS.contains(outputEncoding), "Bad output encoding");
}
ErrorCorrectionLevel ecLevel = ErrorCorrectionLevel.L;
int margin = 4;
String ldString = request.getParameter("chld");
if (ldString != null) {
int pipeIndex = ldString.indexOf('|');
if (pipeIndex < 0) {
// Only an EC level
ecLevel = ErrorCorrectionLevel.valueOf(ldString);
} else {
ecLevel = ErrorCorrectionLevel.valueOf(ldString.substring(0, pipeIndex));
margin = Integer.parseInt(ldString.substring(pipeIndex + 1));
Preconditions.checkArgument(margin > 0, "Bad margin");
}
}
String text;
if (readBody) {
text = CharStreams.toString(request.getReader());
} else {
text = request.getParameter("chl");
}
Preconditions.checkArgument(text != null && !text.isEmpty(), "No input");
return new ChartServletRequestParameters(width, height, outputEncoding, ecLevel, margin, text);
| 325 | 932 | 565 | 1,497 |
36,477 | zxing_zxing | zxing/zxingorg/src/main/java/com/google/zxing/web/DoSFilter.java | DoSFilter | init | class DoSFilter implements Filter {
private Timer timer;
private DoSTracker sourceAddrTracker;
@Override
public void init(FilterConfig filterConfig) {<FILL_FUNCTION_BODY>}
@Override
public void doFilter(ServletRequest request,
ServletResponse response,
FilterChain chain) throws IOException, ServletException {
if (isBanned((HttpServletRequest) request)) {
HttpServletResponse servletResponse = (HttpServletResponse) response;
// Send very short response as requests may be very frequent
servletResponse.setStatus(429); // 429 = Too Many Requests from RFC 6585
servletResponse.getWriter().write("Forbidden");
} else {
chain.doFilter(request, response);
}
}
private boolean isBanned(HttpServletRequest request) {
String remoteHost = request.getHeader("x-forwarded-for");
if (remoteHost != null) {
int comma = remoteHost.indexOf(',');
if (comma >= 0) {
remoteHost = remoteHost.substring(0, comma);
}
remoteHost = remoteHost.trim();
}
// Non-short-circuit "|" below is on purpose
return
(remoteHost != null && sourceAddrTracker.isBanned(remoteHost)) |
sourceAddrTracker.isBanned(request.getRemoteAddr());
}
@Override
public void destroy() {
if (timer != null) {
timer.cancel();
}
}
} |
int maxAccessPerTime = Integer.parseInt(filterConfig.getInitParameter("maxAccessPerTime"));
Preconditions.checkArgument(maxAccessPerTime > 0);
int accessTimeSec = Integer.parseInt(filterConfig.getInitParameter("accessTimeSec"));
Preconditions.checkArgument(accessTimeSec > 0);
long accessTimeMS = TimeUnit.MILLISECONDS.convert(accessTimeSec, TimeUnit.SECONDS);
String maxEntriesValue = filterConfig.getInitParameter("maxEntries");
int maxEntries = Integer.MAX_VALUE;
if (maxEntriesValue != null) {
maxEntries = Integer.parseInt(maxEntriesValue);
Preconditions.checkArgument(maxEntries > 0);
}
String maxLoadValue = filterConfig.getInitParameter("maxLoad");
Double maxLoad = null;
if (maxLoadValue != null) {
maxLoad = Double.valueOf(maxLoadValue);
Preconditions.checkArgument(maxLoad > 0.0);
}
String name = getClass().getSimpleName();
timer = new Timer(name);
sourceAddrTracker = new DoSTracker(timer, name, maxAccessPerTime, accessTimeMS, maxEntries, maxLoad);
| 147 | 400 | 315 | 715 |
36,478 | zxing_zxing | zxing/zxingorg/src/main/java/com/google/zxing/web/DoSTracker.java | TrackerTask | run | class TrackerTask extends TimerTask {
private final String name;
private final Double maxLoad;
private TrackerTask(String name, Double maxLoad) {
this.name = name;
this.maxLoad = maxLoad;
}
@Override
public void run() {<FILL_FUNCTION_BODY>}
} |
// largest count <= maxAccessesPerTime
int maxAllowedCount = 1;
// smallest count > maxAccessesPerTime
int minDisallowedCount = Integer.MAX_VALUE;
int localMAPT = maxAccessesPerTime;
int totalEntries;
int clearedEntries = 0;
synchronized (numRecentAccesses) {
totalEntries = numRecentAccesses.size();
Iterator<Map.Entry<String,AtomicInteger>> accessIt = numRecentAccesses.entrySet().iterator();
while (accessIt.hasNext()) {
Map.Entry<String,AtomicInteger> entry = accessIt.next();
AtomicInteger atomicCount = entry.getValue();
int count = atomicCount.get();
// If number of accesses is below the threshold, remove it entirely
if (count <= localMAPT) {
accessIt.remove();
maxAllowedCount = Math.max(maxAllowedCount, count);
clearedEntries++;
} else {
// Reduce count of accesses held against the host
atomicCount.getAndAdd(-localMAPT);
minDisallowedCount = Math.min(minDisallowedCount, count);
}
}
}
log.info(name + ": " + clearedEntries + " of " + totalEntries + " cleared");
if (maxLoad != null) {
OperatingSystemMXBean mxBean = ManagementFactory.getOperatingSystemMXBean();
if (mxBean == null) {
log.warning("Could not obtain OperatingSystemMXBean; ignoring load");
} else {
double loadAvg = mxBean.getSystemLoadAverage();
if (loadAvg >= 0.0) {
int cores = mxBean.getAvailableProcessors();
double loadRatio = loadAvg / cores;
int newMaxAccessesPerTime = loadRatio > maxLoad ?
Math.min(maxAllowedCount, Math.max(1, maxAccessesPerTime - 1)) :
Math.max(minDisallowedCount, maxAccessesPerTime);
log.info(name + ": Load ratio: " + loadRatio +
" (" + loadAvg + '/' + cores + ") vs " + maxLoad +
" ; new maxAccessesPerTime: " + newMaxAccessesPerTime);
maxAccessesPerTime = newMaxAccessesPerTime;
}
}
}
| 606 | 91 | 598 | 689 |
36,479 | zxing_zxing | zxing/zxingorg/src/main/java/com/google/zxing/web/HTTPSFilter.java | HTTPSFilter | doFilter | class HTTPSFilter extends AbstractFilter {
private static final Pattern HTTP_REGEX = Pattern.compile("http://");
@Override
public void doFilter(ServletRequest servletRequest,
ServletResponse servletResponse,
FilterChain chain) throws IOException, ServletException {<FILL_FUNCTION_BODY>}
} |
if (servletRequest.isSecure()) {
chain.doFilter(servletRequest, servletResponse);
} else {
HttpServletRequest request = (HttpServletRequest) servletRequest;
String url = request.getRequestURL().toString();
String target = HTTP_REGEX.matcher(url).replaceFirst("https://");
redirect(servletResponse, target);
}
| 61 | 86 | 99 | 185 |
36,480 | zxing_zxing | zxing/zxingorg/src/main/java/com/google/zxing/web/OutputUtils.java | OutputUtils | arrayToString | class OutputUtils {
private static final int BYTES_PER_LINE = 16;
private static final int HALF_BYTES_PER_LINE = BYTES_PER_LINE / 2;
private OutputUtils() {
}
public static String arrayToString(byte[] bytes) {<FILL_FUNCTION_BODY>}
private static char hexChar(int value) {
return (char) (value < 10 ? ('0' + value) : ('a' + (value - 10)));
}
} |
StringBuilder result = new StringBuilder(bytes.length * 4);
int i = 0;
while (i < bytes.length) {
int value = bytes[i] & 0xFF;
result.append(hexChar(value / 16));
result.append(hexChar(value % 16));
i++;
if (i % BYTES_PER_LINE == 0) {
result.append('\n');
} else if (i % HALF_BYTES_PER_LINE == 0) {
result.append(" ");
} else {
result.append(' ');
}
}
return result.toString();
| 138 | 137 | 170 | 307 |
36,481 | zxing_zxing | zxing/zxingorg/src/main/java/com/google/zxing/web/ServletContextLogHandler.java | ServletContextLogHandler | publish | class ServletContextLogHandler extends Handler {
private final ServletContext context;
ServletContextLogHandler(ServletContext context) {
this.context = context;
}
@Override
public void publish(LogRecord record) {<FILL_FUNCTION_BODY>}
@Override
public void flush() {
// do nothing
}
@Override
public void close() {
// do nothing
}
} |
Formatter formatter = getFormatter();
String message;
if (formatter == null) {
message = record.getMessage();
} else {
message = formatter.format(record);
}
Throwable throwable = record.getThrown();
if (throwable == null) {
context.log(message);
} else {
context.log(message, throwable);
}
| 87 | 117 | 107 | 224 |
36,482 | zxing_zxing | zxing/zxingorg/src/main/java/com/google/zxing/web/TimeoutFilter.java | TimeoutFilter | doFilter | class TimeoutFilter implements Filter {
private ExecutorService executorService;
private TimeLimiter timeLimiter;
private int timeoutSec;
@Override
public void init(FilterConfig filterConfig) {
executorService = Executors.newCachedThreadPool();
timeLimiter = SimpleTimeLimiter.create(executorService);
timeoutSec = Integer.parseInt(filterConfig.getInitParameter("timeoutSec"));
}
@Override
public void doFilter(ServletRequest request,
ServletResponse response,
FilterChain chain) throws IOException, ServletException {<FILL_FUNCTION_BODY>}
@Override
public void destroy() {
if (executorService != null) {
executorService.shutdownNow();
}
}
} |
try {
timeLimiter.callWithTimeout(new Callable<Void>() {
@Override
public Void call() throws Exception {
chain.doFilter(request, response);
return null;
}
}, timeoutSec, TimeUnit.SECONDS);
} catch (TimeoutException | InterruptedException e) {
HttpServletResponse servletResponse = (HttpServletResponse) response;
servletResponse.setStatus(HttpServletResponse.SC_REQUEST_TIMEOUT);
servletResponse.getWriter().write("Request took too long");
} catch (ExecutionException e) {
if (e.getCause() instanceof ServletException) {
throw (ServletException) e.getCause();
}
if (e.getCause() instanceof IOException) {
throw (IOException) e.getCause();
}
throw new ServletException(e.getCause());
}
| 182 | 203 | 227 | 430 |