Example #1
0
def main():

    if common.debug:
        print "BEGIN offline_sign_tx"

    qrcode_tx_to_sign = Popen(["zbarimg", "--quiet", "images/raw_tx_to_sign.png"], stdout=PIPE).stdout.read()
    tx_to_sign = common.get_qrcode_val_from_str(qrcode_tx_to_sign).split(",")

    unspent_tx_output_details = [{"txid": str(tx_to_sign[1]),
                                  "vout": int(tx_to_sign[2]),
                                  "scriptPubKey": str(tx_to_sign[3])}]

    if common.debug:
        print "raw tx data read from qrcode"

    offline_sign_raw_tx = common.request(common_offline.off_url,
                                         {'method': 'signrawtransaction',
                                        'params': [tx_to_sign[0], unspent_tx_output_details]})

    if not offline_sign_raw_tx["result"]["complete"]:
        print "ERROR! tx signing incomplete!"
        print offline_sign_raw_tx
        sys.exit(1)

    if common.debug:
        print "signed tx offline: " + str(offline_sign_raw_tx)

    qrcode.make(offline_sign_raw_tx["result"]["hex"]).save('images/offline_signed_tx.png')

    if common.debug:
        print "signed offline transaction and saved qrcode: offline_signed_tx.png"
        print "END offline_sign_tx"
Example #2
0
def generate_QRcodes():
    for i in range(1, len(checkpoints) + 1):
        img = qrcode.make('%s/item/%s' %(config['base_url'],
            uuid_str(i)))
        img.save('checkpoint_%d.png' %(i))
    img = qrcode.make('%s/start' % (config['base_url']))
    img.save('start.png')
Example #3
0
def item_create(form):
    record = db(db.geo_item.f_name == request.vars.f_name).select().first()
    if record.f_qrcode == None:
        arg = str(record.id)
        path = 'http://siri.pythonanywhere.com/byui_art/default/item_details?itemId=' + arg + '&qr=True'
        tiny = ""
        shortSuccess = False
        try:
            shortener = Shortener('Tinyurl')
            tiny = "{}".format(shortener.short(path))
            session.tinyCreateException = tiny
            shortSuccess = True
        except:
            session.tinyCreateException = "There was a problem with the url shortener. Please try again."

        if shortSuccess:
            code = qrcode.make(tiny)
        else:
            code = qrcode.make(path)
        qrName='geo_item.f_qrcode.%s.jpg' % (uuid.uuid4())
        code.save(request.folder + 'uploads/qrcodes/' + qrName, 'JPEG')
        record.update_record(f_qrcode=qrName)
        qr_text(qrName, record.f_name, record.f_alt5, tiny)
    try:
        imgPath = request.folder + 'uploads/' + record.f_image
        thumbName = 'geo_item.f_thumb.%s.%s.jpg' % (uuid.uuid4(), record.id)
        thumb = Image.open(request.folder + 'uploads/' + record.f_image)
        thumb.thumbnail((350, 10000), Image.ANTIALIAS)
        thumb.save(request.folder + 'uploads/thumbs/' + thumbName, 'JPEG')
        record.update_record(f_thumb=thumbName)
    except:
        session.itemCreateException = "there was a problem updating the image in item_create: " + record.f_name
    return dict()
Example #4
0
    def response(self):
        """
        Create a response dict to be returned (JSON formatted) to the API client.

        If this is an OK response for an OATH token, this involves creating a
        QR code image with the plaintext key etc. to facilitate provisioning of
        smart phone apps such as Google Authenticator.

        :return: Response
        :rtype: dict
        """
        res = {'status': 'ERROR'}
        if self._status:
            res['status'] = 'OK'
        self._logger.debug("Creating {!r} response for {!r}".format(self._status, self._request))
        if isinstance(self._request.token, AddOATHTokenRequest):
            if self._status:
                key_uri = self._request.token.key_uri(self.aead)
                buf = StringIO.StringIO()
                qrcode.make(key_uri).save(buf)
                self._logger.info("Created authuser with id {!s}, credential id {!s}".format(self._user.user_id,
                                                                                             self._token_id))
                res['OATH'] = {'user_id': self._user.user_id,
                               'hmac_key': self.aead.secret,
                               'key_uri': key_uri,
                               'qr_png': buf.getvalue().encode('base64'),
                               }
        res['nonce'] = self._request.nonce  # Copy nonce (request id) from request to response
        return res
Example #5
0
def make_qr(src_text):
  img = None
  if len(src_text) < 1024:
    img = qrcode.make( src_text )
  else:
    img = qrcode.make("too long keyword")
  return img
Example #6
0
def get_state(**kwargs):
    eppn = mock_auth.authenticate(kwargs)
    current_app.logger.debug('Getting state for user with eppn {}.'.format(eppn))
    proofing_state = current_app.proofing_statedb.get_state_by_eppn(eppn, raise_on_missing=False)
    if not proofing_state:
        current_app.logger.debug('No proofing state found, initializing new proofing flow.'.format(eppn))
        state = get_unique_hash()
        nonce = get_unique_hash()
        token = get_unique_hash()
        proofing_state = OidcProofingState({'eduPersonPrincipalName': eppn, 'state': state, 'nonce': nonce,
                                            'token': token})
        claims_request = ClaimsRequest(userinfo=Claims(identity=None, vetting_time=None, metadata=None))
        # Initiate proofing
        response = do_authentication_request(state, nonce, token, claims_request)
        if response.status_code != 200:
            payload = {'error': response.reason, 'message': response.content}
            raise ApiException(status_code=response.status_code, payload=payload)
        # If authentication request went well save user state
        current_app.proofing_statedb.save(proofing_state)
        current_app.logger.debug('Proofing state {} for user {} saved'.format(proofing_state.state, eppn))
    # Return nonce and nonce as qr code
    current_app.logger.debug('Returning nonce for user {}'.format(eppn))
    buf = BytesIO()
    qr_code = '1' + json.dumps({'nonce': proofing_state.nonce, 'token': proofing_state.token})
    qrcode.make(qr_code).save(buf)
    qr_b64 = base64.b64encode(buf.getvalue()).decode()
    ret = {
        'qr_code': qr_code,
        'qr_img': '<img src="data:image/png;base64, {}"/>'.format(qr_b64),
    }
    return ret
Example #7
0
def generate(data):
    md5sum = md5(data).hexdigest()
    filename = '%s.png' % md5sum
    filepath = os.path.join(files_path, filename)
    if not os.path.exists(filepath):
        qrcode.make(data).save(open(filepath, 'wb'))
    return (filename, md5sum)
Example #8
0
File: app.py Project: zparmley/YH12
def vote_qr_code(vote):
    if vote not in votes_config:
        return None
    out = StringIO.StringIO()
    qrcode.make('bitcoin:%s?amount=%s&label=%s' % (votes_config[vote]['address'], votes_config[vote]['ammount'], votes_config[vote]['label'])).save(out)
    resp = make_response(out.getvalue())
    resp.content_type = 'image/png'
    return resp
Example #9
0
 def _genBarcode(self, content):
     md5 = hashlib.md5(bytes(content, 'utf-8')).hexdigest()
     path = os.path.join(PKG_DIR, 'images', 'qrcodes', '{}.png'.format(md5))
     # 是否存在这个md5文件,如果有直接返回结果,如果没有则生成
     if os.path.isfile(path):
         return path
     qrcode.make(content).save(path)
     return path
