proj_name
stringclasses 131
values | relative_path
stringlengths 30
228
| class_name
stringlengths 1
68
| func_name
stringlengths 1
48
| masked_class
stringlengths 78
9.82k
| func_body
stringlengths 46
9.61k
| len_input
int64 29
2.01k
| len_output
int64 14
1.94k
| total
int64 55
2.05k
| relevant_context
stringlengths 0
38.4k
|
---|---|---|---|---|---|---|---|---|---|
zxing_zxing
|
zxing/core/src/main/java/com/google/zxing/datamatrix/encoder/DefaultPlacement.java
|
DefaultPlacement
|
module
|
class DefaultPlacement {
private final CharSequence codewords;
private final int numrows;
private final int numcols;
private final byte[] bits;
/**
* Main constructor
*
* @param codewords the codewords to place
* @param numcols the number of columns
* @param numrows the number of rows
*/
public DefaultPlacement(CharSequence codewords, int numcols, int numrows) {
this.codewords = codewords;
this.numcols = numcols;
this.numrows = numrows;
this.bits = new byte[numcols * numrows];
Arrays.fill(this.bits, (byte) -1); //Initialize with "not set" value
}
final int getNumrows() {
return numrows;
}
final int getNumcols() {
return numcols;
}
final byte[] getBits() {
return bits;
}
public final boolean getBit(int col, int row) {
return bits[row * numcols + col] == 1;
}
private void setBit(int col, int row, boolean bit) {
bits[row * numcols + col] = (byte) (bit ? 1 : 0);
}
private boolean noBit(int col, int row) {
return bits[row * numcols + col] < 0;
}
public final void place() {
int pos = 0;
int row = 4;
int col = 0;
do {
// repeatedly first check for one of the special corner cases, then...
if ((row == numrows) && (col == 0)) {
corner1(pos++);
}
if ((row == numrows - 2) && (col == 0) && ((numcols % 4) != 0)) {
corner2(pos++);
}
if ((row == numrows - 2) && (col == 0) && (numcols % 8 == 4)) {
corner3(pos++);
}
if ((row == numrows + 4) && (col == 2) && ((numcols % 8) == 0)) {
corner4(pos++);
}
// sweep upward diagonally, inserting successive characters...
do {
if ((row < numrows) && (col >= 0) && noBit(col, row)) {
utah(row, col, pos++);
}
row -= 2;
col += 2;
} while (row >= 0 && (col < numcols));
row++;
col += 3;
// and then sweep downward diagonally, inserting successive characters, ...
do {
if ((row >= 0) && (col < numcols) && noBit(col, row)) {
utah(row, col, pos++);
}
row += 2;
col -= 2;
} while ((row < numrows) && (col >= 0));
row += 3;
col++;
// ...until the entire array is scanned
} while ((row < numrows) || (col < numcols));
// Lastly, if the lower right-hand corner is untouched, fill in fixed pattern
if (noBit(numcols - 1, numrows - 1)) {
setBit(numcols - 1, numrows - 1, true);
setBit(numcols - 2, numrows - 2, true);
}
}
private void module(int row, int col, int pos, int bit) {<FILL_FUNCTION_BODY>}
/**
* Places the 8 bits of a utah-shaped symbol character in ECC200.
*
* @param row the row
* @param col the column
* @param pos character position
*/
private void utah(int row, int col, int pos) {
module(row - 2, col - 2, pos, 1);
module(row - 2, col - 1, pos, 2);
module(row - 1, col - 2, pos, 3);
module(row - 1, col - 1, pos, 4);
module(row - 1, col, pos, 5);
module(row, col - 2, pos, 6);
module(row, col - 1, pos, 7);
module(row, col, pos, 8);
}
private void corner1(int pos) {
module(numrows - 1, 0, pos, 1);
module(numrows - 1, 1, pos, 2);
module(numrows - 1, 2, pos, 3);
module(0, numcols - 2, pos, 4);
module(0, numcols - 1, pos, 5);
module(1, numcols - 1, pos, 6);
module(2, numcols - 1, pos, 7);
module(3, numcols - 1, pos, 8);
}
private void corner2(int pos) {
module(numrows - 3, 0, pos, 1);
module(numrows - 2, 0, pos, 2);
module(numrows - 1, 0, pos, 3);
module(0, numcols - 4, pos, 4);
module(0, numcols - 3, pos, 5);
module(0, numcols - 2, pos, 6);
module(0, numcols - 1, pos, 7);
module(1, numcols - 1, pos, 8);
}
private void corner3(int pos) {
module(numrows - 3, 0, pos, 1);
module(numrows - 2, 0, pos, 2);
module(numrows - 1, 0, pos, 3);
module(0, numcols - 2, pos, 4);
module(0, numcols - 1, pos, 5);
module(1, numcols - 1, pos, 6);
module(2, numcols - 1, pos, 7);
module(3, numcols - 1, pos, 8);
}
private void corner4(int pos) {
module(numrows - 1, 0, pos, 1);
module(numrows - 1, numcols - 1, pos, 2);
module(0, numcols - 3, pos, 3);
module(0, numcols - 2, pos, 4);
module(0, numcols - 1, pos, 5);
module(1, numcols - 3, pos, 6);
module(1, numcols - 2, pos, 7);
module(1, numcols - 1, pos, 8);
}
}
|
if (row < 0) {
row += numrows;
col += 4 - ((numrows + 4) % 8);
}
if (col < 0) {
col += numcols;
row += 4 - ((numcols + 4) % 8);
}
// Note the conversion:
int v = codewords.charAt(pos);
v &= 1 << (8 - bit);
setBit(col, row, v != 0);
| 1,781 | 121 | 1,902 |
<no_super_class>
|
zxing_zxing
|
zxing/core/src/main/java/com/google/zxing/datamatrix/encoder/EdifactEncoder.java
|
EdifactEncoder
|
handleEOD
|
class EdifactEncoder implements Encoder {
@Override
public int getEncodingMode() {
return HighLevelEncoder.EDIFACT_ENCODATION;
}
@Override
public void encode(EncoderContext context) {
//step F
StringBuilder buffer = new StringBuilder();
while (context.hasMoreCharacters()) {
char c = context.getCurrentChar();
encodeChar(c, buffer);
context.pos++;
int count = buffer.length();
if (count >= 4) {
context.writeCodewords(encodeToCodewords(buffer));
buffer.delete(0, 4);
int newMode = HighLevelEncoder.lookAheadTest(context.getMessage(), context.pos, getEncodingMode());
if (newMode != getEncodingMode()) {
// Return to ASCII encodation, which will actually handle latch to new mode
context.signalEncoderChange(HighLevelEncoder.ASCII_ENCODATION);
break;
}
}
}
buffer.append((char) 31); //Unlatch
handleEOD(context, buffer);
}
/**
* Handle "end of data" situations
*
* @param context the encoder context
* @param buffer the buffer with the remaining encoded characters
*/
private static void handleEOD(EncoderContext context, CharSequence buffer) {<FILL_FUNCTION_BODY>}
private static void encodeChar(char c, StringBuilder sb) {
if (c >= ' ' && c <= '?') {
sb.append(c);
} else if (c >= '@' && c <= '^') {
sb.append((char) (c - 64));
} else {
HighLevelEncoder.illegalCharacter(c);
}
}
private static String encodeToCodewords(CharSequence sb) {
int len = sb.length();
if (len == 0) {
throw new IllegalStateException("StringBuilder must not be empty");
}
char c1 = sb.charAt(0);
char c2 = len >= 2 ? sb.charAt(1) : 0;
char c3 = len >= 3 ? sb.charAt(2) : 0;
char c4 = len >= 4 ? sb.charAt(3) : 0;
int v = (c1 << 18) + (c2 << 12) + (c3 << 6) + c4;
char cw1 = (char) ((v >> 16) & 255);
char cw2 = (char) ((v >> 8) & 255);
char cw3 = (char) (v & 255);
StringBuilder res = new StringBuilder(3);
res.append(cw1);
if (len >= 2) {
res.append(cw2);
}
if (len >= 3) {
res.append(cw3);
}
return res.toString();
}
}
|
try {
int count = buffer.length();
if (count == 0) {
return; //Already finished
}
if (count == 1) {
//Only an unlatch at the end
context.updateSymbolInfo();
int available = context.getSymbolInfo().getDataCapacity() - context.getCodewordCount();
int remaining = context.getRemainingCharacters();
// The following two lines are a hack inspired by the 'fix' from https://sourceforge.net/p/barcode4j/svn/221/
if (remaining > available) {
context.updateSymbolInfo(context.getCodewordCount() + 1);
available = context.getSymbolInfo().getDataCapacity() - context.getCodewordCount();
}
if (remaining <= available && available <= 2) {
return; //No unlatch
}
}
if (count > 4) {
throw new IllegalStateException("Count must not exceed 4");
}
int restChars = count - 1;
String encoded = encodeToCodewords(buffer);
boolean endOfSymbolReached = !context.hasMoreCharacters();
boolean restInAscii = endOfSymbolReached && restChars <= 2;
if (restChars <= 2) {
context.updateSymbolInfo(context.getCodewordCount() + restChars);
int available = context.getSymbolInfo().getDataCapacity() - context.getCodewordCount();
if (available >= 3) {
restInAscii = false;
context.updateSymbolInfo(context.getCodewordCount() + encoded.length());
//available = context.symbolInfo.dataCapacity - context.getCodewordCount();
}
}
if (restInAscii) {
context.resetSymbolInfo();
context.pos -= restChars;
} else {
context.writeCodewords(encoded);
}
} finally {
context.signalEncoderChange(HighLevelEncoder.ASCII_ENCODATION);
}
| 761 | 516 | 1,277 |
<no_super_class>
|
zxing_zxing
|
zxing/core/src/main/java/com/google/zxing/datamatrix/encoder/EncoderContext.java
|
EncoderContext
|
updateSymbolInfo
|
class EncoderContext {
private final String msg;
private SymbolShapeHint shape;
private Dimension minSize;
private Dimension maxSize;
private final StringBuilder codewords;
int pos;
private int newEncoding;
private SymbolInfo symbolInfo;
private int skipAtEnd;
EncoderContext(String msg) {
//From this point on Strings are not Unicode anymore!
byte[] msgBinary = msg.getBytes(StandardCharsets.ISO_8859_1);
StringBuilder sb = new StringBuilder(msgBinary.length);
for (int i = 0, c = msgBinary.length; i < c; i++) {
char ch = (char) (msgBinary[i] & 0xff);
if (ch == '?' && msg.charAt(i) != '?') {
throw new IllegalArgumentException("Message contains characters outside ISO-8859-1 encoding.");
}
sb.append(ch);
}
this.msg = sb.toString(); //Not Unicode here!
shape = SymbolShapeHint.FORCE_NONE;
this.codewords = new StringBuilder(msg.length());
newEncoding = -1;
}
public void setSymbolShape(SymbolShapeHint shape) {
this.shape = shape;
}
public void setSizeConstraints(Dimension minSize, Dimension maxSize) {
this.minSize = minSize;
this.maxSize = maxSize;
}
public String getMessage() {
return this.msg;
}
public void setSkipAtEnd(int count) {
this.skipAtEnd = count;
}
public char getCurrentChar() {
return msg.charAt(pos);
}
public char getCurrent() {
return msg.charAt(pos);
}
public StringBuilder getCodewords() {
return codewords;
}
public void writeCodewords(String codewords) {
this.codewords.append(codewords);
}
public void writeCodeword(char codeword) {
this.codewords.append(codeword);
}
public int getCodewordCount() {
return this.codewords.length();
}
public int getNewEncoding() {
return newEncoding;
}
public void signalEncoderChange(int encoding) {
this.newEncoding = encoding;
}
public void resetEncoderSignal() {
this.newEncoding = -1;
}
public boolean hasMoreCharacters() {
return pos < getTotalMessageCharCount();
}
private int getTotalMessageCharCount() {
return msg.length() - skipAtEnd;
}
public int getRemainingCharacters() {
return getTotalMessageCharCount() - pos;
}
public SymbolInfo getSymbolInfo() {
return symbolInfo;
}
public void updateSymbolInfo() {
updateSymbolInfo(getCodewordCount());
}
public void updateSymbolInfo(int len) {<FILL_FUNCTION_BODY>}
public void resetSymbolInfo() {
this.symbolInfo = null;
}
}
|
if (this.symbolInfo == null || len > this.symbolInfo.getDataCapacity()) {
this.symbolInfo = SymbolInfo.lookup(len, shape, minSize, maxSize, true);
}
| 806 | 55 | 861 |
<no_super_class>
|
zxing_zxing
|
zxing/core/src/main/java/com/google/zxing/datamatrix/encoder/TextEncoder.java
|
TextEncoder
|
encodeChar
|
class TextEncoder extends C40Encoder {
@Override
public int getEncodingMode() {
return HighLevelEncoder.TEXT_ENCODATION;
}
@Override
int encodeChar(char c, StringBuilder sb) {<FILL_FUNCTION_BODY>}
}
|
if (c == ' ') {
sb.append('\3');
return 1;
}
if (c >= '0' && c <= '9') {
sb.append((char) (c - 48 + 4));
return 1;
}
if (c >= 'a' && c <= 'z') {
sb.append((char) (c - 97 + 14));
return 1;
}
if (c < ' ') {
sb.append('\0'); //Shift 1 Set
sb.append(c);
return 2;
}
if (c <= '/') {
sb.append('\1'); //Shift 2 Set
sb.append((char) (c - 33));
return 2;
}
if (c <= '@') {
sb.append('\1'); //Shift 2 Set
sb.append((char) (c - 58 + 15));
return 2;
}
if (c >= '[' && c <= '_') {
sb.append('\1'); //Shift 2 Set
sb.append((char) (c - 91 + 22));
return 2;
}
if (c == '`') {
sb.append('\2'); //Shift 3 Set
sb.append((char) 0); // '`' - 96 == 0
return 2;
}
if (c <= 'Z') {
sb.append('\2'); //Shift 3 Set
sb.append((char) (c - 65 + 1));
return 2;
}
if (c <= 127) {
sb.append('\2'); //Shift 3 Set
sb.append((char) (c - 123 + 27));
return 2;
}
sb.append("\1\u001e"); //Shift 2, Upper Shift
int len = 2;
len += encodeChar((char) (c - 128), sb);
return len;
| 78 | 520 | 598 |
<methods>public void encode(com.google.zxing.datamatrix.encoder.EncoderContext) ,public int getEncodingMode() <variables>
|
zxing_zxing
|
zxing/core/src/main/java/com/google/zxing/datamatrix/encoder/X12Encoder.java
|
X12Encoder
|
encodeChar
|
class X12Encoder extends C40Encoder {
@Override
public int getEncodingMode() {
return HighLevelEncoder.X12_ENCODATION;
}
@Override
public void encode(EncoderContext context) {
//step C
StringBuilder buffer = new StringBuilder();
while (context.hasMoreCharacters()) {
char c = context.getCurrentChar();
context.pos++;
encodeChar(c, buffer);
int count = buffer.length();
if ((count % 3) == 0) {
writeNextTriplet(context, buffer);
int newMode = HighLevelEncoder.lookAheadTest(context.getMessage(), context.pos, getEncodingMode());
if (newMode != getEncodingMode()) {
// Return to ASCII encodation, which will actually handle latch to new mode
context.signalEncoderChange(HighLevelEncoder.ASCII_ENCODATION);
break;
}
}
}
handleEOD(context, buffer);
}
@Override
int encodeChar(char c, StringBuilder sb) {<FILL_FUNCTION_BODY>}
@Override
void handleEOD(EncoderContext context, StringBuilder buffer) {
context.updateSymbolInfo();
int available = context.getSymbolInfo().getDataCapacity() - context.getCodewordCount();
int count = buffer.length();
context.pos -= count;
if (context.getRemainingCharacters() > 1 || available > 1 ||
context.getRemainingCharacters() != available) {
context.writeCodeword(HighLevelEncoder.X12_UNLATCH);
}
if (context.getNewEncoding() < 0) {
context.signalEncoderChange(HighLevelEncoder.ASCII_ENCODATION);
}
}
}
|
switch (c) {
case '\r':
sb.append('\0');
break;
case '*':
sb.append('\1');
break;
case '>':
sb.append('\2');
break;
case ' ':
sb.append('\3');
break;
default:
if (c >= '0' && c <= '9') {
sb.append((char) (c - 48 + 4));
} else if (c >= 'A' && c <= 'Z') {
sb.append((char) (c - 65 + 14));
} else {
HighLevelEncoder.illegalCharacter(c);
}
break;
}
return 1;
| 472 | 192 | 664 |
<methods>public void encode(com.google.zxing.datamatrix.encoder.EncoderContext) ,public int getEncodingMode() <variables>
|
zxing_zxing
|
zxing/core/src/main/java/com/google/zxing/maxicode/MaxiCodeReader.java
|
MaxiCodeReader
|
extractPureBits
|
class MaxiCodeReader implements Reader {
private static final ResultPoint[] NO_POINTS = new ResultPoint[0];
private static final int MATRIX_WIDTH = 30;
private static final int MATRIX_HEIGHT = 33;
private final Decoder decoder = new Decoder();
/**
* Locates and decodes a MaxiCode in an image.
*
* @return a String representing the content encoded by the MaxiCode
* @throws NotFoundException if a MaxiCode cannot be found
* @throws FormatException if a MaxiCode 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 Result decode(BinaryBitmap image, Map<DecodeHintType,?> hints)
throws NotFoundException, ChecksumException, FormatException {
// Note that MaxiCode reader effectively always assumes PURE_BARCODE mode
// and can't detect it in an image
BitMatrix bits = extractPureBits(image.getBlackMatrix());
DecoderResult decoderResult = decoder.decode(bits, hints);
Result result = new Result(decoderResult.getText(), decoderResult.getRawBytes(), NO_POINTS, BarcodeFormat.MAXICODE);
result.putMetadata(ResultMetadataType.ERRORS_CORRECTED, decoderResult.getErrorsCorrected());
String ecLevel = decoderResult.getECLevel();
if (ecLevel != null) {
result.putMetadata(ResultMetadataType.ERROR_CORRECTION_LEVEL, ecLevel);
}
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>}
}
|
int[] enclosingRectangle = image.getEnclosingRectangle();
if (enclosingRectangle == null) {
throw NotFoundException.getNotFoundInstance();
}
int left = enclosingRectangle[0];
int top = enclosingRectangle[1];
int width = enclosingRectangle[2];
int height = enclosingRectangle[3];
// Now just read off the bits
BitMatrix bits = new BitMatrix(MATRIX_WIDTH, MATRIX_HEIGHT);
for (int y = 0; y < MATRIX_HEIGHT; y++) {
int iy = top + Math.min((y * height + height / 2) / MATRIX_HEIGHT, height - 1);
for (int x = 0; x < MATRIX_WIDTH; x++) {
// srowen: I don't quite understand why the formula below is necessary, but it
// can walk off the image if left + width = the right boundary. So cap it.
int ix = left + Math.min(
(x * width + width / 2 + (y & 0x01) * width / 2) / MATRIX_WIDTH,
width - 1);
if (image.get(ix, iy)) {
bits.set(x, y);
}
}
}
return bits;
| 579 | 356 | 935 |
<no_super_class>
|
zxing_zxing
|
zxing/core/src/main/java/com/google/zxing/maxicode/decoder/Decoder.java
|
Decoder
|
correctErrors
|
class Decoder {
private static final int ALL = 0;
private static final int EVEN = 1;
private static final int ODD = 2;
private final ReedSolomonDecoder rsDecoder;
public Decoder() {
rsDecoder = new ReedSolomonDecoder(GenericGF.MAXICODE_FIELD_64);
}
public DecoderResult decode(BitMatrix bits) throws ChecksumException, FormatException {
return decode(bits, null);
}
public DecoderResult decode(BitMatrix bits,
Map<DecodeHintType,?> hints) throws FormatException, ChecksumException {
BitMatrixParser parser = new BitMatrixParser(bits);
byte[] codewords = parser.readCodewords();
int errorsCorrected = correctErrors(codewords, 0, 10, 10, ALL);
int mode = codewords[0] & 0x0F;
byte[] datawords;
switch (mode) {
case 2:
case 3:
case 4:
errorsCorrected += correctErrors(codewords, 20, 84, 40, EVEN);
errorsCorrected += correctErrors(codewords, 20, 84, 40, ODD);
datawords = new byte[94];
break;
case 5:
errorsCorrected += correctErrors(codewords, 20, 68, 56, EVEN);
errorsCorrected += correctErrors(codewords, 20, 68, 56, ODD);
datawords = new byte[78];
break;
default:
throw FormatException.getFormatInstance();
}
System.arraycopy(codewords, 0, datawords, 0, 10);
System.arraycopy(codewords, 20, datawords, 10, datawords.length - 10);
DecoderResult result = DecodedBitStreamParser.decode(datawords, mode);
result.setErrorsCorrected(errorsCorrected);
return result;
}
private int correctErrors(byte[] codewordBytes,
int start,
int dataCodewords,
int ecCodewords,
int mode) throws ChecksumException {<FILL_FUNCTION_BODY>}
}
|
int codewords = dataCodewords + ecCodewords;
// in EVEN or ODD mode only half the codewords
int divisor = mode == ALL ? 1 : 2;
// First read into an array of ints
int[] codewordsInts = new int[codewords / divisor];
for (int i = 0; i < codewords; i++) {
if ((mode == ALL) || (i % 2 == (mode - 1))) {
codewordsInts[i / divisor] = codewordBytes[i + start] & 0xFF;
}
}
int errorsCorrected = 0;
try {
errorsCorrected = rsDecoder.decodeWithECCount(codewordsInts, ecCodewords / divisor);
} 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 < dataCodewords; i++) {
if ((mode == ALL) || (i % 2 == (mode - 1))) {
codewordBytes[i + start] = (byte) codewordsInts[i / divisor];
}
}
return errorsCorrected;
| 592 | 343 | 935 |
<no_super_class>
|
zxing_zxing
|
zxing/core/src/main/java/com/google/zxing/multi/ByQuadrantReader.java
|
ByQuadrantReader
|
decode
|
class ByQuadrantReader implements Reader {
private final Reader delegate;
public ByQuadrantReader(Reader delegate) {
this.delegate = delegate;
}
@Override
public Result decode(BinaryBitmap image)
throws NotFoundException, ChecksumException, FormatException {
return decode(image, null);
}
@Override
public Result decode(BinaryBitmap image, Map<DecodeHintType,?> hints)
throws NotFoundException, ChecksumException, FormatException {<FILL_FUNCTION_BODY>}
@Override
public void reset() {
delegate.reset();
}
private static void makeAbsolute(ResultPoint[] points, int leftOffset, int topOffset) {
if (points != null) {
for (int i = 0; i < points.length; i++) {
ResultPoint relative = points[i];
if (relative != null) {
points[i] = new ResultPoint(relative.getX() + leftOffset, relative.getY() + topOffset);
}
}
}
}
}
|
int width = image.getWidth();
int height = image.getHeight();
int halfWidth = width / 2;
int halfHeight = height / 2;
try {
// No need to call makeAbsolute as results will be relative to original top left here
return delegate.decode(image.crop(0, 0, halfWidth, halfHeight), hints);
} catch (NotFoundException re) {
// continue
}
try {
Result result = delegate.decode(image.crop(halfWidth, 0, halfWidth, halfHeight), hints);
makeAbsolute(result.getResultPoints(), halfWidth, 0);
return result;
} catch (NotFoundException re) {
// continue
}
try {
Result result = delegate.decode(image.crop(0, halfHeight, halfWidth, halfHeight), hints);
makeAbsolute(result.getResultPoints(), 0, halfHeight);
return result;
} catch (NotFoundException re) {
// continue
}
try {
Result result = delegate.decode(image.crop(halfWidth, halfHeight, halfWidth, halfHeight), hints);
makeAbsolute(result.getResultPoints(), halfWidth, halfHeight);
return result;
} catch (NotFoundException re) {
// continue
}
int quarterWidth = halfWidth / 2;
int quarterHeight = halfHeight / 2;
BinaryBitmap center = image.crop(quarterWidth, quarterHeight, halfWidth, halfHeight);
Result result = delegate.decode(center, hints);
makeAbsolute(result.getResultPoints(), quarterWidth, quarterHeight);
return result;
| 285 | 418 | 703 |
<no_super_class>
|
zxing_zxing
|
zxing/core/src/main/java/com/google/zxing/multi/GenericMultipleBarcodeReader.java
|
GenericMultipleBarcodeReader
|
doDecodeMultiple
|
class GenericMultipleBarcodeReader implements MultipleBarcodeReader {
private static final int MIN_DIMENSION_TO_RECUR = 100;
private static final int MAX_DEPTH = 4;
static final Result[] EMPTY_RESULT_ARRAY = new Result[0];
private final Reader delegate;
public GenericMultipleBarcodeReader(Reader delegate) {
this.delegate = delegate;
}
@Override
public Result[] decodeMultiple(BinaryBitmap image) throws NotFoundException {
return decodeMultiple(image, null);
}
@Override
public Result[] decodeMultiple(BinaryBitmap image, Map<DecodeHintType,?> hints)
throws NotFoundException {
List<Result> results = new ArrayList<>();
doDecodeMultiple(image, hints, results, 0, 0, 0);
if (results.isEmpty()) {
throw NotFoundException.getNotFoundInstance();
}
return results.toArray(EMPTY_RESULT_ARRAY);
}
private void doDecodeMultiple(BinaryBitmap image,
Map<DecodeHintType,?> hints,
List<Result> results,
int xOffset,
int yOffset,
int currentDepth) {<FILL_FUNCTION_BODY>}
private static Result translateResultPoints(Result result, int xOffset, int yOffset) {
ResultPoint[] oldResultPoints = result.getResultPoints();
if (oldResultPoints == null) {
return result;
}
ResultPoint[] newResultPoints = new ResultPoint[oldResultPoints.length];
for (int i = 0; i < oldResultPoints.length; i++) {
ResultPoint oldPoint = oldResultPoints[i];
if (oldPoint != null) {
newResultPoints[i] = new ResultPoint(oldPoint.getX() + xOffset, oldPoint.getY() + yOffset);
}
}
Result newResult = new Result(result.getText(),
result.getRawBytes(),
result.getNumBits(),
newResultPoints,
result.getBarcodeFormat(),
result.getTimestamp());
newResult.putAllMetadata(result.getResultMetadata());
return newResult;
}
}
|
if (currentDepth > MAX_DEPTH) {
return;
}
Result result;
try {
result = delegate.decode(image, hints);
} catch (ReaderException ignored) {
return;
}
boolean alreadyFound = false;
for (Result existingResult : results) {
if (existingResult.getText().equals(result.getText())) {
alreadyFound = true;
break;
}
}
if (!alreadyFound) {
results.add(translateResultPoints(result, xOffset, yOffset));
}
ResultPoint[] resultPoints = result.getResultPoints();
if (resultPoints == null || resultPoints.length == 0) {
return;
}
int width = image.getWidth();
int height = image.getHeight();
float minX = width;
float minY = height;
float maxX = 0.0f;
float maxY = 0.0f;
for (ResultPoint point : resultPoints) {
if (point == null) {
continue;
}
float x = point.getX();
float y = point.getY();
if (x < minX) {
minX = x;
}
if (y < minY) {
minY = y;
}
if (x > maxX) {
maxX = x;
}
if (y > maxY) {
maxY = y;
}
}
// Decode left of barcode
if (minX > MIN_DIMENSION_TO_RECUR) {
doDecodeMultiple(image.crop(0, 0, (int) minX, height),
hints, results,
xOffset, yOffset,
currentDepth + 1);
}
// Decode above barcode
if (minY > MIN_DIMENSION_TO_RECUR) {
doDecodeMultiple(image.crop(0, 0, width, (int) minY),
hints, results,
xOffset, yOffset,
currentDepth + 1);
}
// Decode right of barcode
if (maxX < width - MIN_DIMENSION_TO_RECUR) {
doDecodeMultiple(image.crop((int) maxX, 0, width - (int) maxX, height),
hints, results,
xOffset + (int) maxX, yOffset,
currentDepth + 1);
}
// Decode below barcode
if (maxY < height - MIN_DIMENSION_TO_RECUR) {
doDecodeMultiple(image.crop(0, (int) maxY, width, height - (int) maxY),
hints, results,
xOffset, yOffset + (int) maxY,
currentDepth + 1);
}
| 579 | 717 | 1,296 |
<no_super_class>
|
zxing_zxing
|
zxing/core/src/main/java/com/google/zxing/multi/qrcode/QRCodeMultiReader.java
|
QRCodeMultiReader
|
processStructuredAppend
|
class QRCodeMultiReader extends QRCodeReader implements MultipleBarcodeReader {
private static final Result[] EMPTY_RESULT_ARRAY = new Result[0];
private static final ResultPoint[] NO_POINTS = new ResultPoint[0];
@Override
public Result[] decodeMultiple(BinaryBitmap image) throws NotFoundException {
return decodeMultiple(image, null);
}
@Override
public Result[] decodeMultiple(BinaryBitmap image, Map<DecodeHintType,?> hints) throws NotFoundException {
List<Result> results = new ArrayList<>();
DetectorResult[] detectorResults = new MultiDetector(image.getBlackMatrix()).detectMulti(hints);
for (DetectorResult detectorResult : detectorResults) {
try {
DecoderResult decoderResult = getDecoder().decode(detectorResult.getBits(), hints);
ResultPoint[] 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());
}
results.add(result);
} catch (ReaderException re) {
// ignore and continue
}
}
if (results.isEmpty()) {
return EMPTY_RESULT_ARRAY;
} else {
results = processStructuredAppend(results);
return results.toArray(EMPTY_RESULT_ARRAY);
}
}
static List<Result> processStructuredAppend(List<Result> results) {<FILL_FUNCTION_BODY>}
private static final class SAComparator implements Comparator<Result>, Serializable {
@Override
public int compare(Result a, Result b) {
int aNumber = (int) a.getResultMetadata().get(ResultMetadataType.STRUCTURED_APPEND_SEQUENCE);
int bNumber = (int) b.getResultMetadata().get(ResultMetadataType.STRUCTURED_APPEND_SEQUENCE);
return Integer.compare(aNumber, bNumber);
}
}
}
|
List<Result> newResults = new ArrayList<>();
List<Result> saResults = new ArrayList<>();
for (Result result : results) {
if (result.getResultMetadata().containsKey(ResultMetadataType.STRUCTURED_APPEND_SEQUENCE)) {
saResults.add(result);
} else {
newResults.add(result);
}
}
if (saResults.isEmpty()) {
return results;
}
// sort and concatenate the SA list items
Collections.sort(saResults, new SAComparator());
StringBuilder newText = new StringBuilder();
ByteArrayOutputStream newRawBytes = new ByteArrayOutputStream();
ByteArrayOutputStream newByteSegment = new ByteArrayOutputStream();
for (Result saResult : saResults) {
newText.append(saResult.getText());
byte[] saBytes = saResult.getRawBytes();
newRawBytes.write(saBytes, 0, saBytes.length);
@SuppressWarnings("unchecked")
Iterable<byte[]> byteSegments =
(Iterable<byte[]>) saResult.getResultMetadata().get(ResultMetadataType.BYTE_SEGMENTS);
if (byteSegments != null) {
for (byte[] segment : byteSegments) {
newByteSegment.write(segment, 0, segment.length);
}
}
}
Result newResult = new Result(newText.toString(), newRawBytes.toByteArray(), NO_POINTS, BarcodeFormat.QR_CODE);
if (newByteSegment.size() > 0) {
newResult.putMetadata(ResultMetadataType.BYTE_SEGMENTS, Collections.singletonList(newByteSegment.toByteArray()));
}
newResults.add(newResult);
return newResults;
| 796 | 455 | 1,251 |
<methods>public non-sealed void <init>() ,public com.google.zxing.Result decode(com.google.zxing.BinaryBitmap) throws com.google.zxing.NotFoundException, com.google.zxing.ChecksumException, com.google.zxing.FormatException,public final com.google.zxing.Result decode(com.google.zxing.BinaryBitmap, Map<com.google.zxing.DecodeHintType,?>) throws com.google.zxing.NotFoundException, com.google.zxing.ChecksumException, com.google.zxing.FormatException,public void reset() <variables>private static final com.google.zxing.ResultPoint[] NO_POINTS,private final com.google.zxing.qrcode.decoder.Decoder decoder
|
zxing_zxing
|
zxing/core/src/main/java/com/google/zxing/multi/qrcode/detector/MultiDetector.java
|
MultiDetector
|
detectMulti
|
class MultiDetector extends Detector {
private static final DetectorResult[] EMPTY_DETECTOR_RESULTS = new DetectorResult[0];
public MultiDetector(BitMatrix image) {
super(image);
}
public DetectorResult[] detectMulti(Map<DecodeHintType,?> hints) throws NotFoundException {<FILL_FUNCTION_BODY>}
}
|
BitMatrix image = getImage();
ResultPointCallback resultPointCallback =
hints == null ? null : (ResultPointCallback) hints.get(DecodeHintType.NEED_RESULT_POINT_CALLBACK);
MultiFinderPatternFinder finder = new MultiFinderPatternFinder(image, resultPointCallback);
FinderPatternInfo[] infos = finder.findMulti(hints);
if (infos.length == 0) {
throw NotFoundException.getNotFoundInstance();
}
List<DetectorResult> result = new ArrayList<>();
for (FinderPatternInfo info : infos) {
try {
result.add(processFinderPatternInfo(info));
} catch (ReaderException e) {
// ignore
}
}
if (result.isEmpty()) {
return EMPTY_DETECTOR_RESULTS;
} else {
return result.toArray(EMPTY_DETECTOR_RESULTS);
}
| 104 | 246 | 350 |
<methods>public void <init>(com.google.zxing.common.BitMatrix) ,public com.google.zxing.common.DetectorResult detect() throws com.google.zxing.NotFoundException, com.google.zxing.FormatException,public final com.google.zxing.common.DetectorResult detect(Map<com.google.zxing.DecodeHintType,?>) throws com.google.zxing.NotFoundException, com.google.zxing.FormatException<variables>private final non-sealed com.google.zxing.common.BitMatrix image,private com.google.zxing.ResultPointCallback resultPointCallback
|
zxing_zxing
|
zxing/core/src/main/java/com/google/zxing/multi/qrcode/detector/MultiFinderPatternFinder.java
|
ModuleSizeComparator
|
selectMultipleBestPatterns
|
class ModuleSizeComparator implements Comparator<FinderPattern>, Serializable {
@Override
public int compare(FinderPattern center1, FinderPattern center2) {
float value = center2.getEstimatedModuleSize() - center1.getEstimatedModuleSize();
return value < 0.0 ? -1 : value > 0.0 ? 1 : 0;
}
}
public MultiFinderPatternFinder(BitMatrix image, ResultPointCallback resultPointCallback) {
super(image, resultPointCallback);
}
/**
* @return the 3 best {@link FinderPattern}s from our list of candidates. The "best" are
* those that have been detected at least 2 times, and whose module
* size differs from the average among those patterns the least
* @throws NotFoundException if 3 such finder patterns do not exist
*/
private FinderPattern[][] selectMultipleBestPatterns() throws NotFoundException {<FILL_FUNCTION_BODY>
|
List<FinderPattern> possibleCenters = new ArrayList<>();
for (FinderPattern fp : getPossibleCenters()) {
if (fp.getCount() >= 2) {
possibleCenters.add(fp);
}
}
int size = possibleCenters.size();
if (size < 3) {
// Couldn't find enough finder patterns
throw NotFoundException.getNotFoundInstance();
}
/*
* Begin HE modifications to safely detect multiple codes of equal size
*/
if (size == 3) {
return new FinderPattern[][] { possibleCenters.toArray(EMPTY_FP_ARRAY) };
}
// Sort by estimated module size to speed up the upcoming checks
Collections.sort(possibleCenters, new ModuleSizeComparator());
/*
* Now lets start: build a list of tuples of three finder locations that
* - feature similar module sizes
* - are placed in a distance so the estimated module count is within the QR specification
* - have similar distance between upper left/right and left top/bottom finder patterns
* - form a triangle with 90° angle (checked by comparing top right/bottom left distance
* with pythagoras)
*
* Note: we allow each point to be used for more than one code region: this might seem
* counterintuitive at first, but the performance penalty is not that big. At this point,
* we cannot make a good quality decision whether the three finders actually represent
* a QR code, or are just by chance laid out so it looks like there might be a QR code there.
* So, if the layout seems right, lets have the decoder try to decode.
*/
List<FinderPattern[]> results = new ArrayList<>(); // holder for the results
for (int i1 = 0; i1 < (size - 2); i1++) {
FinderPattern p1 = possibleCenters.get(i1);
if (p1 == null) {
continue;
}
for (int i2 = i1 + 1; i2 < (size - 1); i2++) {
FinderPattern p2 = possibleCenters.get(i2);
if (p2 == null) {
continue;
}
// Compare the expected module sizes; if they are really off, skip
float vModSize12 = (p1.getEstimatedModuleSize() - p2.getEstimatedModuleSize()) /
Math.min(p1.getEstimatedModuleSize(), p2.getEstimatedModuleSize());
float vModSize12A = Math.abs(p1.getEstimatedModuleSize() - p2.getEstimatedModuleSize());
if (vModSize12A > DIFF_MODSIZE_CUTOFF && vModSize12 >= DIFF_MODSIZE_CUTOFF_PERCENT) {
// break, since elements are ordered by the module size deviation there cannot be
// any more interesting elements for the given p1.
break;
}
for (int i3 = i2 + 1; i3 < size; i3++) {
FinderPattern p3 = possibleCenters.get(i3);
if (p3 == null) {
continue;
}
// Compare the expected module sizes; if they are really off, skip
float vModSize23 = (p2.getEstimatedModuleSize() - p3.getEstimatedModuleSize()) /
Math.min(p2.getEstimatedModuleSize(), p3.getEstimatedModuleSize());
float vModSize23A = Math.abs(p2.getEstimatedModuleSize() - p3.getEstimatedModuleSize());
if (vModSize23A > DIFF_MODSIZE_CUTOFF && vModSize23 >= DIFF_MODSIZE_CUTOFF_PERCENT) {
// break, since elements are ordered by the module size deviation there cannot be
// any more interesting elements for the given p1.
break;
}
FinderPattern[] test = {p1, p2, p3};
ResultPoint.orderBestPatterns(test);
// Calculate the distances: a = topleft-bottomleft, b=topleft-topright, c = diagonal
FinderPatternInfo info = new FinderPatternInfo(test);
float dA = ResultPoint.distance(info.getTopLeft(), info.getBottomLeft());
float dC = ResultPoint.distance(info.getTopRight(), info.getBottomLeft());
float dB = ResultPoint.distance(info.getTopLeft(), info.getTopRight());
// Check the sizes
float estimatedModuleCount = (dA + dB) / (p1.getEstimatedModuleSize() * 2.0f);
if (estimatedModuleCount > MAX_MODULE_COUNT_PER_EDGE ||
estimatedModuleCount < MIN_MODULE_COUNT_PER_EDGE) {
continue;
}
// Calculate the difference of the edge lengths in percent
float vABBC = Math.abs((dA - dB) / Math.min(dA, dB));
if (vABBC >= 0.1f) {
continue;
}
// Calculate the diagonal length by assuming a 90° angle at topleft
float dCpy = (float) Math.sqrt((double) dA * dA + (double) dB * dB);
// Compare to the real distance in %
float vPyC = Math.abs((dC - dCpy) / Math.min(dC, dCpy));
if (vPyC >= 0.1f) {
continue;
}
// All tests passed!
results.add(test);
}
}
}
if (!results.isEmpty()) {
return results.toArray(EMPTY_FP_2D_ARRAY);
}
// Nothing found!
throw NotFoundException.getNotFoundInstance();
| 245 | 1,468 | 1,713 |
<methods>public void <init>(com.google.zxing.common.BitMatrix) ,public void <init>(com.google.zxing.common.BitMatrix, com.google.zxing.ResultPointCallback) <variables>private static final int CENTER_QUORUM,protected static final int MAX_MODULES,protected static final int MIN_SKIP,private final non-sealed int[] crossCheckStateCount,private boolean hasSkipped,private final non-sealed com.google.zxing.common.BitMatrix image,private static final com.google.zxing.qrcode.detector.FinderPatternFinder.EstimatedModuleComparator moduleComparator,private final non-sealed List<com.google.zxing.qrcode.detector.FinderPattern> possibleCenters,private final non-sealed com.google.zxing.ResultPointCallback resultPointCallback
|
zxing_zxing
|
zxing/core/src/main/java/com/google/zxing/oned/CodaBarWriter.java
|
CodaBarWriter
|
encode
|
class CodaBarWriter extends OneDimensionalCodeWriter {
private static final char[] START_END_CHARS = {'A', 'B', 'C', 'D'};
private static final char[] ALT_START_END_CHARS = {'T', 'N', '*', 'E'};
private static final char[] CHARS_WHICH_ARE_TEN_LENGTH_EACH_AFTER_DECODED = {'/', ':', '+', '.'};
private static final char DEFAULT_GUARD = START_END_CHARS[0];
@Override
protected Collection<BarcodeFormat> getSupportedWriteFormats() {
return Collections.singleton(BarcodeFormat.CODABAR);
}
@Override
public boolean[] encode(String contents) {<FILL_FUNCTION_BODY>}
}
|
if (contents.length() < 2) {
// Can't have a start/end guard, so tentatively add default guards
contents = DEFAULT_GUARD + contents + DEFAULT_GUARD;
} else {
// Verify input and calculate decoded length.
char firstChar = Character.toUpperCase(contents.charAt(0));
char lastChar = Character.toUpperCase(contents.charAt(contents.length() - 1));
boolean startsNormal = CodaBarReader.arrayContains(START_END_CHARS, firstChar);
boolean endsNormal = CodaBarReader.arrayContains(START_END_CHARS, lastChar);
boolean startsAlt = CodaBarReader.arrayContains(ALT_START_END_CHARS, firstChar);
boolean endsAlt = CodaBarReader.arrayContains(ALT_START_END_CHARS, lastChar);
if (startsNormal) {
if (!endsNormal) {
throw new IllegalArgumentException("Invalid start/end guards: " + contents);
}
// else already has valid start/end
} else if (startsAlt) {
if (!endsAlt) {
throw new IllegalArgumentException("Invalid start/end guards: " + contents);
}
// else already has valid start/end
} else {
// Doesn't start with a guard
if (endsNormal || endsAlt) {
throw new IllegalArgumentException("Invalid start/end guards: " + contents);
}
// else doesn't end with guard either, so add a default
contents = DEFAULT_GUARD + contents + DEFAULT_GUARD;
}
}
// The start character and the end character are decoded to 10 length each.
int resultLength = 20;
for (int i = 1; i < contents.length() - 1; i++) {
if (Character.isDigit(contents.charAt(i)) || contents.charAt(i) == '-' || contents.charAt(i) == '$') {
resultLength += 9;
} else if (CodaBarReader.arrayContains(CHARS_WHICH_ARE_TEN_LENGTH_EACH_AFTER_DECODED, contents.charAt(i))) {
resultLength += 10;
} else {
throw new IllegalArgumentException("Cannot encode : '" + contents.charAt(i) + '\'');
}
}
// A blank is placed between each character.
resultLength += contents.length() - 1;
boolean[] result = new boolean[resultLength];
int position = 0;
for (int index = 0; index < contents.length(); index++) {
char c = Character.toUpperCase(contents.charAt(index));
if (index == 0 || index == contents.length() - 1) {
// The start/end chars are not in the CodaBarReader.ALPHABET.
switch (c) {
case 'T':
c = 'A';
break;
case 'N':
c = 'B';
break;
case '*':
c = 'C';
break;
case 'E':
c = 'D';
break;
}
}
int code = 0;
for (int i = 0; i < CodaBarReader.ALPHABET.length; i++) {
// Found any, because I checked above.
if (c == CodaBarReader.ALPHABET[i]) {
code = CodaBarReader.CHARACTER_ENCODINGS[i];
break;
}
}
boolean color = true;
int counter = 0;
int bit = 0;
while (bit < 7) { // A character consists of 7 digit.
result[position] = color;
position++;
if (((code >> (6 - bit)) & 1) == 0 || counter == 1) {
color = !color; // Flip the color.
bit++;
counter = 0;
} else {
counter++;
}
}
if (index < contents.length() - 1) {
result[position] = false;
position++;
}
}
return result;
| 210 | 1,047 | 1,257 |
<methods>public non-sealed void <init>() ,public abstract boolean[] encode(java.lang.String) ,public boolean[] encode(java.lang.String, Map<com.google.zxing.EncodeHintType,?>) ,public final com.google.zxing.common.BitMatrix encode(java.lang.String, com.google.zxing.BarcodeFormat, int, int) ,public com.google.zxing.common.BitMatrix encode(java.lang.String, com.google.zxing.BarcodeFormat, int, int, Map<com.google.zxing.EncodeHintType,?>) ,public int getDefaultMargin() <variables>private static final java.util.regex.Pattern NUMERIC
|
zxing_zxing
|
zxing/core/src/main/java/com/google/zxing/oned/Code39Writer.java
|
Code39Writer
|
encode
|
class Code39Writer extends OneDimensionalCodeWriter {
@Override
protected Collection<BarcodeFormat> getSupportedWriteFormats() {
return Collections.singleton(BarcodeFormat.CODE_39);
}
@Override
public boolean[] encode(String contents) {<FILL_FUNCTION_BODY>}
private static void toIntArray(int a, int[] toReturn) {
for (int i = 0; i < 9; i++) {
int temp = a & (1 << (8 - i));
toReturn[i] = temp == 0 ? 1 : 2;
}
}
private static String tryToConvertToExtendedMode(String contents) {
int length = contents.length();
StringBuilder extendedContent = new StringBuilder();
for (int i = 0; i < length; i++) {
char character = contents.charAt(i);
switch (character) {
case '\u0000':
extendedContent.append("%U");
break;
case ' ':
case '-':
case '.':
extendedContent.append(character);
break;
case '@':
extendedContent.append("%V");
break;
case '`':
extendedContent.append("%W");
break;
default:
if (character <= 26) {
extendedContent.append('$');
extendedContent.append((char) ('A' + (character - 1)));
} else if (character < ' ') {
extendedContent.append('%');
extendedContent.append((char) ('A' + (character - 27)));
} else if (character <= ',' || character == '/' || character == ':') {
extendedContent.append('/');
extendedContent.append((char) ('A' + (character - 33)));
} else if (character <= '9') {
extendedContent.append((char) ('0' + (character - 48)));
} else if (character <= '?') {
extendedContent.append('%');
extendedContent.append((char) ('F' + (character - 59)));
} else if (character <= 'Z') {
extendedContent.append((char) ('A' + (character - 65)));
} else if (character <= '_') {
extendedContent.append('%');
extendedContent.append((char) ('K' + (character - 91)));
} else if (character <= 'z') {
extendedContent.append('+');
extendedContent.append((char) ('A' + (character - 97)));
} else if (character <= 127) {
extendedContent.append('%');
extendedContent.append((char) ('P' + (character - 123)));
} else {
throw new IllegalArgumentException(
"Requested content contains a non-encodable character: '" + contents.charAt(i) + "'");
}
break;
}
}
return extendedContent.toString();
}
}
|
int length = contents.length();
if (length > 80) {
throw new IllegalArgumentException(
"Requested contents should be less than 80 digits long, but got " + length);
}
for (int i = 0; i < length; i++) {
int indexInString = Code39Reader.ALPHABET_STRING.indexOf(contents.charAt(i));
if (indexInString < 0) {
contents = tryToConvertToExtendedMode(contents);
length = contents.length();
if (length > 80) {
throw new IllegalArgumentException("Requested contents should be less than 80 digits long, but got " +
length + " (extended full ASCII mode)");
}
break;
}
}
int[] widths = new int[9];
int codeWidth = 24 + 1 + (13 * length);
boolean[] result = new boolean[codeWidth];
toIntArray(Code39Reader.ASTERISK_ENCODING, widths);
int pos = appendPattern(result, 0, widths, true);
int[] narrowWhite = {1};
pos += appendPattern(result, pos, narrowWhite, false);
//append next character to byte matrix
for (int i = 0; i < length; i++) {
int indexInString = Code39Reader.ALPHABET_STRING.indexOf(contents.charAt(i));
toIntArray(Code39Reader.CHARACTER_ENCODINGS[indexInString], widths);
pos += appendPattern(result, pos, widths, true);
pos += appendPattern(result, pos, narrowWhite, false);
}
toIntArray(Code39Reader.ASTERISK_ENCODING, widths);
appendPattern(result, pos, widths, true);
return result;
| 752 | 465 | 1,217 |
<methods>public non-sealed void <init>() ,public abstract boolean[] encode(java.lang.String) ,public boolean[] encode(java.lang.String, Map<com.google.zxing.EncodeHintType,?>) ,public final com.google.zxing.common.BitMatrix encode(java.lang.String, com.google.zxing.BarcodeFormat, int, int) ,public com.google.zxing.common.BitMatrix encode(java.lang.String, com.google.zxing.BarcodeFormat, int, int, Map<com.google.zxing.EncodeHintType,?>) ,public int getDefaultMargin() <variables>private static final java.util.regex.Pattern NUMERIC
|
zxing_zxing
|
zxing/core/src/main/java/com/google/zxing/oned/Code93Writer.java
|
Code93Writer
|
encode
|
class Code93Writer extends OneDimensionalCodeWriter {
@Override
protected Collection<BarcodeFormat> getSupportedWriteFormats() {
return Collections.singleton(BarcodeFormat.CODE_93);
}
/**
* @param contents barcode contents to encode. It should not be encoded for extended characters.
* @return a {@code boolean[]} of horizontal pixels (false = white, true = black)
*/
@Override
public boolean[] encode(String contents) {<FILL_FUNCTION_BODY>}
/**
* @param target output to append to
* @param pos start position
* @param pattern pattern to append
* @param startColor unused
* @return 9
* @deprecated without replacement; intended as an internal-only method
*/
@Deprecated
protected static int appendPattern(boolean[] target, int pos, int[] pattern, boolean startColor) {
for (int bit : pattern) {
target[pos++] = bit != 0;
}
return 9;
}
private static int appendPattern(boolean[] target, int pos, int a) {
for (int i = 0; i < 9; i++) {
int temp = a & (1 << (8 - i));
target[pos + i] = temp != 0;
}
return 9;
}
private static int computeChecksumIndex(String contents, int maxWeight) {
int weight = 1;
int total = 0;
for (int i = contents.length() - 1; i >= 0; i--) {
int indexInString = Code93Reader.ALPHABET_STRING.indexOf(contents.charAt(i));
total += indexInString * weight;
if (++weight > maxWeight) {
weight = 1;
}
}
return total % 47;
}
static String convertToExtended(String contents) {
int length = contents.length();
StringBuilder extendedContent = new StringBuilder(length * 2);
for (int i = 0; i < length; i++) {
char character = contents.charAt(i);
// ($)=a, (%)=b, (/)=c, (+)=d. see Code93Reader.ALPHABET_STRING
if (character == 0) {
// NUL: (%)U
extendedContent.append("bU");
} else if (character <= 26) {
// SOH - SUB: ($)A - ($)Z
extendedContent.append('a');
extendedContent.append((char) ('A' + character - 1));
} else if (character <= 31) {
// ESC - US: (%)A - (%)E
extendedContent.append('b');
extendedContent.append((char) ('A' + character - 27));
} else if (character == ' ' || character == '$' || character == '%' || character == '+') {
// space $ % +
extendedContent.append(character);
} else if (character <= ',') {
// ! " # & ' ( ) * ,: (/)A - (/)L
extendedContent.append('c');
extendedContent.append((char) ('A' + character - '!'));
} else if (character <= '9') {
extendedContent.append(character);
} else if (character == ':') {
// :: (/)Z
extendedContent.append("cZ");
} else if (character <= '?') {
// ; - ?: (%)F - (%)J
extendedContent.append('b');
extendedContent.append((char) ('F' + character - ';'));
} else if (character == '@') {
// @: (%)V
extendedContent.append("bV");
} else if (character <= 'Z') {
// A - Z
extendedContent.append(character);
} else if (character <= '_') {
// [ - _: (%)K - (%)O
extendedContent.append('b');
extendedContent.append((char) ('K' + character - '['));
} else if (character == '`') {
// `: (%)W
extendedContent.append("bW");
} else if (character <= 'z') {
// a - z: (*)A - (*)Z
extendedContent.append('d');
extendedContent.append((char) ('A' + character - 'a'));
} else if (character <= 127) {
// { - DEL: (%)P - (%)T
extendedContent.append('b');
extendedContent.append((char) ('P' + character - '{'));
} else {
throw new IllegalArgumentException(
"Requested content contains a non-encodable character: '" + character + "'");
}
}
return extendedContent.toString();
}
}
|
contents = convertToExtended(contents);
int length = contents.length();
if (length > 80) {
throw new IllegalArgumentException("Requested contents should be less than 80 digits long after " +
"converting to extended encoding, but got " + length);
}
//length of code + 2 start/stop characters + 2 checksums, each of 9 bits, plus a termination bar
int codeWidth = (contents.length() + 2 + 2) * 9 + 1;
boolean[] result = new boolean[codeWidth];
//start character (*)
int pos = appendPattern(result, 0, Code93Reader.ASTERISK_ENCODING);
for (int i = 0; i < length; i++) {
int indexInString = Code93Reader.ALPHABET_STRING.indexOf(contents.charAt(i));
pos += appendPattern(result, pos, Code93Reader.CHARACTER_ENCODINGS[indexInString]);
}
//add two checksums
int check1 = computeChecksumIndex(contents, 20);
pos += appendPattern(result, pos, Code93Reader.CHARACTER_ENCODINGS[check1]);
//append the contents to reflect the first checksum added
contents += Code93Reader.ALPHABET_STRING.charAt(check1);
int check2 = computeChecksumIndex(contents, 15);
pos += appendPattern(result, pos, Code93Reader.CHARACTER_ENCODINGS[check2]);
//end character (*)
pos += appendPattern(result, pos, Code93Reader.ASTERISK_ENCODING);
//termination bar (single black bar)
result[pos] = true;
return result;
| 1,223 | 449 | 1,672 |
<methods>public non-sealed void <init>() ,public abstract boolean[] encode(java.lang.String) ,public boolean[] encode(java.lang.String, Map<com.google.zxing.EncodeHintType,?>) ,public final com.google.zxing.common.BitMatrix encode(java.lang.String, com.google.zxing.BarcodeFormat, int, int) ,public com.google.zxing.common.BitMatrix encode(java.lang.String, com.google.zxing.BarcodeFormat, int, int, Map<com.google.zxing.EncodeHintType,?>) ,public int getDefaultMargin() <variables>private static final java.util.regex.Pattern NUMERIC
|
zxing_zxing
|
zxing/core/src/main/java/com/google/zxing/oned/EAN13Reader.java
|
EAN13Reader
|
decodeMiddle
|
class EAN13Reader extends UPCEANReader {
// For an EAN-13 barcode, the first digit is represented by the parities used
// to encode the next six digits, according to the table below. For example,
// if the barcode is 5 123456 789012 then the value of the first digit is
// signified by using odd for '1', even for '2', even for '3', odd for '4',
// odd for '5', and even for '6'. See http://en.wikipedia.org/wiki/EAN-13
//
// Parity of next 6 digits
// Digit 0 1 2 3 4 5
// 0 Odd Odd Odd Odd Odd Odd
// 1 Odd Odd Even Odd Even Even
// 2 Odd Odd Even Even Odd Even
// 3 Odd Odd Even Even Even Odd
// 4 Odd Even Odd Odd Even Even
// 5 Odd Even Even Odd Odd Even
// 6 Odd Even Even Even Odd Odd
// 7 Odd Even Odd Even Odd Even
// 8 Odd Even Odd Even Even Odd
// 9 Odd Even Even Odd Even Odd
//
// Note that the encoding for '0' uses the same parity as a UPC barcode. Hence
// a UPC barcode can be converted to an EAN-13 barcode by prepending a 0.
//
// The encoding is represented by the following array, which is a bit pattern
// using Odd = 0 and Even = 1. For example, 5 is represented by:
//
// Odd Even Even Odd Odd Even
// in binary:
// 0 1 1 0 0 1 == 0x19
//
static final int[] FIRST_DIGIT_ENCODINGS = {
0x00, 0x0B, 0x0D, 0xE, 0x13, 0x19, 0x1C, 0x15, 0x16, 0x1A
};
private final int[] decodeMiddleCounters;
public EAN13Reader() {
decodeMiddleCounters = new int[4];
}
@Override
protected int decodeMiddle(BitArray row,
int[] startRange,
StringBuilder resultString) throws NotFoundException {<FILL_FUNCTION_BODY>}
@Override
BarcodeFormat getBarcodeFormat() {
return BarcodeFormat.EAN_13;
}
/**
* Based on pattern of odd-even ('L' and 'G') patterns used to encoded the explicitly-encoded
* digits in a barcode, determines the implicitly encoded first digit and adds it to the
* result string.
*
* @param resultString string to insert decoded first digit into
* @param lgPatternFound int whose bits indicates the pattern of odd/even L/G patterns used to
* encode digits
* @throws NotFoundException if first digit cannot be determined
*/
private static void determineFirstDigit(StringBuilder resultString, int lgPatternFound)
throws NotFoundException {
for (int d = 0; d < 10; d++) {
if (lgPatternFound == FIRST_DIGIT_ENCODINGS[d]) {
resultString.insert(0, (char) ('0' + d));
return;
}
}
throw NotFoundException.getNotFoundInstance();
}
}
|
int[] counters = decodeMiddleCounters;
counters[0] = 0;
counters[1] = 0;
counters[2] = 0;
counters[3] = 0;
int end = row.getSize();
int rowOffset = startRange[1];
int lgPatternFound = 0;
for (int x = 0; x < 6 && rowOffset < end; x++) {
int bestMatch = decodeDigit(row, counters, rowOffset, L_AND_G_PATTERNS);
resultString.append((char) ('0' + bestMatch % 10));
for (int counter : counters) {
rowOffset += counter;
}
if (bestMatch >= 10) {
lgPatternFound |= 1 << (5 - x);
}
}
determineFirstDigit(resultString, lgPatternFound);
int[] middleRange = findGuardPattern(row, rowOffset, true, MIDDLE_PATTERN);
rowOffset = middleRange[1];
for (int x = 0; x < 6 && rowOffset < end; x++) {
int bestMatch = decodeDigit(row, counters, rowOffset, L_PATTERNS);
resultString.append((char) ('0' + bestMatch));
for (int counter : counters) {
rowOffset += counter;
}
}
return rowOffset;
| 978 | 366 | 1,344 |
<methods>public com.google.zxing.Result decodeRow(int, com.google.zxing.common.BitArray, Map<com.google.zxing.DecodeHintType,?>) throws com.google.zxing.NotFoundException, com.google.zxing.ChecksumException, com.google.zxing.FormatException,public com.google.zxing.Result decodeRow(int, com.google.zxing.common.BitArray, int[], Map<com.google.zxing.DecodeHintType,?>) throws com.google.zxing.NotFoundException, com.google.zxing.ChecksumException, com.google.zxing.FormatException<variables>static final int[] END_PATTERN,static final non-sealed int[][] L_AND_G_PATTERNS,static final int[][] L_PATTERNS,private static final float MAX_AVG_VARIANCE,private static final float MAX_INDIVIDUAL_VARIANCE,static final int[] MIDDLE_PATTERN,static final int[] START_END_PATTERN,private final non-sealed java.lang.StringBuilder decodeRowStringBuffer,private final non-sealed com.google.zxing.oned.EANManufacturerOrgSupport eanManSupport,private final non-sealed com.google.zxing.oned.UPCEANExtensionSupport extensionReader
|
zxing_zxing
|
zxing/core/src/main/java/com/google/zxing/oned/EAN13Writer.java
|
EAN13Writer
|
encode
|
class EAN13Writer extends UPCEANWriter {
private static final int CODE_WIDTH = 3 + // start guard
(7 * 6) + // left bars
5 + // middle guard
(7 * 6) + // right bars
3; // end guard
@Override
protected Collection<BarcodeFormat> getSupportedWriteFormats() {
return Collections.singleton(BarcodeFormat.EAN_13);
}
@Override
public boolean[] encode(String contents) {<FILL_FUNCTION_BODY>}
}
|
int length = contents.length();
switch (length) {
case 12:
// No check digit present, calculate it and add it
int check;
try {
check = UPCEANReader.getStandardUPCEANChecksum(contents);
} catch (FormatException fe) {
throw new IllegalArgumentException(fe);
}
contents += check;
break;
case 13:
try {
if (!UPCEANReader.checkStandardUPCEANChecksum(contents)) {
throw new IllegalArgumentException("Contents do not pass checksum");
}
} catch (FormatException ignored) {
throw new IllegalArgumentException("Illegal contents");
}
break;
default:
throw new IllegalArgumentException(
"Requested contents should be 12 or 13 digits long, but got " + length);
}
checkNumeric(contents);
int firstDigit = Character.digit(contents.charAt(0), 10);
int parities = EAN13Reader.FIRST_DIGIT_ENCODINGS[firstDigit];
boolean[] result = new boolean[CODE_WIDTH];
int pos = 0;
pos += appendPattern(result, pos, UPCEANReader.START_END_PATTERN, true);
// See EAN13Reader for a description of how the first digit & left bars are encoded
for (int i = 1; i <= 6; i++) {
int digit = Character.digit(contents.charAt(i), 10);
if ((parities >> (6 - i) & 1) == 1) {
digit += 10;
}
pos += appendPattern(result, pos, UPCEANReader.L_AND_G_PATTERNS[digit], false);
}
pos += appendPattern(result, pos, UPCEANReader.MIDDLE_PATTERN, false);
for (int i = 7; i <= 12; i++) {
int digit = Character.digit(contents.charAt(i), 10);
pos += appendPattern(result, pos, UPCEANReader.L_PATTERNS[digit], true);
}
appendPattern(result, pos, UPCEANReader.START_END_PATTERN, true);
return result;
| 146 | 580 | 726 |
<methods>public non-sealed void <init>() ,public int getDefaultMargin() <variables>
|
zxing_zxing
|
zxing/core/src/main/java/com/google/zxing/oned/EAN8Reader.java
|
EAN8Reader
|
decodeMiddle
|
class EAN8Reader extends UPCEANReader {
private final int[] decodeMiddleCounters;
public EAN8Reader() {
decodeMiddleCounters = new int[4];
}
@Override
protected int decodeMiddle(BitArray row,
int[] startRange,
StringBuilder result) throws NotFoundException {<FILL_FUNCTION_BODY>}
@Override
BarcodeFormat getBarcodeFormat() {
return BarcodeFormat.EAN_8;
}
}
|
int[] counters = decodeMiddleCounters;
counters[0] = 0;
counters[1] = 0;
counters[2] = 0;
counters[3] = 0;
int end = row.getSize();
int rowOffset = startRange[1];
for (int x = 0; x < 4 && rowOffset < end; x++) {
int bestMatch = decodeDigit(row, counters, rowOffset, L_PATTERNS);
result.append((char) ('0' + bestMatch));
for (int counter : counters) {
rowOffset += counter;
}
}
int[] middleRange = findGuardPattern(row, rowOffset, true, MIDDLE_PATTERN);
rowOffset = middleRange[1];
for (int x = 0; x < 4 && rowOffset < end; x++) {
int bestMatch = decodeDigit(row, counters, rowOffset, L_PATTERNS);
result.append((char) ('0' + bestMatch));
for (int counter : counters) {
rowOffset += counter;
}
}
return rowOffset;
| 138 | 300 | 438 |
<methods>public com.google.zxing.Result decodeRow(int, com.google.zxing.common.BitArray, Map<com.google.zxing.DecodeHintType,?>) throws com.google.zxing.NotFoundException, com.google.zxing.ChecksumException, com.google.zxing.FormatException,public com.google.zxing.Result decodeRow(int, com.google.zxing.common.BitArray, int[], Map<com.google.zxing.DecodeHintType,?>) throws com.google.zxing.NotFoundException, com.google.zxing.ChecksumException, com.google.zxing.FormatException<variables>static final int[] END_PATTERN,static final non-sealed int[][] L_AND_G_PATTERNS,static final int[][] L_PATTERNS,private static final float MAX_AVG_VARIANCE,private static final float MAX_INDIVIDUAL_VARIANCE,static final int[] MIDDLE_PATTERN,static final int[] START_END_PATTERN,private final non-sealed java.lang.StringBuilder decodeRowStringBuffer,private final non-sealed com.google.zxing.oned.EANManufacturerOrgSupport eanManSupport,private final non-sealed com.google.zxing.oned.UPCEANExtensionSupport extensionReader
|
zxing_zxing
|
zxing/core/src/main/java/com/google/zxing/oned/EAN8Writer.java
|
EAN8Writer
|
encode
|
class EAN8Writer extends UPCEANWriter {
private static final int CODE_WIDTH = 3 + // start guard
(7 * 4) + // left bars
5 + // middle guard
(7 * 4) + // right bars
3; // end guard
@Override
protected Collection<BarcodeFormat> getSupportedWriteFormats() {
return Collections.singleton(BarcodeFormat.EAN_8);
}
/**
* @return a byte array of horizontal pixels (false = white, true = black)
*/
@Override
public boolean[] encode(String contents) {<FILL_FUNCTION_BODY>}
}
|
int length = contents.length();
switch (length) {
case 7:
// No check digit present, calculate it and add it
int check;
try {
check = UPCEANReader.getStandardUPCEANChecksum(contents);
} catch (FormatException fe) {
throw new IllegalArgumentException(fe);
}
contents += check;
break;
case 8:
try {
if (!UPCEANReader.checkStandardUPCEANChecksum(contents)) {
throw new IllegalArgumentException("Contents do not pass checksum");
}
} catch (FormatException ignored) {
throw new IllegalArgumentException("Illegal contents");
}
break;
default:
throw new IllegalArgumentException(
"Requested contents should be 7 or 8 digits long, but got " + length);
}
checkNumeric(contents);
boolean[] result = new boolean[CODE_WIDTH];
int pos = 0;
pos += appendPattern(result, pos, UPCEANReader.START_END_PATTERN, true);
for (int i = 0; i <= 3; i++) {
int digit = Character.digit(contents.charAt(i), 10);
pos += appendPattern(result, pos, UPCEANReader.L_PATTERNS[digit], false);
}
pos += appendPattern(result, pos, UPCEANReader.MIDDLE_PATTERN, false);
for (int i = 4; i <= 7; i++) {
int digit = Character.digit(contents.charAt(i), 10);
pos += appendPattern(result, pos, UPCEANReader.L_PATTERNS[digit], true);
}
appendPattern(result, pos, UPCEANReader.START_END_PATTERN, true);
return result;
| 170 | 468 | 638 |
<methods>public non-sealed void <init>() ,public int getDefaultMargin() <variables>
|
zxing_zxing
|
zxing/core/src/main/java/com/google/zxing/oned/ITFWriter.java
|
ITFWriter
|
encode
|
class ITFWriter extends OneDimensionalCodeWriter {
private static final int[] START_PATTERN = {1, 1, 1, 1};
private static final int[] END_PATTERN = {3, 1, 1};
private static final int W = 3; // Pixel width of a 3x wide line
private static final int N = 1; // Pixed width of a narrow line
// See ITFReader.PATTERNS
private static final int[][] PATTERNS = {
{N, N, W, W, N}, // 0
{W, N, N, N, W}, // 1
{N, W, N, N, W}, // 2
{W, W, N, N, N}, // 3
{N, N, W, N, W}, // 4
{W, N, W, N, N}, // 5
{N, W, W, N, N}, // 6
{N, N, N, W, W}, // 7
{W, N, N, W, N}, // 8
{N, W, N, W, N} // 9
};
@Override
protected Collection<BarcodeFormat> getSupportedWriteFormats() {
return Collections.singleton(BarcodeFormat.ITF);
}
@Override
public boolean[] encode(String contents) {<FILL_FUNCTION_BODY>}
}
|
int length = contents.length();
if (length % 2 != 0) {
throw new IllegalArgumentException("The length of the input should be even");
}
if (length > 80) {
throw new IllegalArgumentException(
"Requested contents should be less than 80 digits long, but got " + length);
}
checkNumeric(contents);
boolean[] result = new boolean[9 + 9 * length];
int pos = appendPattern(result, 0, START_PATTERN, true);
for (int i = 0; i < length; i += 2) {
int one = Character.digit(contents.charAt(i), 10);
int two = Character.digit(contents.charAt(i + 1), 10);
int[] encoding = new int[10];
for (int j = 0; j < 5; j++) {
encoding[2 * j] = PATTERNS[one][j];
encoding[2 * j + 1] = PATTERNS[two][j];
}
pos += appendPattern(result, pos, encoding, true);
}
appendPattern(result, pos, END_PATTERN, true);
return result;
| 366 | 306 | 672 |
<methods>public non-sealed void <init>() ,public abstract boolean[] encode(java.lang.String) ,public boolean[] encode(java.lang.String, Map<com.google.zxing.EncodeHintType,?>) ,public final com.google.zxing.common.BitMatrix encode(java.lang.String, com.google.zxing.BarcodeFormat, int, int) ,public com.google.zxing.common.BitMatrix encode(java.lang.String, com.google.zxing.BarcodeFormat, int, int, Map<com.google.zxing.EncodeHintType,?>) ,public int getDefaultMargin() <variables>private static final java.util.regex.Pattern NUMERIC
|
zxing_zxing
|
zxing/core/src/main/java/com/google/zxing/oned/MultiFormatOneDReader.java
|
MultiFormatOneDReader
|
decodeRow
|
class MultiFormatOneDReader extends OneDReader {
private static final OneDReader[] EMPTY_ONED_ARRAY = new OneDReader[0];
private final OneDReader[] readers;
public MultiFormatOneDReader(Map<DecodeHintType,?> hints) {
@SuppressWarnings("unchecked")
Collection<BarcodeFormat> possibleFormats = hints == null ? null :
(Collection<BarcodeFormat>) hints.get(DecodeHintType.POSSIBLE_FORMATS);
boolean useCode39CheckDigit = hints != null &&
hints.get(DecodeHintType.ASSUME_CODE_39_CHECK_DIGIT) != null;
Collection<OneDReader> readers = new ArrayList<>();
if (possibleFormats != null) {
if (possibleFormats.contains(BarcodeFormat.EAN_13) ||
possibleFormats.contains(BarcodeFormat.UPC_A) ||
possibleFormats.contains(BarcodeFormat.EAN_8) ||
possibleFormats.contains(BarcodeFormat.UPC_E)) {
readers.add(new MultiFormatUPCEANReader(hints));
}
if (possibleFormats.contains(BarcodeFormat.CODE_39)) {
readers.add(new Code39Reader(useCode39CheckDigit));
}
if (possibleFormats.contains(BarcodeFormat.CODE_93)) {
readers.add(new Code93Reader());
}
if (possibleFormats.contains(BarcodeFormat.CODE_128)) {
readers.add(new Code128Reader());
}
if (possibleFormats.contains(BarcodeFormat.ITF)) {
readers.add(new ITFReader());
}
if (possibleFormats.contains(BarcodeFormat.CODABAR)) {
readers.add(new CodaBarReader());
}
if (possibleFormats.contains(BarcodeFormat.RSS_14)) {
readers.add(new RSS14Reader());
}
if (possibleFormats.contains(BarcodeFormat.RSS_EXPANDED)) {
readers.add(new RSSExpandedReader());
}
}
if (readers.isEmpty()) {
readers.add(new MultiFormatUPCEANReader(hints));
readers.add(new Code39Reader());
readers.add(new CodaBarReader());
readers.add(new Code93Reader());
readers.add(new Code128Reader());
readers.add(new ITFReader());
readers.add(new RSS14Reader());
readers.add(new RSSExpandedReader());
}
this.readers = readers.toArray(EMPTY_ONED_ARRAY);
}
@Override
public Result decodeRow(int rowNumber,
BitArray row,
Map<DecodeHintType,?> hints) throws NotFoundException {<FILL_FUNCTION_BODY>}
@Override
public void reset() {
for (Reader reader : readers) {
reader.reset();
}
}
}
|
for (OneDReader reader : readers) {
try {
return reader.decodeRow(rowNumber, row, hints);
} catch (ReaderException re) {
// continue
}
}
throw NotFoundException.getNotFoundInstance();
| 805 | 66 | 871 |
<methods>public non-sealed void <init>() ,public com.google.zxing.Result decode(com.google.zxing.BinaryBitmap) throws com.google.zxing.NotFoundException, com.google.zxing.FormatException,public com.google.zxing.Result decode(com.google.zxing.BinaryBitmap, Map<com.google.zxing.DecodeHintType,?>) throws com.google.zxing.NotFoundException, com.google.zxing.FormatException,public abstract com.google.zxing.Result decodeRow(int, com.google.zxing.common.BitArray, Map<com.google.zxing.DecodeHintType,?>) throws com.google.zxing.NotFoundException, com.google.zxing.ChecksumException, com.google.zxing.FormatException,public void reset() <variables>
|
zxing_zxing
|
zxing/core/src/main/java/com/google/zxing/oned/MultiFormatUPCEANReader.java
|
MultiFormatUPCEANReader
|
decodeRow
|
class MultiFormatUPCEANReader extends OneDReader {
private static final UPCEANReader[] EMPTY_READER_ARRAY = new UPCEANReader[0];
private final UPCEANReader[] readers;
public MultiFormatUPCEANReader(Map<DecodeHintType,?> hints) {
@SuppressWarnings("unchecked")
Collection<BarcodeFormat> possibleFormats = hints == null ? null :
(Collection<BarcodeFormat>) hints.get(DecodeHintType.POSSIBLE_FORMATS);
Collection<UPCEANReader> readers = new ArrayList<>();
if (possibleFormats != null) {
if (possibleFormats.contains(BarcodeFormat.EAN_13)) {
readers.add(new EAN13Reader());
} else if (possibleFormats.contains(BarcodeFormat.UPC_A)) {
readers.add(new UPCAReader());
}
if (possibleFormats.contains(BarcodeFormat.EAN_8)) {
readers.add(new EAN8Reader());
}
if (possibleFormats.contains(BarcodeFormat.UPC_E)) {
readers.add(new UPCEReader());
}
}
if (readers.isEmpty()) {
readers.add(new EAN13Reader());
// UPC-A is covered by EAN-13
readers.add(new EAN8Reader());
readers.add(new UPCEReader());
}
this.readers = readers.toArray(EMPTY_READER_ARRAY);
}
@Override
public Result decodeRow(int rowNumber,
BitArray row,
Map<DecodeHintType,?> hints) throws NotFoundException {<FILL_FUNCTION_BODY>}
@Override
public void reset() {
for (Reader reader : readers) {
reader.reset();
}
}
}
|
// Compute this location once and reuse it on multiple implementations
int[] startGuardPattern = UPCEANReader.findStartGuardPattern(row);
for (UPCEANReader reader : readers) {
try {
Result result = reader.decodeRow(rowNumber, row, startGuardPattern, hints);
// Special case: a 12-digit code encoded in UPC-A is identical to a "0"
// followed by those 12 digits encoded as EAN-13. Each will recognize such a code,
// UPC-A as a 12-digit string and EAN-13 as a 13-digit string starting with "0".
// Individually these are correct and their readers will both read such a code
// and correctly call it EAN-13, or UPC-A, respectively.
//
// In this case, if we've been looking for both types, we'd like to call it
// a UPC-A code. But for efficiency we only run the EAN-13 decoder to also read
// UPC-A. So we special case it here, and convert an EAN-13 result to a UPC-A
// result if appropriate.
//
// But, don't return UPC-A if UPC-A was not a requested format!
boolean ean13MayBeUPCA =
result.getBarcodeFormat() == BarcodeFormat.EAN_13 &&
result.getText().charAt(0) == '0';
@SuppressWarnings("unchecked")
Collection<BarcodeFormat> possibleFormats =
hints == null ? null : (Collection<BarcodeFormat>) hints.get(DecodeHintType.POSSIBLE_FORMATS);
boolean canReturnUPCA = possibleFormats == null || possibleFormats.contains(BarcodeFormat.UPC_A);
if (ean13MayBeUPCA && canReturnUPCA) {
// Transfer the metadata across
Result resultUPCA = new Result(result.getText().substring(1),
result.getRawBytes(),
result.getResultPoints(),
BarcodeFormat.UPC_A);
resultUPCA.putAllMetadata(result.getResultMetadata());
return resultUPCA;
}
return result;
} catch (ReaderException ignored) {
// continue
}
}
throw NotFoundException.getNotFoundInstance();
| 497 | 603 | 1,100 |
<methods>public non-sealed void <init>() ,public com.google.zxing.Result decode(com.google.zxing.BinaryBitmap) throws com.google.zxing.NotFoundException, com.google.zxing.FormatException,public com.google.zxing.Result decode(com.google.zxing.BinaryBitmap, Map<com.google.zxing.DecodeHintType,?>) throws com.google.zxing.NotFoundException, com.google.zxing.FormatException,public abstract com.google.zxing.Result decodeRow(int, com.google.zxing.common.BitArray, Map<com.google.zxing.DecodeHintType,?>) throws com.google.zxing.NotFoundException, com.google.zxing.ChecksumException, com.google.zxing.FormatException,public void reset() <variables>
|
zxing_zxing
|
zxing/core/src/main/java/com/google/zxing/oned/OneDimensionalCodeWriter.java
|
OneDimensionalCodeWriter
|
getDefaultMargin
|
class OneDimensionalCodeWriter implements Writer {
private static final Pattern NUMERIC = Pattern.compile("[0-9]+");
/**
* Encode the contents to boolean array expression of one-dimensional barcode.
* Start code and end code should be included in result, and side margins should not be included.
*
* @param contents barcode contents to encode
* @return a {@code boolean[]} of horizontal pixels (false = white, true = black)
*/
public abstract boolean[] encode(String contents);
/**
* Can be overwritten if the encode requires to read the hints map. Otherwise it defaults to {@code encode}.
* @param contents barcode contents to encode
* @param hints encoding hints
* @return a {@code boolean[]} of horizontal pixels (false = white, true = black)
*/
public boolean[] encode(String contents, Map<EncodeHintType,?> hints) {
return encode(contents);
}
@Override
public final BitMatrix encode(String contents, BarcodeFormat format, int width, int height) {
return encode(contents, format, width, height, null);
}
/**
* Encode the contents following specified format.
* {@code width} and {@code height} are required size. This method may return bigger size
* {@code BitMatrix} when specified size is too small. The user can set both {@code width} and
* {@code height} to zero to get minimum size barcode. If negative value is set to {@code width}
* or {@code height}, {@code IllegalArgumentException} is thrown.
*/
@Override
public BitMatrix encode(String contents,
BarcodeFormat format,
int width,
int height,
Map<EncodeHintType,?> hints) {
if (contents.isEmpty()) {
throw new IllegalArgumentException("Found empty contents");
}
if (width < 0 || height < 0) {
throw new IllegalArgumentException("Negative size is not allowed. Input: "
+ width + 'x' + height);
}
Collection<BarcodeFormat> supportedFormats = getSupportedWriteFormats();
if (supportedFormats != null && !supportedFormats.contains(format)) {
throw new IllegalArgumentException("Can only encode " + supportedFormats +
", but got " + format);
}
int sidesMargin = getDefaultMargin();
if (hints != null && hints.containsKey(EncodeHintType.MARGIN)) {
sidesMargin = Integer.parseInt(hints.get(EncodeHintType.MARGIN).toString());
}
boolean[] code = encode(contents, hints);
return renderResult(code, width, height, sidesMargin);
}
protected Collection<BarcodeFormat> getSupportedWriteFormats() {
return null;
}
/**
* @return a byte array of horizontal pixels (0 = white, 1 = black)
*/
private static BitMatrix renderResult(boolean[] code, int width, int height, int sidesMargin) {
int inputWidth = code.length;
// Add quiet zone on both sides.
int fullWidth = inputWidth + sidesMargin;
int outputWidth = Math.max(width, fullWidth);
int outputHeight = Math.max(1, height);
int multiple = outputWidth / fullWidth;
int leftPadding = (outputWidth - (inputWidth * multiple)) / 2;
BitMatrix output = new BitMatrix(outputWidth, outputHeight);
for (int inputX = 0, outputX = leftPadding; inputX < inputWidth; inputX++, outputX += multiple) {
if (code[inputX]) {
output.setRegion(outputX, 0, multiple, outputHeight);
}
}
return output;
}
/**
* @param contents string to check for numeric characters
* @throws IllegalArgumentException if input contains characters other than digits 0-9.
*/
protected static void checkNumeric(String contents) {
if (!NUMERIC.matcher(contents).matches()) {
throw new IllegalArgumentException("Input should only contain digits 0-9");
}
}
/**
* @param target encode black/white pattern into this array
* @param pos position to start encoding at in {@code target}
* @param pattern lengths of black/white runs to encode
* @param startColor starting color - false for white, true for black
* @return the number of elements added to target.
*/
protected static int appendPattern(boolean[] target, int pos, int[] pattern, boolean startColor) {
boolean color = startColor;
int numAdded = 0;
for (int len : pattern) {
for (int j = 0; j < len; j++) {
target[pos++] = color;
}
numAdded += len;
color = !color; // flip color after each segment
}
return numAdded;
}
public int getDefaultMargin() {<FILL_FUNCTION_BODY>}
}
|
// CodaBar spec requires a side margin to be more than ten times wider than narrow space.
// This seems like a decent idea for a default for all formats.
return 10;
| 1,260 | 48 | 1,308 |
<no_super_class>
|
zxing_zxing
|
zxing/core/src/main/java/com/google/zxing/oned/UPCAReader.java
|
UPCAReader
|
maybeReturnResult
|
class UPCAReader extends UPCEANReader {
private final UPCEANReader ean13Reader = new EAN13Reader();
@Override
public Result decodeRow(int rowNumber,
BitArray row,
int[] startGuardRange,
Map<DecodeHintType,?> hints)
throws NotFoundException, FormatException, ChecksumException {
return maybeReturnResult(ean13Reader.decodeRow(rowNumber, row, startGuardRange, hints));
}
@Override
public Result decodeRow(int rowNumber, BitArray row, Map<DecodeHintType,?> hints)
throws NotFoundException, FormatException, ChecksumException {
return maybeReturnResult(ean13Reader.decodeRow(rowNumber, row, hints));
}
@Override
public Result decode(BinaryBitmap image) throws NotFoundException, FormatException {
return maybeReturnResult(ean13Reader.decode(image));
}
@Override
public Result decode(BinaryBitmap image, Map<DecodeHintType,?> hints)
throws NotFoundException, FormatException {
return maybeReturnResult(ean13Reader.decode(image, hints));
}
@Override
BarcodeFormat getBarcodeFormat() {
return BarcodeFormat.UPC_A;
}
@Override
protected int decodeMiddle(BitArray row, int[] startRange, StringBuilder resultString)
throws NotFoundException {
return ean13Reader.decodeMiddle(row, startRange, resultString);
}
private static Result maybeReturnResult(Result result) throws FormatException {<FILL_FUNCTION_BODY>}
}
|
String text = result.getText();
if (text.charAt(0) == '0') {
Result upcaResult = new Result(text.substring(1), null, result.getResultPoints(), BarcodeFormat.UPC_A);
if (result.getResultMetadata() != null) {
upcaResult.putAllMetadata(result.getResultMetadata());
}
return upcaResult;
} else {
throw FormatException.getFormatInstance();
}
| 428 | 122 | 550 |
<methods>public com.google.zxing.Result decodeRow(int, com.google.zxing.common.BitArray, Map<com.google.zxing.DecodeHintType,?>) throws com.google.zxing.NotFoundException, com.google.zxing.ChecksumException, com.google.zxing.FormatException,public com.google.zxing.Result decodeRow(int, com.google.zxing.common.BitArray, int[], Map<com.google.zxing.DecodeHintType,?>) throws com.google.zxing.NotFoundException, com.google.zxing.ChecksumException, com.google.zxing.FormatException<variables>static final int[] END_PATTERN,static final non-sealed int[][] L_AND_G_PATTERNS,static final int[][] L_PATTERNS,private static final float MAX_AVG_VARIANCE,private static final float MAX_INDIVIDUAL_VARIANCE,static final int[] MIDDLE_PATTERN,static final int[] START_END_PATTERN,private final non-sealed java.lang.StringBuilder decodeRowStringBuffer,private final non-sealed com.google.zxing.oned.EANManufacturerOrgSupport eanManSupport,private final non-sealed com.google.zxing.oned.UPCEANExtensionSupport extensionReader
|
zxing_zxing
|
zxing/core/src/main/java/com/google/zxing/oned/UPCAWriter.java
|
UPCAWriter
|
encode
|
class UPCAWriter implements Writer {
private final EAN13Writer subWriter = new EAN13Writer();
@Override
public BitMatrix encode(String contents, BarcodeFormat format, int width, int height) {
return encode(contents, format, width, height, null);
}
@Override
public BitMatrix encode(String contents,
BarcodeFormat format,
int width,
int height,
Map<EncodeHintType,?> hints) {<FILL_FUNCTION_BODY>}
}
|
if (format != BarcodeFormat.UPC_A) {
throw new IllegalArgumentException("Can only encode UPC-A, but got " + format);
}
// Transform a UPC-A code into the equivalent EAN-13 code and write it that way
return subWriter.encode('0' + contents, BarcodeFormat.EAN_13, width, height, hints);
| 139 | 100 | 239 |
<no_super_class>
|
zxing_zxing
|
zxing/core/src/main/java/com/google/zxing/oned/UPCEANExtension2Support.java
|
UPCEANExtension2Support
|
decodeRow
|
class UPCEANExtension2Support {
private final int[] decodeMiddleCounters = new int[4];
private final StringBuilder decodeRowStringBuffer = new StringBuilder();
Result decodeRow(int rowNumber, BitArray row, int[] extensionStartRange) throws NotFoundException {<FILL_FUNCTION_BODY>}
private int decodeMiddle(BitArray row, int[] startRange, StringBuilder resultString) throws NotFoundException {
int[] counters = decodeMiddleCounters;
counters[0] = 0;
counters[1] = 0;
counters[2] = 0;
counters[3] = 0;
int end = row.getSize();
int rowOffset = startRange[1];
int checkParity = 0;
for (int x = 0; x < 2 && rowOffset < end; x++) {
int bestMatch = UPCEANReader.decodeDigit(row, counters, rowOffset, UPCEANReader.L_AND_G_PATTERNS);
resultString.append((char) ('0' + bestMatch % 10));
for (int counter : counters) {
rowOffset += counter;
}
if (bestMatch >= 10) {
checkParity |= 1 << (1 - x);
}
if (x != 1) {
// Read off separator if not last
rowOffset = row.getNextSet(rowOffset);
rowOffset = row.getNextUnset(rowOffset);
}
}
if (resultString.length() != 2) {
throw NotFoundException.getNotFoundInstance();
}
if (Integer.parseInt(resultString.toString()) % 4 != checkParity) {
throw NotFoundException.getNotFoundInstance();
}
return rowOffset;
}
/**
* @param raw raw content of extension
* @return formatted interpretation of raw content as a {@link Map} mapping
* one {@link ResultMetadataType} to appropriate value, or {@code null} if not known
*/
private static Map<ResultMetadataType,Object> parseExtensionString(String raw) {
if (raw.length() != 2) {
return null;
}
Map<ResultMetadataType,Object> result = new EnumMap<>(ResultMetadataType.class);
result.put(ResultMetadataType.ISSUE_NUMBER, Integer.valueOf(raw));
return result;
}
}
|
StringBuilder result = decodeRowStringBuffer;
result.setLength(0);
int end = decodeMiddle(row, extensionStartRange, result);
String resultString = result.toString();
Map<ResultMetadataType,Object> extensionData = parseExtensionString(resultString);
Result extensionResult =
new Result(resultString,
null,
new ResultPoint[] {
new ResultPoint((extensionStartRange[0] + extensionStartRange[1]) / 2.0f, rowNumber),
new ResultPoint(end, rowNumber),
},
BarcodeFormat.UPC_EAN_EXTENSION);
if (extensionData != null) {
extensionResult.putAllMetadata(extensionData);
}
return extensionResult;
| 618 | 192 | 810 |
<no_super_class>
|
zxing_zxing
|
zxing/core/src/main/java/com/google/zxing/oned/UPCEANExtension5Support.java
|
UPCEANExtension5Support
|
parseExtension5String
|
class UPCEANExtension5Support {
private static final int[] CHECK_DIGIT_ENCODINGS = {
0x18, 0x14, 0x12, 0x11, 0x0C, 0x06, 0x03, 0x0A, 0x09, 0x05
};
private final int[] decodeMiddleCounters = new int[4];
private final StringBuilder decodeRowStringBuffer = new StringBuilder();
Result decodeRow(int rowNumber, BitArray row, int[] extensionStartRange) throws NotFoundException {
StringBuilder result = decodeRowStringBuffer;
result.setLength(0);
int end = decodeMiddle(row, extensionStartRange, result);
String resultString = result.toString();
Map<ResultMetadataType,Object> extensionData = parseExtensionString(resultString);
Result extensionResult =
new Result(resultString,
null,
new ResultPoint[] {
new ResultPoint((extensionStartRange[0] + extensionStartRange[1]) / 2.0f, rowNumber),
new ResultPoint(end, rowNumber),
},
BarcodeFormat.UPC_EAN_EXTENSION);
if (extensionData != null) {
extensionResult.putAllMetadata(extensionData);
}
return extensionResult;
}
private int decodeMiddle(BitArray row, int[] startRange, StringBuilder resultString) throws NotFoundException {
int[] counters = decodeMiddleCounters;
counters[0] = 0;
counters[1] = 0;
counters[2] = 0;
counters[3] = 0;
int end = row.getSize();
int rowOffset = startRange[1];
int lgPatternFound = 0;
for (int x = 0; x < 5 && rowOffset < end; x++) {
int bestMatch = UPCEANReader.decodeDigit(row, counters, rowOffset, UPCEANReader.L_AND_G_PATTERNS);
resultString.append((char) ('0' + bestMatch % 10));
for (int counter : counters) {
rowOffset += counter;
}
if (bestMatch >= 10) {
lgPatternFound |= 1 << (4 - x);
}
if (x != 4) {
// Read off separator if not last
rowOffset = row.getNextSet(rowOffset);
rowOffset = row.getNextUnset(rowOffset);
}
}
if (resultString.length() != 5) {
throw NotFoundException.getNotFoundInstance();
}
int checkDigit = determineCheckDigit(lgPatternFound);
if (extensionChecksum(resultString.toString()) != checkDigit) {
throw NotFoundException.getNotFoundInstance();
}
return rowOffset;
}
private static int extensionChecksum(CharSequence s) {
int length = s.length();
int sum = 0;
for (int i = length - 2; i >= 0; i -= 2) {
sum += s.charAt(i) - '0';
}
sum *= 3;
for (int i = length - 1; i >= 0; i -= 2) {
sum += s.charAt(i) - '0';
}
sum *= 3;
return sum % 10;
}
private static int determineCheckDigit(int lgPatternFound)
throws NotFoundException {
for (int d = 0; d < 10; d++) {
if (lgPatternFound == CHECK_DIGIT_ENCODINGS[d]) {
return d;
}
}
throw NotFoundException.getNotFoundInstance();
}
/**
* @param raw raw content of extension
* @return formatted interpretation of raw content as a {@link Map} mapping
* one {@link ResultMetadataType} to appropriate value, or {@code null} if not known
*/
private static Map<ResultMetadataType,Object> parseExtensionString(String raw) {
if (raw.length() != 5) {
return null;
}
Object value = parseExtension5String(raw);
if (value == null) {
return null;
}
Map<ResultMetadataType,Object> result = new EnumMap<>(ResultMetadataType.class);
result.put(ResultMetadataType.SUGGESTED_PRICE, value);
return result;
}
private static String parseExtension5String(String raw) {<FILL_FUNCTION_BODY>}
}
|
String currency;
switch (raw.charAt(0)) {
case '0':
currency = "£";
break;
case '5':
currency = "$";
break;
case '9':
// Reference: http://www.jollytech.com
switch (raw) {
case "90000":
// No suggested retail price
return null;
case "99991":
// Complementary
return "0.00";
case "99990":
return "Used";
}
// Otherwise... unknown currency?
currency = "";
break;
default:
currency = "";
break;
}
int rawAmount = Integer.parseInt(raw.substring(1));
String unitsString = String.valueOf(rawAmount / 100);
int hundredths = rawAmount % 100;
String hundredthsString = hundredths < 10 ? "0" + hundredths : String.valueOf(hundredths);
return currency + unitsString + '.' + hundredthsString;
| 1,176 | 274 | 1,450 |
<no_super_class>
|
zxing_zxing
|
zxing/core/src/main/java/com/google/zxing/oned/UPCEANExtensionSupport.java
|
UPCEANExtensionSupport
|
decodeRow
|
class UPCEANExtensionSupport {
private static final int[] EXTENSION_START_PATTERN = {1,1,2};
private final UPCEANExtension2Support twoSupport = new UPCEANExtension2Support();
private final UPCEANExtension5Support fiveSupport = new UPCEANExtension5Support();
Result decodeRow(int rowNumber, BitArray row, int rowOffset) throws NotFoundException {<FILL_FUNCTION_BODY>}
}
|
int[] extensionStartRange = UPCEANReader.findGuardPattern(row, rowOffset, false, EXTENSION_START_PATTERN);
try {
return fiveSupport.decodeRow(rowNumber, row, extensionStartRange);
} catch (ReaderException ignored) {
return twoSupport.decodeRow(rowNumber, row, extensionStartRange);
}
| 117 | 92 | 209 |
<no_super_class>
|
zxing_zxing
|
zxing/core/src/main/java/com/google/zxing/oned/UPCEReader.java
|
UPCEReader
|
convertUPCEtoUPCA
|
class UPCEReader extends UPCEANReader {
/**
* The pattern that marks the middle, and end, of a UPC-E pattern.
* There is no "second half" to a UPC-E barcode.
*/
private static final int[] MIDDLE_END_PATTERN = {1, 1, 1, 1, 1, 1};
// For an UPC-E barcode, the final digit is represented by the parities used
// to encode the middle six digits, according to the table below.
//
// Parity of next 6 digits
// Digit 0 1 2 3 4 5
// 0 Even Even Even Odd Odd Odd
// 1 Even Even Odd Even Odd Odd
// 2 Even Even Odd Odd Even Odd
// 3 Even Even Odd Odd Odd Even
// 4 Even Odd Even Even Odd Odd
// 5 Even Odd Odd Even Even Odd
// 6 Even Odd Odd Odd Even Even
// 7 Even Odd Even Odd Even Odd
// 8 Even Odd Even Odd Odd Even
// 9 Even Odd Odd Even Odd Even
//
// The encoding is represented by the following array, which is a bit pattern
// using Odd = 0 and Even = 1. For example, 5 is represented by:
//
// Odd Even Even Odd Odd Even
// in binary:
// 0 1 1 0 0 1 == 0x19
//
/**
* See {@link #L_AND_G_PATTERNS}; these values similarly represent patterns of
* even-odd parity encodings of digits that imply both the number system (0 or 1)
* used, and the check digit.
*/
static final int[][] NUMSYS_AND_CHECK_DIGIT_PATTERNS = {
{0x38, 0x34, 0x32, 0x31, 0x2C, 0x26, 0x23, 0x2A, 0x29, 0x25},
{0x07, 0x0B, 0x0D, 0x0E, 0x13, 0x19, 0x1C, 0x15, 0x16, 0x1A}
};
private final int[] decodeMiddleCounters;
public UPCEReader() {
decodeMiddleCounters = new int[4];
}
@Override
protected int decodeMiddle(BitArray row, int[] startRange, StringBuilder result)
throws NotFoundException {
int[] counters = decodeMiddleCounters;
counters[0] = 0;
counters[1] = 0;
counters[2] = 0;
counters[3] = 0;
int end = row.getSize();
int rowOffset = startRange[1];
int lgPatternFound = 0;
for (int x = 0; x < 6 && rowOffset < end; x++) {
int bestMatch = decodeDigit(row, counters, rowOffset, L_AND_G_PATTERNS);
result.append((char) ('0' + bestMatch % 10));
for (int counter : counters) {
rowOffset += counter;
}
if (bestMatch >= 10) {
lgPatternFound |= 1 << (5 - x);
}
}
determineNumSysAndCheckDigit(result, lgPatternFound);
return rowOffset;
}
@Override
protected int[] decodeEnd(BitArray row, int endStart) throws NotFoundException {
return findGuardPattern(row, endStart, true, MIDDLE_END_PATTERN);
}
@Override
protected boolean checkChecksum(String s) throws FormatException {
return super.checkChecksum(convertUPCEtoUPCA(s));
}
private static void determineNumSysAndCheckDigit(StringBuilder resultString, int lgPatternFound)
throws NotFoundException {
for (int numSys = 0; numSys <= 1; numSys++) {
for (int d = 0; d < 10; d++) {
if (lgPatternFound == NUMSYS_AND_CHECK_DIGIT_PATTERNS[numSys][d]) {
resultString.insert(0, (char) ('0' + numSys));
resultString.append((char) ('0' + d));
return;
}
}
}
throw NotFoundException.getNotFoundInstance();
}
@Override
BarcodeFormat getBarcodeFormat() {
return BarcodeFormat.UPC_E;
}
/**
* Expands a UPC-E value back into its full, equivalent UPC-A code value.
*
* @param upce UPC-E code as string of digits
* @return equivalent UPC-A code as string of digits
*/
public static String convertUPCEtoUPCA(String upce) {<FILL_FUNCTION_BODY>}
}
|
char[] upceChars = new char[6];
upce.getChars(1, 7, upceChars, 0);
StringBuilder result = new StringBuilder(12);
result.append(upce.charAt(0));
char lastChar = upceChars[5];
switch (lastChar) {
case '0':
case '1':
case '2':
result.append(upceChars, 0, 2);
result.append(lastChar);
result.append("0000");
result.append(upceChars, 2, 3);
break;
case '3':
result.append(upceChars, 0, 3);
result.append("00000");
result.append(upceChars, 3, 2);
break;
case '4':
result.append(upceChars, 0, 4);
result.append("00000");
result.append(upceChars[4]);
break;
default:
result.append(upceChars, 0, 5);
result.append("0000");
result.append(lastChar);
break;
}
// Only append check digit in conversion if supplied
if (upce.length() >= 8) {
result.append(upce.charAt(7));
}
return result.toString();
| 1,390 | 367 | 1,757 |
<methods>public com.google.zxing.Result decodeRow(int, com.google.zxing.common.BitArray, Map<com.google.zxing.DecodeHintType,?>) throws com.google.zxing.NotFoundException, com.google.zxing.ChecksumException, com.google.zxing.FormatException,public com.google.zxing.Result decodeRow(int, com.google.zxing.common.BitArray, int[], Map<com.google.zxing.DecodeHintType,?>) throws com.google.zxing.NotFoundException, com.google.zxing.ChecksumException, com.google.zxing.FormatException<variables>static final int[] END_PATTERN,static final non-sealed int[][] L_AND_G_PATTERNS,static final int[][] L_PATTERNS,private static final float MAX_AVG_VARIANCE,private static final float MAX_INDIVIDUAL_VARIANCE,static final int[] MIDDLE_PATTERN,static final int[] START_END_PATTERN,private final non-sealed java.lang.StringBuilder decodeRowStringBuffer,private final non-sealed com.google.zxing.oned.EANManufacturerOrgSupport eanManSupport,private final non-sealed com.google.zxing.oned.UPCEANExtensionSupport extensionReader
|
zxing_zxing
|
zxing/core/src/main/java/com/google/zxing/oned/UPCEWriter.java
|
UPCEWriter
|
encode
|
class UPCEWriter extends UPCEANWriter {
private static final int CODE_WIDTH = 3 + // start guard
(7 * 6) + // bars
6; // end guard
@Override
protected Collection<BarcodeFormat> getSupportedWriteFormats() {
return Collections.singleton(BarcodeFormat.UPC_E);
}
@Override
public boolean[] encode(String contents) {<FILL_FUNCTION_BODY>}
}
|
int length = contents.length();
switch (length) {
case 7:
// No check digit present, calculate it and add it
int check;
try {
check = UPCEANReader.getStandardUPCEANChecksum(UPCEReader.convertUPCEtoUPCA(contents));
} catch (FormatException fe) {
throw new IllegalArgumentException(fe);
}
contents += check;
break;
case 8:
try {
if (!UPCEANReader.checkStandardUPCEANChecksum(UPCEReader.convertUPCEtoUPCA(contents))) {
throw new IllegalArgumentException("Contents do not pass checksum");
}
} catch (FormatException ignored) {
throw new IllegalArgumentException("Illegal contents");
}
break;
default:
throw new IllegalArgumentException(
"Requested contents should be 7 or 8 digits long, but got " + length);
}
checkNumeric(contents);
int firstDigit = Character.digit(contents.charAt(0), 10);
if (firstDigit != 0 && firstDigit != 1) {
throw new IllegalArgumentException("Number system must be 0 or 1");
}
int checkDigit = Character.digit(contents.charAt(7), 10);
int parities = UPCEReader.NUMSYS_AND_CHECK_DIGIT_PATTERNS[firstDigit][checkDigit];
boolean[] result = new boolean[CODE_WIDTH];
int pos = appendPattern(result, 0, UPCEANReader.START_END_PATTERN, true);
for (int i = 1; i <= 6; i++) {
int digit = Character.digit(contents.charAt(i), 10);
if ((parities >> (6 - i) & 1) == 1) {
digit += 10;
}
pos += appendPattern(result, pos, UPCEANReader.L_AND_G_PATTERNS[digit], false);
}
appendPattern(result, pos, UPCEANReader.END_PATTERN, false);
return result;
| 123 | 548 | 671 |
<methods>public non-sealed void <init>() ,public int getDefaultMargin() <variables>
|
zxing_zxing
|
zxing/core/src/main/java/com/google/zxing/oned/rss/AbstractRSSReader.java
|
AbstractRSSReader
|
isFinderPattern
|
class AbstractRSSReader extends OneDReader {
private static final float MAX_AVG_VARIANCE = 0.2f;
private static final float MAX_INDIVIDUAL_VARIANCE = 0.45f;
/** Minimum ratio 10:12 (minus 0.5 for variance), from section 7.2.7 of ISO/IEC 24724:2006. */
private static final float MIN_FINDER_PATTERN_RATIO = 9.5f / 12.0f;
/** Maximum ratio 12:14 (plus 0.5 for variance), from section 7.2.7 of ISO/IEC 24724:2006. */
private static final float MAX_FINDER_PATTERN_RATIO = 12.5f / 14.0f;
private final int[] decodeFinderCounters;
private final int[] dataCharacterCounters;
private final float[] oddRoundingErrors;
private final float[] evenRoundingErrors;
private final int[] oddCounts;
private final int[] evenCounts;
protected AbstractRSSReader() {
decodeFinderCounters = new int[4];
dataCharacterCounters = new int[8];
oddRoundingErrors = new float[4];
evenRoundingErrors = new float[4];
oddCounts = new int[dataCharacterCounters.length / 2];
evenCounts = new int[dataCharacterCounters.length / 2];
}
protected final int[] getDecodeFinderCounters() {
return decodeFinderCounters;
}
protected final int[] getDataCharacterCounters() {
return dataCharacterCounters;
}
protected final float[] getOddRoundingErrors() {
return oddRoundingErrors;
}
protected final float[] getEvenRoundingErrors() {
return evenRoundingErrors;
}
protected final int[] getOddCounts() {
return oddCounts;
}
protected final int[] getEvenCounts() {
return evenCounts;
}
protected static int parseFinderValue(int[] counters,
int[][] finderPatterns) throws NotFoundException {
for (int value = 0; value < finderPatterns.length; value++) {
if (patternMatchVariance(counters, finderPatterns[value], MAX_INDIVIDUAL_VARIANCE) <
MAX_AVG_VARIANCE) {
return value;
}
}
throw NotFoundException.getNotFoundInstance();
}
/**
* @param array values to sum
* @return sum of values
* @deprecated call {@link MathUtils#sum(int[])}
*/
@Deprecated
protected static int count(int[] array) {
return MathUtils.sum(array);
}
protected static void increment(int[] array, float[] errors) {
int index = 0;
float biggestError = errors[0];
for (int i = 1; i < array.length; i++) {
if (errors[i] > biggestError) {
biggestError = errors[i];
index = i;
}
}
array[index]++;
}
protected static void decrement(int[] array, float[] errors) {
int index = 0;
float biggestError = errors[0];
for (int i = 1; i < array.length; i++) {
if (errors[i] < biggestError) {
biggestError = errors[i];
index = i;
}
}
array[index]--;
}
protected static boolean isFinderPattern(int[] counters) {<FILL_FUNCTION_BODY>}
}
|
int firstTwoSum = counters[0] + counters[1];
int sum = firstTwoSum + counters[2] + counters[3];
float ratio = firstTwoSum / (float) sum;
if (ratio >= MIN_FINDER_PATTERN_RATIO && ratio <= MAX_FINDER_PATTERN_RATIO) {
// passes ratio test in spec, but see if the counts are unreasonable
int minCounter = Integer.MAX_VALUE;
int maxCounter = Integer.MIN_VALUE;
for (int counter : counters) {
if (counter > maxCounter) {
maxCounter = counter;
}
if (counter < minCounter) {
minCounter = counter;
}
}
return maxCounter < 10 * minCounter;
}
return false;
| 956 | 208 | 1,164 |
<methods>public non-sealed void <init>() ,public com.google.zxing.Result decode(com.google.zxing.BinaryBitmap) throws com.google.zxing.NotFoundException, com.google.zxing.FormatException,public com.google.zxing.Result decode(com.google.zxing.BinaryBitmap, Map<com.google.zxing.DecodeHintType,?>) throws com.google.zxing.NotFoundException, com.google.zxing.FormatException,public abstract com.google.zxing.Result decodeRow(int, com.google.zxing.common.BitArray, Map<com.google.zxing.DecodeHintType,?>) throws com.google.zxing.NotFoundException, com.google.zxing.ChecksumException, com.google.zxing.FormatException,public void reset() <variables>
|
zxing_zxing
|
zxing/core/src/main/java/com/google/zxing/oned/rss/DataCharacter.java
|
DataCharacter
|
equals
|
class DataCharacter {
private final int value;
private final int checksumPortion;
public DataCharacter(int value, int checksumPortion) {
this.value = value;
this.checksumPortion = checksumPortion;
}
public final int getValue() {
return value;
}
public final int getChecksumPortion() {
return checksumPortion;
}
@Override
public final String toString() {
return value + "(" + checksumPortion + ')';
}
@Override
public final boolean equals(Object o) {<FILL_FUNCTION_BODY>}
@Override
public final int hashCode() {
return value ^ checksumPortion;
}
}
|
if (!(o instanceof DataCharacter)) {
return false;
}
DataCharacter that = (DataCharacter) o;
return value == that.value && checksumPortion == that.checksumPortion;
| 200 | 56 | 256 |
<no_super_class>
|
zxing_zxing
|
zxing/core/src/main/java/com/google/zxing/oned/rss/FinderPattern.java
|
FinderPattern
|
equals
|
class FinderPattern {
private final int value;
private final int[] startEnd;
private final ResultPoint[] resultPoints;
public FinderPattern(int value, int[] startEnd, int start, int end, int rowNumber) {
this.value = value;
this.startEnd = startEnd;
this.resultPoints = new ResultPoint[] {
new ResultPoint(start, rowNumber),
new ResultPoint(end, rowNumber),
};
}
public int getValue() {
return value;
}
public int[] getStartEnd() {
return startEnd;
}
public ResultPoint[] getResultPoints() {
return resultPoints;
}
@Override
public boolean equals(Object o) {<FILL_FUNCTION_BODY>}
@Override
public int hashCode() {
return value;
}
}
|
if (!(o instanceof FinderPattern)) {
return false;
}
FinderPattern that = (FinderPattern) o;
return value == that.value;
| 225 | 44 | 269 |
<no_super_class>
|
zxing_zxing
|
zxing/core/src/main/java/com/google/zxing/oned/rss/RSSUtils.java
|
RSSUtils
|
getRSSvalue
|
class RSSUtils {
private RSSUtils() {}
public static int getRSSvalue(int[] widths, int maxWidth, boolean noNarrow) {<FILL_FUNCTION_BODY>}
private static int combins(int n, int r) {
int maxDenom;
int minDenom;
if (n - r > r) {
minDenom = r;
maxDenom = n - r;
} else {
minDenom = n - r;
maxDenom = r;
}
int val = 1;
int j = 1;
for (int i = n; i > maxDenom; i--) {
val *= i;
if (j <= minDenom) {
val /= j;
j++;
}
}
while (j <= minDenom) {
val /= j;
j++;
}
return val;
}
}
|
int n = 0;
for (int width : widths) {
n += width;
}
int val = 0;
int narrowMask = 0;
int elements = widths.length;
for (int bar = 0; bar < elements - 1; bar++) {
int elmWidth;
for (elmWidth = 1, narrowMask |= 1 << bar;
elmWidth < widths[bar];
elmWidth++, narrowMask &= ~(1 << bar)) {
int subVal = combins(n - elmWidth - 1, elements - bar - 2);
if (noNarrow && (narrowMask == 0) &&
(n - elmWidth - (elements - bar - 1) >= elements - bar - 1)) {
subVal -= combins(n - elmWidth - (elements - bar),
elements - bar - 2);
}
if (elements - bar - 1 > 1) {
int lessVal = 0;
for (int mxwElement = n - elmWidth - (elements - bar - 2);
mxwElement > maxWidth; mxwElement--) {
lessVal += combins(n - elmWidth - mxwElement - 1,
elements - bar - 3);
}
subVal -= lessVal * (elements - 1 - bar);
} else if (n - elmWidth > maxWidth) {
subVal--;
}
val += subVal;
}
n -= elmWidth;
}
return val;
| 244 | 394 | 638 |
<no_super_class>
|
zxing_zxing
|
zxing/core/src/main/java/com/google/zxing/oned/rss/expanded/BitArrayBuilder.java
|
BitArrayBuilder
|
buildBitArray
|
class BitArrayBuilder {
private BitArrayBuilder() {
}
static BitArray buildBitArray(List<ExpandedPair> pairs) {<FILL_FUNCTION_BODY>}
}
|
int charNumber = (pairs.size() * 2) - 1;
if (pairs.get(pairs.size() - 1).getRightChar() == null) {
charNumber -= 1;
}
int size = 12 * charNumber;
BitArray binary = new BitArray(size);
int accPos = 0;
ExpandedPair firstPair = pairs.get(0);
int firstValue = firstPair.getRightChar().getValue();
for (int i = 11; i >= 0; --i) {
if ((firstValue & (1 << i)) != 0) {
binary.set(accPos);
}
accPos++;
}
for (int i = 1; i < pairs.size(); ++i) {
ExpandedPair currentPair = pairs.get(i);
int leftValue = currentPair.getLeftChar().getValue();
for (int j = 11; j >= 0; --j) {
if ((leftValue & (1 << j)) != 0) {
binary.set(accPos);
}
accPos++;
}
if (currentPair.getRightChar() != null) {
int rightValue = currentPair.getRightChar().getValue();
for (int j = 11; j >= 0; --j) {
if ((rightValue & (1 << j)) != 0) {
binary.set(accPos);
}
accPos++;
}
}
}
return binary;
| 51 | 384 | 435 |
<no_super_class>
|
zxing_zxing
|
zxing/core/src/main/java/com/google/zxing/oned/rss/expanded/ExpandedPair.java
|
ExpandedPair
|
toString
|
class ExpandedPair {
private final DataCharacter leftChar;
private final DataCharacter rightChar;
private final FinderPattern finderPattern;
ExpandedPair(DataCharacter leftChar,
DataCharacter rightChar,
FinderPattern finderPattern) {
this.leftChar = leftChar;
this.rightChar = rightChar;
this.finderPattern = finderPattern;
}
DataCharacter getLeftChar() {
return this.leftChar;
}
DataCharacter getRightChar() {
return this.rightChar;
}
FinderPattern getFinderPattern() {
return this.finderPattern;
}
boolean mustBeLast() {
return this.rightChar == null;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
@Override
public boolean equals(Object o) {
if (!(o instanceof ExpandedPair)) {
return false;
}
ExpandedPair that = (ExpandedPair) o;
return Objects.equals(leftChar, that.leftChar) &&
Objects.equals(rightChar, that.rightChar) &&
Objects.equals(finderPattern, that.finderPattern);
}
@Override
public int hashCode() {
return Objects.hashCode(leftChar) ^ Objects.hashCode(rightChar) ^ Objects.hashCode(finderPattern);
}
}
|
return
"[ " + leftChar + " , " + rightChar + " : " +
(finderPattern == null ? "null" : finderPattern.getValue()) + " ]";
| 364 | 48 | 412 |
<no_super_class>
|
zxing_zxing
|
zxing/core/src/main/java/com/google/zxing/oned/rss/expanded/ExpandedRow.java
|
ExpandedRow
|
equals
|
class ExpandedRow {
private final List<ExpandedPair> pairs;
private final int rowNumber;
ExpandedRow(List<ExpandedPair> pairs, int rowNumber) {
this.pairs = new ArrayList<>(pairs);
this.rowNumber = rowNumber;
}
List<ExpandedPair> getPairs() {
return this.pairs;
}
int getRowNumber() {
return this.rowNumber;
}
boolean isEquivalent(List<ExpandedPair> otherPairs) {
return this.pairs.equals(otherPairs);
}
@Override
public String toString() {
return "{ " + pairs + " }";
}
/**
* Two rows are equal if they contain the same pairs in the same order.
*/
@Override
public boolean equals(Object o) {<FILL_FUNCTION_BODY>}
@Override
public int hashCode() {
return pairs.hashCode();
}
}
|
if (!(o instanceof ExpandedRow)) {
return false;
}
ExpandedRow that = (ExpandedRow) o;
return this.pairs.equals(that.pairs);
| 261 | 52 | 313 |
<no_super_class>
|
zxing_zxing
|
zxing/core/src/main/java/com/google/zxing/oned/rss/expanded/decoders/AI01320xDecoder.java
|
AI01320xDecoder
|
checkWeight
|
class AI01320xDecoder extends AI013x0xDecoder {
AI01320xDecoder(BitArray information) {
super(information);
}
@Override
protected void addWeightCode(StringBuilder buf, int weight) {
if (weight < 10000) {
buf.append("(3202)");
} else {
buf.append("(3203)");
}
}
@Override
protected int checkWeight(int weight) {<FILL_FUNCTION_BODY>}
}
|
if (weight < 10000) {
return weight;
}
return weight - 10000;
| 151 | 36 | 187 |
<methods>public java.lang.String parseInformation() throws com.google.zxing.NotFoundException<variables>private static final int HEADER_SIZE,private static final int WEIGHT_SIZE
|
zxing_zxing
|
zxing/core/src/main/java/com/google/zxing/oned/rss/expanded/decoders/AI01392xDecoder.java
|
AI01392xDecoder
|
parseInformation
|
class AI01392xDecoder extends AI01decoder {
private static final int HEADER_SIZE = 5 + 1 + 2;
private static final int LAST_DIGIT_SIZE = 2;
AI01392xDecoder(BitArray information) {
super(information);
}
@Override
public String parseInformation() throws NotFoundException, FormatException {<FILL_FUNCTION_BODY>}
}
|
if (this.getInformation().getSize() < HEADER_SIZE + GTIN_SIZE) {
throw NotFoundException.getNotFoundInstance();
}
StringBuilder buf = new StringBuilder();
encodeCompressedGtin(buf, HEADER_SIZE);
int lastAIdigit =
this.getGeneralDecoder().extractNumericValueFromBitArray(HEADER_SIZE + GTIN_SIZE, LAST_DIGIT_SIZE);
buf.append("(392");
buf.append(lastAIdigit);
buf.append(')');
DecodedInformation decodedInformation =
this.getGeneralDecoder().decodeGeneralPurposeField(HEADER_SIZE + GTIN_SIZE + LAST_DIGIT_SIZE, null);
buf.append(decodedInformation.getNewString());
return buf.toString();
| 116 | 218 | 334 |
<methods><variables>static final int GTIN_SIZE
|
zxing_zxing
|
zxing/core/src/main/java/com/google/zxing/oned/rss/expanded/decoders/AI01393xDecoder.java
|
AI01393xDecoder
|
parseInformation
|
class AI01393xDecoder extends AI01decoder {
private static final int HEADER_SIZE = 5 + 1 + 2;
private static final int LAST_DIGIT_SIZE = 2;
private static final int FIRST_THREE_DIGITS_SIZE = 10;
AI01393xDecoder(BitArray information) {
super(information);
}
@Override
public String parseInformation() throws NotFoundException, FormatException {<FILL_FUNCTION_BODY>}
}
|
if (this.getInformation().getSize() < HEADER_SIZE + GTIN_SIZE) {
throw NotFoundException.getNotFoundInstance();
}
StringBuilder buf = new StringBuilder();
encodeCompressedGtin(buf, HEADER_SIZE);
int lastAIdigit =
this.getGeneralDecoder().extractNumericValueFromBitArray(HEADER_SIZE + GTIN_SIZE, LAST_DIGIT_SIZE);
buf.append("(393");
buf.append(lastAIdigit);
buf.append(')');
int firstThreeDigits = this.getGeneralDecoder().extractNumericValueFromBitArray(
HEADER_SIZE + GTIN_SIZE + LAST_DIGIT_SIZE, FIRST_THREE_DIGITS_SIZE);
if (firstThreeDigits / 100 == 0) {
buf.append('0');
}
if (firstThreeDigits / 10 == 0) {
buf.append('0');
}
buf.append(firstThreeDigits);
DecodedInformation generalInformation = this.getGeneralDecoder().decodeGeneralPurposeField(
HEADER_SIZE + GTIN_SIZE + LAST_DIGIT_SIZE + FIRST_THREE_DIGITS_SIZE, null);
buf.append(generalInformation.getNewString());
return buf.toString();
| 137 | 357 | 494 |
<methods><variables>static final int GTIN_SIZE
|
zxing_zxing
|
zxing/core/src/main/java/com/google/zxing/oned/rss/expanded/decoders/AI013x0x1xDecoder.java
|
AI013x0x1xDecoder
|
parseInformation
|
class AI013x0x1xDecoder extends AI01weightDecoder {
private static final int HEADER_SIZE = 7 + 1;
private static final int WEIGHT_SIZE = 20;
private static final int DATE_SIZE = 16;
private final String dateCode;
private final String firstAIdigits;
AI013x0x1xDecoder(BitArray information, String firstAIdigits, String dateCode) {
super(information);
this.dateCode = dateCode;
this.firstAIdigits = firstAIdigits;
}
@Override
public String parseInformation() throws NotFoundException {<FILL_FUNCTION_BODY>}
private void encodeCompressedDate(StringBuilder buf, int currentPos) {
int numericDate = this.getGeneralDecoder().extractNumericValueFromBitArray(currentPos, DATE_SIZE);
if (numericDate == 38400) {
return;
}
buf.append('(');
buf.append(this.dateCode);
buf.append(')');
int day = numericDate % 32;
numericDate /= 32;
int month = numericDate % 12 + 1;
numericDate /= 12;
int year = numericDate;
if (year / 10 == 0) {
buf.append('0');
}
buf.append(year);
if (month / 10 == 0) {
buf.append('0');
}
buf.append(month);
if (day / 10 == 0) {
buf.append('0');
}
buf.append(day);
}
@Override
protected void addWeightCode(StringBuilder buf, int weight) {
buf.append('(');
buf.append(this.firstAIdigits);
buf.append(weight / 100000);
buf.append(')');
}
@Override
protected int checkWeight(int weight) {
return weight % 100000;
}
}
|
if (this.getInformation().getSize() != HEADER_SIZE + GTIN_SIZE + WEIGHT_SIZE + DATE_SIZE) {
throw NotFoundException.getNotFoundInstance();
}
StringBuilder buf = new StringBuilder();
encodeCompressedGtin(buf, HEADER_SIZE);
encodeCompressedWeight(buf, HEADER_SIZE + GTIN_SIZE, WEIGHT_SIZE);
encodeCompressedDate(buf, HEADER_SIZE + GTIN_SIZE + WEIGHT_SIZE);
return buf.toString();
| 543 | 140 | 683 |
<no_super_class>
|
zxing_zxing
|
zxing/core/src/main/java/com/google/zxing/oned/rss/expanded/decoders/AI013x0xDecoder.java
|
AI013x0xDecoder
|
parseInformation
|
class AI013x0xDecoder extends AI01weightDecoder {
private static final int HEADER_SIZE = 4 + 1;
private static final int WEIGHT_SIZE = 15;
AI013x0xDecoder(BitArray information) {
super(information);
}
@Override
public String parseInformation() throws NotFoundException {<FILL_FUNCTION_BODY>}
}
|
if (this.getInformation().getSize() != HEADER_SIZE + GTIN_SIZE + WEIGHT_SIZE) {
throw NotFoundException.getNotFoundInstance();
}
StringBuilder buf = new StringBuilder();
encodeCompressedGtin(buf, HEADER_SIZE);
encodeCompressedWeight(buf, HEADER_SIZE + GTIN_SIZE, WEIGHT_SIZE);
return buf.toString();
| 108 | 110 | 218 |
<no_super_class>
|
zxing_zxing
|
zxing/core/src/main/java/com/google/zxing/oned/rss/expanded/decoders/AI01AndOtherAIs.java
|
AI01AndOtherAIs
|
parseInformation
|
class AI01AndOtherAIs extends AI01decoder {
private static final int HEADER_SIZE = 1 + 1 + 2; //first bit encodes the linkage flag,
//the second one is the encodation method, and the other two are for the variable length
AI01AndOtherAIs(BitArray information) {
super(information);
}
@Override
public String parseInformation() throws NotFoundException, FormatException {<FILL_FUNCTION_BODY>}
}
|
StringBuilder buff = new StringBuilder();
buff.append("(01)");
int initialGtinPosition = buff.length();
int firstGtinDigit = this.getGeneralDecoder().extractNumericValueFromBitArray(HEADER_SIZE, 4);
buff.append(firstGtinDigit);
this.encodeCompressedGtinWithoutAI(buff, HEADER_SIZE + 4, initialGtinPosition);
return this.getGeneralDecoder().decodeAllCodes(buff, HEADER_SIZE + 44);
| 125 | 142 | 267 |
<methods><variables>static final int GTIN_SIZE
|
zxing_zxing
|
zxing/core/src/main/java/com/google/zxing/oned/rss/expanded/decoders/AI01decoder.java
|
AI01decoder
|
appendCheckDigit
|
class AI01decoder extends AbstractExpandedDecoder {
static final int GTIN_SIZE = 40;
AI01decoder(BitArray information) {
super(information);
}
final void encodeCompressedGtin(StringBuilder buf, int currentPos) {
buf.append("(01)");
int initialPosition = buf.length();
buf.append('9');
encodeCompressedGtinWithoutAI(buf, currentPos, initialPosition);
}
final void encodeCompressedGtinWithoutAI(StringBuilder buf, int currentPos, int initialBufferPosition) {
for (int i = 0; i < 4; ++i) {
int currentBlock = this.getGeneralDecoder().extractNumericValueFromBitArray(currentPos + 10 * i, 10);
if (currentBlock / 100 == 0) {
buf.append('0');
}
if (currentBlock / 10 == 0) {
buf.append('0');
}
buf.append(currentBlock);
}
appendCheckDigit(buf, initialBufferPosition);
}
private static void appendCheckDigit(StringBuilder buf, int currentPos) {<FILL_FUNCTION_BODY>}
}
|
int checkDigit = 0;
for (int i = 0; i < 13; i++) {
int digit = buf.charAt(i + currentPos) - '0';
checkDigit += (i & 0x01) == 0 ? 3 * digit : digit;
}
checkDigit = 10 - (checkDigit % 10);
if (checkDigit == 10) {
checkDigit = 0;
}
buf.append(checkDigit);
| 318 | 130 | 448 |
<methods>public static com.google.zxing.oned.rss.expanded.decoders.AbstractExpandedDecoder createDecoder(com.google.zxing.common.BitArray) ,public abstract java.lang.String parseInformation() throws com.google.zxing.NotFoundException, com.google.zxing.FormatException<variables>private final non-sealed com.google.zxing.oned.rss.expanded.decoders.GeneralAppIdDecoder generalDecoder,private final non-sealed com.google.zxing.common.BitArray information
|
zxing_zxing
|
zxing/core/src/main/java/com/google/zxing/oned/rss/expanded/decoders/AI01weightDecoder.java
|
AI01weightDecoder
|
encodeCompressedWeight
|
class AI01weightDecoder extends AI01decoder {
AI01weightDecoder(BitArray information) {
super(information);
}
final void encodeCompressedWeight(StringBuilder buf, int currentPos, int weightSize) {<FILL_FUNCTION_BODY>}
protected abstract void addWeightCode(StringBuilder buf, int weight);
protected abstract int checkWeight(int weight);
}
|
int originalWeightNumeric = this.getGeneralDecoder().extractNumericValueFromBitArray(currentPos, weightSize);
addWeightCode(buf, originalWeightNumeric);
int weightNumeric = checkWeight(originalWeightNumeric);
int currentDivisor = 100000;
for (int i = 0; i < 5; ++i) {
if (weightNumeric / currentDivisor == 0) {
buf.append('0');
}
currentDivisor /= 10;
}
buf.append(weightNumeric);
| 106 | 143 | 249 |
<methods><variables>static final int GTIN_SIZE
|
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);
| 168 | 561 | 729 |
<no_super_class>
|
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());
| 1,302 | 50 | 1,352 |
<no_super_class>
|
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);
| 976 | 610 | 1,586 |
<no_super_class>
|
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);
| 285 | 48 | 333 |
<no_super_class>
|
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);
| 892 | 338 | 1,230 |
<no_super_class>
|
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;
| 389 | 34 | 423 |
<no_super_class>
|
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;
| 434 | 204 | 638 |
<no_super_class>
|
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;
| 818 | 309 | 1,127 |
<no_super_class>
|
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;
| 1,324 | 532 | 1,856 |
<no_super_class>
|
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];
| 653 | 30 | 683 |
<no_super_class>
|
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);
| 1,813 | 84 | 1,897 |
<no_super_class>
|
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;
| 332 | 91 | 423 |
<no_super_class>
|
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;
| 401 | 58 | 459 |
<no_super_class>
|
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;
| 1,112 | 853 | 1,965 |
<no_super_class>
|
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;
| 535 | 461 | 996 |
<no_super_class>
|
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;
| 313 | 795 | 1,108 |
<no_super_class>
|
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;
| 1,334 | 350 | 1,684 |
<no_super_class>
|
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;
| 1,168 | 347 | 1,515 |
<no_super_class>
|
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.
| 170 | 77 | 247 |
<no_super_class>
|
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;
| 312 | 80 | 392 |
<methods>public void <init>(float, float) ,public static float distance(com.google.zxing.ResultPoint, com.google.zxing.ResultPoint) ,public final boolean equals(java.lang.Object) ,public final float getX() ,public final float getY() ,public final int hashCode() ,public static void orderBestPatterns(com.google.zxing.ResultPoint[]) ,public final java.lang.String toString() <variables>private final non-sealed float x,private final non-sealed float y
|
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);
| 407 | 94 | 501 |
<methods>public void <init>(float, float) ,public static float distance(com.google.zxing.ResultPoint, com.google.zxing.ResultPoint) ,public final boolean equals(java.lang.Object) ,public final float getX() ,public final float getY() ,public final int hashCode() ,public static void orderBestPatterns(com.google.zxing.ResultPoint[]) ,public final java.lang.String toString() <variables>private final non-sealed float x,private final non-sealed float y
|
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();
| 363 | 155 | 518 |
<no_super_class>
|
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();
| 817 | 98 | 915 |
<no_super_class>
|
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();
| 415 | 168 | 583 |
<no_super_class>
|
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);
| 1,727 | 33 | 1,760 |
<methods>public com.google.zxing.LuminanceSource crop(int, int, int, int) ,public final int getHeight() ,public abstract byte[] getMatrix() ,public abstract byte[] getRow(int, byte[]) ,public final int getWidth() ,public com.google.zxing.LuminanceSource invert() ,public boolean isCropSupported() ,public boolean isRotateSupported() ,public com.google.zxing.LuminanceSource rotateCounterClockwise() ,public com.google.zxing.LuminanceSource rotateCounterClockwise45() ,public final java.lang.String toString() <variables>private final non-sealed int height,private final non-sealed int width
|
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));
| 50 | 294 | 344 |
<no_super_class>
|
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");
}
| 560 | 572 | 1,132 |
<no_super_class>
|
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);
| 556 | 435 | 991 |
<no_super_class>
|
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());
| 487 | 148 | 635 |
<methods>public void <init>() throws java.awt.HeadlessException,public void <init>(java.awt.GraphicsConfiguration) ,public void <init>(java.lang.String) throws java.awt.HeadlessException,public void <init>(java.lang.String, java.awt.GraphicsConfiguration) ,public javax.accessibility.AccessibleContext getAccessibleContext() ,public java.awt.Container getContentPane() ,public int getDefaultCloseOperation() ,public java.awt.Component getGlassPane() ,public java.awt.Graphics getGraphics() ,public javax.swing.JMenuBar getJMenuBar() ,public javax.swing.JLayeredPane getLayeredPane() ,public javax.swing.JRootPane getRootPane() ,public javax.swing.TransferHandler getTransferHandler() ,public static boolean isDefaultLookAndFeelDecorated() ,public void remove(java.awt.Component) ,public void repaint(long, int, int, int, int) ,public void setContentPane(java.awt.Container) ,public void setDefaultCloseOperation(int) ,public static void setDefaultLookAndFeelDecorated(boolean) ,public void setGlassPane(java.awt.Component) ,public void setIconImage(java.awt.Image) ,public void setJMenuBar(javax.swing.JMenuBar) ,public void setLayeredPane(javax.swing.JLayeredPane) ,public void setLayout(java.awt.LayoutManager) ,public void setTransferHandler(javax.swing.TransferHandler) ,public void update(java.awt.Graphics) <variables>protected javax.accessibility.AccessibleContext accessibleContext,private int defaultCloseOperation,private static final java.lang.Object defaultLookAndFeelDecoratedKey,protected javax.swing.JRootPane rootPane,protected boolean rootPaneCheckingEnabled,private javax.swing.TransferHandler transferHandler
|
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);
}
}
| 1,588 | 201 | 1,789 |
<no_super_class>
|
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;
| 256 | 120 | 376 |
<no_super_class>
|
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;
| 332 | 129 | 461 |
<no_super_class>
|
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);
}
| 1,307 | 56 | 1,363 |
<no_super_class>
|
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);
| 932 | 565 | 1,497 |
<no_super_class>
|
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);
| 400 | 315 | 715 |
<no_super_class>
|
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;
}
}
}
| 91 | 598 | 689 |
<no_super_class>
|
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);
}
| 86 | 99 | 185 |
<methods>public final void destroy() ,public final void init(FilterConfig) <variables>
|
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();
| 137 | 170 | 307 |
<no_super_class>
|
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);
}
| 117 | 107 | 224 |
<methods>public abstract void close() throws java.lang.SecurityException,public abstract void flush() ,public java.lang.String getEncoding() ,public java.util.logging.ErrorManager getErrorManager() ,public java.util.logging.Filter getFilter() ,public java.util.logging.Formatter getFormatter() ,public java.util.logging.Level getLevel() ,public boolean isLoggable(java.util.logging.LogRecord) ,public abstract void publish(java.util.logging.LogRecord) ,public synchronized void setEncoding(java.lang.String) throws java.lang.SecurityException, java.io.UnsupportedEncodingException,public synchronized void setErrorManager(java.util.logging.ErrorManager) ,public synchronized void setFilter(java.util.logging.Filter) throws java.lang.SecurityException,public synchronized void setFormatter(java.util.logging.Formatter) throws java.lang.SecurityException,public synchronized void setLevel(java.util.logging.Level) throws java.lang.SecurityException<variables>private volatile java.lang.String encoding,private volatile java.util.logging.ErrorManager errorManager,private volatile java.util.logging.Filter filter,private volatile java.util.logging.Formatter formatter,private volatile java.util.logging.Level logLevel,private final java.util.logging.LogManager manager,private static final int offValue
|
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());
}
| 203 | 227 | 430 |
<no_super_class>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.