ValurError when creating a Pygame surface in a class - class

for some reason, this code doesn't work and for the life of me I can't figure out
import pygame as py
py.init()
py.font.init()
c_size = 35
monaco = py.font.SysFont("monaco", int(round(c_size * 1.4)))
class Button(object):
def __init__(self,title):
self.title = title
self.width = monaco.size(self.title)[0]
self.height = monaco.size(self.title)[1]
self.surf = py.Surface(int(self.width), int(self.height))
stop = Button("Stop")
Raises this error:
Traceback (most recent call last):
File "/Users/yonatanmitzna/Desktop/hiuoho.py", line 21, in <module>
stop = Button("Stop")
File "/Users/yonatanmitzna/Desktop/hiuoho.py", line 19, in __init__
self.surf = py.Surface(int(self.width), int(self.height))
ValueError: size needs to be (int width, int height)
I tried to test the type of the values going into the py.Surface command, and they are both int! no clue why this doesn't work.

The argument to pygame.Surface must be a tuple with the size of the surface, instead of 2 separate arguments:
self.surf = py.Surface((int(self.width), int(self.height)))
self.surf = py.Surface((int(self.width), int(self.height)))

Related

Bokeh RangeSlider callback issue, source.change.emit() gives error "Cannot read property 'emit' of undefined"

I recently started on a new project that requires me to plot lat and long data on a map. I've managed to plot everything out so far, but I've gotten stuck at creating the callback function for the Range Slider I'm using to control which data to plot.
My current code uses this response here by Amstrad2Python as its base. Running the code that Amstrad2Python provided gave me no errors. However, when I try to run the code, it gives me the error "Cannot read property 'emit' of undefined" when I check the console output in the html plot.
Here is sample code that is similar to the actual code I am using, which creates the exact same error:
import bokeh.events as bev
import bokeh.layouts as bla
import bokeh.models as bmo
import numpy as np
import pandas as pd
from bokeh.plotting import figure, output_file, show
sample_data = pd.DataFrame(
data=np.array(
[
[1, 12, 21, 15000],
[2, 25, 90, 15500],
[3, 37, 47, 15500],
[4, 41, 56, 15000],
[5, 50, 21, 14500]
]
),
columns=['Seconds', 'lat', 'long', 'alt']
)
#create 2 sources, 1 for editting, 1 for referencing
source = bmo.ColumnDataSource(sample_data) #const data
filtered_source = bmo.ColumnDataSource(sample_data) #alterable data
#create callback function
callback = bmo.CustomJS(args=dict(source=source, filtered_source = filtered_source),
code="""
var data = source.data;
var start = cb_obj.value[0];
var end = cb_obj.value[1];
function generateNewDataObject(oldDataObject){
var newDataObject = {}
for (var key of Object.keys(oldDataObject)){
newDataObject[key] = [];
}
return newDataObject
}
function addRowToAccumulator(accumulator, dataObject, index) {
for (var key of Object.keys(dataObject)){
accumulator[key][index] = dataObject[key][index];
}
return accumulator;
}
var new_data = generateNewDataObject(data);
for (var i = 0; i < source.data['Seconds'].length; i++){
if (source.data['Seconds'][i] > start) {
if (source.data['Seconds'][i] <= end) {
new_data = addRowToAccumulator(new_data, source.data, i);
}
}
}
console.log(new_data)
filtered_source = new_data;
filtered_source.change.emit();
""")
#create slider and add on_change event
testSlider = bmo.RangeSlider(width = 525, bar_color = 'red',
start = 0, end = sample_data['Seconds'].max(),
value=(0,1), step = 1 )
testSlider.js_on_change('value', callback)
#create figure and plot points
p = figure(toolbar_location = 'below',
x_axis_label = 'Longitude', y_axis_label = 'Latitude')
p.circle(x = 'long', y = 'lat', source=filtered_source)
#create layout and show
layout = bla.column(p, testSlider)
show(layout)
For reference, this is the resulting error I get when I try to change the slider:
https://i.stack.imgur.com/OTBEm.png
Does anyone know what the issue is with my current code? Any feedback regarding to my code is also appreciated. Thank you in advance.
You need to assign the new_data to the .data field of filtered_source.
When changing the line filtered_source = new_data; to filtered_source.data = new_data;, your example works for me.

