Attempts to estimate the qr-code's version based on distance between position patterns.
If it can't estimate it based on distance return -1
329096
int estimateVersionBySize( QrCode qr ) {
		// Just need the homography for this corner square square
		gridReader.setMarkerUnknownVersion(qr,0);

		// Compute location of position patterns relative to corner PP
		gridReader.imageToGrid(qr.ppRight.get(0),grid);

		// see if pp is miss aligned. Probably not a flat surface
		// or they don't belong to the same qr code
		if( Math.abs(grid.y/grid.x) >= 0.3 )
			return -1;

		double versionX = ((grid.x+7)-17)/4;

		gridReader.imageToGrid(qr.ppDown.get(0),grid);

		if( Math.abs(grid.x/grid.y) >= 0.3 )
			return -1;

		double versionY = ((grid.y+7)-17)/4;

		// see if they are in agreement
		if( Math.abs(versionX-versionY)/Math.max(versionX,versionY) > 0.4 )
			return -1;

		return (int)((versionX+versionY)/2.0 + 0.5);
	}
1028256
def qrcode(self, data, **kwargs):
        
        barcode.validate_qrcode_args(**kwargs)
        return self._qrcode_impl(data, **kwargs)
650672
private int decodeKanji( QrCode qr , PackedBits8 data, int bitLocation ) {
		int lengthBits = QrCodeEncoder.getLengthBitsKanji(qr.version);

		int length = data.read(bitLocation,lengthBits,true);
		bitLocation += lengthBits;

		byte rawdata[] = new byte[ length*2 ];

		for (int i = 0; i < length; i++) {
			if( data.size < bitLocation+13 ) {
				qr.failureCause = QrCode.Failure.MESSAGE_OVERFLOW;
				return -1;
			}
			int letter = data.read(bitLocation,13,true);
			bitLocation += 13;

			letter = ((letter/0x0C0) << 8) | (letter%0x0C0);

			if (letter < 0x01F00) {
				// In the 0x8140 to 0x9FFC range
				letter += 0x08140;
			} else {
				// In the 0xE040 to 0xEBBF range
				letter += 0x0C140;
			}
			rawdata[i*2] = (byte) (letter >> 8);
			rawdata[i*2 + 1] = (byte) letter;
		}

		// Shift_JIS may not be supported in some environments:
		try {
			workString.append( new String(rawdata, "Shift_JIS") );
		} catch (UnsupportedEncodingException ignored) {
			qr.failureCause = KANJI_UNAVAILABLE;
			return -1;
		}

		return bitLocation;
	}
321926
function reorderFinderPatterns(pattern1, pattern2, pattern3) {
        // Find distances between pattern centers
        const oneTwoDistance = distance(pattern1, pattern2);
        const twoThreeDistance = distance(pattern2, pattern3);
        const oneThreeDistance = distance(pattern1, pattern3);
        let bottomLeft;
        let topLeft;
        let topRight;
        // Assume one closest to other two is B; A and C will just be guesses at first
        if (twoThreeDistance >= oneTwoDistance && twoThreeDistance >= oneThreeDistance) {
            [bottomLeft, topLeft, topRight] = [pattern2, pattern1, pattern3];
        }
        else if (oneThreeDistance >= twoThreeDistance && oneThreeDistance >= oneTwoDistance) {
            [bottomLeft, topLeft, topRight] = [pattern1, pattern2, pattern3];
        }
        else {
            [bottomLeft, topLeft, topRight] = [pattern1, pattern3, pattern2];
        }
        // Use cross product to figure out whether bottomLeft (A) and topRight (C) are correct or flipped in relation to topLeft (B)
        // This asks whether BC x BA has a positive z component, which is the arrangement we want. If it's negative, then
        // we've got it flipped around and should swap topRight and bottomLeft.
        if (((topRight.x - topLeft.x) * (bottomLeft.y - topLeft.y)) - ((topRight.y - topLeft.y) * (bottomLeft.x - topLeft.x)) < 0) {
            [bottomLeft, topRight] = [topRight, bottomLeft];
        }
        return { bottomLeft, topLeft, topRight };
    }
338114
def lookup_samecode(self, local, state):
        """"""
        for location in self.samecodes:
            if state.lower() == self.samecodes[location]['state'].lower():
                if local.lower() == self.samecodes[location]['local'].lower():
                    return self.samecodes[location]
        return False