Example #10
0
def qr(uid, task, filetype, tempfile=False):
    endpoint = ".download_temp" if tempfile else ".download"
    url = url_for(endpoint, uid=uid, taskname=task, filetype=filetype, _external=True)

    img = StringIO()
    qrcode.make(url, box_size=3).save(img)
    img.seek(0)

    return send_file(img, mimetype="image/png")
def qrc(data):
    import cStringIO
    import qrcode
    import qrcode.image.svg

    out = cStringIO.StringIO()
    qrcode.make(data, image_factory=qrcode.image.svg.SvgPathImage).save(out)
    qrsvg = out.getvalue()

    return re.search('d="(.*?)"', qrsvg).group(1)
Example #12
0
def make_qrcode_base64(text):
    # Create a temporary placeholder to the image
    with BytesIO() as stream:
        # Generate the qrcode and save to the stream
        qrcode.make(text).save(stream)

        # Get the image bytes, then encode to base64
        image_data = b64encode(stream.getvalue())

    return image_data
Example #13
0
def _getQRCode(text):
    try:
        import qrcode
        import base64
        import Image    # required by qrcode but not formally a dependency
    except:
        return None

    data = StringIO()
    qrcode.make(text, box_size=5).save(data, 'png')
    return 'data:image/png;base64,' + base64.b64encode(data.getvalue())
def main():
    if common.debug:
        print "BEGIN offline_create_address"

    offline_address1 = common.request(common_offline.off_url, {'method': 'getnewaddress'})["result"]
    qrcode.make(offline_address1).save("images/offline_address1.png")
    offline_address2 = common.request(common_offline.off_url, {'method': 'getnewaddress'})["result"]
    qrcode.make(offline_address2).save("images/offline_address2.png")

    if common.debug:
        print "offline address1: " + offline_address1
        print "offline address2: " + offline_address2
        print "offline addresses saved to qrcode"
        print "END offline_create_address"
Example #15
0
def get_state(**kwargs):
    # TODO: Authenticate user authn response:
    # TODO: Look up user in central db
    eppn = mock_auth.authenticate(kwargs)
    current_app.logger.debug('Getting state for user with eppn {!s}.'.format(eppn))
    proofing_state = current_app.proofing_statedb.get_state_by_eppn(eppn, raise_on_missing=False)
    if not proofing_state:
        current_app.logger.debug('No proofing state found, initializing new proofing flow.'.format(eppn))
        state = get_unique_hash()
        nonce = get_unique_hash()
        proofing_state = OidcProofingState({'eduPersonPrincipalName': eppn, 'state': state, 'nonce': nonce})
        # Initiate proofing
        args = {
            'client_id': current_app.oidc_client.client_id,
            'response_type': 'code id_token token',
            'response_mode': 'query',
            'scope': ['openid'],
            'redirect_uri': url_for('oidc_proofing.authorization_response', _external=True),
            'state': state,
            'nonce': nonce,
            'claims': ClaimsRequest(userinfo=Claims(identity=None)).to_json()
        }
        current_app.logger.debug('AuthenticationRequest args:')
        current_app.logger.debug(args)
        try:
            response = requests.post(current_app.oidc_client.authorization_endpoint, data=args)
        except requests.exceptions.ConnectionError as e:
            msg = 'No connection to authorization endpoint: {!s}'.format(e)
            current_app.logger.error(msg)
            raise ApiException(payload={'error': msg})
        # If authentication request went well save user state
        if response.status_code == 200:
            current_app.logger.debug('Authentication request delivered to provider {!s}'.format(
                current_app.config['PROVIDER_CONFIGURATION_INFO']['issuer']))
            current_app.proofing_statedb.save(proofing_state)
            current_app.logger.debug('Proofing state {!s} for user {!s} saved'.format(proofing_state.state, eppn))
        else:
            payload = {'error': response.reason, 'message': response.content}
            raise ApiException(status_code=response.status_code, payload=payload)
    # Return nonce and nonce as qr code
    current_app.logger.debug('Returning nonce for user {!s}'.format(eppn))
    buf = StringIO()
    qrcode.make(proofing_state.nonce).save(buf)
    qr_b64 = buf.getvalue().encode('base64')
    ret = {
        'nonce': proofing_state.nonce,
        'qr_img': '<img src="data:image/png;base64, {!s}"/>'.format(qr_b64),
    }
    return ret
Example #16
0
    def get(self, request, *args, **kwargs):
        # Get the data from the session
        try:
            key = self.request.session[self.session_key_name]
            del self.request.session[self.session_key_name]
        except KeyError:
            raise Http404()

        # Get data for qrcode
        image_factory_string = getattr(settings, 'TWO_FACTOR_QR_FACTORY', self.default_qr_factory)
        image_factory = import_string(image_factory_string)
        content_type = self.image_content_types[image_factory.kind]
        try:
            username = self.request.user.get_username()
        except AttributeError:
            username = self.request.user.username

        otpauth_url = get_otpauth_url(accountname=username,
                                      issuer=get_current_site(self.request).name,
                                      secret=key,
                                      digits=totp_digits())

        # Make and return QR code
        img = qrcode.make(otpauth_url, image_factory=image_factory)
        resp = HttpResponse(content_type=content_type)
        img.save(resp)
        return resp
Example #17
0
    def encode(user, secret, organization, otp_type):
        """Encodes a HOTP or TOTP URL into a QR Code.

        The URL format conforms to what is expected by Google Authenticator.
        https://code.google.com/p/google-authenticator/wiki/KeyUriFormat

        Keyword arguments:
        user -- The user of the HOTP or TOTP secret
        secret -- The shared secret used to generate the TOTP value
        organization -- The issuer for the HOTP or TOTP secret
        otp_type -- The OTP type. Accepted values are hotp or totp

        Returns:
        The encoded QR Code image as a PIL Image type.

        """

        otp_types = ['hotp', 'totp']

        if otp_type not in otp_types:
            raise IncorrectOTPType()

        url = ''.join(['otpauth://', otp_type, '/', organization,
                       ':', user, '?', 'secret=', secret])

        return qrcode.make(url)
Example #18
0
    def get(self, request, *args, **kwargs):
        # Get the data from the session
        try:
            key = self.request.session[self.session_key_name]
            del self.request.session[self.session_key_name]
        except KeyError:
            raise Http404()

        # Get data for qrcode
        image_factory_string = getattr(settings, 'TWO_FACTOR_QR_FACTORY', self.default_qr_factory)
        image_factory = import_by_path(image_factory_string)
        content_type = self.image_content_types[image_factory.kind]
        try:
            username = self.request.user.get_username()
        except AttributeError:
            username = self.request.user.username

        site_name = get_current_site(self.request).name
        alias = '{site_name}:{username}'.format(
            username=username, site_name=site_name)

        # Make and return QR code
        img = qrcode.make(get_otpauth_url(alias, key, site_name), image_factory=image_factory)
        resp = HttpResponse(content_type=content_type)
        img.save(resp)
        return resp
Example #19
0
 def get(self, request, slug):
     survey = get_object_or_404(Survey, slug=slug)
     img = qrcode.make(settings.HOST_URL + survey.get_absolute_url())
     response = HttpResponse(mimetype='image/png')
     response['Content-Disposition'] = 'attachment; filename=%s.png' % survey.slug
     img.save(response, 'PNG')
     return response
Example #20
0
 def create_website_qrcode(self):
     storage = get_storage_class(settings.DEFAULT_FILE_STORAGE)()
     img_name = '%s-webite-qrcode.png' % self.id
     img_file = BytesIO()
     img = qrcode.make(self.website, image_factory=PymagingImage)
     img.save(img_file)
     storage.save(img_name, img_file)
