Ejemplo n.º 1
0
    def make_qr_code(self):
        '''
        Make a QR code for the book.  This could be useful somewhere I guess.
        It contains the ISBN, title and Authors of the book.
        Maybe it should contain the owner name , yes YOU, just in case you ever need
        to split up you and your parter's books.  You know why that might be
        needed.
        TODO. Maybe print the ISBN too.
              Change output dir
        DONE: Store images in the DB
        '''
        from db_queries import sql as sql
        db_query = sql()
        if QR_CODE:
            import getpass
            user = getpass.getuser()
            # Do the QR thang
            qr_data = 'ISBN:'+ str(self.abook.id) \
              + ';TITLE:' +  str(self.abook.title) \
              + ';AUTHORS:' + str(self.abook.authors) \
              + ";OWNER:" + user
            qr = qrencode.encode(qr_data)
            # Rescale using the size and add a 1 px border
            size = qr[1]

            qr = qrencode.encode_scaled(qr_data, (size*3)+2)
            img = qr[2]

            count = db_query.get_qrcode_count(self.abook.id)
            if count == 0:
                sql = 'INSERT INTO qrcodes(caption,img) VALUES(%s,%s)' # But how to get them back out again?  See below.
                args = ("ISBN: " + str(self.abook.id), img, )
                self.cur.execute (sql, args)
                self.db.commit()
Ejemplo n.º 2
0
def exportwallet(wallet):
	db = open_db(os.path.join(WALLET_PATH,wallet))
	it = db.iteritems()
	it.seek_to_first()
	q = { "wallet" : wallet }
	a = []
	for k,v in it:
		if k[0] =="k":
			_,addr_type,child = k.split('.')
			a.append((addr_type,child))
		elif k == "_root":
			q.update({
					"root_id" : v
				})	
		elif k == "entropy":
			q.update({
					"entropy" : v
				})	
		elif k == "hmac":
			q.update({
					"hmac" : v
				})	
	q.update({
			"keys" : a
		})	
			
	result = base64.b64encode(str(q).encode('ascii')).decode('ascii')
	qr_code = "ip://" + result
	qr = qrencode.encode(qr_code,qrencode.QR_ECLEVEL_L)
	qr[2].save('wallet_qr_{0}_{1}_{2}.png'.format(qr[0],qr[1],wallet))
	return result
Ejemplo n.º 3
0
 def create_qrcode(filename, target_file):
     url = Config.get("url") + filename
     _, _, img = qrencode.encode(data=url, level=1)
     w, h = Screen.get_instance().get_size()
     sz = h / Config.get("qrcode")["screen_height_ratio"]
     img = img.resize((sz, sz))
     img.save(target_file)
Ejemplo n.º 4
0
def encodeText(text, zoom=5):
	'''Encodes text into a QPixmap with 5 pixels wide squares'''
	import qrencode
	_, rows, pilimage = qrencode.encode(text)
	temp = tempfile.NamedTemporaryFile(suffix='.png')
	pilimage.save(temp.name)
	return QPixmap(temp.name).scaled(rows * zoom, rows * zoom)
Ejemplo n.º 5
0
def encodeText(text, zoom=5):
    '''Encodes text into a QPixmap with 5 pixels wide squares'''
    import qrencode
    _, rows, pilimage = qrencode.encode(text)
    temp = tempfile.NamedTemporaryFile(suffix='.png')
    pilimage.save(temp.name)
    return QPixmap(temp.name).scaled(rows * zoom, rows * zoom)
    def create_img_data(self, btc_uri):
        (_, size, img) = qrencode.encode(btc_uri)
        if size < 400: img = img.resize((400, 400), Image.NEAREST)

        buf = StringIO()
        img.save(buf, format='PNG')
        imgdata = "data:image/png,%s" % urllib.quote(buf.getvalue())
        return imgdata
Ejemplo n.º 7
0
def qrcode_stream(text, pixel_size=8, format='png', **kwargs):
    (version, size, im) = qrcode_scale(qrencode.encode(text, **kwargs),
                                       pixel_size)

    buf = StringIO.StringIO()
    #qrencode.encode_scaled(text, size, **kwargs)[2].save(buf, format=format) # AllanC - encode_scaled dose not include the border reuiqred by the standard
    im.save(buf, format=format)
    return buf.getvalue()
