├── __init__.py ├── qrcode ├── exceptions.py ├── constants.py ├── __init__.py ├── base.py ├── main.py ├── util.py └── six.py ├── README.md ├── main.py ├── oledImage.py └── LICENSE.md /__init__.py: -------------------------------------------------------------------------------- 1 | from main import dispQrCode 2 | from qrcode.main import QRCode -------------------------------------------------------------------------------- /qrcode/exceptions.py: -------------------------------------------------------------------------------- 1 | class DataOverflowError(Exception): 2 | pass 3 | -------------------------------------------------------------------------------- /qrcode/constants.py: -------------------------------------------------------------------------------- 1 | # QR error correct levels 2 | ERROR_CORRECT_L = 1 3 | ERROR_CORRECT_M = 0 4 | ERROR_CORRECT_Q = 3 5 | ERROR_CORRECT_H = 2 6 | -------------------------------------------------------------------------------- /qrcode/__init__.py: -------------------------------------------------------------------------------- 1 | from main import QRCode 2 | from constants import ( # noqa 3 | ERROR_CORRECT_L, ERROR_CORRECT_M, ERROR_CORRECT_Q, ERROR_CORRECT_H) 4 | 5 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # oled-qr-code-generator 2 | Encode text and display QR Code on OLED Expansion 3 | 4 | 5 | # Tutorial 6 | 7 | Check out the full tutorial on using this repo here: https://wiki.onion.io/Projects/OLED-QR-Code-Generator 8 | 9 | 10 | # Installation 11 | 12 | 13 | ## Required Packages 14 | 15 | Install the following packages: 16 | ``` 17 | opkg update 18 | opkg install git git-http python-light python-codecs pyOledExp 19 | ``` 20 | 21 | ## Grabbing the Repo 22 | 23 | On your Omega: 24 | ``` 25 | git clone https://github.com/OnionIoT/oledQrCodeGenerator.git 26 | ``` 27 | 28 | 29 | 30 | # Generating a QR Code 31 | 32 | Run the following command: 33 | ``` 34 | python oledQrCodeGenerator/main.py '' 35 | ``` 36 | 37 | This will create a QR Code with the specified text and display it on the OLED Display. 38 | 39 | 40 | 41 | ## Using the Module 42 | 43 | The code here can also be used as a module to be included in other scripts. 44 | 45 | ``` 46 | import oledQrCodeGenerator 47 | 48 | 49 | oledQrCodeGenerator.dispQrCode('Hello!') 50 | ``` 51 | 52 | 53 | 54 | # Acknowledgements 55 | 56 | The code in the `qrcode` directory is a stripped-down version of lincolnloop's `python-qrcode` repo: 57 | https://github.com/lincolnloop/python-qrcode 58 | -------------------------------------------------------------------------------- /main.py: -------------------------------------------------------------------------------- 1 | import oledImage 2 | import qrcode 3 | from OmegaExpansion import oledExp 4 | 5 | def dispQrCode (data, imageFile='qr-code.lcd'): 6 | # setup the QR Code generator 7 | qr = qrcode.QRCode( 8 | version=3, 9 | error_correction=qrcode.constants.ERROR_CORRECT_L, 10 | box_size=10, 11 | border=1, 12 | ) 13 | 14 | print '> Encoding %d characters'%(len(data)) 15 | qr.add_data(data) 16 | qr.make(fit=True) 17 | 18 | matrix = qr.get_matrix() 19 | matrixRows = len(matrix) 20 | matrixCols = len(matrix[0]) 21 | print '> Generated QR Code: %dx%d pixels'%(matrixCols, matrixRows ) 22 | 23 | # check the size 24 | if matrixCols > oledImage.SCREEN_WIDTH or matrixRows > oledImage.SCREEN_HEIGHT: 25 | print 'ERROR: Generated QR code is too large for the OLED Display! Try less text!' 26 | exit() 27 | 28 | # double the QR code size if it's less than half of the OLED size 29 | dMatrix = oledImage.doubleMatrixSize(matrix) 30 | xOffset = oledImage.SCREEN_WIDTH/2 - len(dMatrix[0])/2 31 | 32 | 33 | ## convert the QR code to an OLED image 34 | screen = oledImage.convertToOledImg(dMatrix, xOffset, 0) 35 | oledImage.printToFile(screen, imageFile) 36 | 37 | 38 | ## display the image on the OLED Expansion 39 | oledExp.driverInit() # initialize the screen 40 | oledExp.setDisplayMode(1) # invert the colours 41 | oledExp.drawFromFile(imageFile) # display the image file 42 | 43 | 44 | 45 | if __name__ == '__main__': # pragma: no cover 46 | import sys 47 | data = "" 48 | 49 | # check for arguments 50 | if len(sys.argv) < 2: 51 | print 'Expected data to encode!' 52 | print 'Using default text :)' 53 | data = 'Onion Omega: Invent the Future' 54 | else: 55 | # load the data 56 | data = sys.argv[1] 57 | 58 | # run the function to generate the qr code and display on the OLED 59 | dispQrCode(data) 60 | 61 | -------------------------------------------------------------------------------- /oledImage.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | 4 | SCREEN_WIDTH = 128 5 | SCREEN_HEIGHT = 64 6 | 7 | SCREEN_PAGE_HEIGHT = 8 8 | SCREEN_PAGES = (SCREEN_HEIGHT/SCREEN_PAGE_HEIGHT) 9 | 10 | 11 | # print the oled image to the screen 12 | def printScreen (obj, newlines=True): 13 | sys.stdout.softspace=0 14 | for row in obj: 15 | for point in row: 16 | print '%02x'%point, 17 | if newlines == True: 18 | print ' ' 19 | print ' ' 20 | 21 | # print the oled image to a file 22 | # 1024 bytes in a row 23 | def printToFile(obj, filename): 24 | out = [] 25 | f = open(filename, 'w') 26 | for row in obj: 27 | for point in row: 28 | if type(point) is int: 29 | byte = str('%02x'%point) 30 | f.write(byte) 31 | 32 | f.close() 33 | 34 | # convert boolean to a 1 or 0, bitshift the appropriate number of bits 35 | def matrixPointToBit (bool, bitNumber): 36 | val = 0 37 | if bool == True: 38 | val = 1 << bitNumber 39 | 40 | return val 41 | 42 | 43 | # convert a vertical row of 8 pixels to an OLED byte 44 | def matrixPointsToByte (matrix, X, startingY): 45 | byte = 0 46 | for i in range(0,8): 47 | row = startingY + i 48 | #print 'matrix(%d,%d)= '%(X, row), 49 | if (row < len(matrix)-1): 50 | data = matrix[row][X] 51 | #print data 52 | else: 53 | data = 0 54 | #print 'ZERO' 55 | 56 | byte |= matrixPointToBit(data, i) 57 | 58 | return byte 59 | 60 | # convert a boolean matrix to an oled image 61 | # matrix - the boolean matrix to convert 62 | # xOffset - how much to shift the image on the X axis in the OLED image 63 | # yOffset - how much to shift the image on the Y axis in the OLED image 64 | def convertToOledImg (matrix, xOffset, yOffset): 65 | oled = [[0] * SCREEN_WIDTH for x in xrange(SCREEN_PAGES)] 66 | 67 | # loop through the rows (increasing by page size) 68 | for y in range(0, len(matrix), SCREEN_PAGES): 69 | yy = yOffset + y 70 | # loop through each pixel in the row 71 | for x in range(0, len(matrix[y]) ): 72 | # convert the 8 vertical pixels to a byte 73 | byte = matrixPointsToByte(matrix, x, y) 74 | # set this byte in the oled screen object 75 | oled[y/SCREEN_PAGES][x + xOffset] = byte 76 | 77 | return oled 78 | 79 | # 80 | def doubleMatrixSize (matrix): 81 | rows = len(matrix) 82 | cols = len(matrix[0]) 83 | 84 | if rows <= (SCREEN_HEIGHT/2): 85 | dMatrix = [[0] * cols*2 for x in xrange(rows*2)] 86 | 87 | for y in range(0, rows): 88 | for x in range(0, cols): 89 | # copy this matrix point to 4 new matrix points 90 | dMatrix[y*2][x*2] = matrix[y][x] 91 | dMatrix[y*2][x*2+1] = matrix[y][x] 92 | dMatrix[y*2+1][x*2] = matrix[y][x] 93 | dMatrix[y*2+1][x*2+1] = matrix[y][x] 94 | print '> Doubled QR Code size: %dx%d'%(len(dMatrix[0]), len(dMatrix) ) 95 | else: 96 | dMatrix = matrix 97 | 98 | return dMatrix 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | -------------------------------------------------------------------------------- /qrcode/base.py: -------------------------------------------------------------------------------- 1 | from . import constants 2 | 3 | EXP_TABLE = list(range(256)) 4 | 5 | LOG_TABLE = list(range(256)) 6 | 7 | for i in range(8): 8 | EXP_TABLE[i] = 1 << i 9 | 10 | for i in range(8, 256): 11 | EXP_TABLE[i] = ( 12 | EXP_TABLE[i - 4] ^ EXP_TABLE[i - 5] ^ EXP_TABLE[i - 6] ^ 13 | EXP_TABLE[i - 8]) 14 | 15 | for i in range(255): 16 | LOG_TABLE[EXP_TABLE[i]] = i 17 | 18 | RS_BLOCK_OFFSET = { 19 | constants.ERROR_CORRECT_L: 0, 20 | constants.ERROR_CORRECT_M: 1, 21 | constants.ERROR_CORRECT_Q: 2, 22 | constants.ERROR_CORRECT_H: 3, 23 | } 24 | 25 | RS_BLOCK_TABLE = [ 26 | 27 | # L 28 | # M 29 | # Q 30 | # H 31 | 32 | # 1 33 | [1, 26, 19], 34 | [1, 26, 16], 35 | [1, 26, 13], 36 | [1, 26, 9], 37 | 38 | # 2 39 | [1, 44, 34], 40 | [1, 44, 28], 41 | [1, 44, 22], 42 | [1, 44, 16], 43 | 44 | # 3 45 | [1, 70, 55], 46 | [1, 70, 44], 47 | [2, 35, 17], 48 | [2, 35, 13], 49 | 50 | # 4 51 | [1, 100, 80], 52 | [2, 50, 32], 53 | [2, 50, 24], 54 | [4, 25, 9], 55 | 56 | # 5 57 | [1, 134, 108], 58 | [2, 67, 43], 59 | [2, 33, 15, 2, 34, 16], 60 | [2, 33, 11, 2, 34, 12], 61 | 62 | # 6 63 | [2, 86, 68], 64 | [4, 43, 27], 65 | [4, 43, 19], 66 | [4, 43, 15], 67 | 68 | # 7 69 | [2, 98, 78], 70 | [4, 49, 31], 71 | [2, 32, 14, 4, 33, 15], 72 | [4, 39, 13, 1, 40, 14], 73 | 74 | # 8 75 | [2, 121, 97], 76 | [2, 60, 38, 2, 61, 39], 77 | [4, 40, 18, 2, 41, 19], 78 | [4, 40, 14, 2, 41, 15], 79 | 80 | # 9 81 | [2, 146, 116], 82 | [3, 58, 36, 2, 59, 37], 83 | [4, 36, 16, 4, 37, 17], 84 | [4, 36, 12, 4, 37, 13], 85 | 86 | # 10 87 | [2, 86, 68, 2, 87, 69], 88 | [4, 69, 43, 1, 70, 44], 89 | [6, 43, 19, 2, 44, 20], 90 | [6, 43, 15, 2, 44, 16], 91 | 92 | # 11 93 | [4, 101, 81], 94 | [1, 80, 50, 4, 81, 51], 95 | [4, 50, 22, 4, 51, 23], 96 | [3, 36, 12, 8, 37, 13], 97 | 98 | # 12 99 | [2, 116, 92, 2, 117, 93], 100 | [6, 58, 36, 2, 59, 37], 101 | [4, 46, 20, 6, 47, 21], 102 | [7, 42, 14, 4, 43, 15], 103 | 104 | # 13 105 | [4, 133, 107], 106 | [8, 59, 37, 1, 60, 38], 107 | [8, 44, 20, 4, 45, 21], 108 | [12, 33, 11, 4, 34, 12], 109 | 110 | # 14 111 | [3, 145, 115, 1, 146, 116], 112 | [4, 64, 40, 5, 65, 41], 113 | [11, 36, 16, 5, 37, 17], 114 | [11, 36, 12, 5, 37, 13], 115 | 116 | # 15 117 | [5, 109, 87, 1, 110, 88], 118 | [5, 65, 41, 5, 66, 42], 119 | [5, 54, 24, 7, 55, 25], 120 | [11, 36, 12], 121 | 122 | # 16 123 | [5, 122, 98, 1, 123, 99], 124 | [7, 73, 45, 3, 74, 46], 125 | [15, 43, 19, 2, 44, 20], 126 | [3, 45, 15, 13, 46, 16], 127 | 128 | # 17 129 | [1, 135, 107, 5, 136, 108], 130 | [10, 74, 46, 1, 75, 47], 131 | [1, 50, 22, 15, 51, 23], 132 | [2, 42, 14, 17, 43, 15], 133 | 134 | # 18 135 | [5, 150, 120, 1, 151, 121], 136 | [9, 69, 43, 4, 70, 44], 137 | [17, 50, 22, 1, 51, 23], 138 | [2, 42, 14, 19, 43, 15], 139 | 140 | # 19 141 | [3, 141, 113, 4, 142, 114], 142 | [3, 70, 44, 11, 71, 45], 143 | [17, 47, 21, 4, 48, 22], 144 | [9, 39, 13, 16, 40, 14], 145 | 146 | # 20 147 | [3, 135, 107, 5, 136, 108], 148 | [3, 67, 41, 13, 68, 42], 149 | [15, 54, 24, 5, 55, 25], 150 | [15, 43, 15, 10, 44, 16], 151 | 152 | # 21 153 | [4, 144, 116, 4, 145, 117], 154 | [17, 68, 42], 155 | [17, 50, 22, 6, 51, 23], 156 | [19, 46, 16, 6, 47, 17], 157 | 158 | # 22 159 | [2, 139, 111, 7, 140, 112], 160 | [17, 74, 46], 161 | [7, 54, 24, 16, 55, 25], 162 | [34, 37, 13], 163 | 164 | # 23 165 | [4, 151, 121, 5, 152, 122], 166 | [4, 75, 47, 14, 76, 48], 167 | [11, 54, 24, 14, 55, 25], 168 | [16, 45, 15, 14, 46, 16], 169 | 170 | # 24 171 | [6, 147, 117, 4, 148, 118], 172 | [6, 73, 45, 14, 74, 46], 173 | [11, 54, 24, 16, 55, 25], 174 | [30, 46, 16, 2, 47, 17], 175 | 176 | # 25 177 | [8, 132, 106, 4, 133, 107], 178 | [8, 75, 47, 13, 76, 48], 179 | [7, 54, 24, 22, 55, 25], 180 | [22, 45, 15, 13, 46, 16], 181 | 182 | # 26 183 | [10, 142, 114, 2, 143, 115], 184 | [19, 74, 46, 4, 75, 47], 185 | [28, 50, 22, 6, 51, 23], 186 | [33, 46, 16, 4, 47, 17], 187 | 188 | # 27 189 | [8, 152, 122, 4, 153, 123], 190 | [22, 73, 45, 3, 74, 46], 191 | [8, 53, 23, 26, 54, 24], 192 | [12, 45, 15, 28, 46, 16], 193 | 194 | # 28 195 | [3, 147, 117, 10, 148, 118], 196 | [3, 73, 45, 23, 74, 46], 197 | [4, 54, 24, 31, 55, 25], 198 | [11, 45, 15, 31, 46, 16], 199 | 200 | # 29 201 | [7, 146, 116, 7, 147, 117], 202 | [21, 73, 45, 7, 74, 46], 203 | [1, 53, 23, 37, 54, 24], 204 | [19, 45, 15, 26, 46, 16], 205 | 206 | # 30 207 | [5, 145, 115, 10, 146, 116], 208 | [19, 75, 47, 10, 76, 48], 209 | [15, 54, 24, 25, 55, 25], 210 | [23, 45, 15, 25, 46, 16], 211 | 212 | # 31 213 | [13, 145, 115, 3, 146, 116], 214 | [2, 74, 46, 29, 75, 47], 215 | [42, 54, 24, 1, 55, 25], 216 | [23, 45, 15, 28, 46, 16], 217 | 218 | # 32 219 | [17, 145, 115], 220 | [10, 74, 46, 23, 75, 47], 221 | [10, 54, 24, 35, 55, 25], 222 | [19, 45, 15, 35, 46, 16], 223 | 224 | # 33 225 | [17, 145, 115, 1, 146, 116], 226 | [14, 74, 46, 21, 75, 47], 227 | [29, 54, 24, 19, 55, 25], 228 | [11, 45, 15, 46, 46, 16], 229 | 230 | # 34 231 | [13, 145, 115, 6, 146, 116], 232 | [14, 74, 46, 23, 75, 47], 233 | [44, 54, 24, 7, 55, 25], 234 | [59, 46, 16, 1, 47, 17], 235 | 236 | # 35 237 | [12, 151, 121, 7, 152, 122], 238 | [12, 75, 47, 26, 76, 48], 239 | [39, 54, 24, 14, 55, 25], 240 | [22, 45, 15, 41, 46, 16], 241 | 242 | # 36 243 | [6, 151, 121, 14, 152, 122], 244 | [6, 75, 47, 34, 76, 48], 245 | [46, 54, 24, 10, 55, 25], 246 | [2, 45, 15, 64, 46, 16], 247 | 248 | # 37 249 | [17, 152, 122, 4, 153, 123], 250 | [29, 74, 46, 14, 75, 47], 251 | [49, 54, 24, 10, 55, 25], 252 | [24, 45, 15, 46, 46, 16], 253 | 254 | # 38 255 | [4, 152, 122, 18, 153, 123], 256 | [13, 74, 46, 32, 75, 47], 257 | [48, 54, 24, 14, 55, 25], 258 | [42, 45, 15, 32, 46, 16], 259 | 260 | # 39 261 | [20, 147, 117, 4, 148, 118], 262 | [40, 75, 47, 7, 76, 48], 263 | [43, 54, 24, 22, 55, 25], 264 | [10, 45, 15, 67, 46, 16], 265 | 266 | # 40 267 | [19, 148, 118, 6, 149, 119], 268 | [18, 75, 47, 31, 76, 48], 269 | [34, 54, 24, 34, 55, 25], 270 | [20, 45, 15, 61, 46, 16] 271 | 272 | ] 273 | 274 | 275 | def glog(n): 276 | if n < 1: # pragma: no cover 277 | raise ValueError("glog(%s)" % n) 278 | return LOG_TABLE[n] 279 | 280 | 281 | def gexp(n): 282 | return EXP_TABLE[n % 255] 283 | 284 | 285 | class Polynomial: 286 | 287 | def __init__(self, num, shift): 288 | if not num: # pragma: no cover 289 | raise Exception("%s/%s" % (len(num), shift)) 290 | 291 | offset = 0 292 | 293 | for item in num: 294 | if item != 0: 295 | break 296 | offset += 1 297 | 298 | self.num = [0] * (len(num) - offset + shift) 299 | for i in range(len(num) - offset): 300 | self.num[i] = num[i + offset] 301 | 302 | def __getitem__(self, index): 303 | return self.num[index] 304 | 305 | def __iter__(self): 306 | return iter(self.num) 307 | 308 | def __len__(self): 309 | return len(self.num) 310 | 311 | def __mul__(self, other): 312 | num = [0] * (len(self) + len(other) - 1) 313 | 314 | for i, item in enumerate(self): 315 | for j, other_item in enumerate(other): 316 | num[i + j] ^= gexp(glog(item) + glog(other_item)) 317 | 318 | return Polynomial(num, 0) 319 | 320 | def __mod__(self, other): 321 | difference = len(self) - len(other) 322 | if difference < 0: 323 | return self 324 | 325 | ratio = glog(self[0]) - glog(other[0]) 326 | 327 | num = self[:] 328 | 329 | num = [ 330 | item ^ gexp(glog(other_item) + ratio) 331 | for item, other_item in zip(self, other)] 332 | if difference: 333 | num.extend(self[-difference:]) 334 | 335 | # recursive call 336 | return Polynomial(num, 0) % other 337 | 338 | 339 | class RSBlock: 340 | 341 | def __init__(self, total_count, data_count): 342 | self.total_count = total_count 343 | self.data_count = data_count 344 | 345 | 346 | def rs_blocks(version, error_correction): 347 | if error_correction not in RS_BLOCK_OFFSET: # pragma: no cover 348 | raise Exception( 349 | "bad rs block @ version: %s / error_correction: %s" % 350 | (version, error_correction)) 351 | offset = RS_BLOCK_OFFSET[error_correction] 352 | rs_block = RS_BLOCK_TABLE[(version - 1) * 4 + offset] 353 | 354 | blocks = [] 355 | 356 | for i in range(0, len(rs_block), 3): 357 | count, total_count, data_count = rs_block[i:i + 3] 358 | for j in range(count): 359 | blocks.append(RSBlock(total_count, data_count)) 360 | 361 | return blocks 362 | -------------------------------------------------------------------------------- /qrcode/main.py: -------------------------------------------------------------------------------- 1 | from . import constants, exceptions, util 2 | # REMOVED image factory 3 | 4 | import six 5 | from bisect import bisect_left 6 | 7 | 8 | def make(data=None, **kwargs): 9 | qr = QRCode(**kwargs) 10 | qr.add_data(data) 11 | #return qr.make_image() 12 | 13 | 14 | def _check_version(version): 15 | if version < 1 or version > 40: 16 | raise ValueError( 17 | "Invalid version (was %s, expected 1 to 40)" % version) 18 | 19 | 20 | def _check_box_size(size): 21 | if int(size) <= 0: 22 | raise ValueError( 23 | "Invalid box size (was %s, expected larger than 0)" % size) 24 | 25 | 26 | class QRCode: 27 | 28 | def __init__(self, version=None, 29 | error_correction=constants.ERROR_CORRECT_M, 30 | box_size=10, border=4): 31 | _check_box_size(box_size) 32 | self.version = version and int(version) 33 | self.error_correction = int(error_correction) 34 | self.box_size = int(box_size) 35 | # Spec says border should be at least four boxes wide, but allow for 36 | # any (e.g. for producing printable QR codes). 37 | self.border = int(border) 38 | # REMOVED image factory 39 | self.clear() 40 | 41 | def clear(self): 42 | """ 43 | Reset the internal data. 44 | """ 45 | self.modules = None 46 | self.modules_count = 0 47 | self.data_cache = None 48 | self.data_list = [] 49 | 50 | def add_data(self, data, optimize=20): 51 | """ 52 | Add data to this QR Code. 53 | 54 | :param optimize: Data will be split into multiple chunks to optimize 55 | the QR size by finding to more compressed modes of at least this 56 | length. Set to ``0`` to avoid optimizing at all. 57 | """ 58 | if isinstance(data, util.QRData): 59 | self.data_list.append(data) 60 | else: 61 | if optimize: 62 | self.data_list.extend(util.optimal_data_chunks(data)) 63 | else: 64 | self.data_list.append(util.QRData(data)) 65 | self.data_cache = None 66 | 67 | def make(self, fit=True): 68 | """ 69 | Compile the data into a QR Code array. 70 | 71 | :param fit: If ``True`` (or if a size has not been provided), find the 72 | best fit for the data to avoid data overflow errors. 73 | """ 74 | if fit or (self.version is None): 75 | self.best_fit(start=self.version) 76 | self.makeImpl(False, self.best_mask_pattern()) 77 | 78 | def makeImpl(self, test, mask_pattern): 79 | _check_version(self.version) 80 | self.modules_count = self.version * 4 + 17 81 | self.modules = [None] * self.modules_count 82 | 83 | for row in range(self.modules_count): 84 | 85 | self.modules[row] = [None] * self.modules_count 86 | 87 | for col in range(self.modules_count): 88 | self.modules[row][col] = None # (col + row) % 3 89 | 90 | self.setup_position_probe_pattern(0, 0) 91 | self.setup_position_probe_pattern(self.modules_count - 7, 0) 92 | self.setup_position_probe_pattern(0, self.modules_count - 7) 93 | self.setup_position_adjust_pattern() 94 | self.setup_timing_pattern() 95 | self.setup_type_info(test, mask_pattern) 96 | 97 | if self.version >= 7: 98 | self.setup_type_number(test) 99 | 100 | if self.data_cache is None: 101 | self.data_cache = util.create_data( 102 | self.version, self.error_correction, self.data_list) 103 | self.map_data(self.data_cache, mask_pattern) 104 | 105 | def setup_position_probe_pattern(self, row, col): 106 | for r in range(-1, 8): 107 | 108 | if row + r <= -1 or self.modules_count <= row + r: 109 | continue 110 | 111 | for c in range(-1, 8): 112 | 113 | if col + c <= -1 or self.modules_count <= col + c: 114 | continue 115 | 116 | if (0 <= r and r <= 6 and (c == 0 or c == 6) 117 | or (0 <= c and c <= 6 and (r == 0 or r == 6)) 118 | or (2 <= r and r <= 4 and 2 <= c and c <= 4)): 119 | self.modules[row + r][col + c] = True 120 | else: 121 | self.modules[row + r][col + c] = False 122 | 123 | def best_fit(self, start=None): 124 | """ 125 | Find the minimum size required to fit in the data. 126 | """ 127 | if start is None: 128 | start = 1 129 | _check_version(start) 130 | 131 | # Corresponds to the code in util.create_data, except we don't yet know 132 | # version, so optimistically assume start and check later 133 | mode_sizes = util.mode_sizes_for_version(start) 134 | buffer = util.BitBuffer() 135 | for data in self.data_list: 136 | buffer.put(data.mode, 4) 137 | buffer.put(len(data), mode_sizes[data.mode]) 138 | data.write(buffer) 139 | 140 | needed_bits = len(buffer) 141 | self.version = bisect_left(util.BIT_LIMIT_TABLE[self.error_correction], 142 | needed_bits, start) 143 | if self.version == 41: 144 | raise exceptions.DataOverflowError() 145 | 146 | # Now check whether we need more bits for the mode sizes, recursing if 147 | # our guess was too low 148 | if mode_sizes is not util.mode_sizes_for_version(self.version): 149 | self.best_fit(start=self.version) 150 | return self.version 151 | 152 | def best_mask_pattern(self): 153 | """ 154 | Find the most efficient mask pattern. 155 | """ 156 | min_lost_point = 0 157 | pattern = 0 158 | 159 | for i in range(8): 160 | self.makeImpl(True, i) 161 | 162 | lost_point = util.lost_point(self.modules) 163 | 164 | if i == 0 or min_lost_point > lost_point: 165 | min_lost_point = lost_point 166 | pattern = i 167 | 168 | return pattern 169 | 170 | def print_tty(self, out=None): 171 | """ 172 | Output the QR Code only using TTY colors. 173 | 174 | If the data has not been compiled yet, make it first. 175 | """ 176 | if out is None: 177 | import sys 178 | out = sys.stdout 179 | 180 | if not out.isatty(): 181 | raise OSError("Not a tty") 182 | 183 | if self.data_cache is None: 184 | self.make() 185 | 186 | modcount = self.modules_count 187 | out.write("\x1b[1;47m" + (" " * (modcount * 2 + 4)) + "\x1b[0m\n") 188 | for r in range(modcount): 189 | out.write("\x1b[1;47m \x1b[40m") 190 | for c in range(modcount): 191 | if self.modules[r][c]: 192 | out.write(" ") 193 | else: 194 | out.write("\x1b[1;47m \x1b[40m") 195 | out.write("\x1b[1;47m \x1b[0m\n") 196 | out.write("\x1b[1;47m" + (" " * (modcount * 2 + 4)) + "\x1b[0m\n") 197 | out.flush() 198 | 199 | def print_ascii(self, out=None, tty=False, invert=False): 200 | """ 201 | Output the QR Code using ASCII characters. 202 | 203 | :param tty: use fixed TTY color codes (forces invert=True) 204 | :param invert: invert the ASCII characters (solid <-> transparent) 205 | """ 206 | if out is None: 207 | import sys 208 | if sys.version_info < (2, 7): 209 | # On Python versions 2.6 and earlier, stdout tries to encode 210 | # strings using ASCII rather than stdout.encoding, so use this 211 | # workaround. 212 | import codecs 213 | out = codecs.getwriter(sys.stdout.encoding)(sys.stdout) 214 | else: 215 | out = sys.stdout 216 | 217 | if tty and not out.isatty(): 218 | raise OSError("Not a tty") 219 | 220 | if self.data_cache is None: 221 | self.make() 222 | 223 | modcount = self.modules_count 224 | codes = [six.int2byte(code).decode('cp437') 225 | for code in (255, 223, 220, 219)] 226 | if tty: 227 | invert = True 228 | if invert: 229 | codes.reverse() 230 | 231 | def get_module(x, y): 232 | if (invert and self.border and 233 | max(x, y) >= modcount+self.border): 234 | return 1 235 | if min(x, y) < 0 or max(x, y) >= modcount: 236 | return 0 237 | return self.modules[x][y] 238 | 239 | for r in range(-self.border, modcount+self.border, 2): 240 | if tty: 241 | if not invert or r < modcount+self.border-1: 242 | out.write('\x1b[48;5;232m') # Background black 243 | out.write('\x1b[38;5;255m') # Foreground white 244 | for c in range(-self.border, modcount+self.border): 245 | pos = get_module(r, c) + (get_module(r+1, c) << 1) 246 | out.write(codes[pos]) 247 | if tty: 248 | out.write('\x1b[0m') 249 | out.write('\n') 250 | out.flush() 251 | 252 | # REMOVED make_image function 253 | 254 | 255 | def setup_timing_pattern(self): 256 | for r in range(8, self.modules_count - 8): 257 | if self.modules[r][6] is not None: 258 | continue 259 | self.modules[r][6] = (r % 2 == 0) 260 | 261 | for c in range(8, self.modules_count - 8): 262 | if self.modules[6][c] is not None: 263 | continue 264 | self.modules[6][c] = (c % 2 == 0) 265 | 266 | def setup_position_adjust_pattern(self): 267 | pos = util.pattern_position(self.version) 268 | 269 | for i in range(len(pos)): 270 | 271 | for j in range(len(pos)): 272 | 273 | row = pos[i] 274 | col = pos[j] 275 | 276 | if self.modules[row][col] is not None: 277 | continue 278 | 279 | for r in range(-2, 3): 280 | 281 | for c in range(-2, 3): 282 | 283 | if (r == -2 or r == 2 or c == -2 or c == 2 or 284 | (r == 0 and c == 0)): 285 | self.modules[row + r][col + c] = True 286 | else: 287 | self.modules[row + r][col + c] = False 288 | 289 | def setup_type_number(self, test): 290 | bits = util.BCH_type_number(self.version) 291 | 292 | for i in range(18): 293 | mod = (not test and ((bits >> i) & 1) == 1) 294 | self.modules[i // 3][i % 3 + self.modules_count - 8 - 3] = mod 295 | 296 | for i in range(18): 297 | mod = (not test and ((bits >> i) & 1) == 1) 298 | self.modules[i % 3 + self.modules_count - 8 - 3][i // 3] = mod 299 | 300 | def setup_type_info(self, test, mask_pattern): 301 | data = (self.error_correction << 3) | mask_pattern 302 | bits = util.BCH_type_info(data) 303 | 304 | # vertical 305 | for i in range(15): 306 | 307 | mod = (not test and ((bits >> i) & 1) == 1) 308 | 309 | if i < 6: 310 | self.modules[i][8] = mod 311 | elif i < 8: 312 | self.modules[i + 1][8] = mod 313 | else: 314 | self.modules[self.modules_count - 15 + i][8] = mod 315 | 316 | # horizontal 317 | for i in range(15): 318 | 319 | mod = (not test and ((bits >> i) & 1) == 1) 320 | 321 | if i < 8: 322 | self.modules[8][self.modules_count - i - 1] = mod 323 | elif i < 9: 324 | self.modules[8][15 - i - 1 + 1] = mod 325 | else: 326 | self.modules[8][15 - i - 1] = mod 327 | 328 | # fixed module 329 | self.modules[self.modules_count - 8][8] = (not test) 330 | 331 | def map_data(self, data, mask_pattern): 332 | inc = -1 333 | row = self.modules_count - 1 334 | bitIndex = 7 335 | byteIndex = 0 336 | 337 | mask_func = util.mask_func(mask_pattern) 338 | 339 | data_len = len(data) 340 | 341 | for col in six.moves.xrange(self.modules_count - 1, 0, -2): 342 | 343 | if col <= 6: 344 | col -= 1 345 | 346 | col_range = (col, col-1) 347 | 348 | while True: 349 | 350 | for c in col_range: 351 | 352 | if self.modules[row][c] is None: 353 | 354 | dark = False 355 | 356 | if byteIndex < data_len: 357 | dark = (((data[byteIndex] >> bitIndex) & 1) == 1) 358 | 359 | if mask_func(row, c): 360 | dark = not dark 361 | 362 | self.modules[row][c] = dark 363 | bitIndex -= 1 364 | 365 | if bitIndex == -1: 366 | byteIndex += 1 367 | bitIndex = 7 368 | 369 | row += inc 370 | 371 | if row < 0 or self.modules_count <= row: 372 | row -= inc 373 | inc = -inc 374 | break 375 | 376 | def get_matrix(self): 377 | """ 378 | Return the QR Code as a multidimensonal array, including the border. 379 | 380 | To return the array without a border, set ``self.border`` to 0 first. 381 | """ 382 | if self.data_cache is None: 383 | self.make() 384 | 385 | if not self.border: 386 | return self.modules 387 | 388 | width = len(self.modules) + self.border*2 389 | code = [[False]*width] * self.border 390 | x_border = [False]*self.border 391 | for module in self.modules: 392 | code.append(x_border + module + x_border) 393 | code += [[False]*width] * self.border 394 | 395 | return code 396 | -------------------------------------------------------------------------------- /qrcode/util.py: -------------------------------------------------------------------------------- 1 | import re 2 | import math 3 | 4 | import six 5 | from six.moves import xrange 6 | 7 | from . import base, exceptions 8 | 9 | # QR encoding modes. 10 | MODE_NUMBER = 1 << 0 11 | MODE_ALPHA_NUM = 1 << 1 12 | MODE_8BIT_BYTE = 1 << 2 13 | MODE_KANJI = 1 << 3 14 | 15 | # Encoding mode sizes. 16 | MODE_SIZE_SMALL = { 17 | MODE_NUMBER: 10, 18 | MODE_ALPHA_NUM: 9, 19 | MODE_8BIT_BYTE: 8, 20 | MODE_KANJI: 8, 21 | } 22 | MODE_SIZE_MEDIUM = { 23 | MODE_NUMBER: 12, 24 | MODE_ALPHA_NUM: 11, 25 | MODE_8BIT_BYTE: 16, 26 | MODE_KANJI: 10, 27 | } 28 | MODE_SIZE_LARGE = { 29 | MODE_NUMBER: 14, 30 | MODE_ALPHA_NUM: 13, 31 | MODE_8BIT_BYTE: 16, 32 | MODE_KANJI: 12, 33 | } 34 | 35 | ALPHA_NUM = six.b('0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:') 36 | RE_ALPHA_NUM = re.compile(six.b('^[') + re.escape(ALPHA_NUM) + six.b(']*\Z')) 37 | 38 | # The number of bits for numeric delimited data lengths. 39 | NUMBER_LENGTH = {3: 10, 2: 7, 1: 4} 40 | 41 | PATTERN_POSITION_TABLE = [ 42 | [], 43 | [6, 18], 44 | [6, 22], 45 | [6, 26], 46 | [6, 30], 47 | [6, 34], 48 | [6, 22, 38], 49 | [6, 24, 42], 50 | [6, 26, 46], 51 | [6, 28, 50], 52 | [6, 30, 54], 53 | [6, 32, 58], 54 | [6, 34, 62], 55 | [6, 26, 46, 66], 56 | [6, 26, 48, 70], 57 | [6, 26, 50, 74], 58 | [6, 30, 54, 78], 59 | [6, 30, 56, 82], 60 | [6, 30, 58, 86], 61 | [6, 34, 62, 90], 62 | [6, 28, 50, 72, 94], 63 | [6, 26, 50, 74, 98], 64 | [6, 30, 54, 78, 102], 65 | [6, 28, 54, 80, 106], 66 | [6, 32, 58, 84, 110], 67 | [6, 30, 58, 86, 114], 68 | [6, 34, 62, 90, 118], 69 | [6, 26, 50, 74, 98, 122], 70 | [6, 30, 54, 78, 102, 126], 71 | [6, 26, 52, 78, 104, 130], 72 | [6, 30, 56, 82, 108, 134], 73 | [6, 34, 60, 86, 112, 138], 74 | [6, 30, 58, 86, 114, 142], 75 | [6, 34, 62, 90, 118, 146], 76 | [6, 30, 54, 78, 102, 126, 150], 77 | [6, 24, 50, 76, 102, 128, 154], 78 | [6, 28, 54, 80, 106, 132, 158], 79 | [6, 32, 58, 84, 110, 136, 162], 80 | [6, 26, 54, 82, 110, 138, 166], 81 | [6, 30, 58, 86, 114, 142, 170] 82 | ] 83 | 84 | G15 = ( 85 | (1 << 10) | (1 << 8) | (1 << 5) | (1 << 4) | (1 << 2) | (1 << 1) | 86 | (1 << 0)) 87 | G18 = ( 88 | (1 << 12) | (1 << 11) | (1 << 10) | (1 << 9) | (1 << 8) | (1 << 5) | 89 | (1 << 2) | (1 << 0)) 90 | G15_MASK = (1 << 14) | (1 << 12) | (1 << 10) | (1 << 4) | (1 << 1) 91 | 92 | PAD0 = 0xEC 93 | PAD1 = 0x11 94 | 95 | # Precompute bit count limits, indexed by error correction level and code size 96 | _data_count = lambda block: block.data_count 97 | BIT_LIMIT_TABLE = [ 98 | [0] + [8*sum(map(_data_count, base.rs_blocks(version, error_correction))) 99 | for version in xrange(1, 41)] 100 | for error_correction in xrange(4) 101 | ] 102 | 103 | 104 | def BCH_type_info(data): 105 | d = data << 10 106 | while BCH_digit(d) - BCH_digit(G15) >= 0: 107 | d ^= (G15 << (BCH_digit(d) - BCH_digit(G15))) 108 | 109 | return ((data << 10) | d) ^ G15_MASK 110 | 111 | 112 | def BCH_type_number(data): 113 | d = data << 12 114 | while BCH_digit(d) - BCH_digit(G18) >= 0: 115 | d ^= (G18 << (BCH_digit(d) - BCH_digit(G18))) 116 | return (data << 12) | d 117 | 118 | 119 | def BCH_digit(data): 120 | digit = 0 121 | while data != 0: 122 | digit += 1 123 | data >>= 1 124 | return digit 125 | 126 | 127 | def pattern_position(version): 128 | return PATTERN_POSITION_TABLE[version - 1] 129 | 130 | 131 | def mask_func(pattern): 132 | """ 133 | Return the mask function for the given mask pattern. 134 | """ 135 | if pattern == 0: # 000 136 | return lambda i, j: (i + j) % 2 == 0 137 | if pattern == 1: # 001 138 | return lambda i, j: i % 2 == 0 139 | if pattern == 2: # 010 140 | return lambda i, j: j % 3 == 0 141 | if pattern == 3: # 011 142 | return lambda i, j: (i + j) % 3 == 0 143 | if pattern == 4: # 100 144 | return lambda i, j: (math.floor(i / 2) + math.floor(j / 3)) % 2 == 0 145 | if pattern == 5: # 101 146 | return lambda i, j: (i * j) % 2 + (i * j) % 3 == 0 147 | if pattern == 6: # 110 148 | return lambda i, j: ((i * j) % 2 + (i * j) % 3) % 2 == 0 149 | if pattern == 7: # 111 150 | return lambda i, j: ((i * j) % 3 + (i + j) % 2) % 2 == 0 151 | raise TypeError("Bad mask pattern: " + pattern) # pragma: no cover 152 | 153 | 154 | def mode_sizes_for_version(version): 155 | if version < 10: 156 | return MODE_SIZE_SMALL 157 | elif version < 27: 158 | return MODE_SIZE_MEDIUM 159 | else: 160 | return MODE_SIZE_LARGE 161 | 162 | 163 | def length_in_bits(mode, version): 164 | if mode not in ( 165 | MODE_NUMBER, MODE_ALPHA_NUM, MODE_8BIT_BYTE, MODE_KANJI): 166 | raise TypeError("Invalid mode (%s)" % mode) # pragma: no cover 167 | 168 | if version < 1 or version > 40: # pragma: no cover 169 | raise ValueError( 170 | "Invalid version (was %s, expected 1 to 40)" % version) 171 | 172 | return mode_sizes_for_version(version)[mode] 173 | 174 | 175 | def lost_point(modules): 176 | modules_count = len(modules) 177 | 178 | lost_point = 0 179 | 180 | lost_point = _lost_point_level1(modules, modules_count) 181 | lost_point += _lost_point_level2(modules, modules_count) 182 | lost_point += _lost_point_level3(modules, modules_count) 183 | lost_point += _lost_point_level4(modules, modules_count) 184 | 185 | return lost_point 186 | 187 | 188 | def _lost_point_level1(modules, modules_count): 189 | lost_point = 0 190 | 191 | modules_range = xrange(modules_count) 192 | row_range_first = (0, 1) 193 | row_range_last = (-1, 0) 194 | row_range_standard = (-1, 0, 1) 195 | 196 | col_range_first = ((0, 1), (1,)) 197 | col_range_last = ((-1, 0), (-1,)) 198 | col_range_standard = ((-1, 0, 1), (-1, 1)) 199 | 200 | for row in modules_range: 201 | 202 | if row == 0: 203 | row_range = row_range_first 204 | elif row == modules_count-1: 205 | row_range = row_range_last 206 | else: 207 | row_range = row_range_standard 208 | 209 | for col in modules_range: 210 | 211 | sameCount = 0 212 | dark = modules[row][col] 213 | 214 | if col == 0: 215 | col_range = col_range_first 216 | elif col == modules_count-1: 217 | col_range = col_range_last 218 | else: 219 | col_range = col_range_standard 220 | 221 | for r in row_range: 222 | 223 | row_offset = row + r 224 | 225 | if r != 0: 226 | col_idx = 0 227 | else: 228 | col_idx = 1 229 | 230 | for c in col_range[col_idx]: 231 | 232 | if dark == modules[row_offset][col + c]: 233 | sameCount += 1 234 | 235 | if sameCount > 5: 236 | lost_point += (3 + sameCount - 5) 237 | 238 | return lost_point 239 | 240 | 241 | def _lost_point_level2(modules, modules_count): 242 | lost_point = 0 243 | 244 | modules_range = xrange(modules_count - 1) 245 | 246 | for row in modules_range: 247 | this_row = modules[row] 248 | next_row = modules[row+1] 249 | for col in modules_range: 250 | count = 0 251 | if this_row[col]: 252 | count += 1 253 | if next_row[col]: 254 | count += 1 255 | if this_row[col + 1]: 256 | count += 1 257 | if next_row[col + 1]: 258 | count += 1 259 | if count == 0 or count == 4: 260 | lost_point += 3 261 | 262 | return lost_point 263 | 264 | 265 | def _lost_point_level3(modules, modules_count): 266 | modules_range_short = xrange(modules_count-6) 267 | 268 | lost_point = 0 269 | for row in xrange(modules_count): 270 | this_row = modules[row] 271 | for col in modules_range_short: 272 | if (this_row[col] 273 | and not this_row[col + 1] 274 | and this_row[col + 2] 275 | and this_row[col + 3] 276 | and this_row[col + 4] 277 | and not this_row[col + 5] 278 | and this_row[col + 6]): 279 | lost_point += 40 280 | 281 | for col in xrange(modules_count): 282 | for row in modules_range_short: 283 | if (modules[row][col] 284 | and not modules[row + 1][col] 285 | and modules[row + 2][col] 286 | and modules[row + 3][col] 287 | and modules[row + 4][col] 288 | and not modules[row + 5][col] 289 | and modules[row + 6][col]): 290 | lost_point += 40 291 | 292 | return lost_point 293 | 294 | 295 | def _lost_point_level4(modules, modules_count): 296 | modules_range = xrange(modules_count) 297 | dark_count = 0 298 | 299 | for row in modules_range: 300 | this_row = modules[row] 301 | for col in modules_range: 302 | if this_row[col]: 303 | dark_count += 1 304 | 305 | ratio = abs(100 * dark_count / modules_count / modules_count - 50) / 5 306 | return ratio * 10 307 | 308 | 309 | def optimal_data_chunks(data, minimum=4): 310 | """ 311 | An iterator returning QRData chunks optimized to the data content. 312 | 313 | :param minimum: The minimum number of bytes in a row to split as a chunk. 314 | """ 315 | data = to_bytestring(data) 316 | re_repeat = ( 317 | six.b('{') + six.text_type(minimum).encode('ascii') + six.b(',}')) 318 | num_pattern = re.compile(six.b('\d') + re_repeat) 319 | num_bits = _optimal_split(data, num_pattern) 320 | alpha_pattern = re.compile( 321 | six.b('[') + re.escape(ALPHA_NUM) + six.b(']') + re_repeat) 322 | for is_num, chunk in num_bits: 323 | if is_num: 324 | yield QRData(chunk, mode=MODE_NUMBER, check_data=False) 325 | else: 326 | for is_alpha, sub_chunk in _optimal_split(chunk, alpha_pattern): 327 | if is_alpha: 328 | mode = MODE_ALPHA_NUM 329 | else: 330 | mode = MODE_8BIT_BYTE 331 | yield QRData(sub_chunk, mode=mode, check_data=False) 332 | 333 | 334 | def _optimal_split(data, pattern): 335 | while data: 336 | match = re.search(pattern, data) 337 | if not match: 338 | break 339 | start, end = match.start(), match.end() 340 | if start: 341 | yield False, data[:start] 342 | yield True, data[start:end] 343 | data = data[end:] 344 | if data: 345 | yield False, data 346 | 347 | 348 | def to_bytestring(data): 349 | """ 350 | Convert data to a (utf-8 encoded) byte-string if it isn't a byte-string 351 | already. 352 | """ 353 | if not isinstance(data, six.binary_type): 354 | data = six.text_type(data).encode('utf-8') 355 | return data 356 | 357 | 358 | def optimal_mode(data): 359 | """ 360 | Calculate the optimal mode for this chunk of data. 361 | """ 362 | if data.isdigit(): 363 | return MODE_NUMBER 364 | if RE_ALPHA_NUM.match(data): 365 | return MODE_ALPHA_NUM 366 | return MODE_8BIT_BYTE 367 | 368 | 369 | class QRData: 370 | """ 371 | Data held in a QR compatible format. 372 | 373 | Doesn't currently handle KANJI. 374 | """ 375 | 376 | def __init__(self, data, mode=None, check_data=True): 377 | """ 378 | If ``mode`` isn't provided, the most compact QR data type possible is 379 | chosen. 380 | """ 381 | if check_data: 382 | data = to_bytestring(data) 383 | 384 | if mode is None: 385 | self.mode = optimal_mode(data) 386 | else: 387 | self.mode = mode 388 | if mode not in (MODE_NUMBER, MODE_ALPHA_NUM, MODE_8BIT_BYTE): 389 | raise TypeError("Invalid mode (%s)" % mode) # pragma: no cover 390 | if check_data and mode < optimal_mode(data): # pragma: no cover 391 | raise ValueError( 392 | "Provided data can not be represented in mode " 393 | "{0}".format(mode)) 394 | 395 | self.data = data 396 | 397 | def __len__(self): 398 | return len(self.data) 399 | 400 | def write(self, buffer): 401 | if self.mode == MODE_NUMBER: 402 | for i in xrange(0, len(self.data), 3): 403 | chars = self.data[i:i + 3] 404 | bit_length = NUMBER_LENGTH[len(chars)] 405 | buffer.put(int(chars), bit_length) 406 | elif self.mode == MODE_ALPHA_NUM: 407 | for i in xrange(0, len(self.data), 2): 408 | chars = self.data[i:i + 2] 409 | if len(chars) > 1: 410 | buffer.put( 411 | ALPHA_NUM.find(chars[0]) * 45 + 412 | ALPHA_NUM.find(chars[1]), 11) 413 | else: 414 | buffer.put(ALPHA_NUM.find(chars), 6) 415 | else: 416 | if six.PY3: 417 | # Iterating a bytestring in Python 3 returns an integer, 418 | # no need to ord(). 419 | data = self.data 420 | else: 421 | data = [ord(c) for c in self.data] 422 | for c in data: 423 | buffer.put(c, 8) 424 | 425 | def __repr__(self): 426 | return repr(self.data) 427 | 428 | 429 | class BitBuffer: 430 | 431 | def __init__(self): 432 | self.buffer = [] 433 | self.length = 0 434 | 435 | def __repr__(self): 436 | return ".".join([str(n) for n in self.buffer]) 437 | 438 | def get(self, index): 439 | buf_index = math.floor(index / 8) 440 | return ((self.buffer[buf_index] >> (7 - index % 8)) & 1) == 1 441 | 442 | def put(self, num, length): 443 | for i in range(length): 444 | self.put_bit(((num >> (length - i - 1)) & 1) == 1) 445 | 446 | def __len__(self): 447 | return self.length 448 | 449 | def put_bit(self, bit): 450 | buf_index = self.length // 8 451 | if len(self.buffer) <= buf_index: 452 | self.buffer.append(0) 453 | if bit: 454 | self.buffer[buf_index] |= (0x80 >> (self.length % 8)) 455 | self.length += 1 456 | 457 | 458 | def create_bytes(buffer, rs_blocks): 459 | offset = 0 460 | 461 | maxDcCount = 0 462 | maxEcCount = 0 463 | 464 | dcdata = [0] * len(rs_blocks) 465 | ecdata = [0] * len(rs_blocks) 466 | 467 | for r in range(len(rs_blocks)): 468 | 469 | dcCount = rs_blocks[r].data_count 470 | ecCount = rs_blocks[r].total_count - dcCount 471 | 472 | maxDcCount = max(maxDcCount, dcCount) 473 | maxEcCount = max(maxEcCount, ecCount) 474 | 475 | dcdata[r] = [0] * dcCount 476 | 477 | for i in range(len(dcdata[r])): 478 | dcdata[r][i] = 0xff & buffer.buffer[i + offset] 479 | offset += dcCount 480 | 481 | # Get error correction polynomial. 482 | rsPoly = base.Polynomial([1], 0) 483 | for i in range(ecCount): 484 | rsPoly = rsPoly * base.Polynomial([1, base.gexp(i)], 0) 485 | 486 | rawPoly = base.Polynomial(dcdata[r], len(rsPoly) - 1) 487 | 488 | modPoly = rawPoly % rsPoly 489 | ecdata[r] = [0] * (len(rsPoly) - 1) 490 | for i in range(len(ecdata[r])): 491 | modIndex = i + len(modPoly) - len(ecdata[r]) 492 | if (modIndex >= 0): 493 | ecdata[r][i] = modPoly[modIndex] 494 | else: 495 | ecdata[r][i] = 0 496 | 497 | totalCodeCount = 0 498 | for rs_block in rs_blocks: 499 | totalCodeCount += rs_block.total_count 500 | 501 | data = [None] * totalCodeCount 502 | index = 0 503 | 504 | for i in range(maxDcCount): 505 | for r in range(len(rs_blocks)): 506 | if i < len(dcdata[r]): 507 | data[index] = dcdata[r][i] 508 | index += 1 509 | 510 | for i in range(maxEcCount): 511 | for r in range(len(rs_blocks)): 512 | if i < len(ecdata[r]): 513 | data[index] = ecdata[r][i] 514 | index += 1 515 | 516 | return data 517 | 518 | 519 | def create_data(version, error_correction, data_list): 520 | 521 | buffer = BitBuffer() 522 | for data in data_list: 523 | buffer.put(data.mode, 4) 524 | buffer.put(len(data), length_in_bits(data.mode, version)) 525 | data.write(buffer) 526 | 527 | # Calculate the maximum number of bits for the given version. 528 | rs_blocks = base.rs_blocks(version, error_correction) 529 | bit_limit = 0 530 | for block in rs_blocks: 531 | bit_limit += block.data_count * 8 532 | 533 | if len(buffer) > bit_limit: 534 | raise exceptions.DataOverflowError( 535 | "Code length overflow. Data size (%s) > size available (%s)" % 536 | (len(buffer), bit_limit)) 537 | 538 | # Terminate the bits (add up to four 0s). 539 | for i in range(min(bit_limit - len(buffer), 4)): 540 | buffer.put_bit(False) 541 | 542 | # Delimit the string into 8-bit words, padding with 0s if necessary. 543 | delimit = len(buffer) % 8 544 | if delimit: 545 | for i in range(8 - delimit): 546 | buffer.put_bit(False) 547 | 548 | # Add special alternating padding bitstrings until buffer is full. 549 | bytes_to_fill = (bit_limit - len(buffer)) // 8 550 | for i in range(bytes_to_fill): 551 | if i % 2 == 0: 552 | buffer.put(PAD0, 8) 553 | else: 554 | buffer.put(PAD1, 8) 555 | 556 | return create_bytes(buffer, rs_blocks) 557 | -------------------------------------------------------------------------------- /qrcode/six.py: -------------------------------------------------------------------------------- 1 | """Utilities for writing code that runs on Python 2 and 3""" 2 | 3 | # Copyright (c) 2010-2015 Benjamin Peterson 4 | # 5 | # Permission is hereby granted, free of charge, to any person obtaining a copy 6 | # of this software and associated documentation files (the "Software"), to deal 7 | # in the Software without restriction, including without limitation the rights 8 | # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | # copies of the Software, and to permit persons to whom the Software is 10 | # furnished to do so, subject to the following conditions: 11 | # 12 | # The above copyright notice and this permission notice shall be included in all 13 | # copies or substantial portions of the Software. 14 | # 15 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | # SOFTWARE. 22 | 23 | from __future__ import absolute_import 24 | 25 | import functools 26 | import itertools 27 | import operator 28 | import sys 29 | import types 30 | 31 | __author__ = "Benjamin Peterson " 32 | __version__ = "1.10.0" 33 | 34 | 35 | # Useful for very coarse version differentiation. 36 | PY2 = sys.version_info[0] == 2 37 | PY3 = sys.version_info[0] == 3 38 | PY34 = sys.version_info[0:2] >= (3, 4) 39 | 40 | if PY3: 41 | string_types = str, 42 | integer_types = int, 43 | class_types = type, 44 | text_type = str 45 | binary_type = bytes 46 | 47 | MAXSIZE = sys.maxsize 48 | else: 49 | string_types = basestring, 50 | integer_types = (int, long) 51 | class_types = (type, types.ClassType) 52 | text_type = unicode 53 | binary_type = str 54 | 55 | if sys.platform.startswith("java"): 56 | # Jython always uses 32 bits. 57 | MAXSIZE = int((1 << 31) - 1) 58 | else: 59 | # It's possible to have sizeof(long) != sizeof(Py_ssize_t). 60 | class X(object): 61 | 62 | def __len__(self): 63 | return 1 << 31 64 | try: 65 | len(X()) 66 | except OverflowError: 67 | # 32-bit 68 | MAXSIZE = int((1 << 31) - 1) 69 | else: 70 | # 64-bit 71 | MAXSIZE = int((1 << 63) - 1) 72 | del X 73 | 74 | 75 | def _add_doc(func, doc): 76 | """Add documentation to a function.""" 77 | func.__doc__ = doc 78 | 79 | 80 | def _import_module(name): 81 | """Import module, returning the module after the last dot.""" 82 | __import__(name) 83 | return sys.modules[name] 84 | 85 | 86 | class _LazyDescr(object): 87 | 88 | def __init__(self, name): 89 | self.name = name 90 | 91 | def __get__(self, obj, tp): 92 | result = self._resolve() 93 | setattr(obj, self.name, result) # Invokes __set__. 94 | try: 95 | # This is a bit ugly, but it avoids running this again by 96 | # removing this descriptor. 97 | delattr(obj.__class__, self.name) 98 | except AttributeError: 99 | pass 100 | return result 101 | 102 | 103 | class MovedModule(_LazyDescr): 104 | 105 | def __init__(self, name, old, new=None): 106 | super(MovedModule, self).__init__(name) 107 | if PY3: 108 | if new is None: 109 | new = name 110 | self.mod = new 111 | else: 112 | self.mod = old 113 | 114 | def _resolve(self): 115 | return _import_module(self.mod) 116 | 117 | def __getattr__(self, attr): 118 | _module = self._resolve() 119 | value = getattr(_module, attr) 120 | setattr(self, attr, value) 121 | return value 122 | 123 | 124 | class _LazyModule(types.ModuleType): 125 | 126 | def __init__(self, name): 127 | super(_LazyModule, self).__init__(name) 128 | self.__doc__ = self.__class__.__doc__ 129 | 130 | def __dir__(self): 131 | attrs = ["__doc__", "__name__"] 132 | attrs += [attr.name for attr in self._moved_attributes] 133 | return attrs 134 | 135 | # Subclasses should override this 136 | _moved_attributes = [] 137 | 138 | 139 | class MovedAttribute(_LazyDescr): 140 | 141 | def __init__(self, name, old_mod, new_mod, old_attr=None, new_attr=None): 142 | super(MovedAttribute, self).__init__(name) 143 | if PY3: 144 | if new_mod is None: 145 | new_mod = name 146 | self.mod = new_mod 147 | if new_attr is None: 148 | if old_attr is None: 149 | new_attr = name 150 | else: 151 | new_attr = old_attr 152 | self.attr = new_attr 153 | else: 154 | self.mod = old_mod 155 | if old_attr is None: 156 | old_attr = name 157 | self.attr = old_attr 158 | 159 | def _resolve(self): 160 | module = _import_module(self.mod) 161 | return getattr(module, self.attr) 162 | 163 | 164 | class _SixMetaPathImporter(object): 165 | 166 | """ 167 | A meta path importer to import six.moves and its submodules. 168 | 169 | This class implements a PEP302 finder and loader. It should be compatible 170 | with Python 2.5 and all existing versions of Python3 171 | """ 172 | 173 | def __init__(self, six_module_name): 174 | self.name = six_module_name 175 | self.known_modules = {} 176 | 177 | def _add_module(self, mod, *fullnames): 178 | for fullname in fullnames: 179 | self.known_modules[self.name + "." + fullname] = mod 180 | 181 | def _get_module(self, fullname): 182 | return self.known_modules[self.name + "." + fullname] 183 | 184 | def find_module(self, fullname, path=None): 185 | if fullname in self.known_modules: 186 | return self 187 | return None 188 | 189 | def __get_module(self, fullname): 190 | try: 191 | return self.known_modules[fullname] 192 | except KeyError: 193 | raise ImportError("This loader does not know module " + fullname) 194 | 195 | def load_module(self, fullname): 196 | try: 197 | # in case of a reload 198 | return sys.modules[fullname] 199 | except KeyError: 200 | pass 201 | mod = self.__get_module(fullname) 202 | if isinstance(mod, MovedModule): 203 | mod = mod._resolve() 204 | else: 205 | mod.__loader__ = self 206 | sys.modules[fullname] = mod 207 | return mod 208 | 209 | def is_package(self, fullname): 210 | """ 211 | Return true, if the named module is a package. 212 | 213 | We need this method to get correct spec objects with 214 | Python 3.4 (see PEP451) 215 | """ 216 | return hasattr(self.__get_module(fullname), "__path__") 217 | 218 | def get_code(self, fullname): 219 | """Return None 220 | 221 | Required, if is_package is implemented""" 222 | self.__get_module(fullname) # eventually raises ImportError 223 | return None 224 | get_source = get_code # same as get_code 225 | 226 | _importer = _SixMetaPathImporter(__name__) 227 | 228 | 229 | class _MovedItems(_LazyModule): 230 | 231 | """Lazy loading of moved objects""" 232 | __path__ = [] # mark as package 233 | 234 | 235 | _moved_attributes = [ 236 | MovedAttribute("cStringIO", "cStringIO", "io", "StringIO"), 237 | MovedAttribute("filter", "itertools", "builtins", "ifilter", "filter"), 238 | MovedAttribute("filterfalse", "itertools", "itertools", "ifilterfalse", "filterfalse"), 239 | MovedAttribute("input", "__builtin__", "builtins", "raw_input", "input"), 240 | MovedAttribute("intern", "__builtin__", "sys"), 241 | MovedAttribute("map", "itertools", "builtins", "imap", "map"), 242 | MovedAttribute("getcwd", "os", "os", "getcwdu", "getcwd"), 243 | MovedAttribute("getcwdb", "os", "os", "getcwd", "getcwdb"), 244 | MovedAttribute("range", "__builtin__", "builtins", "xrange", "range"), 245 | MovedAttribute("reload_module", "__builtin__", "importlib" if PY34 else "imp", "reload"), 246 | MovedAttribute("reduce", "__builtin__", "functools"), 247 | MovedAttribute("shlex_quote", "pipes", "shlex", "quote"), 248 | MovedAttribute("StringIO", "StringIO", "io"), 249 | MovedAttribute("UserDict", "UserDict", "collections"), 250 | MovedAttribute("UserList", "UserList", "collections"), 251 | MovedAttribute("UserString", "UserString", "collections"), 252 | MovedAttribute("xrange", "__builtin__", "builtins", "xrange", "range"), 253 | MovedAttribute("zip", "itertools", "builtins", "izip", "zip"), 254 | MovedAttribute("zip_longest", "itertools", "itertools", "izip_longest", "zip_longest"), 255 | MovedModule("builtins", "__builtin__"), 256 | MovedModule("configparser", "ConfigParser"), 257 | MovedModule("copyreg", "copy_reg"), 258 | MovedModule("dbm_gnu", "gdbm", "dbm.gnu"), 259 | MovedModule("_dummy_thread", "dummy_thread", "_dummy_thread"), 260 | MovedModule("http_cookiejar", "cookielib", "http.cookiejar"), 261 | MovedModule("http_cookies", "Cookie", "http.cookies"), 262 | MovedModule("html_entities", "htmlentitydefs", "html.entities"), 263 | MovedModule("html_parser", "HTMLParser", "html.parser"), 264 | MovedModule("http_client", "httplib", "http.client"), 265 | MovedModule("email_mime_multipart", "email.MIMEMultipart", "email.mime.multipart"), 266 | MovedModule("email_mime_nonmultipart", "email.MIMENonMultipart", "email.mime.nonmultipart"), 267 | MovedModule("email_mime_text", "email.MIMEText", "email.mime.text"), 268 | MovedModule("email_mime_base", "email.MIMEBase", "email.mime.base"), 269 | MovedModule("BaseHTTPServer", "BaseHTTPServer", "http.server"), 270 | MovedModule("CGIHTTPServer", "CGIHTTPServer", "http.server"), 271 | MovedModule("SimpleHTTPServer", "SimpleHTTPServer", "http.server"), 272 | MovedModule("cPickle", "cPickle", "pickle"), 273 | MovedModule("queue", "Queue"), 274 | MovedModule("reprlib", "repr"), 275 | MovedModule("socketserver", "SocketServer"), 276 | MovedModule("_thread", "thread", "_thread"), 277 | MovedModule("tkinter", "Tkinter"), 278 | MovedModule("tkinter_dialog", "Dialog", "tkinter.dialog"), 279 | MovedModule("tkinter_filedialog", "FileDialog", "tkinter.filedialog"), 280 | MovedModule("tkinter_scrolledtext", "ScrolledText", "tkinter.scrolledtext"), 281 | MovedModule("tkinter_simpledialog", "SimpleDialog", "tkinter.simpledialog"), 282 | MovedModule("tkinter_tix", "Tix", "tkinter.tix"), 283 | MovedModule("tkinter_ttk", "ttk", "tkinter.ttk"), 284 | MovedModule("tkinter_constants", "Tkconstants", "tkinter.constants"), 285 | MovedModule("tkinter_dnd", "Tkdnd", "tkinter.dnd"), 286 | MovedModule("tkinter_colorchooser", "tkColorChooser", 287 | "tkinter.colorchooser"), 288 | MovedModule("tkinter_commondialog", "tkCommonDialog", 289 | "tkinter.commondialog"), 290 | MovedModule("tkinter_tkfiledialog", "tkFileDialog", "tkinter.filedialog"), 291 | MovedModule("tkinter_font", "tkFont", "tkinter.font"), 292 | MovedModule("tkinter_messagebox", "tkMessageBox", "tkinter.messagebox"), 293 | MovedModule("tkinter_tksimpledialog", "tkSimpleDialog", 294 | "tkinter.simpledialog"), 295 | MovedModule("urllib_parse", __name__ + ".moves.urllib_parse", "urllib.parse"), 296 | MovedModule("urllib_error", __name__ + ".moves.urllib_error", "urllib.error"), 297 | MovedModule("urllib", __name__ + ".moves.urllib", __name__ + ".moves.urllib"), 298 | MovedModule("urllib_robotparser", "robotparser", "urllib.robotparser"), 299 | MovedModule("xmlrpc_client", "xmlrpclib", "xmlrpc.client"), 300 | MovedModule("xmlrpc_server", "SimpleXMLRPCServer", "xmlrpc.server"), 301 | ] 302 | # Add windows specific modules. 303 | if sys.platform == "win32": 304 | _moved_attributes += [ 305 | MovedModule("winreg", "_winreg"), 306 | ] 307 | 308 | for attr in _moved_attributes: 309 | setattr(_MovedItems, attr.name, attr) 310 | if isinstance(attr, MovedModule): 311 | _importer._add_module(attr, "moves." + attr.name) 312 | del attr 313 | 314 | _MovedItems._moved_attributes = _moved_attributes 315 | 316 | moves = _MovedItems(__name__ + ".moves") 317 | _importer._add_module(moves, "moves") 318 | 319 | 320 | class Module_six_moves_urllib_parse(_LazyModule): 321 | 322 | """Lazy loading of moved objects in six.moves.urllib_parse""" 323 | 324 | 325 | _urllib_parse_moved_attributes = [ 326 | MovedAttribute("ParseResult", "urlparse", "urllib.parse"), 327 | MovedAttribute("SplitResult", "urlparse", "urllib.parse"), 328 | MovedAttribute("parse_qs", "urlparse", "urllib.parse"), 329 | MovedAttribute("parse_qsl", "urlparse", "urllib.parse"), 330 | MovedAttribute("urldefrag", "urlparse", "urllib.parse"), 331 | MovedAttribute("urljoin", "urlparse", "urllib.parse"), 332 | MovedAttribute("urlparse", "urlparse", "urllib.parse"), 333 | MovedAttribute("urlsplit", "urlparse", "urllib.parse"), 334 | MovedAttribute("urlunparse", "urlparse", "urllib.parse"), 335 | MovedAttribute("urlunsplit", "urlparse", "urllib.parse"), 336 | MovedAttribute("quote", "urllib", "urllib.parse"), 337 | MovedAttribute("quote_plus", "urllib", "urllib.parse"), 338 | MovedAttribute("unquote", "urllib", "urllib.parse"), 339 | MovedAttribute("unquote_plus", "urllib", "urllib.parse"), 340 | MovedAttribute("urlencode", "urllib", "urllib.parse"), 341 | MovedAttribute("splitquery", "urllib", "urllib.parse"), 342 | MovedAttribute("splittag", "urllib", "urllib.parse"), 343 | MovedAttribute("splituser", "urllib", "urllib.parse"), 344 | MovedAttribute("uses_fragment", "urlparse", "urllib.parse"), 345 | MovedAttribute("uses_netloc", "urlparse", "urllib.parse"), 346 | MovedAttribute("uses_params", "urlparse", "urllib.parse"), 347 | MovedAttribute("uses_query", "urlparse", "urllib.parse"), 348 | MovedAttribute("uses_relative", "urlparse", "urllib.parse"), 349 | ] 350 | for attr in _urllib_parse_moved_attributes: 351 | setattr(Module_six_moves_urllib_parse, attr.name, attr) 352 | del attr 353 | 354 | Module_six_moves_urllib_parse._moved_attributes = _urllib_parse_moved_attributes 355 | 356 | _importer._add_module(Module_six_moves_urllib_parse(__name__ + ".moves.urllib_parse"), 357 | "moves.urllib_parse", "moves.urllib.parse") 358 | 359 | 360 | class Module_six_moves_urllib_error(_LazyModule): 361 | 362 | """Lazy loading of moved objects in six.moves.urllib_error""" 363 | 364 | 365 | _urllib_error_moved_attributes = [ 366 | MovedAttribute("URLError", "urllib2", "urllib.error"), 367 | MovedAttribute("HTTPError", "urllib2", "urllib.error"), 368 | MovedAttribute("ContentTooShortError", "urllib", "urllib.error"), 369 | ] 370 | for attr in _urllib_error_moved_attributes: 371 | setattr(Module_six_moves_urllib_error, attr.name, attr) 372 | del attr 373 | 374 | Module_six_moves_urllib_error._moved_attributes = _urllib_error_moved_attributes 375 | 376 | _importer._add_module(Module_six_moves_urllib_error(__name__ + ".moves.urllib.error"), 377 | "moves.urllib_error", "moves.urllib.error") 378 | 379 | 380 | class Module_six_moves_urllib_request(_LazyModule): 381 | 382 | """Lazy loading of moved objects in six.moves.urllib_request""" 383 | 384 | 385 | _urllib_request_moved_attributes = [ 386 | MovedAttribute("urlopen", "urllib2", "urllib.request"), 387 | MovedAttribute("install_opener", "urllib2", "urllib.request"), 388 | MovedAttribute("build_opener", "urllib2", "urllib.request"), 389 | MovedAttribute("pathname2url", "urllib", "urllib.request"), 390 | MovedAttribute("url2pathname", "urllib", "urllib.request"), 391 | MovedAttribute("getproxies", "urllib", "urllib.request"), 392 | MovedAttribute("Request", "urllib2", "urllib.request"), 393 | MovedAttribute("OpenerDirector", "urllib2", "urllib.request"), 394 | MovedAttribute("HTTPDefaultErrorHandler", "urllib2", "urllib.request"), 395 | MovedAttribute("HTTPRedirectHandler", "urllib2", "urllib.request"), 396 | MovedAttribute("HTTPCookieProcessor", "urllib2", "urllib.request"), 397 | MovedAttribute("ProxyHandler", "urllib2", "urllib.request"), 398 | MovedAttribute("BaseHandler", "urllib2", "urllib.request"), 399 | MovedAttribute("HTTPPasswordMgr", "urllib2", "urllib.request"), 400 | MovedAttribute("HTTPPasswordMgrWithDefaultRealm", "urllib2", "urllib.request"), 401 | MovedAttribute("AbstractBasicAuthHandler", "urllib2", "urllib.request"), 402 | MovedAttribute("HTTPBasicAuthHandler", "urllib2", "urllib.request"), 403 | MovedAttribute("ProxyBasicAuthHandler", "urllib2", "urllib.request"), 404 | MovedAttribute("AbstractDigestAuthHandler", "urllib2", "urllib.request"), 405 | MovedAttribute("HTTPDigestAuthHandler", "urllib2", "urllib.request"), 406 | MovedAttribute("ProxyDigestAuthHandler", "urllib2", "urllib.request"), 407 | MovedAttribute("HTTPHandler", "urllib2", "urllib.request"), 408 | MovedAttribute("HTTPSHandler", "urllib2", "urllib.request"), 409 | MovedAttribute("FileHandler", "urllib2", "urllib.request"), 410 | MovedAttribute("FTPHandler", "urllib2", "urllib.request"), 411 | MovedAttribute("CacheFTPHandler", "urllib2", "urllib.request"), 412 | MovedAttribute("UnknownHandler", "urllib2", "urllib.request"), 413 | MovedAttribute("HTTPErrorProcessor", "urllib2", "urllib.request"), 414 | MovedAttribute("urlretrieve", "urllib", "urllib.request"), 415 | MovedAttribute("urlcleanup", "urllib", "urllib.request"), 416 | MovedAttribute("URLopener", "urllib", "urllib.request"), 417 | MovedAttribute("FancyURLopener", "urllib", "urllib.request"), 418 | MovedAttribute("proxy_bypass", "urllib", "urllib.request"), 419 | ] 420 | for attr in _urllib_request_moved_attributes: 421 | setattr(Module_six_moves_urllib_request, attr.name, attr) 422 | del attr 423 | 424 | Module_six_moves_urllib_request._moved_attributes = _urllib_request_moved_attributes 425 | 426 | _importer._add_module(Module_six_moves_urllib_request(__name__ + ".moves.urllib.request"), 427 | "moves.urllib_request", "moves.urllib.request") 428 | 429 | 430 | class Module_six_moves_urllib_response(_LazyModule): 431 | 432 | """Lazy loading of moved objects in six.moves.urllib_response""" 433 | 434 | 435 | _urllib_response_moved_attributes = [ 436 | MovedAttribute("addbase", "urllib", "urllib.response"), 437 | MovedAttribute("addclosehook", "urllib", "urllib.response"), 438 | MovedAttribute("addinfo", "urllib", "urllib.response"), 439 | MovedAttribute("addinfourl", "urllib", "urllib.response"), 440 | ] 441 | for attr in _urllib_response_moved_attributes: 442 | setattr(Module_six_moves_urllib_response, attr.name, attr) 443 | del attr 444 | 445 | Module_six_moves_urllib_response._moved_attributes = _urllib_response_moved_attributes 446 | 447 | _importer._add_module(Module_six_moves_urllib_response(__name__ + ".moves.urllib.response"), 448 | "moves.urllib_response", "moves.urllib.response") 449 | 450 | 451 | class Module_six_moves_urllib_robotparser(_LazyModule): 452 | 453 | """Lazy loading of moved objects in six.moves.urllib_robotparser""" 454 | 455 | 456 | _urllib_robotparser_moved_attributes = [ 457 | MovedAttribute("RobotFileParser", "robotparser", "urllib.robotparser"), 458 | ] 459 | for attr in _urllib_robotparser_moved_attributes: 460 | setattr(Module_six_moves_urllib_robotparser, attr.name, attr) 461 | del attr 462 | 463 | Module_six_moves_urllib_robotparser._moved_attributes = _urllib_robotparser_moved_attributes 464 | 465 | _importer._add_module(Module_six_moves_urllib_robotparser(__name__ + ".moves.urllib.robotparser"), 466 | "moves.urllib_robotparser", "moves.urllib.robotparser") 467 | 468 | 469 | class Module_six_moves_urllib(types.ModuleType): 470 | 471 | """Create a six.moves.urllib namespace that resembles the Python 3 namespace""" 472 | __path__ = [] # mark as package 473 | parse = _importer._get_module("moves.urllib_parse") 474 | error = _importer._get_module("moves.urllib_error") 475 | request = _importer._get_module("moves.urllib_request") 476 | response = _importer._get_module("moves.urllib_response") 477 | robotparser = _importer._get_module("moves.urllib_robotparser") 478 | 479 | def __dir__(self): 480 | return ['parse', 'error', 'request', 'response', 'robotparser'] 481 | 482 | _importer._add_module(Module_six_moves_urllib(__name__ + ".moves.urllib"), 483 | "moves.urllib") 484 | 485 | 486 | def add_move(move): 487 | """Add an item to six.moves.""" 488 | setattr(_MovedItems, move.name, move) 489 | 490 | 491 | def remove_move(name): 492 | """Remove item from six.moves.""" 493 | try: 494 | delattr(_MovedItems, name) 495 | except AttributeError: 496 | try: 497 | del moves.__dict__[name] 498 | except KeyError: 499 | raise AttributeError("no such move, %r" % (name,)) 500 | 501 | 502 | if PY3: 503 | _meth_func = "__func__" 504 | _meth_self = "__self__" 505 | 506 | _func_closure = "__closure__" 507 | _func_code = "__code__" 508 | _func_defaults = "__defaults__" 509 | _func_globals = "__globals__" 510 | else: 511 | _meth_func = "im_func" 512 | _meth_self = "im_self" 513 | 514 | _func_closure = "func_closure" 515 | _func_code = "func_code" 516 | _func_defaults = "func_defaults" 517 | _func_globals = "func_globals" 518 | 519 | 520 | try: 521 | advance_iterator = next 522 | except NameError: 523 | def advance_iterator(it): 524 | return it.next() 525 | next = advance_iterator 526 | 527 | 528 | try: 529 | callable = callable 530 | except NameError: 531 | def callable(obj): 532 | return any("__call__" in klass.__dict__ for klass in type(obj).__mro__) 533 | 534 | 535 | if PY3: 536 | def get_unbound_function(unbound): 537 | return unbound 538 | 539 | create_bound_method = types.MethodType 540 | 541 | def create_unbound_method(func, cls): 542 | return func 543 | 544 | Iterator = object 545 | else: 546 | def get_unbound_function(unbound): 547 | return unbound.im_func 548 | 549 | def create_bound_method(func, obj): 550 | return types.MethodType(func, obj, obj.__class__) 551 | 552 | def create_unbound_method(func, cls): 553 | return types.MethodType(func, None, cls) 554 | 555 | class Iterator(object): 556 | 557 | def next(self): 558 | return type(self).__next__(self) 559 | 560 | callable = callable 561 | _add_doc(get_unbound_function, 562 | """Get the function out of a possibly unbound function""") 563 | 564 | 565 | get_method_function = operator.attrgetter(_meth_func) 566 | get_method_self = operator.attrgetter(_meth_self) 567 | get_function_closure = operator.attrgetter(_func_closure) 568 | get_function_code = operator.attrgetter(_func_code) 569 | get_function_defaults = operator.attrgetter(_func_defaults) 570 | get_function_globals = operator.attrgetter(_func_globals) 571 | 572 | 573 | if PY3: 574 | def iterkeys(d, **kw): 575 | return iter(d.keys(**kw)) 576 | 577 | def itervalues(d, **kw): 578 | return iter(d.values(**kw)) 579 | 580 | def iteritems(d, **kw): 581 | return iter(d.items(**kw)) 582 | 583 | def iterlists(d, **kw): 584 | return iter(d.lists(**kw)) 585 | 586 | viewkeys = operator.methodcaller("keys") 587 | 588 | viewvalues = operator.methodcaller("values") 589 | 590 | viewitems = operator.methodcaller("items") 591 | else: 592 | def iterkeys(d, **kw): 593 | return d.iterkeys(**kw) 594 | 595 | def itervalues(d, **kw): 596 | return d.itervalues(**kw) 597 | 598 | def iteritems(d, **kw): 599 | return d.iteritems(**kw) 600 | 601 | def iterlists(d, **kw): 602 | return d.iterlists(**kw) 603 | 604 | viewkeys = operator.methodcaller("viewkeys") 605 | 606 | viewvalues = operator.methodcaller("viewvalues") 607 | 608 | viewitems = operator.methodcaller("viewitems") 609 | 610 | _add_doc(iterkeys, "Return an iterator over the keys of a dictionary.") 611 | _add_doc(itervalues, "Return an iterator over the values of a dictionary.") 612 | _add_doc(iteritems, 613 | "Return an iterator over the (key, value) pairs of a dictionary.") 614 | _add_doc(iterlists, 615 | "Return an iterator over the (key, [values]) pairs of a dictionary.") 616 | 617 | 618 | if PY3: 619 | def b(s): 620 | return s.encode("latin-1") 621 | 622 | def u(s): 623 | return s 624 | unichr = chr 625 | import struct 626 | int2byte = struct.Struct(">B").pack 627 | del struct 628 | byte2int = operator.itemgetter(0) 629 | indexbytes = operator.getitem 630 | iterbytes = iter 631 | import io 632 | StringIO = io.StringIO 633 | BytesIO = io.BytesIO 634 | _assertCountEqual = "assertCountEqual" 635 | if sys.version_info[1] <= 1: 636 | _assertRaisesRegex = "assertRaisesRegexp" 637 | _assertRegex = "assertRegexpMatches" 638 | else: 639 | _assertRaisesRegex = "assertRaisesRegex" 640 | _assertRegex = "assertRegex" 641 | else: 642 | def b(s): 643 | return s 644 | # Workaround for standalone backslash 645 | 646 | def u(s): 647 | return unicode(s.replace(r'\\', r'\\\\'), "unicode_escape") 648 | unichr = unichr 649 | int2byte = chr 650 | 651 | def byte2int(bs): 652 | return ord(bs[0]) 653 | 654 | def indexbytes(buf, i): 655 | return ord(buf[i]) 656 | iterbytes = functools.partial(itertools.imap, ord) 657 | import StringIO 658 | StringIO = BytesIO = StringIO.StringIO 659 | _assertCountEqual = "assertItemsEqual" 660 | _assertRaisesRegex = "assertRaisesRegexp" 661 | _assertRegex = "assertRegexpMatches" 662 | _add_doc(b, """Byte literal""") 663 | _add_doc(u, """Text literal""") 664 | 665 | 666 | def assertCountEqual(self, *args, **kwargs): 667 | return getattr(self, _assertCountEqual)(*args, **kwargs) 668 | 669 | 670 | def assertRaisesRegex(self, *args, **kwargs): 671 | return getattr(self, _assertRaisesRegex)(*args, **kwargs) 672 | 673 | 674 | def assertRegex(self, *args, **kwargs): 675 | return getattr(self, _assertRegex)(*args, **kwargs) 676 | 677 | 678 | if PY3: 679 | exec_ = getattr(moves.builtins, "exec") 680 | 681 | def reraise(tp, value, tb=None): 682 | if value is None: 683 | value = tp() 684 | if value.__traceback__ is not tb: 685 | raise value.with_traceback(tb) 686 | raise value 687 | 688 | else: 689 | def exec_(_code_, _globs_=None, _locs_=None): 690 | """Execute code in a namespace.""" 691 | if _globs_ is None: 692 | frame = sys._getframe(1) 693 | _globs_ = frame.f_globals 694 | if _locs_ is None: 695 | _locs_ = frame.f_locals 696 | del frame 697 | elif _locs_ is None: 698 | _locs_ = _globs_ 699 | exec("""exec _code_ in _globs_, _locs_""") 700 | 701 | exec_("""def reraise(tp, value, tb=None): 702 | raise tp, value, tb 703 | """) 704 | 705 | 706 | if sys.version_info[:2] == (3, 2): 707 | exec_("""def raise_from(value, from_value): 708 | if from_value is None: 709 | raise value 710 | raise value from from_value 711 | """) 712 | elif sys.version_info[:2] > (3, 2): 713 | exec_("""def raise_from(value, from_value): 714 | raise value from from_value 715 | """) 716 | else: 717 | def raise_from(value, from_value): 718 | raise value 719 | 720 | 721 | print_ = getattr(moves.builtins, "print", None) 722 | if print_ is None: 723 | def print_(*args, **kwargs): 724 | """The new-style print function for Python 2.4 and 2.5.""" 725 | fp = kwargs.pop("file", sys.stdout) 726 | if fp is None: 727 | return 728 | 729 | def write(data): 730 | if not isinstance(data, basestring): 731 | data = str(data) 732 | # If the file has an encoding, encode unicode with it. 733 | if (isinstance(fp, file) and 734 | isinstance(data, unicode) and 735 | fp.encoding is not None): 736 | errors = getattr(fp, "errors", None) 737 | if errors is None: 738 | errors = "strict" 739 | data = data.encode(fp.encoding, errors) 740 | fp.write(data) 741 | want_unicode = False 742 | sep = kwargs.pop("sep", None) 743 | if sep is not None: 744 | if isinstance(sep, unicode): 745 | want_unicode = True 746 | elif not isinstance(sep, str): 747 | raise TypeError("sep must be None or a string") 748 | end = kwargs.pop("end", None) 749 | if end is not None: 750 | if isinstance(end, unicode): 751 | want_unicode = True 752 | elif not isinstance(end, str): 753 | raise TypeError("end must be None or a string") 754 | if kwargs: 755 | raise TypeError("invalid keyword arguments to print()") 756 | if not want_unicode: 757 | for arg in args: 758 | if isinstance(arg, unicode): 759 | want_unicode = True 760 | break 761 | if want_unicode: 762 | newline = unicode("\n") 763 | space = unicode(" ") 764 | else: 765 | newline = "\n" 766 | space = " " 767 | if sep is None: 768 | sep = space 769 | if end is None: 770 | end = newline 771 | for i, arg in enumerate(args): 772 | if i: 773 | write(sep) 774 | write(arg) 775 | write(end) 776 | if sys.version_info[:2] < (3, 3): 777 | _print = print_ 778 | 779 | def print_(*args, **kwargs): 780 | fp = kwargs.get("file", sys.stdout) 781 | flush = kwargs.pop("flush", False) 782 | _print(*args, **kwargs) 783 | if flush and fp is not None: 784 | fp.flush() 785 | 786 | _add_doc(reraise, """Reraise an exception.""") 787 | 788 | if sys.version_info[0:2] < (3, 4): 789 | def wraps(wrapped, assigned=functools.WRAPPER_ASSIGNMENTS, 790 | updated=functools.WRAPPER_UPDATES): 791 | def wrapper(f): 792 | f = functools.wraps(wrapped, assigned, updated)(f) 793 | f.__wrapped__ = wrapped 794 | return f 795 | return wrapper 796 | else: 797 | wraps = functools.wraps 798 | 799 | 800 | def with_metaclass(meta, *bases): 801 | """Create a base class with a metaclass.""" 802 | # This requires a bit of explanation: the basic idea is to make a dummy 803 | # metaclass for one level of class instantiation that replaces itself with 804 | # the actual metaclass. 805 | class metaclass(meta): 806 | 807 | def __new__(cls, name, this_bases, d): 808 | return meta(name, bases, d) 809 | return type.__new__(metaclass, 'temporary_class', (), {}) 810 | 811 | 812 | def add_metaclass(metaclass): 813 | """Class decorator for creating a class with a metaclass.""" 814 | def wrapper(cls): 815 | orig_vars = cls.__dict__.copy() 816 | slots = orig_vars.get('__slots__') 817 | if slots is not None: 818 | if isinstance(slots, str): 819 | slots = [slots] 820 | for slots_var in slots: 821 | orig_vars.pop(slots_var) 822 | orig_vars.pop('__dict__', None) 823 | orig_vars.pop('__weakref__', None) 824 | return metaclass(cls.__name__, cls.__bases__, orig_vars) 825 | return wrapper 826 | 827 | 828 | def python_2_unicode_compatible(klass): 829 | """ 830 | A decorator that defines __unicode__ and __str__ methods under Python 2. 831 | Under Python 3 it does nothing. 832 | 833 | To support Python 2 and 3 with a single code base, define a __str__ method 834 | returning text and apply this decorator to the class. 835 | """ 836 | if PY2: 837 | if '__str__' not in klass.__dict__: 838 | raise ValueError("@python_2_unicode_compatible cannot be applied " 839 | "to %s because it doesn't define __str__()." % 840 | klass.__name__) 841 | klass.__unicode__ = klass.__str__ 842 | klass.__str__ = lambda self: self.__unicode__().encode('utf-8') 843 | return klass 844 | 845 | 846 | # Complete the moves implementation. 847 | # This code is at the end of this module to speed up module loading. 848 | # Turn this module into a package. 849 | __path__ = [] # required for PEP 302 and PEP 451 850 | __package__ = __name__ # see PEP 366 @ReservedAssignment 851 | if globals().get("__spec__") is not None: 852 | __spec__.submodule_search_locations = [] # PEP 451 @UndefinedVariable 853 | # Remove other six meta path importers, since they cause problems. This can 854 | # happen if six is removed from sys.modules and then reloaded. (Setuptools does 855 | # this for some reason.) 856 | if sys.meta_path: 857 | for i, importer in enumerate(sys.meta_path): 858 | # Here's some real nastiness: Another "instance" of the six module might 859 | # be floating around. Therefore, we can't use isinstance() to check for 860 | # the six meta path importer, since the other six instance will have 861 | # inserted an importer with different class. 862 | if (type(importer).__name__ == "_SixMetaPathImporter" and 863 | importer.name == __name__): 864 | del sys.meta_path[i] 865 | break 866 | del i, importer 867 | # Finally, add the importer to the meta path import hook. 868 | sys.meta_path.append(_importer) 869 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | {project} Copyright (C) {year} {fullname} 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------