Hi all,
I wanna show a gtk.Window under a gtk.widget.
But I don't know how to retrieve the gtk.widget's coordinates for my gtk.window.
Anyone knows ?
Thanks.
I am using PyGTK to build a GUI application. I want to update the textview widget from another thread but the widget is not getting updated everytime i try an update. What should i do to get a reliable GUI updating?
I have the following model setup.
from django.db import models
from django.contrib.auth.models import User
class SomeManager(models.Manager):
def friends(self):
# return friends bla bla bla
class Relationship(models.Model):
"""(Relationship description)"""
from_user = models.ForeignKey(User, related_name='from_user')
to_user = models.ForeignKey(User, related_name='to_user')
has_requested_friendship = models.BooleanField(default=True)
is_friend = models.BooleanField(default=False)
objects = SomeManager()
relationships = models.ManyToManyField(User, through=Relationship, symmetrical=False)
relationships.contribute_to_class(User, 'relationships')
Here i take the User object and use contribute_to_class to add 'relationships' to the User object. The relationship show up, but if call User.relationships.friends it should run the friends() method, but its failing. Any ideas how i would do this?
Thanks
I have a string which looks like this:
"[segment1][segment2][segment2]"
What I'd like is to be able to split the string into an array, so I'd end up with:
Array[0] = "segment1", Array[1] = "segment2", Array[2] = "segment3"
I've tried using the string split function, but it doesn't seem to do exactly what I want. I was wondering if anyone has some regex which might help me out?
Thanks in advance
I am a SQLAlchemy noob.
Let's say I have an user table in declarative mode:
class User(Base):
__tablename__ = 'user'
id = Column(u'id', Integer(), primary_key=True)
name = Column(u'name', String(50))
When I know user's id without object loaded into session, I update such user like this:
ex = update(User.__table__).where(User.id==123).values(name=u"Bob Marley")
Session.execute(ex)
I dislike using User.__table__, should I stop worrying with that?
Is there a better way to do this?
Thanx!
Hi probably quite a simple question but..
When plotting a graph using matplotlib.pyplot my Y axis goes from -0.04 to 0.03 which is fine but there are 8 labels for increments (eg 0.03,0.02,0.01 etc.). I need more maybe 16 or so.
Thanks for your help
I have a script that parses the filenames of TV episodes (show.name.s01e02.avi for example), grabs the episode name (from the www.thetvdb.com API) and automatically renames them into something nicer (Show Name - [01x02].avi)
The script works fine, that is until you try and use it on files that have Unicode show-names (something I never really thought about, since all the files I have are English, so mostly pretty-much all fall within [a-zA-Z0-9'\-])
How can I allow the regular expressions to match accented characters and the likes? Currently the regex's config section looks like..
config['valid_filename_chars'] = """0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@£$%^&*()_+=-[]{}"'.,<>`~? """
config['valid_filename_chars_regex'] = re.escape(config['valid_filename_chars'])
config['name_parse'] = [
# foo_[s01]_[e01]
re.compile('''^([%s]+?)[ \._\-]\[[Ss]([0-9]+?)\]_\[[Ee]([0-9]+?)\]?[^\\/]*$'''% (config['valid_filename_chars_regex'])),
# foo.1x09*
re.compile('''^([%s]+?)[ \._\-]\[?([0-9]+)x([0-9]+)[^\\/]*$''' % (config['valid_filename_chars_regex'])),
# foo.s01.e01, foo.s01_e01
re.compile('''^([%s]+?)[ \._\-][Ss]([0-9]+)[\.\- ]?[Ee]([0-9]+)[^\\/]*$''' % (config['valid_filename_chars_regex'])),
# foo.103*
re.compile('''^([%s]+)[ \._\-]([0-9]{1})([0-9]{2})[\._ -][^\\/]*$''' % (config['valid_filename_chars_regex'])),
# foo.0103*
re.compile('''^([%s]+)[ \._\-]([0-9]{2})([0-9]{2,3})[\._ -][^\\/]*$''' % (config['valid_filename_chars_regex'])),
]
I'm trying to scrape all the inner html from the <p> elements in a web page using BeautifulSoup. There are internal tags, but I don't care, I just want to get the internal text.
For example, for:
<p>Red</p>
<p><i>Blue</i></p>
<p>Yellow</p>
<p>Light <b>green</b></p>
How can I extract:
Red
Blue
Yellow
Light green
Neither .string nor .contents[0] does what I need. Nor does .extract(), because I don't want to have to specify the internal tags in advance - I want to deal with any that may occur.
Is there a 'just get the visible HTML' type of method in BeautifulSoup?
----UPDATE------
On advice, trying:
p_tags = page.findAll('p',text=True)
for i, p_tag in enumerate(p_tags):
print str(p_tag)
But that doesn't help - it just prints out:
Red
<i>Blue</i>
Yellow
Light <b>green</b>
I have a decorated function (simplified version):
class Memoize:
def __init__(self, function):
self.function = function
self.memoized = {}
def __call__(self, *args, **kwds):
hash = args
try:
return self.memoized[hash]
except KeyError:
self.memoized[hash] = self.function(*args)
return self.memoized[hash]
@Memoize
def _DrawPlot(self, options):
do something...
now I want to add this method to a pre-esisting class.
ROOT.TChain.DrawPlot = _DrawPlot
when I call this method:
chain = TChain()
chain.DrawPlot(opts)
I got:
self.memoized[hash] = self.function(*args)
TypeError: _DrawPlot() takes exactly 2 arguments (1 given)
why doesn't it propagate self?
I want to print the line immediately before the searched string. How can I do that?
Lets say my two lines are
AADRG
SDFJGKDFSDF
and I am searching for SDF. I have found SDFJGKDFSDF, but how can I obtain the previous line AADRG? Does file.readline()-1 work?
What I'm trying to do is query the datastore for a model where the key is not the key of an object I already have. Here's some code:
class User(db.Model):
partner = db.SelfReferenceProperty()
def text_message(self, msg):
user = User.get_or_insert(msg.sender)
if not user.partner:
# user doesn't have a partner, find them one
# BUG: this line returns 'user' himself... :(
other = db.Query(User).filter('partner =', None).get()
if other:
# connect users
else:
# no one to connect to!
The idea is to find another User who doesn't have a partner, that isn't the User we already know.
I've tried filter('key !=, user.key()), filter('__key__ !=, user.key()) and a couple others, and nothing returns another User who doesn't have a partner.
filter('foo !=, user.key()) also returns nothing, for the record.
Just a little background: I'm making a program where a user inputs a skeleton text, two numbers (lower and upper limit), and a list of words. The outputs are a series of modifications on the skeleton text.
Sample inputs:
text = "Player # likes @." (replace # with inputted integers and @ with words in list)
lower = 1
upper = 3
list = "apples, bananas, oranges"
The user can choose to iterate over numbers first:
Player 1 likes apples.
Player 2 likes apples.
Player 3 likes apples.
Or words first:
Player 1 likes apples.
Player 1 likes bananas.
Player 1 likes oranges.
I chose to split these two methods of outputs by creating a different type of dictionary based on either number keys (integers inputted by the user) or word keys (from words in the inputted list) and then later iterating over the values in the dictionary.
Here are the two types of dictionary creation:
def numkey(dict): # {1: ['Player 1 likes apples', 'Player 1 likes...' ] }
text, lower, upper, list = input_sort(dict)
d = {}
for num in range(lower,upper+1):
l = []
for i in list:
l.append(text.replace('#', str(num)).replace('@', i))
d[num] = l
return d
def wordkey(dict): # {'apples': ['Player 1 likes apples', 'Player 2 likes apples'..] }
text, lower, upper, list = input_sort(dict)
d = {}
for i in list:
l = []
for num in range(lower,upper+1):
l.append(text.replace('#', str(num)).replace('@', i))
d[i] = l
return d
It's fine that I have two separate functions for creating different types of dictionaries but I see a lot of repetition between the two. Is there any way I could make one dictionary function and pass in different values to it that would change the order of the nested for loops to create the specific {key : value} pairs I'm looking for?
I'm not sure how this would be done. Is there anything related to functional programming or other paradigms that might help with this? The question is a little abstract and more stylistic/design-oriented than anything.
Is it possible to have multi-level polymorphism in SQLAlchemy? Here's an example:
class Entity(Base):
__tablename__ = 'entities'
id = Column(Integer, primary_key=True)
created_at = Column(DateTime, default=datetime.utcnow, nullable=False)
entity_type = Column(Unicode(20), nullable=False)
__mapper_args__ = {'polymorphic_on': entity_type}
class File(Entity):
__tablename__ = 'files'
id = Column(None, ForeignKey('entities.id'), primary_key=True)
filepath = Column(Unicode(255), nullable=False)
file_type = Column(Unicode(20), nullable=False)
__mapper_args__ = {'polymorphic_identity': u'file', 'polymorphic_on': file_type)
class Image(File):
__mapper_args__ = {'polymorphic_identity': u'image'}
__tablename__ = 'images'
id = Column(None, ForeignKey('files.id'), primary_key=True)
width = Column(Integer)
height = Column(Integer)
When I call Base.metadata.create_all(), SQLAlchemy raises the following error: NotImplementedError: Can't generate DDL for the null type IntegrityError: (IntegrityError) entities.entity_type may not be NULL. This error goes away if I remove the Image model and the polymorphic_on key in File.
What gives?
(Edited: the exception raised was wrong.)
I have a dialog created in PyQt. It's purpose and functionality don't matter.
The init is:
class MyDialog(QWidget, ui_module.Ui_Dialog):
def __init__(self, parent=None):
super(MyDialog, self).__init__(parent)
self.setupUi(self)
self.installEventFilter(self)
self.setWindowFlags(Qt.Dialog | Qt.WindowTitleHint)
self.showMaximized()
Then I have event filtering method:
def eventFilter(self, obj, event):
if event.type() == QEvent.KeyPress:
key = event.key()
if key == Qt.Key_F11:
if self.isFullScreen():
self.setWindowFlags(self._flags)
if self._state == 'm':
self.showMaximized()
else:
self.showNormal()
self.setGeometry(self._geometry)
else:
self._state = 'm' if self.isMaximized() else 'n'
self._flags = self.windowFlags()
self._geometry = self.geometry()
self.setWindowFlags(Qt.Tool | Qt.FramelessWindowHint)
self.showFullScreen()
return True
elif key == Qt.Key_Escape:
self.close()
return QWidget.eventFilter(self, obj, event)
As can be seen, Esc is used for dialog hiding, and F11 is used for toggling full-screen. In addition, if the user changed the dialog mode from the initial maximized to normal and possibly moved the dialog, it's state and position are restored after exiting the full-screen.
Finally, the dialog is created on the MainWindow action triggered:
d = MyDialog(self)
d.show()
It works fine on Linux (Ubuntu Lucid), but quite strange on Windows 7:
if I go to the full-screen from the maximized mode, I can't exit full-screen (on F11 dialog disappears and appears in full-screen mode again). If I change the dialog's mode to Normal (by double-clicking its title), then go to full-screen and then return back, the dialog is shown in the normal mode, in the correct position, but without the title line.
Most probably the reason for both cases is the same - the setWindowFlags doesn't work. But why?
Is it also possible that it is the bug in the recent PyQt version? On Ubuntu I have 4.6.x from apt, and on Windows - the latest installer from the riverbank site.
Hey,
Imagine you have this model:
class Category(models.Model):
node_id = models.IntegerField(primary_key = True)
type_id = models.IntegerField(max_length = 20)
parent_id = models.IntegerField(max_length = 20)
sort_order = models.IntegerField(max_length = 20)
name = models.CharField(max_length = 45)
lft = models.IntegerField(max_length = 20)
rgt = models.IntegerField(max_length = 20)
depth = models.IntegerField(max_length = 20)
added_on = models.DateTimeField(auto_now = True)
updated_on = models.DateTimeField(auto_now = True)
status = models.IntegerField(max_length = 20)
node = models.ForeignKey(Category_info, verbose_name = 'Category_info', to_field = 'node_id'
The important part is the foreignkey.
When I try:
Category.objects.filter(type_id = type_g.type_id, parent_id = offset, status = 1)
I get an error that get returned more than category, which is fine, because it is supposed to return more than one. But I want to filter the results trough another field, which would be type id (from the second Model)
Here it is:
class Category_info(models.Model):
objtree_label_id = models.AutoField(primary_key = True)
node_id = models.IntegerField(unique = True)
language_id = models.IntegerField()
label = models.CharField(max_length = 255)
type_id = models.IntegerField()
The type_id can be any number from 1 - 5. I am desparately trying to get only one result where the type_id would be number 1.
Here is what I want in sql:
SELECT n.*, l.*
FROM objtree_nodes n
JOIN objtree_labels l ON (n.node_id = l.node_id)
WHERE n.type_id = 15 AND n.parent_id = 50 AND l.type_id = 1
Any help is GREATLY appreciated.
Regards
I have two similar codes. The first one works as expected.
urlpatterns = patterns('',
(r'^(?P<n1>\d)/test/', test),
(r'', test2),
{% url testapp.views.test n1=5 %}
But adding the second parameter makes the result return empty string.
urlpatterns = patterns('',
(r'^(?P<n1>\d)/test(?P<n2>\d)/', test),
(r'', test2),)
{% url testapp.views.test n1=5, n2=2 %}
Views signature:
def test(request, n1, n2=1):
Hi,
Is there a direct way of listing out 'all' form errors in Django templates. I'd like to list out both field and non-field errors and any other form errors.
I've found out how to do this on a per-field basis but as said earlier, I'd like to list out everything.
The method I'm using doesn't seem to list out everything.
{% for error in form.errors %}
{{ error|escape }}
{% endfor %}
Thanks.
hello,
recently i want to upload GAppProxy to GAE.
but when i use the appcfg.py to update the files,there comes an error,it was:
urllib2.URLError: urlopen error [Errno 8] _ssl.c:480: EOF occurred in
violation of protocol
i don't know why
PS:i live in china,and may be because of the GFW.
and when i use the type :appengine.google.com and then input the password,i can't redict to the index page,there is an error too,which says:ssl error
So I have a model with a FileField for excel spreadsheet. What I need to do this add another column in this spreadsheet, in each row let user pick from a drop-down list then save it and display it in html. All the picking and uploading will happen through the admin interface. So I have figured out way how to display a spreadsheet in html, however I have no idea how to write this save method. I could really use some hints and tips..
Am running into ValueError, here is the traceback dpaste.com/197332/ .
Am using AutoSlugify , this is my AutoSlugField.py dpaste.com/197330/
Am trying to get the django-tagging system working, this is my models.py
dpaste.com/197331/
Help?
I need to write a gui in Tkinter that can choose a csv file, read it in and generate a sequence of buttons based on the names in the first row of the csv file (later the data in the csv file should be used to run a number of simulations).
So far I have managed to write a Tkinter gui that will read the csv file, but I am stomped as to how I should proceed:
from Tkinter import *
import tkFileDialog
import csv
class Application(Frame):
def __init__(self, master = None):
Frame.__init__(self,master)
self.grid()
self.createWidgets()
def createWidgets(self):
top = self.winfo_toplevel()
self.menuBar = Menu(top)
top["menu"] = self.menuBar
self.subMenu = Menu(self.menuBar)
self.menuBar.add_cascade(label = "File", menu = self.subMenu)
self.subMenu.add_command( label = "Read Data",command = self.readCSV)
def readCSV(self):
self.filename = tkFileDialog.askopenfilename()
f = open(self.filename,"rb")
read = csv.reader(f, delimiter = ",")
app = Application()
app.master.title("test")
app.mainloop()
Any help is greatly appreciated!
hi all, I was condering when I use urllib2.urlopen() does it just to header reads or does it actually bring back the entire webpage?
IE does the HTML page actually get fetch on the urlopen call or the read() call?
handle = urllib2.urlopen(url)
html = handle.read()
The reason I ask is for this workflow...
I have a list of urls (some of them with short url services)
I only want to read the webpage if I haven't seen that url before
I need to call urlopen() and use geturl() to get the final page that link goes to (after the 302 redirects) so I know if I've crawled it yet or not.
I don't want to incur the overhead of having to grab the html if I've already parsed that page.
thanks!