Ejemplo n.º 8
0
	def getQRCode(self,address, amount, label=None, message=None):
		amount = 'amount=' + str(amount) #+ 'X8'
		label = '' if not label else '&label='+label
		message = '' if not message else '&message='+message
		qr_str = 'bitcoin:'+address+'?'+amount + label + message
		print qr_str
		im = qrencode.encode(qr_str,3)
		return im[2].resize((300,300))
Ejemplo n.º 9
0
    def create_img_data(self, btc_uri):
        (_, size, img) = qrencode.encode(btc_uri)
        if size < 400: img = img.resize((400, 400), Image.NEAREST)

        buf = StringIO()
        img.save(buf, format='PNG')
        imgdata = "data:image/png,%s" % urllib.quote(buf.getvalue())
        return imgdata
Ejemplo n.º 10
0
 def getQRCode(self, address, amount, label=None, message=None):
     amount = 'amount=' + str(amount)  #+ 'X8'
     label = '' if not label else '&label=' + label
     message = '' if not message else '&message=' + message
     qr_str = 'bitcoin:' + address + '?' + amount + label + message
     print qr_str
     im = qrencode.encode(qr_str, 3)
     return im[2].resize((300, 300))
Ejemplo n.º 11
0
 def Procesar(self):
     #Captura la informacion y genera el codigo QR
     
     #Define el resultado de los botones de radio
     if self.botonradio1.isChecked() == True:
         sexo = "Masculino"
     elif self.botonradio2.isChecked() == True:
         sexo = "Femenino"
     
     #Se procesa la informacion de los botones de check
     lista = {}
     dias = ("Lunes","Martes","Miercoles","Jueves","Viernes")
     lista["Lunes"] = self.lunes.isChecked()
     lista["Martes"] = self.martes.isChecked()
     lista["Miercoles"] = self.miercoles.isChecked()
     lista["Jueves"] = self.jueves.isChecked()
     lista["Viernes"] = self.viernes.isChecked()
     resultado = ""
     flag = 0
     for dia in lista.keys():
         for i in dias:
             if dia == i:
                 if lista[dia] == True:
                     if flag == 0:
                         resultado = dia
                         flag = 1
                     elif flag == 1:
                         resultado = resultado + ",%s" %dia
     
     #Se le da formato a la informacion recabada para generar el codigo QR
     texto = """
     Nombre:%s\n
     Cedula: %s\n
     Fecha Nacimiento: %s\n
     Sexo: %s\n
     Foto: %s\n
     Dia de participacion: %s\n
     
     """ %(self.nombreEdit.text(),
         self.cedula.text(),
         self.fecha.textFromDateTime(self.fecha.dateTime()),
         sexo,
         self.filename,
         resultado)
         
     #Se verifica si el archivo del codigo qr no existe, si no se borra
     if os.path.isfile("./archivosalida.png"):
         remove("./archivosalida.png")
     
     #Se crea la imagen del codigo qr
     imagen = encode(texto)[2]
     #Se salva la imagen en un archivo.
     imagen.save("./archivosalida.png")
     
     #Se muestra la imagen en la etiqueta
     pixmap = QtGui.QPixmap("./archivosalida.png")
     self.label.setPixmap(pixmap)
Ejemplo n.º 12
0
    def create_img_data(self, address, amount_str):
        (_, size, img) = qrencode.encode("bitcoin:%s?amount=%s&label=" %
                                         (address, amount_str))
        if size < 400: img = img.resize((400, 400), Image.NEAREST)

        buf = StringIO()
        img.save(buf, format='PNG')
        imgdata = "data:image/png,%s" % urllib.quote(buf.getvalue())
        return imgdata
    def create_img_data(self, address, amount_str):
        (_, size, img) = qrencode.encode("bitcoin:%s?amount=%s&label=" %
                (address, amount_str))
        if size < 400: img = img.resize((400, 400), Image.NEAREST)

        buf = StringIO()
        img.save(buf, format='PNG')
        imgdata = "data:image/png,%s" % urllib.quote(buf.getvalue())
        return imgdata
Ejemplo n.º 14
0
 def _getQR_Image(self, qrtext):
     #qrfile = open("qr.png","w")
     version, size, QRimage = qrencode.encode(qrtext,
                                              version=0,
                                              level=0,
                                              hint=2,
                                              case_sensitive=True)
     #qrfile.close()
     sizedQRimage = QRimage.resize((800, 800))
     return sizedQRimage