AttributeError: 'NoneType' object has no attribute 'impl'

After running my program, I am getting a Output, but I also get this error message.
Exception ignored in: <function Model.__del__ at 0x7f02ba33b430>
Traceback (most recent call last):
File "/usr/local/lib/python3.8/dist-packages/deepspeech/__init__.py", line 43, in __del__
AttributeError: 'NoneType' object has no attribute 'impl'
Here is the code - Here I am trying to convert an wv audio file into text using deepspeech library.
from deepspeech import Model
import numpy as np
import os
import wave
import json
from IPython.display import Audio
from IPython.display import clear_output
model_file_path = 'deepspeech-0.8.2-models.pbmm'
lm_file_path = 'deepspeech-0.8.2-models.scorer'
beam_width = 100
lm_alpha = 0.93
lm_beta = 1.18
model = Model(model_file_path)
model.enableExternalScorer(lm_file_path)
model.setScorerAlphaBeta(lm_alpha, lm_beta)
model.setBeamWidth(beam_width)
def read_wav_file(filename):
with wave.open(filename, 'rb') as w:
rate = w.getframerate()
frames = w.getnframes()
buffer = w.readframes(frames)
return buffer, rate
def transcribe(audio_file):
buffer, rate = read_wav_file(audio_file)
data16 = np.frombuffer(buffer, dtype=np.int16)
return model.stt(data16)
print(transcribe('speech.wav'))
Importing IPython is causing the issue, try running your code without it and it should work.
from deepspeech import Model
import numpy as np
import os
import wave
import json
model_file_path = 'deepspeech-0.8.2-models.pbmm'
lm_file_path = 'deepspeech-0.8.2-models.scorer'
beam_width = 100
lm_alpha = 0.93
lm_beta = 1.18
model = Model(model_file_path)
model.enableExternalScorer(lm_file_path)
model.setScorerAlphaBeta(lm_alpha, lm_beta)
model.setBeamWidth(beam_width)
def read_wav_file(filename):
with wave.open(filename, 'rb') as w:
rate = w.getframerate()
frames = w.getnframes()
buffer = w.readframes(frames)
return buffer, rate
def transcribe(audio_file):
buffer, rate = read_wav_file(audio_file)
data16 = np.frombuffer(buffer, dtype=np.int16)
return model.stt(data16)
print(transcribe('speech.wav'))

How make custom dataset for classification task when the class is folder name using Pytorch?