Example #21
0
    def __init__(self, url, color):
        QWidget.__init__(self)
        self.setStyleSheet("background-color: black")

        self.file_name_font = QFont()
        self.file_name_font.setPointSize(24)

        self.file_name_label = QLabel(self)
        self.file_name_label.setText(url)
        self.file_name_label.setFont(self.file_name_font)
        self.file_name_label.setAlignment(Qt.AlignCenter)
        self.file_name_label.setStyleSheet("color: #eee")

        self.qrcode_label = QLabel(self)

        self.notify_font = QFont()
        self.notify_font.setPointSize(12)
        self.notify_label = QLabel(self)
        self.notify_label.setText("Scan above QR to copy information")
        self.notify_label.setFont(self.notify_font)
        self.notify_label.setAlignment(Qt.AlignCenter)
        self.notify_label.setStyleSheet("color: #eee")

        layout = QVBoxLayout(self)
        layout.setContentsMargins(0, 0, 0, 0)
        layout.addStretch()
        layout.addWidget(self.qrcode_label, 0, Qt.AlignCenter)
        layout.addSpacing(20)
        layout.addWidget(self.file_name_label, 0, Qt.AlignCenter)
        layout.addSpacing(40)
        layout.addWidget(self.notify_label, 0, Qt.AlignCenter)
        layout.addStretch()

        self.qrcode_label.setPixmap(qrcode.make(url, image_factory=Image).pixmap())
Example #22
0
def format_element(bfo, width="100"):
    """
    Generate a QR-code image linking to the current record.

    @param width: Width of QR-code image.
    """
    if not HAS_QR:
        return ""

    width = int(width)

    bibrec_id = bfo.control_field("001")
    link = "%s/%s/%s" % (CFG_SITE_SECURE_URL, CFG_SITE_RECORD, bibrec_id)
    hash_val = _get_record_hash(link)

    filename = "%s_%s.png" % (bibrec_id, hash_val)
    filename_url = "/img/qrcodes/%s" % filename
    filename_path = os.path.join(CFG_WEBDIR, "img/qrcodes/%s" % filename)

    if not os.path.exists(filename_path):
        if not os.path.exists(os.path.dirname(filename_path)):
            os.makedirs(os.path.dirname(filename_path))

        img = qrcode.make(link)
        img._img = img._img.convert("RGBA")
        img._img = img._img.resize((width, width), Image.ANTIALIAS)
        img.save(filename_path, "PNG")

    return """<img src="%s" width="%s" />""" % (filename_url, width)
Example #23
0
def make_codes():
    with open('short_urls.csv') as csvfile:
        reader = csv.reader(csvfile)
        for short_url,long_url,count in reader:
            path = long_url.replace('http://exoplanets.seti.org/','')
            img = qrcode.make(short_url)
            img.save('qrcodes/%s.png'%path)
Example #24
0
def remoteScanSetup(request, id):
    #TODO: Security
    
    endpoint = RemoteScanEndpoint.objects.get(pk=id)
    
    url = request.build_absolute_uri(reverse(remoteScan, kwargs={'id': endpoint.id}))
    
    data = {
        "remotescan": {
            "title": endpoint.title,
            "url": url,
            "signing_key": endpoint.auth_key,
            "code_types": ["QR"],
            "version": 1
        }
    }
    
    encodedData = json.dumps(data)
    
    img = qrcode.make(encodedData, image_factory=qrcode.image.svg.SvgPathImage, box_size=20)
    
    out = BytesIO()
    img.save(out)
    out.seek(0)
    
    return HttpResponse(out.read(), content_type="image/svg+xml")    
Example #25
0
    def handle(self, *args, **options):
        events = self.explara.get_events()
        orders = self.explara.get_orders(events[0]['eventId'])
        if not os.path.isdir(settings.QR_CODES_DIR):
            os.makedirs(settings.QR_CODES_DIR)
        for order in orders:
            for attendee in order.get('attendee', []):
                ticket_no = attendee.get('ticketId')
                defaults = {
                    'order_no': order.get('orderNo'),
                    'order_cost': order.get('orderCost'),
                    'address': order.get('address', None),
                    'city': order.get('city', None),
                    'zipcode': order.get('zipcode', None),
                    'name': attendee.get('name'),
                    'email': attendee.get('email') or order.get('email'),
                    'status': attendee.get('status'),
                    'others': order,
                }
                with transaction.atomic():
                    ticket, created = Ticket.objects.update_or_create(
                        ticket_no=ticket_no,
                        defaults=defaults
                    )

                if created:
                    qr_code = qrcode.make(ticket_no)
                    file_name = attendee.get('name') + '_' + ticket_no
                    qr_code.save('{}/{}.png'.format(settings.QR_CODES_DIR, file_name))
Example #26
0
def qr_code_command(bot, update, args):
    message = update.message.text

    if "-help" in args:
        bot.send_chat_action(chat_id=update.message.chat_id, action=ChatAction.TYPING)
        bot.send_message(chat_id=update.message.chat_id, text=help_command())
        return

    if len(args) == 0:
        bot.send_message(chat_id=update.message.chat_id, 
                        text="Wrong syntax. See /qrcode -help.",
                        reply_to_message_id=update.message.message_id)
        return

    # Remove "/qrcode" from the message
    message = message.split(' ', 1)[1].strip()

    # Inform that the bot will send an image
    bot.send_chat_action(chat_id=update.message.chat_id, action=ChatAction.UPLOAD_PHOTO)

    try:
        img = qrcode.make(message)

        qrcode_unique = "qrcode_" + str(update.message.message_id) + ".jpg"

        img.save(qrcode_unique)
    except:
        bot.send_message(chat_id=update.message.chat_id, 
                        text="Failed to create qrcode, try again.",
                        reply_to_message_id=update.message.message_id)
        return

    bot.send_photo(chat_id=update.message.chat_id, photo=open(qrcode_unique, 'rb'))

    os.remove(qrcode_unique)
Example #27
0
    def qrgen(self, url):
        """Generation du qrcode pour l'url"""
        qrc = qrcode.make(url, version = 5, error_correction = qrcode.constants.ERROR_CORRECT_H)
        file_name = self.keygen(12)
        qrc.save('tmp/' + file_name + '.png')

        return file_name
Example #28
0
def tickets_receipt_qr(receipt):

    qrfile = StringIO()
    qr = qrcode.make(external_url('tickets_receipt', receipt=receipt), box_size=2)
    qr.save(qrfile, 'PNG')
    qrfile.seek(0)
    return send_file(qrfile, mimetype='image/png')
Example #29
0
 def store_qrcode(self,article_alias):
     url = self.baselink + article_alias +'.html'
     #print url
     qrcode_file = os.path.join(STATIC_ROOT,'qrcode') + os.sep + article_alias +'.png'
     img = qrcode.make(url)
     img.save(qrcode_file)
     return '/static/qrcode/' + article_alias +'.png'
