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
hello ..
i have the same code as wx Doodle pad in the wx demos
i added a tool to paste images from the clipboard to the pad.
using wx.DrawBitmap() function , but whenever i refresh the buffer .and call funtions ( drawSavedLines and drawSavedBitmap) it keeps putting bitmap above line no matter what i did
even if i called draw bitmap first and then draw lines .
is there anyway to put a line above the bitmap ?
please inform me if i miss anything
thanx in advance
Every time I create an instance of the TestForm specified below, I have to overwrite the standard id format with auto_id=True. How can this be done once only in the form class instead? Any hints are very welcome.
views.py
from django.forms import ModelForm
from models import Test
class TestForm(ModelForm):
class Meta:
model = Test
def test(request):
form = TestForm(auto_id=True)
I'm attempting to learn Tkinter with the goal of being able to create a 'real-time' scope to plot data. As a test, I'm trying to draw a polygon on the canvas every time the 'draw' button is pressed. The triangle position is randomized. I have two problems:
There is a triangle on the canvas as soon as the program starts, why and how do I fix this?
It doesn't draw any triangles when I press the button, at least none that I can see.
CODE
from Tkinter import *
from random import randint
class App:
def __init__(self,master):
#frame = Frame(master)
#frame.pack(side = LEFT)
self.plotspc = Canvas(master,height = 100, width = 200, bg = "white")
self.plotspc.grid(row=0,column = 2, rowspan = 5)
self.button = Button(master, text = "Quit", fg = "red", \
command = master.quit)
self.button.grid(row=0,column=0)
self.drawbutton = Button(master, text = "Draw", command = \
self.pt([50,50]))
self.drawbutton.grid(row = 0, column = 1)
def pt(self, coords):
coords[0] = coords[0] + randint(-20,20)
coords[1] = coords[1] + randint(-20,20)
x = (0,5,10)
y = (0,10,0)
xp = [coords[0] + xv for xv in x]
yp = [coords[1] + yv for yv in y]
ptf = zip(xp,yp)
self.plotspc.create_polygon(*ptf)
if _name_ == "_main_":
root = Tk()
app = App(root)
root.mainloop()
The code is formatting strangely within the code tags, I have no idea how to fix this.
I'm using matplotlib to plot log-normalized images but I would like the original raw image data to be represented in the colorbar rather than the [0-1] interval. I get the feeling there's a more matplotlib'y way of doing this by using some sort of normalization object and not transforming the data beforehand... in any case, there could be negative values in the raw image.
import matplotlib.pyplot as plt
import numpy as np
def log_transform(im):
'''returns log(image) scaled to the interval [0,1]'''
try:
(min, max) = (im[im > 0].min(), im.max())
if (max > min) and (max > 0):
return (np.log(im.clip(min, max)) - np.log(min)) / (np.log(max) - np.log(min))
except:
pass
return im
a = np.ones((100,100))
for i in range(100): a[i] = i
f = plt.figure()
ax = f.add_subplot(111)
res = ax.imshow(log_transform(a))
# the colorbar drawn shows [0-1], but I want to see [0-99]
cb = f.colorbar(res)
I've tried using cb.set_array, but that didn't appear to do anything, and cb.set_clim, but that rescales the colors completely.
Thanks in advance for any help :)
Hello,
I have three panes with the InfoPane center option.
I want to know how to set their size.
Using this code:
import wx
import wx.aui
class MyFrame(wx.Frame):
def __init__(self, parent, id=-1, title='wx.aui Test',
pos=wx.DefaultPosition, size=(800, 600),
style=wx.DEFAULT_FRAME_STYLE):
wx.Frame.__init__(self, parent, id, title, pos, size, style)
self._mgr = wx.aui.AuiManager(self)
# create several text controls
text1 = wx.TextCtrl(self, -1, 'Pane 1 - sample text',
wx.DefaultPosition, wx.Size(200,150),
wx.NO_BORDER | wx.TE_MULTILINE)
text2 = wx.TextCtrl(self, -1, 'Pane 2 - sample text',
wx.DefaultPosition, wx.Size(200,150),
wx.NO_BORDER | wx.TE_MULTILINE)
text3 = wx.TextCtrl(self, -1, 'Main content window',
wx.DefaultPosition, wx.Size(200,150),
wx.NO_BORDER | wx.TE_MULTILINE)
# add the panes to the manager
self._mgr.AddPane(text1, wx.CENTER)
self._mgr.AddPane(text2, wx.CENTER)
self._mgr.AddPane(text3, wx.CENTER)
# tell the manager to 'commit' all the changes just made
self._mgr.Update()
self.Bind(wx.EVT_CLOSE, self.OnClose)
def OnClose(self, event):
# deinitialize the frame manager
self._mgr.UnInit()
# delete the frame
self.Destroy()
app = wx.App()
frame = MyFrame(None)
frame.Show()
app.MainLoop()
I want to know what is called when we change the size of the panes.
If you tell me that, I can do the rest by myself :)
Given the output of inspect.stack(), is it possible to get the function objects from anywhere from the stack frame and call these? If so, how?
(I already know how to get the names of the functions.)
Here is what I'm getting at: Let's say I'm a function and I'm trying to determine if my caller is a generator or a regular function? I need to call inspect.isgeneratorfunction() on the function object. And how do you figure out who called you? inspect.stack(), right? So if I can somehow put those together, I'll have the answer to my question. Perhaps there is an easier way to do this?
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.
lib.py
from django.core.urlresolvers import reverse
def render_reverse(f, kwargs):
"""
kwargs is a dictionary, usually of the form {'args': [cbid]}
"""
return reverse(f, **kwargs)
tests.py
from lib import render_reverse, print_ls
class LibTest(unittest.TestCase):
def test_render_reverse_is_correct(self):
#with patch('webclient.apps.codebundles.lib.reverse') as mock_reverse:
with patch('django.core.urlresolvers.reverse') as mock_reverse:
from lib import render_reverse
mock_f = MagicMock(name='f', return_value='dummy_views')
mock_kwargs = MagicMock(name='kwargs',return_value={'args':['123']})
mock_reverse.return_value = '/natrium/cb/details/123'
response = render_reverse(mock_f(), mock_kwargs())
self.assertTrue('/natrium/cb/details/' in response)
But instead, I get
File "/var/lib/graphyte-webclient/graphyte-webenv/lib/python2.6/site-packages/django/core/urlresolvers.py", line 296, in reverse
"arguments '%s' not found." % (lookup_view_s, args, kwargs))
NoReverseMatch: Reverse for 'dummy_readfile' with arguments '('123',)' and keyword arguments '{}' not found.
Why is it calling reverse instead of my mock_reverse (it is looking up my urls.py!!)
The author of Mock library Michael Foord did a video cast here (around 9:17), and in the example he passed the mock object request to the view function index. Furthermore, he patched POll and assigned an expected return value.
Isn't that what I am doing here? I patched reverse?
Thanks.
I have a 100x200 2D array expressed as a numpy array consisting of black (0) and white (255) cells. It is a bitmap file. I then have 2D shapes (it's easiest to think of them as letters) that are also 2D black and white cells.
I know I can naively iterate through the matrix but this is going to be a 'hot' portion of my code so speed is an concern. Is there a fast way to perform this in numpy/scipy?
I looked briefly at Scipy's correlate function. I am not interested in 'fuzzy matches', only exact matches. I also looked at some academic papers but they are above my head.
Hi all -
I'm creating an arbitrary number of instances (using for loops and ranges). At some event in the future, I need to change an attribute for only one of the instances. What's the best way to do this?
Right now, I'm doing the following:
1) Manage the instances in a list.
2) Iterate through the list to find a key value.
3) Once I find the right object within the list (i.e. key value = value I'm looking for), change whatever attribute I need to change.
for Instance within ListofInstances:
if Instance.KeyValue == SearchValue:
Instance.AttributeToChange = 10
This feels really inefficient: I'm basically iterating over the entire list of instances, even through I only need to change an attribute in one of them.
Should I be storing the Instance references in a structure more suitable for random access (e.g. dictionary with KeyValue as the dictionary key?) Is a dictionary any more efficient in this case? Should I be using something else?
Thanks,
Mike
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!
Hi everyone,
I've updated SQLAlchemy to 0.6 but it broke everything. I've noticed it returns tuple not a dictionary anymore. Here's a sample query:
query = session.query(User.id, User.username, User.email).filter(and_(User.id == id, User.username == username)).limit(1)
result = session.execute(query).fetchone()
This piece of code used to return a dictionary in 0.5.
My question is how can I return a dictionary?
Why I can't redefine the __and__ operator?
class Cut(object):
def __init__(self, cut):
self.cut = cut
def __and__(self, other):
return Cut("(" + self.cut + ") && (" + other.cut + ")")
a = Cut("a>0")
b = cut("b>0")
c = a and b
print c.cut()
I want (a>0) && (b>0), but I got b, that the usual behaviour of and
Is it possible to customize a django application to have accept localized date format (e.g dd/mm/yy) in a DateField on an admin form ?
I have a model class :
class MyModel(models.Model):
date = models.DateField("Date")
And associated admin class
class MyModelAdmin(admin.ModelAdmin):
pass
On django administration interface, I would like to be able to input a date in following format : dd/mm/yyyy. However, the date field in the admin form expects yyyy-mm-dd.
How can I customize things ? Nota bene : I have already specified my custom language code (fr-FR) in settings.py, but it seems to have no effect on this date input matter.
Thanks in advance for your answer
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.
Proxy configuration of a machine can be easily fetched using
def check_proxy():
import urllib2
http_proxy = urllib2.getproxies().get('http')
I need to write a test for the above written function. In order to do that I need to:-
Set the system-wide proxy to an
invalid URL during the test(sounds
like a bad idea).
Supply an invalid
URL to http_proxy.
How can I achieve either of the above?
"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.
newthing = Link(user=request.user,last_updated=datetime.datetime.now())
However, this uses datetime , not the MYSQL "now()".
How can I use mysql's now()?
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?
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.
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)
What's the best approach of creating a RESTful web api in CherryPy? I've been looking around for a few days now and nothing seems great. For Django it seems that are lots of tools to do this, but not for CherryPy or I am not aware of them