The problem is dataloader is returning the wrong class for correspond image?
for example if I print the class_to_idx from the train_loader, when batch size is 1I was expecting to get one class per batch, but currently it’s returning all the classes which is 15 classes per image.
In this case, the classes are folder class (all images exist in one folder belongs to one class)
snippet is here:(this is a function to return the class from the folder name dir)
import os
def find_classes(dir): # Finds the class folders in a dataset, dir (string): Root directory path.
classes = [d.name for d in os.scandir(dir) if d.is_dir()]
classes.sort()
class_to_idx = {classes[i]: i for i in range(len(classes))}
return classes, class_to_idx
here is the main snippet for create a custom dataset and dataloder
def main():
class CustomDataset(Dataset):
def __init__(self, image_paths, classes, class_to_id):
self.image_paths = image_paths
self.transforms = transforms.ToTensor()
classes, class_to_id = find_classes('D:/Neda/Echo_View_Classification/avi_images/')
self.classes = classes
self.class_to_idx = class_to_idx
def __getitem__(self, index):
image = Image.open(self.image_paths[index])
t_image = image.convert('L')
t_image = self.transforms(t_image)
class_to_idx = self.class_to_idx
return t_image, class_to_idx, self.image_paths[index]
def __len__(self):
return len(self.image_paths)
folder_data = glob.glob("D:\\Neda\\Echo_View_Classification\\avi_images\\*\\*.png") # no augmnetation
#numpy.savetxt('distribution_class.csv', numpy.c_[folder_data], fmt=['%s'], comments='', delimiter = ",")
#split these path using a certain percentage
len_data = len(folder_data)
print("count of dataset: ", len_data)
split_1 = int(0.6 * len(folder_data))
split_2 = int(0.8 * len(folder_data))
folder_data.sort()
train_image_paths = folder_data[:split_1]
print("count of train images is: ", len(train_image_paths))
numpy.savetxt('im_training_path_1.csv', numpy.c_[train_image_paths], fmt=['%s'], comments='', delimiter = ",")
valid_image_paths = folder_data[split_1:split_2]
print("count of validation image is: ", len(valid_image_paths))
numpy.savetxt('im_valid_path_1.csv', numpy.c_[valid_image_paths], fmt=['%s'], comments='', delimiter = ",")
test_image_paths = folder_data[split_2:]
print("count of test images is: ", len(test_image_paths))
numpy.savetxt('im_testing_path_1.csv', numpy.c_[test_image_paths], fmt=['%s'], comments='', delimiter = ",")
classes = ['1_PLAX_1_PLAX_full',
'1_PLAX_2_PLAX_valves',
'1_PLAX_4_PLAX_TV',
'2_PSAX_1_PSAX_AV',
'2_PSAX_2_PSAX_LV',
'3_Apical_1_MV_LA_IAS',
'3_Apical_2_A2CH',
'3_Apical_3_A3CH',
'3_Apical_5_A5CH',
'4_A4CH_1_A4CH_LV',
'4_A4CH_2_A4CH_RV',
'4_Subcostal_1_Subcostal_heart',
'4_Subcostal_2_Subcostal_IVC',
'root_5_Suprasternal',
'root_6_OTHER']
class_to_idx = {'1_PLAX_1_PLAX_full': 0,
'1_PLAX_2_PLAX_valves': 1,
'1_PLAX_4_PLAX_TV': 2,
'2_PSAX_1_PSAX_AV': 3,
'2_PSAX_2_PSAX_LV': 4,
'3_Apical_1_MV_LA_IAS': 5,
'3_Apical_2_A2CH': 6,
'3_Apical_3_A3CH': 7,
'3_Apical_5_A5CH': 8,
'4_A4CH_1_A4CH_LV': 9,
'4_A4CH_2_A4CH_RV': 10,
'4_Subcostal_1_Subcostal_heart': 11,
'4_Subcostal_2_Subcostal_IVC': 12,
'root_5_Suprasternal': 13,
'root_6_OTHER': 14}
train_dataset = CustomDataset(train_image_paths, class_to_idx, classes)
train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=1, shuffle=False, num_workers=0)
valid_dataset = CustomDataset(valid_image_paths, class_to_idx, classes)
valid_loader = torch.utils.data.DataLoader(valid_dataset, batch_size=1, shuffle=False, num_workers=0)
test_dataset = CustomDataset(test_image_paths, class_to_idx, classes)
test_loader = torch.utils.data.DataLoader(test_dataset, batch_size=1, shuffle=False, num_workers=0)
dataLoaders = {
'train': train_loader,
'valid': valid_loader,
'test': test_loader,
}
I think ImageFolder from torchvision.datasets will help you in loading your data.

Apscheduler runs once then throws TypeError

