I am trying to merge a Qr Code onto a pdf. When I split the code into two separate scripts it works fine. I am new to phython any help is appreciated. I am running this on RHEL 7.4 in Phyton 2.7
Yes I know it's old but it is a 3rd party server and I cannot upgrade it.
[user#myserver scripts]$ python pdf_test3.py
Traceback (most recent call last):
File "pdf_test3.py", line 28, in <module>
qcode = pyqrcode("http://www.weather.com","/cfg/test.png")
File "pdf_test3.py", line 8, in __init__
qrCode = self.create(url)
AttributeError: pyqrcode instance has no attribute 'create'
from fpdf import FPDF
from pyqrcode import QRCode
import png
import sys
class pyqrcode(QRCode):
def __init__(self, url,fileOutputDir):
qrCode = self.create(url)
# create qr code and save it as a svg image
qrCode.png(fileOutputDir, scale=1)
class PDF(FPDF):
def __init__(self,imageFileName):
# file name, left,top,heght,width
self.image(imageFileName, 200,1,20,20)
self.cell(30, 10, 'Title', 1, 0, 'C')
# Page footer
def footer(self):
# Position at 1.5 cm from bottom
self.set_y(-15)
# Arial italic 8
self.set_font('Arial', 'I', 8)
# Page number
self.cell(0, 10, 'Page ' + str(self.page_no()) + '/{nb}', 0, 0, 'C')
# Instantiation of inherited class
qcode = pyqrcode("http://www.weather.com","/cfg/test.png")
pdf = PDF()
pdf.alias_nb_pages()
pdf.add_page()
pdf.set_font('Times', '', 12)
for i in range(1, 5):
pdf.cell(0, 10, 'Hello World.' + str(i), 0, 1)
pdf.output('test.pdf', 'F')
Your error is saying that your own pyqrcode instance has no create function, which it does not. Also, best not to name a class with the same name as a module
You can fix that by importing the create function
from fpdf import FPDF
from pyqrcode import QRCode
from pyqrcode import create as create_qrcode
import png
import sys
class PyQRcode(QRCode):
def __init__(self, url,fileOutputDir):
qrCode = create_qrcode(url)
Related
This is my first flask application and i tried my best to get it running. Nevertheless i stuck into one error.
I tried to create a python flask app but stuck into an error.
here is my code
flask.py
from test_displayclass import Bartender
class MyFlask:
bartender = Bartender()
def __init__(self):
#self.bartender = Bartender()
self.bartender.test()
from flask import Flask
app = Flask(__name__)
my_flask = MyFlask()
#app.route("/Test")
def Test():
return my_flask.test.APIfunction
if __name__ == "__main__":
app.run(debug=True,port=9999)
test_displayclass.py
import adafruit_ssd1306
import busio
from board import SCL, SDA
from PIL import Image, ImageDraw, ImageFont
class Display():
def __init__(self):
i2c = busio.I2C(SCL, SDA)
self.oled = adafruit_ssd1306.SSD1306_I2C(128, 64, i2c, addr=0x3C)
self.oled.fill(0)
self.oled.show()
def drawImage(self, image):
self.oled(image)
self.oled.show()
class Bartender():
def __init__(self):
self.oled = Display()
def test(self):
image = Image.new("1", (20, 20))
draw = ImageDraw.Draw(image)
font = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", 25)
self.len = len("e")
draw.text(
(0, 40 - 2 // 2),
"e",
font=font,
fill=255,
)
Error is:
Traceback (most recent call last):
File "/home/pi/Smart-Bartender/bartender_flask_new_test.py", line 13, in <module>
my_flask = MyFlask()
File "/home/pi/Smart-Bartender/bartender_flask_new_test.py", line 8, in __init__
self.bartender.test()
File "/home/pi/Smart-Bartender/test_displayclass.py", line 61, in test
self.oled.drawImage(image)
File "/home/pi/Smart-Bartender/test_displayclass.py", line 33, in drawImage
self.oled(image)
TypeError: 'SSD1306_I2C' object is not callable
Can you advice me how to do it the correct waY?
Need of taken the function self.oled.image(image)
I want to run this code in jupyter notebook but it gives me that error :
ImportError: cannot import name 'document' from 'browser' (C:\Users\pc\anaconda3\lib\site-packages\browser_init_.py)
What should I do ?
from browser import document, window
def sketch(p):
def setup():
p.createCanvas(500, 500)
p.stroke(p.color("blue"))
p.line(10, 10, 100, 100)
def draw():
pass
p.setup = setup
p.draw = draw
myP5 = window.p5.new(sketch)
I cannot correctly display Arabic text inside a table despite being displayed correctly using drawCentredString!!
Here's an example:
from arabic_reshaper import reshape
from bidi.algorithm import get_display
def arabic(text):
return get_display(reshape(text))
# This works
_canvas.setFont("NotoNaskhArabic-Regular", 24)
_canvas.drawCentredString(x=A4[0] / 2 - 10, y=760, text=arabic("نص عربي"))
# But this doesn't work
_canvas.setFont("NotoNaskhArabic-Regular", 18)
_head = Table([ [arabic("نص عربي")] ])
_head.wrapOn(_canvas, 0, 0)
_head.drawOn(_canvas, 10, 700)
After rendering
You will find an example here:
https://github.com/abduhbm/python-flask-ar-pdf/blob/c76c9be5a9f996fed17ac0e19443ae9f5db022a0/api/endpoints/pdf.py#L43
# randomize.py
import os
import sys
import re
import shuti1
import json
import cProfile
import random
li = ["dog dot", "do don't", "dumb-dumb", "no match"]
for element in li:
m = re.match("(d\w+)\W(d\w+)", element)
if m:
print(m.groups())
for _, __ in enumerate(sys.path):
shuti1.initialize('Hello', '!', 'HackerEarth')
print __
while True:
li_random = random.choice(li)
print li_random
if li[0] in li_random:
break
# shuti1.py
import sys
import randomize
import collections
import math
from collections import Counter
class HackerEarth(object):
def __init__(self, name, role, hobby):
self.name = name
self.role = role
self.hobby = hobby
def print_details(self):
print "Name:", self.name
print "Role:", self.role
print "Hobby:", self.hobb
cnt = Counter()
for word in ['red', 'blue', 'red', 'green', 'blue', 'blue']:
cnt[word] += 1
def initialize(greet, character, company):
print greet, character, company
when i run the program i got the error like:
Traceback (most recent call last):
File "C:/Users/SAGAR/Desktop/randomize.py", line 5, in <module>
import shuti1
File "C:\Python34\shuti1.py", line 3, in <module>
import randomize
File "C:/Users/SAGAR/Desktop\randomize.py", line 18, in <module>
shuti1.initialize('Hello', '!', 'HackerEarth')
AttributeError: 'module' object has no attribute 'initialize'
I'm gonna take a guess that initialize is part of the HackerEarth class as you didn't indent much to be sure. If that's the case, initialize is not part of the module, it is part of the class, so you would need a HackerEarth object in order to call it.
If that isn't the case, it could be the cyclic imports that Peter Wood mentioned (sorry, don't know how to tag!). What that means is that you are importing shuti1.py into randomize.py and randomize.py into shuti1.py. This can be confirmed looking at the error message:
File "C:/Users/SAGAR/Desktop/randomize.py", line 5, in
import shuti1
File "C:\Python34\shuti1.py", line 3, in
import randomize
Lastly, it could be caused by an IDE if you are using one. Pycharm requires all imported files to be in the project or part of your python directory. Check for something like that if you can't fix it with the other 2 things.
Hope it helps
this is what i am getting when i execute the following code.
Traceback (most recent call last):
File "usrp.py",line 100 in <module>
tb.set_freq(i)
File "usrp.py",line 77 in set_freq
self.wxgui_fftsink2_0.set_baseband_freq(self.freq)
File "usr/local/lib/python2.7/dist-packages/gnuradio/wxgui/common.py",line 131 in set
def set(value): controller[key]=value
File "usr/local/lib/python2.7/dist-packages/gnuradio/wxgui/pubsub.py",line 44 in _setitem_
elif self._proxies[key] is not None:
AttributeError: 'fft_window' object has no attribute '_proxies'
i have seen this kind of error in cyclic dependency.i have earlier solved cyclic dependency by just importing the package instead of using from keyword.i had tried import gnuradio in ths case but of no use.Following is the code on which i am working on.it would be great help if this could be resolved.i haven't come across this kind of an error.
#!/usr/bin/env python
##################################################
# Gnuradio Python Flow Graph
# Title: Usrp
# Generated: Sat Feb 21 11:26:17 2015
##################################################
#################################################
# Gnuradio Python Flow Graph
# Title: Usrp
# Generated: Sat Feb 21 11:26:17 2015
##################################################
from gnuradio import analog
from gnuradio import blocks
from gnuradio import eng_notation
from gnuradio import gr
from gnuradio import wxgui
from gnuradio.eng_option import eng_option
from gnuradio.fft import window
from gnuradio.filter import firdes
from gnuradio.wxgui import fftsink2
from grc_gnuradio import wxgui as grc_wxgui
from optparse import OptionParser
import wx,time,random
class usrp(grc_wxgui.top_block_gui):
def __init__(self):
grc_wxgui.top_block_gui.__init__(self, title="Usrp")
##################################################
# Variables
##################################################
self.samp_rate = samp_rate = 32000
self.freq = freq = 900e6
##################################################
# Blocks
##################################################
self.wxgui_fftsink2_0 = fftsink2.fft_sink_c(
self.GetWin(),
baseband_freq=freq,
y_per_div=10,
y_divs=10,
ref_level=0,
ref_scale=2.0,
sample_rate=samp_rate
fft_size=1024,
fft_rate=15,
average=False,
avg_alpha=None,
title="FFT Plot",
peak_hold=False,
)
self.Add(self.wxgui_fftsink2_0.win)
self.blocks_throttle_0 = blocks.throttle(gr.sizeof_gr_complex*1, samp_rate,True)
self.analog_sig_source_x_0 = analog.sig_source_c(samp_rate, analog.GR_SIN_WAVE, 100e3,1, 0)
##################################################
# Connections
##################################################
self.connect((self.analog_sig_source_x_0, 0), (self.blocks_throttle_0, 0))
self.connect((self.blocks_throttle_0, 0), (self.wxgui_fftsink2_0, 0))
def get_samp_rate(self):
return self.samp_rate
def set_samp_rate(self, samp_rate):
self.samp_rate = samp_rate
self.wxgui_fftsink2_0.set_sample_rate(self.samp_rate)
self.analog_sig_source_x_0.set_sampling_freq(self.samp_rate)
self.blocks_throttle_0.set_sample_rate(self.samp_rate)
def get_freq(self):
return self.freq
def set_freq(self, freq):
self.freq = freq
self.wxgui_fftsink2_0.set_baseband_freq(self.freq)
if __name__ == '__main__':
import ctypes
import sys
if sys.platform.startswith('linux'):
try:
x11 = ctypes.cdll.LoadLibrary('libX11.so')
x11.XInitThreads()
except:
print "Warning: failed to XInitThreads()"
parser = OptionParser(option_class=eng_option, usage="%prog: [options]")
(options, args) = parser.parse_args()
tb = usrp()
def t_range(beg,end,incr):
while beg<=end:
yield beg
beg+=incr
j=2
for i in t_range(910e6,1010e6,10e6):
tb.set_freq(i)
#time.sleep(j)
tb.Start(True)
time.sleep(j)
tb.Wait()
This is most likely not a cyclic dependency issue.
I'm however a bit concerned about that error. You see, pubsub's __init__ generates a _proxies attribute, so if a class is a subclass of pubsub, it should have _proxies; if it's not, it shouldn't see that call.
class pubsub(dict):
def __init__(self):
self._publishers = { }
self._subscribers = { }
self._proxies = { }
....
So, interestingly, your script works for me (after fixing a missing , in line 45), which might indicate you're mixing sources of different GNU Radio versions:
As a solution, I recommend making sure you're really using one version of GNU Radio, preferably the latest, and installed from source (debian's packages are rather up-to-date, too, thanks to Maitland), which can happen automagically using PyBOMBS.