Example #30
0
def coll_create(form):
    record = db(db.geo_collection.f_name == request.vars.f_name).select().first()
    arg = str(record.id)
    path = 'http://siri.pythonanywhere.com/byui_art/default/collection_details?collectionId=' + arg + '&qr=True'
    tiny = ""
    #######################################################################
    ################## TESTING PYSHORTENERS : TINYURL #####################
    #######################################################################
    
    try:
        shortener = Shortener('TinyurlShortener')
        tiny = "{}".format(shortener.short(path))
    except:
        session.tinyCreateException = "There was a problem with the url shortener. Please try again."
    
    #######################################################################
    ###################### END PYSHORTENERS : TINYURL #####################
    #######################################################################
    

    
    code = qrcode.make(tiny)
    qrName='geo_collection.f_qrcode.%s.jpg' % (uuid.uuid4())
    code.save(request.folder + 'uploads/qrcodes/' + qrName, 'JPEG')
    qr_text(qrName, record.f_name, record.f_location, tiny)
    record.update_record(f_qrcode=qrName)
    return dict()
Example #31
0
def gera_qrcode(impressao, contagem):
    """Gera o qrcode"""
    print(impressao, contagem)
    img = qrcode.make(str(contagem))
    gera_vvpat(img, impressao)
Example #32
0
def generate_qrcode(string, size=128):
    stream = six.BytesIO()
    qrcode.make(string, image_factory=qrcode.image.svg.SvgImage, box_size=10).save(stream)
    b64_image_string = base64.b64encode(stream.getvalue()).decode('utf-8')
    return f"<img  width='128' src='data:image/svg+xml;base64,{ b64_image_string }'>"
Example #33
0
import qrcode
img = qrcode.make("KATHIRESAN M\nTERAFAST NETWORKS PVT LTD\nCHENNAI - 600 0091")
img.save('kathiresan.PNG')
Example #34
0
 def create_id():
     x1=e1.get()
     x2=e2.get()
     x3=e3.get()
     x4=e4.get()
     x5=e5.get()
     x6=e6.get()
     x7=e7.get()
     #rows=[x1,x2,x3,x4,x5]
     (x,y)=(50,50)
     message = 'A.C.E.T '
     company=message
     color = 'rgb(0, 0, 0)'
     font = ImageFont.truetype('arial.ttf', size=80)
     draw.text((x, y), message, fill=color, font=font)
     (x, y) = (600, 75)
     ID=''
     if x7==' ':
         idno=random.randint(10000000,90000000)
         ID = str('ID'+str(idno))
         idno=ID
     else:
         idno=x7
         ID=str(x7)
     color = 'rgb(0, 0, 0)'
     font = ImageFont.truetype('arial.ttf', size=60)
     draw.text((x, y), ID, fill=color, font=font)
     rows=[ID,x1,x3,x2,x4,x5,x6]
     (x, y) = (50, 250)
     message = x1
     name=message
     color = 'rgb(0, 0, 0)' 
     font = ImageFont.truetype('arial.ttf', size=45)
     draw.text((x, y),'NAME:-'+ message, fill=color, font=font)
     (x, y) = (50, 350)
     message = x2
     color = 'rgb(0, 0, 0)' 
     draw.text((x, y),'D.O.B.:-'+ message, fill=color, font=font)
     (x, y) = (50, 450)
     message = x3
     color = 'rgb(0, 0, 0)'  
     draw.text((x, y),'BRANCH:-'+ message, fill=color, font=font)
     (x, y) = (50, 550)
     message = x4
     color = 'rgb(0, 0, 0)'  
     draw.text((x, y), 'MOB:-'+message, fill=color, font=font)
     (x, y) = (50, 650)
     message = x6
     color = 'rgb(255, 0, 0)'
     draw.text((x, y),'Blood group:-'+ message, fill=color, font=font)
     (x, y) = (50, 750)
     message = x5
     temp=message
     color = 'rgb(0, 0, 0)'
     draw.text((x, y),'EMAIL:-'+ message, fill=color, font=font)
     '''(x, y) = (50, 750)
     message = input('Enter Your Address: ')
     color = 'rgb(0, 0, 0)' # black color 
     draw.text((x, y), message, fill=color, font=font)'''
     image.save(str(name)+'.png')
     img = qrcode.make(str(company)+str(idno))   
     img.save(str(idno)+'.bmp')
     til = Image.open(name+'.png')
     im = Image.open(str(idno)+'.bmp') 
     til.paste(im,(600,350))
     #cookImage = PhotoImage(file = filename)
     #cookImage = ImageTk.PhotoImage(Image.open(filename))
     #ima = Image.open(filename) #25x25
     print('Done')
     #image2=cookImage.resize((100,50),Image.ANTIALIAS)
     #cookImage=ImageTk.PhotoImage(cookImage)
     #cookImage=cookImage.resize(25,25)
     width=25
     height=25
     #i = ima.resize((width, height), Image.BICUBIC)  
     #til.paste(cookImage,(600,350))
     til.save(name+'.png')
     with open('allstudent.csv', 'a') as csvfile: 
         csvwriter = csv.writer(csvfile) 
         #csvwriter.writerow(fields) 
         csvwriter.writerow(rows)
     print(ID,x1,x2,x3,x4,x5,x6)
     result=firebase.put('all student id'+x3,ID,{"name":x1,'email':x5,'mobile no':x4,'date of birth':x2,'blood group':x6})
     print(result)
     try:
         gmailaddress = '*****@*****.**'
         gmailpassword = '******'
         mailto = x5
         msg = 'id created'
         mailServer = smtplib.SMTP('smtp.gmail.com' , 587)
         mailServer.starttls()
         mailServer.login(gmailaddress , gmailpassword)
         mailServer.sendmail(gmailaddress, mailto , msg)
         print(" \n Sent!")
         mailServer.quit()
     except:
         print("network error ")
Example #35
0
def qrcode_create(factory, data, box_size):
    img = qrcode.make(data, image_factory=factory, box_size=box_size)
    output = io.BytesIO()
    img.save(output)
    return output
def gen_qrcode(text: str) -> str:
    img = qrcode.make(text)
    img_buffer = io.BytesIO()
    img.save(img_buffer)
    return base64.b64encode(img_buffer.getvalue()).decode()
Example #37
0
def get_qrcode_img(host, port, cert_path, macaroon_path):
    url = get_lndconnect_url(host, port, cert_path, macaroon_path)

    img = qrcode.make(url)

    return img
Example #38
0
    def createCATScript(self):
        
        debug_directory = self.debug_directory
        
        catia_root_directory_dict = self.catia_root_directory_dict
        
        titleblock_script_template_file_name = self.titleblock_script_template_file_name 
        
        rename = self.rename
        
        web_url = self.web_url
                
        script_directory = debug_directory + 'CATScript\\' # 存放CATScript文件夹
        
        html_directory = debug_directory + 'html\\' # 存放html文件夹
        
        qrcode_directory = debug_directory + 'qrcode\\' # 存放html文件夹
        
        all_directory = [debug_directory,script_directory,html_directory,qrcode_directory]
        
        for directory in all_directory:
            if not os.path.isdir(directory):
                os.makedirs(directory)
                print 'Create new directory:',directory
                
        titleblock_batch_outfile_name = debug_directory + 'create_titleblock.bat'
        titleblock_batch_outfile = open(titleblock_batch_outfile_name, 'w') # 添加标题栏批处理文件
        
        rename_batch_outfile_name = debug_directory + 'rename.bat'
        rename_batch_outfile = open(rename_batch_outfile_name, 'w') # 文件改名批处理文件
        
        html_code_type = 'utf-8' # html文件编码
        script_code_type = 'utf-8' # CATScript文件编码
        cmd_code_type = 'gbk' # cmd文件编码
        
        header,data = self.readExcel() # 读取excel文件数据
        
        for catia_directory in catia_root_directory_dict.keys():
            old_directory = catia_directory
            new_directory = catia_root_directory_dict[catia_directory]

            if not os.path.isdir(new_directory):
                os.makedirs(new_directory)
                print 'Create new directory:',new_directory
            
            filenames = getFiles(old_directory)
            
            directories = {}
            
            for filename in filenames:
                if isSuffixFile(filename[1],suffixs=['CATPart','CATDrawing']):
                    if filename[0] not in directories:
                        directories[filename[0]] = {'CATPart':[],'CATDrawing':[]}
            
            for directory in directories.keys():
                for filename in filenames:
                    if filename[0] is directory:
                        if isSuffixFile(filename[1],suffixs=['CATPart']):
                            directories[directory]['CATPart'].append(filename[1])
                        if isSuffixFile(filename[1],suffixs=['CATDrawing']):
                            directories[directory]['CATDrawing'].append(filename[1])
            
            for directory in directories.keys()[:]:
#                print directory
                directories[directory]['CATDrawing'].sort()
#                print directories[directory]['CATDrawing']
                for i, drawing_name in enumerate(directories[directory]['CATDrawing']):
                    
                    part_name_old = u'%s\%s' % (directory,directories[directory]['CATPart'][0])
#                    print part_name_old
                    
                    drawing_name_old = u'%s\%s' % (directory,drawing_name)
#                    print drawing_name_old
                    
                    if rename == True:
                        rows_number = getRowsNumber(data[u'原始编号'],part_name_old)
                    if rename == False:
                        rows_number = getRowsNumber(data[u'三维文件名称'],part_name_old)
#                    print rows_number
                    
                    part_directory_name = u'%s %s' % (data[u'三维文件名称'][rows_number],data[u'中文名称'][rows_number])
#                    print 'part_directory_name',part_directory_name
                    
                    
                    part_directory_full_name = u'%s%s' % (new_directory,part_directory_name)
#                    print 'part_directory_full_name',part_directory_full_name
                    
                    part_name_new = u'%s\%s.CATPart' % (part_directory_full_name,data[u'三维文件名称'][rows_number])
#                    print part_name_new
                    
                    drawing_numner_new = data[u'二维文件名称'][rows_number]
                    drawing_numner_new = unicode(int(drawing_numner_new) + i*100)
#                    print drawing_numner_new

                    drawing_name_new = u'%s\%s.CATDrawing' % (part_directory_full_name,drawing_numner_new)
                    print drawing_name_new.encode(cmd_code_type)
#                    print repr(drawing_name_new)
                    
                    export_suffix = u'pdf'
                    export_name_new= u'%s\%s.%s' % (part_directory_full_name,drawing_numner_new,export_suffix)
#                    print export_name_new
                    
                    drawing_chinese_material = data[u'中文材料'][rows_number]
#                    print drawing_chinese_material
                    
                    drawing_material_standard = data[u'材料标准'][rows_number]
#                    print drawing_material_standard
                    
                    drawing_chinese_name = data[u'中文名称'][rows_number]
#                    print drawing_chinese_name
                    
                    if not os.path.isdir(part_directory_full_name):
                        os.makedirs(part_directory_full_name)
                        print 'Create new directory:',part_directory_full_name

#==============================================================================
# 生成html文件
#==============================================================================
                    html_outfile_name = u'%s\\%s.htm' % (html_directory,drawing_numner_new)
                    html_outfile = open(html_outfile_name, 'w')

                    line = u"""<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>%s</title>
</head>
<body>

<table width="100%%">""" % part_directory_name
                    print >>html_outfile,line.encode(html_code_type)
                    
                    keys = [
#                            u'原始编号',
                            u'中文名称',
                            u'二维文件名称',
                            u'三维文件名称',
#                            u'装配处',
#                            u'页数',
#                            u'任务分配',
                            u'发动机类型',
#                            u'发动机类型编号',
                            u'发动机级别',
#                            u'发动机级别编号',
                            u'部件分组',
#                            u'部件分组编号',
                            u'零件分组',
#                            u'零件分组编号',
#                            u'零件分组统计',
                            u'零件号',
                            u'图纸尺寸',
                            u'页号',
                            u'版本号',
                            u'中文材料',
                            u'材料标准',
#                            u'产品序号',
#                            u'产品编号',
                            ]
                            
                    for key in keys:
                        line = '<tr><td width=\"40%%\"><b>%s</b></td>          <td>%s</td></tr>' % (key,data[key][rows_number])
                        print >>html_outfile,line.encode(html_code_type)
                        
                    line = u"""</table>

</body>
</html>"""
                    print >>html_outfile,line.encode(html_code_type)
                    
                    html_outfile.close()
#==============================================================================
# 生成标题栏CATScript文件
#==============================================================================
                    infile = open(titleblock_script_template_file_name, 'r')
                    lines = infile.readlines()
                    for i, line in enumerate(lines):
                        lines[i] = line.decode(script_code_type)
                    infile.close()

                    qrcode_image_url = u'http://%s/%s.htm' % (web_url,drawing_numner_new)
                    qrcode_image = qrcode.make(qrcode_image_url)
                    qrcode_image_full_name = u'%s%s.png' % (qrcode_directory,drawing_numner_new)
                    qrcode_image.save(qrcode_image_full_name)
                    
                    for i, line in enumerate(lines):
                        if u'Text_18 =' in line:
#                            print line
                            lines[i] = u'  Text_18 = \"%s\" + vbLf + \"%s\"\n' % (drawing_chinese_material,drawing_material_standard)
                        if u'Text_19 =' in line:
#                            print line
                            lines[i] = u'  Text_19 = \"%s\"\n' % u'清华大学'
                        if u'Text_20 =' in line:
#                            print line
                            lines[i] = u'  Text_20 = \"%s\"\n' % drawing_chinese_name
                        if u'Text_21 =' in line:
#                            print line
                            lines[i] = u'  Text_21 = \"%s\"\n' % drawing_numner_new
                        if u'drawing_document' in line:
#                            print line
                            lines[i] = u'  Set drawingDocument1 = documents1.Open(\"%s\")\n' % drawing_name_old
                        if u'save_as' in line:
#                            print line
                            lines[i] = u'  drawingDocument1.SaveAs \"%s\"\n' % drawing_name_new
                        if u'export_data' in line:
#                            print line
                            lines[i] = u'  drawingDocument1.ExportData \"%s\", \"%s\"\n' % (export_name_new,export_suffix)
                        if u'Qrcode =' in line:
#                            print line
                            lines[i] = u'  Qrcode = \"%s\"\n' % (qrcode_image_full_name)

                    titleblock_outfile_name = '%sGB_Titleblock_%s.CATScript' % (script_directory,drawing_numner_new)
                    titleblock_outfile = open(titleblock_outfile_name, 'w')
                    for line in lines:
                        titleblock_outfile.writelines(line.encode(script_code_type))
                    titleblock_outfile.close()
#==============================================================================
# 生成改名CATScript文件
#==============================================================================
                    rename_outfile_name = '%srename_%s.CATScript' % (script_directory,drawing_numner_new)
                    rename_outfile = open(rename_outfile_name, 'w')
                    print >>rename_outfile, u'Language=\"VBSCRIPT\"'.encode(html_code_type)
                    print >>rename_outfile, u'Sub CATMain()'.encode(html_code_type)
                    lines = u"""
CATIA.DisplayFileAlerts = False
Set documents1 = CATIA.Documents
Set drawingDocument1 = documents1.Open("%s")
Set partDocument1 = documents1.Open("%s")
Set product1 = partDocument1.GetItem("Part1")
product1.PartNumber = "%s"
partDocument1.SaveAs "%s"
drawingDocument1.SaveAs "%s"
drawingDocument1.ExportData "%s", "%s"
partDocument1.Close
drawingDocument1.Close
""" % (drawing_name_old,part_name_old,part_directory_name,part_name_new,drawing_name_new,export_name_new,export_suffix)
                    print >>rename_outfile, lines.encode(html_code_type)
                    print >>rename_outfile, u'End Sub'.encode(html_code_type)
                    rename_outfile.close()