I'm trying to add a list of someone's soundcloud followers to a database every hour. I have the code working to pull their list of followers and add them to a db, but I run into errors when I use it with apscheduler.
Here's an example of the error:
Traceback (most recent call last):
File "desktop/SoundcloudProject/artistdailyfollowers.py", line 59, in <module>
scheduler.add_job(inserttodaysdata(), 'interval', hours=1)
File "//anaconda/lib/python3.5/site-packages/apscheduler/schedulers/base.py", line 425, in add_job
job = Job(self, **job_kwargs)
File "//anaconda/lib/python3.5/site-packages/apscheduler/job.py", line 44, in __init__
self._modify(id=id or uuid4().hex, **kwargs)
File "//anaconda/lib/python3.5/site-packages/apscheduler/job.py", line 165, in _modify
raise TypeError('func must be a callable or a textual reference to one')
TypeError: func must be a callable or a textual reference to one
Here's the code:
import soundcloud
import sqlite3
import datetime
import time
from apscheduler.schedulers.blocking import BlockingScheduler
client = soundcloud.Client(client_id='f3b669e6e4509690939aed943c56dc99')
conn = sqlite3.connect('desktop/SoundcloudProject/RageLogic.db')
c = conn.cursor()
writenow = datetime.datetime.now()
print("If this is printing that means it's running")
print("The time is now: \n" +str(writenow))
page ='https://soundcloud.com/ragelogic'
page_size = 200
def create_table():
c.execute('CREATE TABLE IF NOT EXISTS RageLogicFollowersByDay(day TEXT, list_of_followers TEXT)')
#add todays date and a list of followers to the db
def inserttodaysdata():
global page
full = False
user = client.get('/resolve', url=page)
ufollowing = []
ufirstfollowing = client.get('/users/'+str(user.id)+'/followers', order='id',limit=page_size, linked_partitioning=1)
for user in ufirstfollowing.collection:
ufollowing.append(user.id)
if hasattr(ufirstfollowing, "next_href"):
#print("MANYFOLLOWING")
newlink = ufirstfollowing.next_href
try:
while full == False:
newlist = client.get(newlink)
for user in newlist.collection:
ufollowing.append(user.id)
print(len(ufollowing))
if newlist.next_href == None:
print("full")
full = True
else:
newlink = newlist.next_href
except AttributeError:
None
#print(len(ufollowing))
wtl = []
wtl = repr(ufollowing)
writenow = datetime.datetime.now()
c.execute("INSERT INTO RageLogicFollowersByDay (day, list_of_followers) VALUES (?, ?)",(str(writenow), wtl))
conn.commit()
#create_table()
scheduler = BlockingScheduler()
scheduler.add_job(inserttodaysdata(), 'interval', hours=1)
scheduler.start()
I'm really new to this whole thing and any help anyone could give would be awesome, thanks!
See this line:
scheduler.add_job(inserttodaysdata(), 'interval', hours=1)
and it should be
scheduler.add_job(inserttodaysdata, 'interval', hours=1)
You're calling inserttodaysdata() and passing its return value to add_job(). Don't do that. Pass the function itself, not its call result.
I solved it with just adding time-zone:
scheduler = BackgroundScheduler(timezone="Europe/Berlin")

Open subwindow in GTK3

When Canonical-Quickly sets up a new project it has the following line for the "About dialog":
self.AboutDialog = AboutNewAppDialog
I edited the menu item in glade and added the following code to the python code for the main window:
self.menuabout = self.builder.get_object("menuabout")
and
def on_menuabout_activate(self, menuitem, data=None):
print("About activated")
self.response = self.AboutDialog.run()
self.AboutDialog.hide()
But this produces the error:
self.response = self.AboutDialog.run()
TypeError: run() takes exactly 1 argument (0 given)
I am also working through this tutorial which is using a similar syntax: http://gnipsel.com/glade/glade02b.html
When I place Gtk.Dialog into the brackets the program crashes:
self.response = self.AboutDialog.run(Gtk.Dialog)
My second try:
#!/usr/bin/env python
from gi.repository import Gtk
class Handler:
def on_mainwindow_destroy(self, menuitem):
print("destroy window")
Gtk.main_quit()
def on_menuquit_activate(self, menuitem):
print("quit from menu")
Gtk.main_quit()
def on_menuabout_activate(self, menuitem, data=None):
print("menu about activated")
response = aboutdialog.run()
aboutdialog.hide()
builder = Gtk.Builder()
builder.add_from_file("psn.glade")
builder.connect_signals(Handler())
window = builder.get_object("mainwindow")
window.show_all()
Gtk.main()
Error:
"Traceback (most recent call last):
File "psn_main.py", line 21, in on_menuabout_activate
response = aboutdialog.run()
NameError: name 'aboutdialog' is not defined"
I got it to work using the following code. The function is activated by a menu item which calls "on_menuabout_activate". It prints a debug message to the console. Then it gets the aboutdialog-window from the glade file and runs it:
def on_menuabout_activate(self, menuitem, data=None):
print("menu about activated")
aboutdialog = builder.get_object("aboutdialog")
aboutdialog.run()