82462
boolean centerOnSquare(QrCode.Alignment pattern, float guessY, float guessX) {
		float step = 1;
		float bestMag = Float.MAX_VALUE;
		float bestX = guessX;
		float bestY = guessY;

		for (int i = 0; i < 10; i++) {
			for (int row = 0; row < 3; row++) {
				float gridy = guessY - 1f + row;
				for (int col = 0; col < 3; col++) {
					float gridx = guessX - 1f + col;

					samples[row*3+col] = reader.read(gridy,gridx);
				}
			}

			float dx = (samples[2]+samples[5]+samples[8])-(samples[0]+samples[3]+samples[6]);
			float dy = (samples[6]+samples[7]+samples[8])-(samples[0]+samples[1]+samples[2]);

			float r = (float)Math.sqrt(dx*dx + dy*dy);

			if( bestMag > r ) {
//				System.out.println("good step at "+i);
				bestMag = r;
				bestX = guessX;
				bestY = guessY;
			} else {
//				System.out.println("bad step at "+i);
				step *= 0.75f;
			}

			if( r > 0 ) {
				guessX = bestX + step * dx / r;
				guessY = bestY + step * dy / r;
			} else {
				break;
			}
		}

		pattern.moduleFound.x = bestX;
		pattern.moduleFound.y = bestY;

		reader.gridToImage((float)pattern.moduleFound.y,(float)pattern.moduleFound.x,pattern.pixel);

		return true;
	}
203804
void initializePatterns(QrCode qr) {
		int where[] = QrCode.VERSION_INFO[qr.version].alignment;
		qr.alignment.reset();
		lookup.reset();
		for (int row = 0; row < where.length; row++ ) {
			for (int col = 0; col < where.length; col++) {
				boolean skip = false;
				if( row == 0 && col == 0 )
					skip = true;
				else if( row == 0 && col == where.length-1 )
					skip = true;
				else if( row == where.length-1 && col == 0)
					skip = true;

				if( skip ) {
					lookup.add(null);
				} else {
					QrCode.Alignment a = qr.alignment.grow();
					a.moduleX = where[col];
					a.moduleY = where[row];
					lookup.add(a);
				}
			}
		}
	}
684199
def compare(self, v1, v2):
        
        try:
            if len(v1) != len(v2): return 0
            for x, y in zip(v1, v2):
                if abs( x - y ) > self.tolerance:
                    return 0
            return 1
        except:
            # some patterns may not be vectors
            try:
                if abs( v1 - v2 ) > self.tolerance:
                    return 0
                else:
                    return 1
            except:
                return 0
1328027
def _found_barcode(self, record, sample, barcode=None):
        """"""
        assert record.id == self.current_record['sequence_name']
        self.current_record['sample'] = sample
1253947
def distance(self,rng):
    
    if self.chr != rng.chr: return -1
    c = self.cmp(rng)
    if c == 0: return 0
    if c < 0:
      return rng.start - self.end-1
    return self.start - rng.end-1
472120
def guess_version(redeem_script):
    '''
    
    '''
    n = riemann.get_current_network_name()
    if 'sprout' in n:
        return 1
    if 'overwinter' in n:
        return 3
    if 'sapling' in n:
        return 4
    try:
        script_array = redeem_script.split()
        script_array.index('OP_CHECKSEQUENCEVERIFY')
        return 2
    except ValueError:
        return 1
1154557
def _check_normalization(self):
        
        lastDistance = None
        distance     = None
        for idx in xrange(len(self) - 1):
            distance = self[idx+1][0] - self[idx][0]

            # first run
            if lastDistance is None:
                lastDistance = distance
                continue

            if lastDistance != distance:
                return False

            lastDistance = distance

        return True
1225777
private void createPositionPatternGraph() {
		// Add items to NN search

		nn.setPoints((List)positionPatterns.toList(),false);

		for (int i = 0; i < positionPatterns.size(); i++) {
			PositionPatternNode f = positionPatterns.get(i);

			// The QR code version specifies the number of "modules"/blocks across the marker is
			// A position pattern is 7 blocks. A version 1 qr code is 21 blocks. Each version past one increments
			// by 4 blocks. The search is relative to the center of each position pattern, hence the - 7
			double maximumQrCodeWidth = f.largestSide*(17+4*maxVersionQR-7.0)/7.0;
			double searchRadius = 1.2*maximumQrCodeWidth; // search 1/2 the width + some fudge factor
			searchRadius*=searchRadius;

			// Connect all the finder patterns which are near by each other together in a graph
			search.findNearest(f,searchRadius,Integer.MAX_VALUE,searchResults);

			if( searchResults.size > 1) {
				for (int j = 0; j < searchResults.size; j++) {
					NnData<SquareNode> r = searchResults.get(j);

					if( r.point == f ) continue; // skip over if it's the square that initiated the search

					considerConnect(f,r.point);
				}
			}
		}
	}