Ejemplo n.º 15
0
    def draw_footer(self):
        if not self.receipt and self.paymentterms:
            fullheight = len(self.paymentterms.splitlines()) * self.fontheight('DejaVu Serif', 6)
            t = self.canvas.beginText()
            t.setTextOrigin(cm(2), cm(1) + fullheight)
            t.setFont("DejaVu Serif", 6)
            self.textlines(t, self.paymentterms)
            self.canvas.drawText(t)

        if self.bankinfo:
            fullheight = 2 * self.fontheight('DejaVu Serif Bold', 9) + (2 + len(self.bankinfo.splitlines())) * self.fontheight('DejaVu Serif', 7)

            t = self.canvas.beginText()
            t.setTextOrigin(cm(13), cm(1) + fullheight)
            t.setFont("DejaVu Serif Bold", 9)
            t.textLine("Payment reference")

            t.setFont("DejaVu Serif", 7)
            t.textLine(self.paymentref)
            t.textLine("")

            t.setFont("DejaVu Serif Bold", 9)
            t.textLine("Bank references")

            t.setFont("DejaVu Serif", 7)
            self.textlines(t, self.bankinfo)

            self.canvas.drawText(t)

        if self.paymentlink:
            style = ParagraphStyle('temp')
            style.fontName = 'DejaVu Serif'
            style.fontSize = 5
            p = Paragraph('Payment details and instructions:<br/><nobr><a href="{0}">{0}</a></nobr>'.format(self.paymentlink), style)
            p.wrapOn(self.canvas, cm(12), cm(2))
            p.drawOn(self.canvas, cm(2), cm(3.5))

            try:
                import qrencode
                (ver, size, qrimage) = qrencode.encode(self.paymentlink)
                qrimage = qrimage.resize((size * 4, size * 4))
                self.canvas.drawImage(ImageReader(qrimage),
                                      cm(2), cm(1.8),
                                      cm(1.5), cm(1.5))
            except ImportError:
                # If we don't have the qrcode module, we just don't bother drawing the
                # QR code for the link
                pass

            if self.reverse_vat:
                t = self.canvas.beginText()
                t.setTextOrigin(cm(2), cm(4.8))
                t.setFont("DejaVu Serif", 6)
                self.textlines(t, "* Services subject to the reverse charge - VAT to be accounted for by the recipient as per Article 196 of Council Directive 2006/112/EC")
                self.canvas.drawText(t)
Ejemplo n.º 16
0
def QR(c, element, context):
    eclevel = {
        'L': qrencode.QR_ECLEVEL_L,
        'M': qrencode.QR_ECLEVEL_M,
        'Q': qrencode.QR_ECLEVEL_Q,
        'H': qrencode.QR_ECLEVEL_H
    }[element.get('eclevel', 'L')]

    version, pixels, qr = qrencode.encode(
        pystache.render(element['text'], context), 0, eclevel,
        qrencode.QR_MODE_8, element.get('caseSensitive', True))
    qr = qr.resize((pixels * 64, pixels * 64), Image.NEAREST)
    size = element['size'] * units.mm
    c.drawImage(ImageReader(qr),
                float(element['x']) * units.mm,
                -float(element['y']) * units.mm - size, size, size)
