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.
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.
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!
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>
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.
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):
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
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.)
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?
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!
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..
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?
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.
>>> import math
>>> math.pow(2, 3000)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
OverflowError: math range error
How can I fix it? thanx.
hi there, are there any way to create an object form any class inside a numpy array?¿. Something like:
a = zeros(4)
for i in range(4):
a[i]=Register()
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
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!
If my model for Items is:
class Item(models.Model):
name = models.CharField(max_length=500)
startDate = models.DateField("Start Date", unique="true")
endDate = models.DateField("End Date")
Each Item needs to have a unique date range. for example, if i create an Item that has a date range of June 1st to June 8th, how can I keep and Item with a date range of June 3rd to June 5th from being created (or render an error with template logic)?
The original list project_keys = sorted(projects.keys()) is [101, 102, 103, 104, 105, 106, 107, 108, 109, 110] where the following projects were deemed invalid this year: 108, 109, 110.
Thus:
for project in projects.itervalues():
# The projects dictionary is mapped to the Project class
if project.invalid:
# Where invalid is a Bool parameter in the Project class
project_keys.remove(project.proj_id)
print project_keys
This will return a list of integers (which are project id's) as such:
[101, 102, 103, 104, 105, 106, 107]
Sweet.
Now, I wanted it try the same thing using a list comprehension.
project_keys = [project_keys.remove(project.proj_id) for project in projects.itervalues() if project.invalid
print project_keys
This returns:
[None, None, None]
So I'm populating a list with the same number as the removed elements but they're Nones?
Can someone point out what I'm doing wrong?
Additionally, why would I use a list comprehension over the for-if block at the top? Conciseness? Looks nicer?
When a user sends a filled form, I want to print an error message in case there is an input error. One of the GAE sample codes does this by embedding the error message in the URI.
Inside the form handler (get):
self.redirect('/compose?error_message=%s' % message)
and in the handler (get) of redirected URI, gets the message from request:
values = {
'error_message': self.request.get('error_message'),
...
Is there a way to accomplish the same without embedding the message in the URI?
hi,a webproxy on app engine oncyberspace.appspot.com , save cookie in the database, when i try to login in the google with my account, it redirect to google.com . how to solve these problem ? and another problem , when i this the above web to login in twitter,it works !but i can not use it to update my tweet. i don't know why, may be i can't pass oauth . how to solve this ?
In my web app I would like to be able to email self-authenticating links to users. These links will contain a unique token (uuid). When they click the link the token being present in the query string will be enough to authenticate them and they won't have to enter their username and password.
What's the best way to do this?