520965
public boolean process(T image , QrCode qr ) {
		this.qr = qr;
		// this must be cleared before calling setMarker or else the distortion will be messed up
		qr.alignment.reset();

		reader.setImage(image);
		reader.setMarker(qr);

		threshold = (float)qr.threshCorner;

		initializePatterns(qr);

		// version 1 has no alignment patterns
		if( qr.version <= 1 )
			return true;
		return localizePositionPatterns(QrCode.VERSION_INFO[qr.version].alignment);
	}
326951
static QrCodeMaskPattern selectMask( QrCode qr ) {
		int N = qr.getNumberOfModules();
		int totalBytes = QrCode.VERSION_INFO[qr.version].codewords;
		List<Point2D_I32> locations = QrCode.LOCATION_BITS[qr.version];

		QrCodeMaskPattern bestMask = null;
		double bestScore = Double.MAX_VALUE;

		PackedBits8 bits = new PackedBits8();
		bits.size = totalBytes * 8;
		bits.data = qr.rawbits;

		if (bits.size > locations.size())
			throw new RuntimeException("BUG in code");

		// Bit value of 0 = white. 1 = black
		QrCodeCodeWordLocations matrix = new QrCodeCodeWordLocations(qr.version);
		for (QrCodeMaskPattern mask : QrCodeMaskPattern.values()) {
			double score = scoreMask(N, locations, bits, matrix, mask);
			if (score < bestScore) {
				bestScore = score;
				bestMask = mask;
			}
		}
		return bestMask;
	}
623151
def compare_version(a, b):  # Ignore PyDocStyleBear
    

    def _range(q):
        """Convert a version string to array of integers.

        "1.2.3" -> [1, 2, 3]

        :param q: str
        :return: List[int]
        """
        r = []
        for n in q.replace("-", ".").split("."):
            try:
                r.append(int(n))
            except ValueError:
                # sort rc*, alpha, beta etc. lower than their non-annotated counterparts
                r.append(-1)
        return r

    def _append_zeros(x, num_zeros):
        """Append `num_zeros` zeros to a copy of `x` and return it.

        :param x: List[int]
        :param num_zeros: int
        :return: List[int]
        """
        nx = list(x)
        for _ in range(num_zeros):
            nx.append(0)
        return nx

    def _cardinal(x, y):
        """Make both input lists be of same cardinality.

        :param x: List[int]
        :param y: List[int]
        :return: List[int]
        """
        lx, ly = len(x), len(y)
        if lx == ly:
            return x, y
        elif lx > ly:
            return x, _append_zeros(y, lx - ly)
        else:
            return _append_zeros(x, ly - lx), y

    left, right = _cardinal(_range(a), _range(b))

    return (left > right) - (left < right)
923909
def err(self):
        
        # Initiallize error to nan
        err = odict(self.mle())
        err.update([(k,np.nan*np.ones(2)) for k in err.keys()])

        # Find the maximum likelihood
        a = self.log_likelihood_sparse_array
        j,k = np.unravel_index(a.argmax(),a.shape)

        self.loglike.set_params(distance_modulus=self.distance_modulus_array[j],
                                lon=self.roi.pixels_target.lon[k],
                                lat=self.roi.pixels_target.lat[k])
        self.loglike.sync_params()

        # Find the error in richness, starting at maximum
        lo,hi = np.array(self.loglike.richness_interval())
        err['richness'] = np.array([lo,hi])

        # ADW: This is a rough estimate of the distance uncertainty 
        # hacked to keep the maximum distance modulus on a grid index

        # This is a hack to get the confidence interval to play nice...
        # Require at least three points.
        if (a[:,k]>0).sum() >= 3:
            parabola = Parabola(np.insert(self.distance_modulus_array,0,0.), 
                                np.insert(a[:,k],0,0.) )
            lo,hi = np.array(parabola.confidenceInterval())
            err['distance_modulus'] = self.distance_modulus_array[j] + (hi-lo)/2.*np.array([-1.,1.])

        # ADW: Could estimate lon and lat from the grid.
        # This is just concept right now...
        if (a[j,:]>0).sum() >= 10:
            delta_ts = 2*(a[j,k] - a[j,:])
            pix = np.where(a[j,:][delta_ts < 2.71])[0]
            lons = self.roi.pixels_target.lon[pix]
            lats = self.roi.pixels_target.lat[pix]
            err['lon'] = np.array([ np.min(lons),np.max(lons)])
            err['lat'] = np.array([ np.min(lats),np.max(lats)])

        return err