from threading import Timer
def hello():
print "hello, world"
t = Timer(30.0, hello)
t.start()
i run only once,
how to make it to running forever ?
thanks
For my little framework Pyxer I would like to to be able to use the Google AppEngine datastores also outside of AppEngine projects, because I'm now used to this ORM pattern and for little quick hacks this is nice. I can not use Google AppEngine for all of my projects because of its's limitations in file size and number of files.
A great alternative would also be, if there was a project that provides an ORM with the same naming as the AppEngine datastore. I also like the GQL approach very much, since this is a nice combination of ORM and SQL patterns.
Any ideas where or how I might find such a solution? Thanks.
Has anyone tried using uWSGI with Cherokee? Can you share your experiences and what documents you relied upon the most? I am trying to get started from the documentation on both (uWSGI and Cherokee) websites. Nothing works yet. I am using Ubuntu 10.04.
Hey guys. Here's my problem:
I have a game class that maintains a HUD overlay that has a bunch of elements, including header and footer background sprites. Everything was working fine until I added a 1024x128 footer sprite. Now two of my text labels will not render, despite the fact that they DO exist in my Group and self.elements array. Is there something I'm missing? When I take out the footerHUDImage line, all of the labels render correctly and everything works fine. When I add the footerHUDImage, two of the labels (the first two) no longer render and the third only sometimes renders. HELP PLEASE! Here is the code:
class AoWHUD (object):
def __init__(self, screen, delegate, dataSource):
self.delegate = delegate
self.dataSource = dataSource
self.elements = []
headerHudImage = KJRImage("HUDBackground.png")
self.elements.append(headerHudImage)
headerHudImage.userInteractionEnabled = True
footerHUDImage = KJRImage("ControlsBackground.png")
self.elements.append(footerHUDImage)
footerHUDImage.rect.bottom = screen.get_rect().height
footerHUDImage.userInteractionEnabled = True
lumberMessage = "Lumber: " + str(self.dataSource.lumber)
lumberLabel = KJRLabel(lumberMessage, size = 48, color = (240, 200, 10))
lumberLabel.rect.topleft = (_kSpacingMultiple * 0, 0)
self.elements.append(lumberLabel)
stoneMessage = "Stone: " + str(self.dataSource.stone)
stoneLabel = KJRLabel(stoneMessage, size = 48, color = (240, 200, 10))
stoneLabel.rect.topleft = (_kSpacingMultiple * 1, 0)
self.elements.append(stoneLabel)
metalMessage = "Metal: " + str(self.dataSource.metal)
metalLabel = KJRLabel(metalMessage, size = 48, color = (240, 200, 10))
metalLabel.rect.topleft = (_kSpacingMultiple * 2, 0)
self.elements.append(metalLabel)
foodMessage = "Food: " + str(len(self.dataSource.units)) + "/" + str(self.dataSource.food)
foodLabel = KJRLabel(foodMessage, size = 48, color = (240, 200, 10))
foodLabel.rect.topleft = (_kSpacingMultiple * 3, 0)
self.elements.append(foodLabel)
self.selectionSprites = {32 : pygame.image.load("Selected32.png").convert_alpha(), 64 : pygame.image.load("Selected64.png")}
self._sprites_ = pygame.sprite.Group()
for e in self.elements:
self._sprites_.add(e)
print self.elements
def draw(self, screen):
if self.dataSource.resourcesChanged:
lumberMessage = "Lumber: " + str(self.dataSource.lumber)
stoneMessage = "Stone: " + str(self.dataSource.stone)
metalMessage = "Metal: " + str(self.dataSource.metal)
foodMessage = "Food: " + str(len(self.dataSource.units)) + "/" + str(self.dataSource.food)
self.elements[2].setText(lumberMessage)
self.elements[2].rect.topleft = (_kSpacingMultiple * 0, 0)
self.elements[3].setText(stoneMessage)
self.elements[3].rect.topleft = (_kSpacingMultiple * 1, 0)
self.elements[4].setText(metalMessage)
self.elements[4].rect.topleft = (_kSpacingMultiple * 2, 0)
self.elements[5].setText(foodMessage)
self.elements[5].rect.topleft = (_kSpacingMultiple * 3, 0)
self.dataSource.resourcesChanged = False
self._sprites_.draw(screen)
if self.delegate.selectedUnit:
theSelectionSprite = self.selectionSprites[self.delegate.selectedUnit.rect.width]
screen.blit(theSelectionSprite, self.delegate.selectedUnit.rect)
"8,5,,1,4,7,,,,7,,1,9,3,6,,,8,6,3,9,,2,5,4,,,,,3,2,,,7,4,1,1,,4,,6,9,,5,,,,5,,,1,,6,3,,,6,5,,,,7,4,,1,7,6,,,,8,,5,,,7,1,,3,9,"
I'm doing a programming challenge where i need to parse this sequence into my sudoku script.
Need to get the above sequence into 8,5,0,1,4,7,0,0,0,7,0,1,9,3,6,0,0,8.........
I tried re but without success, help is appreciated, thanks.
I'm planning to perform sentiment analysis on reviews of product features (collected from Amazon dataset). I have extracted review text from the dataset and performed POS tagging on that. I'm able to extract NN/NNP as well. But my doubt is how do I come to know that extracted words classify as features of the products? I know there are classifiers in nltk but I don't know how I should use it for my project. I'm assuming there are 2 ways of finding whether the extracted word is a product feature or not. One is to compare with a bag of words and find out if my word exists in that. Doubt: How do I create/get bag of words? Second way is to implement some kind of apriori algorithm to find out frequently occurring words as features. I would like to know which method is good and how to go about implementing it. Some pointers to available softwares or code snippets would be helpful! Thanks!
Hello.
Here is my problem. I have created a pretty heavy readonly class making many database calls with a static "factory" method. The goal of this method is to avoid killing the database by looking in a pool of already-created objects if an identical instance of the same object (same type, same init parameters) already exists.
If something was found, the method will just return it. No problem. But if not, how may I create an instance of the object, in a way that works with inheritance?
>>> class A(Object):
>>> @classmethod
>>> def get_cached_obj(self, some_identifier):
>>> # Should do something like `return A(idenfier)`, but in a way that works
>>> class B(A):
>>> pass
>>> A.get_cached_obj('foo') # Should do the same as A('foo')
>>> A().get_cached_obj('foo') # Should do the same as A('foo')
>>> B.get_cached_obj('bar') # Should do the same as B('bar')
>>> B().get_cached_obj('bar') # Should do the same as B('bar')
Thanks.
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.
How can I lookup an attribute in any scope by name? My first trial is to use globals() and locals(). e.g.
>>> def foo(name):
... a=1
... print globals().get(name), locals().get(name)
...
>>> foo('a')
None 1
>>> b=1
>>> foo('b')
1 None
>>> foo('foo')
<function foo at 0x014744B0> None
So far so good. However it fails to lookup any built-in names.
>>> range
<built-in function range>
>>> foo('range')
None None
>>> int
<type 'int'>
>>> foo('int')
None None
Any idea on how to lookup built-in attributes?
I've been running my Scrapy project with a couple of accounts (the project scrapes a especific site that requieres login credentials), but no matter the parameters I set, it always runs with the same ones (same credentials).
I'm running under virtualenv. Is there a variable or setting I'm missing?
Edit:
It seems that this problem is Twisted related.
Even when I run:
scrapy crawl -a user='user' -a password='pass' -o items.json -t json SpiderName
I still get an error saying:
ERROR: twisted.internet.error.ReactorNotRestartable
And all the information I get, is the last 'succesful' run of the spider.
Hello,
Can someone give me a simple example involving threads in this manner, please.
Problem with my code is that when I click button One, GUI freezes until its finished. I want buttons to stay responsive when def is being executed. How can i fix that?
class fun:
wTree = None
def __init__( self ):
self.wTree = gtk.glade.XML( "ui.glade" )
dic = {
"on_buttonOne" : self.one,
"on_buttonTwo" : self.two,
}
self.wTree.signal_autoconnect( dic )
gtk.main()
def sone(self, widget):
time.sleep(1)
print "1"
time.sleep(1)
print "2"
time.sleep(1)
print "3"
def stwo(self, widget):
time.sleep(1)
print "4"
time.sleep(1)
print "5"
time.sleep(1)
print "6"
do=fun()
Pretty please, help me.
Hi,
I am in the process of making a webapp, and this webapp needs to have a form wizard. The wizard consists of 3 ModelForms, and it works flawlessly. But I need the second form to be a "edit form". That is, i need it to be a form that is passed an instance.
How can you do this with a form wizard? How do you pass in an instance of a model? I see that the FormWizard class has a get_form method, but isnt there a documented way to use the formwizard for editing/reviewing of data?
I am creating multisites platform. Anybody can make simple site, with my platform. I plan to use django multidb support. One db for one site. And i need to change db settings depending on request.get_host().
I think that i's not good idea. Prompt other decisions? How it is realised on various designers of sites?
I have a small app with Category model and want to make a required foreign key referencing it from Photologue Gallery model.
What's the right approach? I can make many-to-many field in Category, but this way it will not be required in Gallery. Use "register" and modify the Gallery model? Inherit it in my app?
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!
Could you please suggest a simple SMTP server with the very basic APIs(by very basic I mean, to read,write,delete email) that could be run on a linux box?
I just need to convert the crux of the email into XML format and FTP it to another machine.
I am trying to request.user for a form's clean method, but how can I access the request object? Can I modify the clean method to allow variables input?
Thanks.
import wx
class MainFrame(wx.Frame):
def __init__(self,parent,title):
wx.Frame.__init__(self, parent, title=title, size=(640,480))
self.mainPanel=DoubleBufferTest(self,-1)
self.Show(True)
class DoubleBufferTest(wx.Panel):
def __init__(self,parent=None,id=-1):
wx.Panel.__init__(self,parent,id,style=wx.FULL_REPAINT_ON_RESIZE)
self.SetBackgroundColour("#FFFFFF")
self.timer = wx.Timer(self)
self.timer.Start(100)
self.Bind(wx.EVT_TIMER, self.update, self.timer)
self.Bind(wx.EVT_PAINT,self.onPaint)
def onPaint(self,event):
event.Skip()
dc = wx.MemoryDC()
dc.SelectObject(wx.EmptyBitmap(640, 480))
gc = wx.GraphicsContext.Create(dc)
gc.PushState()
gc.SetBrush(wx.Brush("#CFCFCF"))
bgRect=gc.CreatePath()
bgRect.AddRectangle(0,0,640,480)
gc.FillPath(bgRect)
gc.PopState()
dc2=wx.PaintDC(self)
dc2.Blit(0,0,640,480,dc,0,0)
def update(self,event):
self.Refresh()
app = wx.App(False)
f=MainFrame(None,"Test")
app.MainLoop()
I've come up with this code to draw double buffered GraphicsContext content onto a panel, but there's a constant flickering across the window. I've tried different kinds of paths, like lines and curves but it's still there and I don't know what's causing it.
I am building an app using Web2py framework... I don't want to have to use the request object to get all of the querystring parameters, instead I'd like to build my controller with named parameters and have the router unpack the querystring (or form data) dictionary into the named parameters and call my controller.
so instead of a controller method of
create_user():
where I would use the global request() object and look through the vars list... I would prefer instead to have
create_user(first_name, last_name, email):
like I see in other MVC platforms.
is this possible in Web2py already? or is there a plugin for it? or do I need to add that myself?
ok so basically I am asking the question of their name
I want this to be one input rather than Forename and Surname.
Now is there any way of splitting this name? and taking just the last word from the "Sentence" e.g.
name = "Thomas Winter"
print name.split()
and what would be output is just "Winter"
I do not care about concurrency issues.
It is relatively easy to build unique form field:
from django import forms
class UniqueUserEmailField(forms.CharField):
def clean(self, value):
self.check_uniqueness(super(UniqueUserEmailField, self).clean(value))
def check_uniqueness(self, value):
same_user = users.User.all().filter('email', value).get()
if same_user:
raise forms.ValidationError('%s already_registered' % value)
so one could add users on-the-fly. Editing existing user is tricky. This field would not allow to save user having other user email. At the same time it would not allow to save a user with the same email. What code do you use to put a field with uniqueness check into ModelForm?
Hello, I'm loading web-page using urllib. Ther eis russian symbols, but page encoding is 'utf-8'
1
pageData = unicode(requestHandler.read()).decode('utf-8')
UnicodeDecodeError: 'ascii' codec can't decode byte 0xd0 in position 262: ordinal not in range(128)
2
pageData = requestHandler.read()
soupHandler = BeautifulSoup(pageData)
print soupHandler.findAll(...)
UnicodeEncodeError: 'ascii' codec can't encode characters in position 340-345: ordinal not in range(128)
I'm using the nice feature in QMessageBox to optionally show detailed text to the user. However, the window after expansion is still fairly small, and one immediately tries to resize the window so more of the details are visible. Even after setting what I think are the proper settings it won't allow resizing.
Here's the relevant snippet of PyQt4 code:
mb = QMessageBox()
mb.setText("Results written to '%s'" % filename)
mb.setDetailedText(str(myData))
mb.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
mb.setSizeGripEnabled(True)
Am I missing a step and/or is this at all possible?