#==============================================================================
# 写入批处理文件
#==============================================================================
                    print >>titleblock_batch_outfile, (r'cnext -batch -macro %s' % titleblock_outfile_name)
                    print >>rename_batch_outfile, (r'cnext -batch -macro %s' % rename_outfile_name)
                    print
                    
        titleblock_batch_outfile.close()
        rename_batch_outfile.close()
Example #39
0
def main():

    parser = ArgumentParser(usage="%(prog)s")
    common.setup_global_opts(parser)
    parser.add_argument("--keystore",
                        default=KEYSTORE_FILE,
                        help=_("Specify which debug keystore file to use."))
    parser.add_argument(
        "--show-secret-var",
        action="store_true",
        default=False,
        help=_(
            "Print the secret variable to the terminal for easy copy/paste"))
    parser.add_argument(
        "--keep-private-keys",
        action="store_true",
        default=False,
        help=_("Do not remove the private keys generated from the keystore"))
    parser.add_argument("--no-deploy",
                        action="store_true",
                        default=False,
                        help=_("Do not deploy the new files to the repo"))
    parser.add_argument(
        "--file",
        default='app/build/outputs/apk/*.apk',
        help=_('The file to be included in the repo (path or glob)'))
    parser.add_argument("--no-checksum",
                        action="store_true",
                        default=False,
                        help=_("Don't use rsync checksums"))
    parser.add_argument(
        "--archive-older",
        type=int,
        default=20,
        help=_("Set maximum releases in repo before older ones are archived"))
    # TODO add --with-btlog
    options = parser.parse_args()

    # force a tighter umask since this writes private key material
    umask = os.umask(0o077)

    if 'CI' in os.environ:
        v = os.getenv('DEBUG_KEYSTORE')
        debug_keystore = None
        if v:
            debug_keystore = base64.b64decode(v)
        if not debug_keystore:
            logging.error(
                _('DEBUG_KEYSTORE is not set or the value is incomplete'))
            sys.exit(1)
        os.makedirs(os.path.dirname(KEYSTORE_FILE), exist_ok=True)
        if os.path.exists(KEYSTORE_FILE):
            logging.warning(
                _('overwriting existing {path}').format(path=KEYSTORE_FILE))
        with open(KEYSTORE_FILE, 'wb') as fp:
            fp.write(debug_keystore)

        repo_basedir = os.path.join(os.getcwd(), 'fdroid')
        repodir = os.path.join(repo_basedir, 'repo')
        cibase = os.getcwd()
        os.makedirs(repodir, exist_ok=True)

        if 'CI_PROJECT_PATH' in os.environ and 'CI_PROJECT_URL' in os.environ:
            # we are in GitLab CI
            repo_git_base = os.getenv('CI_PROJECT_PATH') + NIGHTLY
            clone_url = os.getenv('CI_PROJECT_URL') + NIGHTLY
            repo_base = clone_url + '/raw/master/fdroid'
            servergitmirror = 'git@' + urlparse(
                clone_url).netloc + ':' + repo_git_base
            deploy_key_url = clone_url + '/settings/repository'
            git_user_name = os.getenv('GITLAB_USER_NAME')
            git_user_email = os.getenv('GITLAB_USER_EMAIL')
        elif 'TRAVIS_REPO_SLUG' in os.environ:
            # we are in Travis CI
            repo_git_base = os.getenv('TRAVIS_REPO_SLUG') + NIGHTLY
            clone_url = 'https://github.com/' + repo_git_base
            _branch = os.getenv('TRAVIS_BRANCH')
            repo_base = 'https://raw.githubusercontent.com/' + repo_git_base + '/' + _branch + '/fdroid'
            servergitmirror = '[email protected]:' + repo_git_base
            deploy_key_url = (
                'https://github.com/' + repo_git_base + '/settings/keys' +
                '\nhttps://developer.github.com/v3/guides/managing-deploy-keys/#deploy-keys'
            )
            git_user_name = repo_git_base
            git_user_email = os.getenv('USER') + '@' + platform.node()
        elif 'CIRCLE_REPOSITORY_URL' in os.environ \
             and 'CIRCLE_PROJECT_USERNAME' in os.environ \
             and 'CIRCLE_PROJECT_REPONAME' in os.environ:
            # we are in Circle CI
            repo_git_base = (os.getenv('CIRCLE_PROJECT_USERNAME') + '/' +
                             os.getenv('CIRCLE_PROJECT_REPONAME') + NIGHTLY)
            clone_url = os.getenv('CIRCLE_REPOSITORY_URL') + NIGHTLY
            repo_base = clone_url + '/raw/master/fdroid'
            servergitmirror = 'git@' + urlparse(
                clone_url).netloc + ':' + repo_git_base
            deploy_key_url = (
                'https://github.com/' + repo_git_base + '/settings/keys' +
                '\nhttps://developer.github.com/v3/guides/managing-deploy-keys/#deploy-keys'
            )
            git_user_name = os.getenv('CIRCLE_USERNAME')
            git_user_email = git_user_name + '@' + platform.node()
        else:
            print(_('ERROR: unsupported CI type, patches welcome!'))
            sys.exit(1)

        repo_url = repo_base + '/repo'
        git_mirror_path = os.path.join(repo_basedir, 'git-mirror')
        git_mirror_repodir = os.path.join(git_mirror_path, 'fdroid', 'repo')
        git_mirror_metadatadir = os.path.join(git_mirror_path, 'fdroid',
                                              'metadata')
        git_mirror_statsdir = os.path.join(git_mirror_path, 'fdroid', 'stats')
        if not os.path.isdir(git_mirror_repodir):
            logging.debug(_('cloning {url}').format(url=clone_url))
            try:
                git.Repo.clone_from(clone_url, git_mirror_path)
            except Exception:
                pass
        if not os.path.isdir(git_mirror_repodir):
            os.makedirs(git_mirror_repodir, mode=0o755)

        mirror_git_repo = git.Repo.init(git_mirror_path)
        writer = mirror_git_repo.config_writer()
        writer.set_value('user', 'name', git_user_name)
        writer.set_value('user', 'email', git_user_email)
        writer.release()
        for remote in mirror_git_repo.remotes:
            mirror_git_repo.delete_remote(remote)

        readme_path = os.path.join(git_mirror_path, 'README.md')
        readme = '''
# {repo_git_base}

[![{repo_url}](icon.png)]({repo_url})

Last updated: {date}'''.format(
            repo_git_base=repo_git_base,
            repo_url=repo_url,
            date=datetime.datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S UTC'))
        with open(readme_path, 'w') as fp:
            fp.write(readme)
        mirror_git_repo.git.add(all=True)
        mirror_git_repo.index.commit("update README")

        icon_path = os.path.join(git_mirror_path, 'icon.png')
        try:
            import qrcode
            qrcode.make(repo_url).save(icon_path)
        except Exception:
            exampleicon = os.path.join(common.get_examples_dir(),
                                       'fdroid-icon.png')
            shutil.copy(exampleicon, icon_path)
        mirror_git_repo.git.add(all=True)
        mirror_git_repo.index.commit("update repo/website icon")
        shutil.copy(icon_path, repo_basedir)

        os.chdir(repo_basedir)
        if os.path.isdir(git_mirror_repodir):
            common.local_rsync(options, git_mirror_repodir + '/', 'repo/')
        if os.path.isdir(git_mirror_metadatadir):
            common.local_rsync(options, git_mirror_metadatadir + '/',
                               'metadata/')
        if os.path.isdir(git_mirror_statsdir):
            common.local_rsync(options, git_mirror_statsdir + '/', 'stats/')

        ssh_private_key_file = _ssh_key_from_debug_keystore()
        # this is needed for GitPython to find the SSH key
        ssh_dir = os.path.join(os.getenv('HOME'), '.ssh')
        os.makedirs(ssh_dir, exist_ok=True)
        ssh_config = os.path.join(ssh_dir, 'config')
        logging.debug(
            _('adding IdentityFile to {path}').format(path=ssh_config))
        with open(ssh_config, 'a') as fp:
            fp.write('\n\nHost *\n\tIdentityFile %s\n' % ssh_private_key_file)

        config = ''
        config += "identity_file = '%s'\n" % ssh_private_key_file
        config += "repo_name = '%s'\n" % repo_git_base
        config += "repo_url = '%s'\n" % repo_url
        config += "repo_icon = 'icon.png'\n"
        config += "repo_description = 'Nightly builds from %s'\n" % git_user_email
        config += "archive_name = '%s'\n" % (repo_git_base + ' archive')
        config += "archive_url = '%s'\n" % (repo_base + '/archive')
        config += "archive_icon = 'icon.png'\n"
        config += "archive_description = 'Old nightly builds that have been archived.'\n"
        config += "archive_older = %i\n" % options.archive_older
        config += "servergitmirrors = '%s'\n" % servergitmirror
        config += "keystore = '%s'\n" % KEYSTORE_FILE
        config += "repo_keyalias = '%s'\n" % KEY_ALIAS
        config += "keystorepass = '******'\n" % PASSWORD
        config += "keypass = '******'\n" % PASSWORD
        config += "keydname = '%s'\n" % DISTINGUISHED_NAME
        config += "make_current_version_link = False\n"
        config += "accepted_formats = ('txt', 'yml')\n"
        config += "update_stats = True\n"
        with open('config.py', 'w') as fp:
            fp.write(config)
        os.chmod('config.py', 0o600)
        config = common.read_config(options)
        common.assert_config_keystore(config)

        for root, dirs, files in os.walk(cibase):
            for d in dirs:
                if d == '.git' or d == '.gradle' or (d == 'fdroid'
                                                     and root == cibase):
                    dirs.remove(d)
            for f in files:
                if f.endswith('-debug.apk'):
                    apkfilename = os.path.join(root, f)
                    logging.debug(
                        _('Striping mystery signature from {apkfilename}').
                        format(apkfilename=apkfilename))
                    destapk = os.path.join(repodir, os.path.basename(f))
                    os.chmod(apkfilename, 0o644)
                    logging.debug(
                        _('Resigning {apkfilename} with provided debug.keystore'
                          ).format(apkfilename=os.path.basename(apkfilename)))
                    common.apk_strip_signatures(apkfilename,
                                                strip_manifest=True)
                    common.sign_apk(apkfilename, destapk, KEY_ALIAS)

        if options.verbose:
            logging.debug(
                _('attempting bare ssh connection to test deploy key:'))
            try:
                subprocess.check_call([
                    'ssh', '-Tvi', ssh_private_key_file,
                    '-oIdentitiesOnly=yes', '-oStrictHostKeyChecking=no',
                    servergitmirror.split(':')[0]
                ])
            except subprocess.CalledProcessError:
                pass

        app_url = clone_url[:-len(NIGHTLY)]
        template = dict()
        template['AuthorName'] = clone_url.split('/')[4]
        template['AuthorWebSite'] = '/'.join(clone_url.split('/')[:4])
        template['Categories'] = ['nightly']
        template['SourceCode'] = app_url
        template['IssueTracker'] = app_url + '/issues'
        template['Summary'] = 'Nightly build of ' + urlparse(app_url).path[1:]
        template['Description'] = template['Summary']
        with open('template.yml', 'w') as fp:
            yaml.dump(template, fp)

        subprocess.check_call([
            'fdroid', 'update', '--rename-apks', '--create-metadata',
            '--verbose'
        ],
                              cwd=repo_basedir)
        common.local_rsync(options, repo_basedir + '/metadata/',
                           git_mirror_metadatadir + '/')
        common.local_rsync(options, repo_basedir + '/stats/',
                           git_mirror_statsdir + '/')
        mirror_git_repo.git.add(all=True)
        mirror_git_repo.index.commit("update app metadata")

        if not options.no_deploy:
            try:
                cmd = [
                    'fdroid', 'server', 'update', '--verbose',
                    '--no-keep-git-mirror-archive'
                ]
                subprocess.check_call(cmd, cwd=repo_basedir)
            except subprocess.CalledProcessError:
                logging.error(
                    _('cannot publish update, did you set the deploy key?') +
                    '\n' + deploy_key_url)
                sys.exit(1)

        if not options.keep_private_keys:
            os.remove(KEYSTORE_FILE)
            if shutil.rmtree.avoids_symlink_attacks:
                shutil.rmtree(os.path.dirname(ssh_private_key_file))

    else:
        if not os.path.isfile(options.keystore):
            androiddir = os.path.dirname(options.keystore)
            if not os.path.exists(androiddir):
                os.mkdir(androiddir)
                logging.info(_('created {path}').format(path=androiddir))
            logging.error(
                _('{path} does not exist!  Create it by running:').format(
                    path=options.keystore) +
                '\n    keytool -genkey -v -keystore ' + options.keystore +
                ' -storepass android \\' +
                '\n     -alias androiddebugkey -keypass android -keyalg RSA -keysize 2048 -validity 10000 \\'
                + '\n     -dname "CN=Android Debug,O=Android,C=US"')
            sys.exit(1)
        ssh_dir = os.path.join(os.getenv('HOME'), '.ssh')
        os.makedirs(os.path.dirname(ssh_dir), exist_ok=True)
        privkey = _ssh_key_from_debug_keystore(options.keystore)
        ssh_private_key_file = os.path.join(ssh_dir, os.path.basename(privkey))
        shutil.move(privkey, ssh_private_key_file)
        shutil.move(privkey + '.pub', ssh_private_key_file + '.pub')
        if shutil.rmtree.avoids_symlink_attacks:
            shutil.rmtree(os.path.dirname(privkey))

        if options.show_secret_var:
            with open(options.keystore, 'rb') as fp:
                debug_keystore = base64.standard_b64encode(
                    fp.read()).decode('ascii')
            print(
                _('\n{path} encoded for the DEBUG_KEYSTORE secret variable:').
                format(path=options.keystore))
            print(debug_keystore)

    os.umask(umask)
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# =============================================================================
# Author :  Will Grant
# =============================================================================

import qrcode
import qrcode.image.svg

qr = qrcode.QRCode(
    version=1,
    error_correction=qrcode.constants.ERROR_CORRECT_H,
    box_size=10,
    border=4,
)

data = "Some text that you want to store in the qrcode"

qr.add_data(data)
qr.make(fit=True)

img = qrcode.make(data, image_factory=factory)

img.save("qrcode.svg")
def makeQrcodeVerifySign(link, npm_mahasiswa, kode_dosen, tipe_bimbingan):
    checkDirQrcode()
    img = qrcode.make(link)
    img.save(f'./kambingqrcode/{npm_mahasiswa}-{kode_dosen}-{tipe_bimbingan}.PNG')
Example #42
0
 def _compute_qr(self):
     for remote in self:
         img = qrcode.make(remote.url)
         img_tmp = BytesIO()
         img.save(img_tmp, format="PNG")
         remote.qr = base64.b64encode(img_tmp.getvalue())
Example #43
0
def create():
    qrcode.make('Make friend').get_image().show()
    time.sleep(20)
Example #44
0
File: qr.py Project: sellenth/crow
from PIL import Image
import qrcode
import os
import sys
import hashlib
import base64
import socket

if __name__ == "__main__":
    if len(sys.argv) == 2:
        random = str(int.from_bytes(os.urandom(16), 'big'))

        img = qrcode.make(sys.argv[1] + ":" + random)
        img.save("out.png")

        with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
            s.connect(('localhost', 55556))
            s.send(
                base64.b64encode(
                    hashlib.sha256(bytes(random, 'ascii')).digest()))
    else:
        print("Use: command <user>")
Example #45
0
        if titolo == '':
            titolo = 'n.d.'
        idx = splitted[0]
        numerocodice = splitted[6]
        if numerocodice in selected:
            collocazione = splitted[4]
            #qrline = "%s # %s # %s # lv. 1 " %(idx,numerocodice,titolo)
            scalefactor = 2
            l_cod = len(numerocodice)
            if l_cod > 9:
                scalefactor = 1.5
            elif l_cod > 13:
                scalefactor = 1
            if len(titolo) > 16:
                rtitolo = titolo[:16]
                if len(titolo) > 60:
                    titolo = "".join([titolo[:60], r"\ldots"])
            else:
                rtitolo = titolo
            qrline = "".join([
                idx.zfill(5), (numerocodice + " ").rjust(18),
                rtitolo.rjust(16), "2"
            ])
            print(qrline)
            img = qrcode.make(qrline)
            img.save(os.path.join(fldQRc, "%s.png" % idx))
            cmd = r"\booklabel{%s}{%s}{%s}{%s}{green}{%s}" % (
                idx, collocazione, numerocodice, titolo, scalefactor)
            fl.write(cmd + "\n")
    fl.write(r"\end{document}" + "\n")
Example #46
0
 def qr_generator(self, _filename, _ManipulationInfo):
     qr_image = qrcode.make(_ManipulationInfo)
     qr_image.save(_filename)
 def set_address(self, address):
     self.qrcode_label.setPixmap(
         qrcode.make(address, image_factory=Image).pixmap())
Example #48
0
import qrcode
from PIL import Image

text = ('VAISHNAV PRINTS')
email = ('Email : [email protected]')
address = (
    'Address : #973,Swaghat Sankeerthana,2nd main road,M C Layout,Vijayanagar,Bangalore-560040'
)
pno = ('Mobile phno :9845615177/8310487294')
img = qrcode.make(
    str(text) + '\n' + str(email) + '\n' + str(address) + '\n' + str(pno))
img.save(
    "/home/vaishnav/Desktop/pycharm/mile_stone_project!/all_QR_code/{}.png".
    format(text))

img.show(
    "/home/vaishnav/Desktop/pycharm/mile_stone_project!/all_QR_code/{}.png".
    format(text))
import qrcode
from PIL import Image


#Genera un secreto de manera aleatoria
secreto = pyotp.random_base32()

# Permite crear el OTP de autenticación
totp_object = pyotp.TOTP(secreto)

# Aqui pondríamos el nombre de nuestra aplicación
totp = totp_object.provisioning_uri(name = "Tarea 2", issuer_name="M8T2 - TOTP")
print("Mi link TOTP es: ",totp)

# Aquí convertimos el link totp a código QR
qr_imagen = qrcode.make(totp)
nombre_archivo = secreto + ".png"
qr_nombre_archivo = open(nombre_archivo, 'wb')
qr_imagen.save(qr_nombre_archivo)
qr_nombre_archivo.close()

#mostramos la imagen del código QR
mostrar_qr = "./"+nombre_archivo
Image.open(mostrar_qr).show()



# Compara el PIN temporal de Google Authenticator con el SECRETO del servidor
# Nos responderá si la validación a sido correcta o no.
otp = input("Ingresa el PIN de Google Authenticator: " )
valid = totp_object.verify(otp)
Example #50
0
def gen_qrcode(data):
    """生成二维码"""
    image = qrcode.make(data)
    buffer = BytesIO()
    image.save(buffer)
    return buffer.getvalue()
Example #51
0
def gen_qrcode(s, qrcode_path):
    img = qrcode.make(s)
    # resize_ = [int(ori_size / 10) for ori_size in ori_sizes]
    img = img.resize(watermark_size)
    img.save(qrcode_path)
Example #52
0
def main_url():
    url = sys.argv[2]
    if not url:
        print("Inserisci un URL valido")
    img = qrcode.make(url)
    img.show()
Example #53
0
plt.savefig('courant2.png', dpi=250)

#cons figure
res = 60 * 18
cons = []
for i in range(len(y[::res])):
    cons.append(floor(y[i * res:(i + 1) * res].sum() * 220 / 36000) / 100)
df3 = pd.DataFrame({"Energie (KWh)": cons}, index=x[::res])
df3.plot.bar()
figure = plt.gcf()
figure.set_size_inches(6, 3)
plt.tight_layout(w_pad=10, h_pad=10)
plt.savefig('cons.png', dpi=250)

#qrcode
qr = qrcode.make("mellahavenir.com")
qr.save("qr.png")

#barcode
codes = encode("mellahavenir.com", columns=5, security_level=1)
image = render_image(codes)
image.save("barc.png")

#temps d'arrets
res = 120
ta = []
for i in range(len(y[::res])):
    if y[i * res:(i + 1) * res].mean() < 0.5:
        ta.append(0)
    else:
        ta.append(1)
Example #54
0
def url(url):
    img = qrcode.make(url)  #已经生成二维码图片对象
    img.save('static/qrimg/1.png')  #保存二维码图片
    return 'static/qrimg/1.png'
Example #55
0
def generate_qrcode_png(string: str):
    stream = io.BytesIO()
    img = qrcode.make(string)
    img.save(stream, "PNG")
    return stream.getvalue()
Example #56
0
import qrcode

#二维码的生成

data = input("请输入一个任意的数据")
img = qrcode.make(data)
img.save("qrcode.jpg")
img.show()

input("按回车键退出")
Example #57
0
# -*- coding: utf-8 -*

from sys import argv
from os.path import splitext
import qrcode

if __name__ == "__main__":

    if len(argv) == 3:
        url = argv[1]
        name = argv[2]
    else:
        exit("$1: URL, $2: QR-image's name")

    if splitext(name)[1] == "":
        name += ".png"

    img = qrcode.make(url)
    img.show()
    img.save(name)

    print("converted\n%s\nto\n%s" % (url, name))
    exit()
Example #58
0
import qrcode
qr = qrcode.make('laptop_name')
qr.save('new.png')
def makeQrcode(data, npm_mahasiswa):
    img = qrcode.make(data)
    img.save(f"{npm_mahasiswa}.PNG")
 def generate_image(self):
         imgFP = self._imagefile
         img = qrcode.make(self._qrurl)
         img.save(imgFP)
         print("File:\t%s \nQR url:\t%s" % (imgFP, self._qrurl))