Ejemplo n.º 17
0
def generate_base64_qr(s, version, requested_size):
    try:
        import qrencode
    except ImportError:
        return ""

    (ver, size, qrimage) = qrencode.encode(s,
                                           version=5,
                                           level=qrencode.QR_ECLEVEL_M)
    if size < requested_size:
        size = (requested_size // size) * size
        qrimage = qrimage.resize((size, size), Image.NEAREST)

    b = BytesIO()
    qrimage.save(b, "png")
    return base64.b64encode(b.getvalue()).decode('ascii')
def generate_pdf(message, signed_message):
    doc = SimpleDocTemplate("qr_code_signed.pdf")
    Story = [Spacer(1,2*inch)]
    style = styles["Normal"]
    p = Paragraph(message, style)
    Story.append(p)
    Story.append(Spacer(1,200)) #0.2*inch
    
    # generate and save qrcode
    qrcode_version, qrcode_size, qrcode_im = qrencode.encode(
                                            signed_message, version=0, level=0,
                                            hint=qrencode.QR_MODE_8,
                                            case_sensitive=True)                
    qrcode_im.save("qrcode.png", "PNG")
    
    doc.build(Story, onFirstPage=myFirstPage, onLaterPages=myLaterPages)
Ejemplo n.º 19
0
def create_qr_code(invoice_id, invoice_total ,exch_rate):
    '''
    Create and save a QR code.
    @param invoice_id
    @param invoice_total
    @param exch_rate
    '''
    qr_data = 'bitcoin:' \
        + get_bitcoin_address('Work Done')[0] \
        + '?amount=' + str(round(invoice_total/exch_rate,8)) \
        + "&label=" + get_bitcoin_address('Work Done')[1] # FIXME: Search term shouldn't be hard coded here
    qr = qrencode.encode(qr_data)
    # Rescale using the size and add a 1 px border
    size = qr[1]
    qr = qrencode.encode_scaled(qr_data, (size*4))
    img = qr[2] #'invoice-' + str(invoice_id) +'.png'
    img.save('qr.png', 'png')
Ejemplo n.º 20
0
    def draw_qrimage(self, o):
        s = o.get('qrcontent')
        if not s:
            return
        if len(s) < 20:
            ver = 1
        elif len(s) < 38:
            ver = 2
        elif len(s) < 61:
            ver = 3
        elif len(s) < 90:
            ver = 4
        elif len(s) < 122:
            ver = 5
        elif len(s) < 154:
            ver = 6
        else:
            raise Exception("String too long for QR encode")

        try:
            import qrencode
        except ImportError:
            o2 = o.copy()
            o2['stroke'] = True
            o2['text'] = "qrencode library\nnot found"
            self.draw_box(o2)
            self.draw_paragraph(o2)
            return

        (ver, size, qrimage) = qrencode.encode(s,
                                               version=ver,
                                               level=qrencode.QR_ECLEVEL_M)
        if size < 500:
            size = (500 // size) * size
            qrimage = qrimage.resize((size, size), Image.NEAREST)

        self.canv.drawImage(
            ImageReader(qrimage),
            getmm(o, 'x'),
            self.calc_y(o),
            getmm(o, 'width'),
            getmm(o, 'height'),
            o.get('mask', 'auto'),
            preserveAspectRatio=True,
        )
def generate_pdf(message, signed_message):
    doc = SimpleDocTemplate("qr_code_signed.pdf")
    Story = [Spacer(1, 2 * inch)]
    style = styles["Normal"]
    p = Paragraph(message, style)
    Story.append(p)
    Story.append(Spacer(1, 200))  #0.2*inch

    # generate and save qrcode
    qrcode_version, qrcode_size, qrcode_im = qrencode.encode(
        signed_message,
        version=0,
        level=0,
        hint=qrencode.QR_MODE_8,
        case_sensitive=True)
    qrcode_im.save("qrcode.png", "PNG")

    doc.build(Story, onFirstPage=myFirstPage, onLaterPages=myLaterPages)
Ejemplo n.º 22
0
  def make_qr_code(self):
    '''
    Make a QR code for the book.  This could be useful somewhere I guess.
    It contains the ISBN, title and Authors of the book.
    Maybe it should contain the owner name , yes YOU, just in case you ever need
    to split up you and your parter's books.  You know why that might be
    needed.
    TODO. Maybe print the ISBN too.
          Change output dir
    DONE: Store images in the DB
    '''
    from db_queries import sql as sql
    db_query = sql()
    if QR_CODE:
      import getpass
      user = getpass.getuser()
      # Do the QR thang
      qr_data = 'ISBN:'+ str(self.abook.id) \
        + ';TITLE:' +  str(self.abook.title) \
        + ';AUTHORS:' + str(self.abook.authors) \
        + ";OWNER:" + user
      qr = qrencode.encode(qr_data)
      # Rescale using the size and add a 1 px border
      size = qr[1]

      qr = qrencode.encode_scaled(qr_data, (size*3)+2)
      img = qr[2]

      count = db_query.get_qrcode_count(self.abook.id)
      if count == 0:
        sql = 'INSERT INTO qrcodes(caption,img) VALUES(%s,%s)' # But how to get them back out again?  See below.
        args = ("ISBN: " + str(self.abook.id), img, )
        self.cur.execute (sql, args)
        self.db.commit()
      #pixmap,mask = pixbuf.render_pixmap_and_mask()
      #img.save('tmp.png', 'png')
      # Display it in the GUI
      #self.qr_img.set_from_image(img, mask) # may need to be gtk.image
      #self.qr_img.set_from_file('tmp.png') # fix this, I don't like using tmp files
      
      '''
Ejemplo n.º 23
0
def handler(req):
    debug = []
    err = lambda s: debug.append(str(s) + '<br>')
    path = req.unparsed_uri[len(BASE_PATH):].split('?')[0]
    if path == 'robots.txt' or path.startswith('.artwork/'):
        # fall back to next apache handler
        return mod_python.apache.DECLINED

    if not req.method in ('GET', 'POST', 'PUT'):
        return mod_python.apache.HTTP_BAD_REQUEST

    req.add_common_vars()
    var = mod_python.util.FieldStorage(req)
    def get_last_value(name, ret=None):
        cand = var.getlist(name)
        if len(cand):
            ret = cand[-1].value
        if isinstance(ret, bytes):
            ret = ret.decode()
        return ret

    try:
        rev = int(get_last_value('rev'))
    except TypeError:
        rev=None
    except ValueError:
        return mod_python.apache.HTTP_BAD_REQUEST

    # understand path, link+revision
    link = get_last_value('link') or None # empty form input
    if link:
        rev, data_hash = get_link(link, rev, get_link(link))
    else:
        if len(path) == 0:
            data_hash = hsh('')
        elif is_storage(STORAGE_DIR, path):
            data_hash = path
        elif get_link(path)[1]:
            link = path
            rev, data_hash = get_link(link, rev, get_link(link))
        elif find_storage(STORAGE_DIR, path):
            data_hash = find_storage(STORAGE_DIR, path)
        else:
            data_hash = None

    # load data
    data = read_storage(STORAGE_DIR, data_hash or '') or ''

    # handle new data
    if req.method == 'PUT':
        content = req.read()
    else:
        content = get_last_value('content', None)
        if req.method == 'POST':
            if get_last_value('linefeed') == 'unix':
                content = content.replace('\r\n', '\n')
    if content != None:
        if get_last_value('append') in (None, '0'):
            data = ''
        data = data + content
        if len(data) > FILE_SIZE_MAX:
            return mod_python.apache.HTTP_REQUEST_ENTITY_TOO_LARGE
        data_hash = hsh(data)
        if not is_storage(STORAGE_DIR, data_hash):
            if clamav and clamav.scan_stream(data.encode()):
                return mod_python.apache.HTTP_FORBIDDEN
            write_storage(STORAGE_DIR, data_hash, data)

    #update link
    if link != None and data_hash != None:
        if data_hash != get_link(link, rev)[1]:
            rev = append_link_history(link, data_hash)
    if link == None and data_hash != None and not find_storage(STORAGE_DIR, path):
        link = path
        rev = append_link_history(link, data_hash)
    if data_hash == None:
        return mod_python.apache.HTTP_NOT_FOUND

    #guess output format
    agent = req.headers_in.get('User-Agent', '').lower()
    if list(filter(lambda a: agent.count(a), ('mozilla', 'opera', 'validator', 'w3m', 'lynx', 'links'))):
        agent, output = 'graphic', 'html'
    else:
        agent, output = 'text', 'raw'
        if content:
            output = 'long'
    output = get_last_value('output', output)
    if output == 'qr':
        output = agent == 'graphic' and 'qr_png' or 'qr_utf8'

    # update browser url?
    BASE_URL = BASE_PROTO + req.headers_in['Host'] + BASE_PATH
    if get_last_value('output', 'html') == 'html':
        if link == None:
            short_hash = uniq_name(STORAGE_DIR, data_hash)
            if path != data_hash and path != short_hash:
                mod_python.util.redirect(req, "%s%s" % (BASE_URL, short_hash),
                    text="%s%s\n" % (BASE_URL, data_hash))
        else:
            if path != link:
                mod_python.util.redirect(req, "%s%s" % (BASE_URL, link),
                    text="%s%s\n" % (BASE_URL, data_hash))

    # url shortener and mime magic
    if not req.headers_in.get('referer', '').startswith(BASE_URL):
        m = re.compile('^(?:http|https|ftp)://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+$')
        if m.match(data):
            mod_python.util.redirect(req, data.rstrip(), permanent=True, text=data)
            return mod_python.apache.OK
        m = magic.Magic(magic.MAGIC_MIME).from_buffer(data).decode()
        if m.startswith('image/') or m == 'application/pdf':
            output = 'raw'

    #output
    req.content_type = "text/plain; charset=utf-8"
    text = []
    out = text.append
    if output == 'html':
        # handle theme
        theme = THEMES[1]
        cookie = mod_python.Cookie.get_cookie(req, 'theme', mod_python.Cookie.MarshalCookie, secret=COOKIE_SECRET)
        if type(cookie) is mod_python.Cookie.MarshalCookie:
            if cookie.value in THEMES:
                theme = cookie.value
        if get_last_value('theme') in THEMES:
            theme = get_last_value('theme')
            cookie = mod_python.Cookie.MarshalCookie(
                'theme', theme, secret=COOKIE_SECRET)
            cookie.expires = time.time() + 86400 * 365
            mod_python.Cookie.add_cookie(req, cookie)

        req.content_type = "text/html; charset=utf-8"
        out('<!DOCTYPE html>\n\n<html>\n<head>')
        out('<meta http-equiv="Content-Type" content="text/html; '
            'charset=utf-8">')
        out('<link rel="stylesheet" type="text/css" '
            'href="%s.artwork/hsh-link-basic.css">' % BASE_PATH)
        out('<link rel="stylesheet" type="text/css" '
            'href="%s.artwork/hsh-link-%s.css">' % (BASE_PATH, theme))
        out('<script src="%s.artwork/hsh-link.js"></script>' % BASE_PATH)
        out('<title>%s</title>\n</head>' % BASE_URL)
        out('<body onLoad="body_loaded()">\n<div class="container">')
        out('<form action="%s" method="POST" enctype="multipart/form-data">'
            % BASE_PATH)
        out('<div class="control">'
            '<a href="%s" title="start from scratch">clear</a>' % BASE_PATH)
        short_hash = data_hash and uniq_name(STORAGE_DIR, data_hash)
        out('<a title="short hash of content: %s" href="%s%s">short</a>'
            % (short_hash, BASE_PATH, short_hash))
        out('<a title="long hash of content: %s" href="%s%s">long</a>'
            % (data_hash, BASE_PATH, data_hash))

        if link:
            out('link=<a title="latest revision of link: %s" '
                'href="%s%s">%s</a>' % (link, BASE_PATH, link, link))
            out('<input type="hidden" name="link" value="%s">' % link)
            if rev != None and get_link(link, rev - 1, None):
                out('rev=<a title="previous revision of link: %s" '
                    'href="?rev=%s">-</a>' % (rev - 1, rev - 1))
            else:
                out('rev=&nbsp;')
            out('<a title="current revision of link: %s" '
                'href="?rev=%i">%i</a>' % ( rev or 0, rev or 0, rev or 0))
            if rev != None and get_link(link, rev + 1, None):
                out('<a title="next revision of link: %s" '
                    'href="?rev=%s">+</a>' % (rev + 1, rev + 1))
            else:
                out('&nbsp;')
        else:
            out('link=<input type="text" placeholder="add a tag/symlink ..." '
                'name="link" class="link" value="">')
        out('linefeed=<select name="linefeed" id="linefeed" '
            'onchange="data_modified()">')
        lf = (data and data.count('\r\n')) and ('', ' selected') or (' selected', '')
        out('<option value="unix"%s>unix</option><option value="dos"%s>dos</option></select>' % lf)
        out(' output=<select name="output" id="output" onchange="output_selected()">')
        for output_ in OUTPUT:
            out('<option value="%s"%s>%s</option>'
                % (output_, output == output_ and ' selected' or '', output_))
        out('</select>')
        out('<input type="submit" id="save" title="save changes" '
            'value="save"> </div>')
        out('<div class="text"><textarea placeholder="Start typing ..." '
            'name="content" id="content" onclick="update_lineno()" '
            'onkeyup="update_lineno()" oninput="data_modified()">%s</textarea>'
            '</div>' % data)
        out('<div class="footer">(c) <a href="http://xmw.de/">xmw.de</a> 2014 '
            '<a href="https://github.com/xmw/hsh-link">sources</a> '
            '<a href="http://validator.w3.org/check?uri=referer">html5</a> '
            '<a href="http://jigsaw.w3.org/css-validator/check/referer">css3</a> '
            'theme=<a href="?theme=xmw">xmw</a> '
            '<a href="?theme=white">white</a>'
            ' line=<input type="text" name="lineno" '
            'id="lineno" value="1" size="4" readonly>')
        out('<a href="http://www.multipath-tcp.org/">mptcp</a>=%s'
            % (is_mptcp(req) and 'yes' or 'no'))
        out('mimetype=%s' % magic.Magic(magic.MAGIC_MIME).from_buffer(data.encode()).decode())
        out('</div></form></div>\n</body>\n</html>\n')
    elif output in ('qr_png', 'qr_ascii', 'qr_utf8'):
        ver, s, img = qrencode.encode(BASE_URL + (link or data_hash or ''),
            level=qrencode.QR_ECLEVEL_L, hint=qrencode.QR_MODE_8, case_sensitive=True)
        img = PIL.ImageOps.expand(img, border=1, fill='white')
        if output == 'qr_png':
            img = img.resize((s * 8, s * 8), PIL.Image.NEAREST)
            req.content_type = "image/png; charset=utf-8"
            img.save(req, 'PNG')
        elif output == 'qr_ascii':
            sym = ('  ', '@@')
            for y in range(img.size[1]):
                out(''.join(map(lambda x: sym[img.getpixel((x,y)) != 0], range(img.size[0]))))
            out('')
        elif output == 'qr_utf8':
            sym = (' ', '▄') , ('▀', '█')
            for y in range(img.size[1]//2):
                out(''.join(map(lambda x: sym[img.getpixel((x,y*2)) != 0][img.getpixel((x,y*2+1)) != 0], range(img.size[0]))))
            if img.size[1] % 2:
                out(''.join(map(lambda x: sym[img.getpixel((x,img.size[1]-1)) != 0][0], range(img.size[0]))))
            out('')
    elif output == 'raw':
        req.content_type = ''
        out(data)
    elif output == 'long':
        out("%s%s\n" % (BASE_URL, data_hash))
    elif output == 'short':
        out("%s%s\n" % (BASE_URL, uniq_name(STORAGE_DIR, data_hash)))
    else:
        return mod_python.apache.HTTP_BAD_REQUEST
    text += debug
    req.write("\n".join(text))
    return mod_python.apache.OK
Ejemplo n.º 24
0
	def __init__(self,stringValue):
		self.image = qrencode.encode(stringValue)[2]
		self.image.save('resources/images/qr.png')
Ejemplo n.º 25
0
def test_encode_bytes(value):
    assert qrencode.encode(value)
Ejemplo n.º 26
0
try:
  db = MySQLdb.connect(db='books',  passwd = 'pu5tu1e');
except:
  print "No database connection"
  db = False
#db= False # debugging
if db: cur = db.cursor()

cur.execute("select * from books;")
#rows = cur.fetchall()

row = cur.fetchone() 
while row is not None:
    title = row[1]
    authors = row[2]
    bar = row[3]
    qr = qrencode.encode('ISBN:'+ str(bar) + ' TITLE:' + str(title) + ' AUTHORS:' + str(authors))
    size = qr[1]
    #print size
    qr = qrencode.encode_scaled('ISBN:'+ str(bar) + ' TITLE:' + str(title) + ' AUTHORS:' + str(authors), size*2)
    img = qr[2]
    size = qr[1]
    #print size
    print str(bar)
    img.save('../ISBN:' + str(bar) + '.png', 'png')
    row = cur.fetchone()




db.close()
Ejemplo n.º 27
0
 def qrencode_fn(s):
     return encode(s)[2]
Ejemplo n.º 28
0
try:
    db = MySQLdb.connect(db='books', passwd='pu5tu1e')
except:
    print "No database connection"
    db = False
#db= False # debugging
if db: cur = db.cursor()

cur.execute("select * from books;")
#rows = cur.fetchall()

row = cur.fetchone()
while row is not None:
    title = row[1]
    authors = row[2]
    bar = row[3]
    qr = qrencode.encode('ISBN:' + str(bar) + ' TITLE:' + str(title) +
                         ' AUTHORS:' + str(authors))
    size = qr[1]
    #print size
    qr = qrencode.encode_scaled(
        'ISBN:' + str(bar) + ' TITLE:' + str(title) + ' AUTHORS:' +
        str(authors), size * 2)
    img = qr[2]
    size = qr[1]
    #print size
    print str(bar)
    img.save('../ISBN:' + str(bar) + '.png', 'png')
    row = cur.fetchone()

db.close()
Ejemplo n.º 29
0
	def qrSet(self, msg):
		""" Set content of displayed qr image. """
		if msg == None or msg == "":
			msg = "Katze"
		(qrVersion, qrSize, qrImg) = qrencode.encode(msg, 0)
		self.qrimg.set_from_pixbuf(self.image2pixbuf(qrImg))
Ejemplo n.º 30
0
def test_encode_string(value):
    assert qrencode.encode(value)
Ejemplo n.º 31
0
 def _getQR_Image(self, qrtext):
     #qrfile = open("qr.png","w")
     version , size, QRimage = qrencode.encode(qrtext, version=0 , level=0, hint=2, case_sensitive=True)
     #qrfile.close()
     sizedQRimage = QRimage.resize((800,800))
     return sizedQRimage
Ejemplo n.º 32
0
def test_encode_invalid_data(value):
    with pytest.raises(ValueError):
        qrencode.encode(value)
Ejemplo n.º 33
0
while srccontent:
    parts.append(srccontent[0:DIVIDE])
    srccontent = srccontent[DIVIDE:]

# ## ###

qrimages = []
maxsize = 0

seqid = 0
for each in parts:
    packaged = adler32 + hex(seqid)[2:].zfill(2) + \
               each.encode('base64').replace('\n','').rstrip('=')
    qrc = qrencode.encode(packaged,
                          0,
                          qrencode.QR_ECLEVEL_M,
                          qrencode.QR_MODE_KANJI,
                          True)
    qrimages.append((qrc[1],qrc[2]))
    maxsize = max(maxsize,qrc[1])
    seqid += 1

# Joining all small codes
imagescount = len(qrimages)
maxsize = int(maxsize * 1.2)

colmax = max(1,
             min(math.ceil(math.sqrt(imagescount)),
                 math.floor(MAXWIDTH * 1.0 / maxsize / SCALERATIO ))
             )
rowmax = math.ceil(imagescount * 1.0 / colmax)
Ejemplo n.º 34
0
def create_barcode(chunkdata):
    version, size, im = qrencode.encode(chunkdata,
                                        level=qrencode.QR_ECLEVEL_H,
                                        case_sensitive=True)
    return im
Ejemplo n.º 35
0
def main():
    global joy_pub

    parser = argparse.ArgumentParser()
    parser.add_argument(
        '--host', type=str, default='localhost',
        help='host name or IP address',)
    parser.add_argument(
        '--port', type=int, default='9381',
        help='port number',)
    parser.add_argument(
        '--qr', action='store_true', default=False,
        help='show QR code',)
    # use argparse, but only after ROS did its thing
    argv = rospy.myargv()
    args = parser.parse_args(argv[1:])

    settings = dict(
        static_path= os.path.join(os.path.dirname(__file__), "static"),
        cookie_secret=os.urandom(1024),
        template_path=os.path.join(os.path.dirname(__file__), "templates"),
        xsrf_cookies= True,
        debug=True,
        )

    echo_ws_path = 'echo'
    base_url = args.host
    if args.port != 80:
        base_url = base_url+':'+str(args.port)

    js_path='web_control.js'
    dd = {'base_url':base_url,
          'echo_ws_path':echo_ws_path,
          'js_path':js_path,
          }

    EchoRouter = SockJSRouter(EchoHandler, r'/'+echo_ws_path)

    application = tornado.web.Application([
        (r'/', MainHandler, dict(cfg=dd)),
        (r'/'+js_path, JSHandler, dict(cfg=dd)),
        ]+EchoRouter.urls,
                                          **settings)


    url = "http://%s"%base_url
    rospy.loginfo("starting web server at %s" % url)

    if args.qr:
        import qrencode
        import Image
        # encode the URL
        _,_,im = qrencode.encode(url)

        # resize the image to be about 512x512
        target_w = 512
        scale = target_w//im.size[0]
        actual_w = im.size[0]*scale
        actual_h = im.size[1]*scale
        im = im.resize( (actual_w, actual_h), Image.NEAREST )

        # save the image
        fobj = tempfile.NamedTemporaryFile(mode='wb',suffix='.png',
                                           prefix='browser_joy_')
        im.save(fobj,'png')
        fname = fobj.name

        # open the image
        if sys.platform.startswith('linux'):
            cmd = 'xdg-open'
        elif sys.platform.startswith('win'):
            cmd = 'start'
        else:
            # mac?
            cmd = 'open'
        full_cmd = ' '.join([cmd,fname])
        subprocess.call(full_cmd,shell=True)

    node_name = os.path.splitext(os.path.basename(__file__))[0]
    rospy.init_node( node_name, disable_signals=True )

    joy_pub = rospy.Publisher("joy", Joy)

    http_server = tornado.httpserver.HTTPServer(application)
    http_server.listen(args.port)
    tornado.ioloop.IOLoop.instance().start()