content stringlengths 85 101k | title stringlengths 0 150 | question stringlengths 15 48k | answers list | answers_scores list | non_answers list | non_answers_scores list | tags list | name stringlengths 35 137 |
|---|---|---|---|---|---|---|---|---|
Q:
Setting up Python on Apache/Windows; IDE question
I am finally learning Python after putting it off for a long time.
I am setting it up on Apache (XAMPP), which version of mod_python should I choose?
If I get mod_python-3.3.1.win32-py2.5-Apache2.2.exe, does that mean I have to download Python 2.5 from here?
EDIT: I'll use this primarily for web development. Which IDE should I use? I like Netbeans for Java and PHP, but they don't have Python.
A:
Do not use mod_python - it is now officially dead. You should use mod_wsgi instead. There are instructions for installing it on Windows.
A:
For an IDE that also plays well with web development, download Aptana Studio
which is built upon eclipse and then get the pydev extension for it.
And you will need the python 2.5 version as you suspect.
| Setting up Python on Apache/Windows; IDE question | I am finally learning Python after putting it off for a long time.
I am setting it up on Apache (XAMPP), which version of mod_python should I choose?
If I get mod_python-3.3.1.win32-py2.5-Apache2.2.exe, does that mean I have to download Python 2.5 from here?
EDIT: I'll use this primarily for web development. Which IDE should I use? I like Netbeans for Java and PHP, but they don't have Python.
| [
"Do not use mod_python - it is now officially dead. You should use mod_wsgi instead. There are instructions for installing it on Windows.\n",
"For an IDE that also plays well with web development, download Aptana Studio\nwhich is built upon eclipse and then get the pydev extension for it.\nAnd you will need the p... | [
4,
1
] | [] | [] | [
"python",
"xampp"
] | stackoverflow_0003287347_python_xampp.txt |
Q:
python using post method for upload file
I have a problem with importing file to calendar over wcap protocol. In documentation http://docs.sun.com/source/816-6416-10/pr10WCAP.html#26125 is said that i should use POST method. I have trayed but with no positiv result. I have no idea hov to forced it to work with python
A:
The wcap reference you provide contains example POST data.
Using the urllib2.urlopen() function with POST data is straightforward.
urllib2.urlopen(url[, data][, timeout])
Open the URL url, which can be either a string or a Request object.
data may be a string specifying additional data to send to the server, or None if no such data is needed. Currently HTTP requests are the only ones that use data; the HTTP request will be a POST instead of a GET when the data parameter is provided. data should be a buffer in the standard application/x-www-form-urlencoded format. The urllib.urlencode() function takes a mapping or sequence of 2-tuples and returns a string in this format.
| python using post method for upload file | I have a problem with importing file to calendar over wcap protocol. In documentation http://docs.sun.com/source/816-6416-10/pr10WCAP.html#26125 is said that i should use POST method. I have trayed but with no positiv result. I have no idea hov to forced it to work with python
| [
"The wcap reference you provide contains example POST data.\nUsing the urllib2.urlopen() function with POST data is straightforward.\n\nurllib2.urlopen(url[, data][, timeout])\nOpen the URL url, which can be either a string or a Request object.\ndata may be a string specifying additional data to send to the server,... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0003288745_python.txt |
Q:
the django template and combine {{ }}
I start with django, and I have a little problem.
Well, I have a tuple (top) and I wanted to display an element of it according to another template value (date, which is a datetime type).
So, I did that :
{{top.date.day}}
Well it doesn't work, so I tried it :
{{ top.{{date.day}} }}
And it didn't work neither.
So what is the good way to do ?
Thanks.
A:
Use the {% with %} tag to assign the intermediate value to another context variable first.
| the django template and combine {{ }} | I start with django, and I have a little problem.
Well, I have a tuple (top) and I wanted to display an element of it according to another template value (date, which is a datetime type).
So, I did that :
{{top.date.day}}
Well it doesn't work, so I tried it :
{{ top.{{date.day}} }}
And it didn't work neither.
So what is the good way to do ?
Thanks.
| [
"Use the {% with %} tag to assign the intermediate value to another context variable first.\n"
] | [
0
] | [] | [] | [
"django",
"python",
"templates"
] | stackoverflow_0003288948_django_python_templates.txt |
Q:
How do I bind an event to the left mouse button being held down?
I need a command to be executed as long as the left mouse button is being held down.
A:
If you want "something to happen" without any intervening events (ie: without the user moving the mouse or pressing any other buttons) your only choice is to poll. Set a flag when the button is pressed, unset it when released. While polling, check the flag and run your code if its set.
Here's something to illustrate the point:
import Tkinter
class App:
def __init__(self, root):
self.root = root
self.mouse_pressed = False
f = Tkinter.Frame(width=100, height=100, background="bisque")
f.pack(padx=100, pady=100)
f.bind("<ButtonPress-1>", self.OnMouseDown)
f.bind("<ButtonRelease-1>", self.OnMouseUp)
def do_work(self):
x = self.root.winfo_pointerx()
y = self.root.winfo_pointery()
print "button is being pressed... %s/%s" % (x, y)
def OnMouseDown(self, event):
self.mouse_pressed = True
self.poll()
def OnMouseUp(self, event):
self.root.after_cancel(self.after_id)
def poll(self):
if self.mouse_pressed:
self.do_work()
self.after_id = self.root.after(250, self.poll)
root=Tkinter.Tk()
app = App(root)
root.mainloop()
However, polling is generally not necessary in a GUI app. You probably only care about what happens while the mouse is pressed and is moving. In that case, instead of the poll function simply bind do_work to a <B1-Motion> event.
A:
Look at table 7-1 of the docs. There are events that specify motion while the button is pressed, <B1-Motion>, <B2-Motion> etc.
If you're not talking about a press-and-move event, then you can start doing your activity on <Button-1> and stop doing it when you receive <B1-Release>.
A:
Use the mouse move/motion events and check the modifier flags. The mouse buttons will show up there.
| How do I bind an event to the left mouse button being held down? | I need a command to be executed as long as the left mouse button is being held down.
| [
"If you want \"something to happen\" without any intervening events (ie: without the user moving the mouse or pressing any other buttons) your only choice is to poll. Set a flag when the button is pressed, unset it when released. While polling, check the flag and run your code if its set.\nHere's something to illus... | [
9,
6,
2
] | [] | [] | [
"event_binding",
"python",
"tkinter"
] | stackoverflow_0003288001_event_binding_python_tkinter.txt |
Q:
Formatting SQL query output in Python/SQLite 3
I use a simple SQL query in Python to grab records from a SQLite 3 database:
cursor.execute ("SELECT due, task FROM tasks WHERE due <> '' ORDER BY due ASC")
rows = cursor.fetchall()
for row in rows:
print '\n%s %s' % (row[0], row[1])
The due field in the database is set to DATE type, so the query returns the data in this field formatted as 2010-07-20 00:00:00.00 How can I remove the 00:00:00.00, so the result contains only the date? Thanks!
A:
I think row[0] is a datetime object. So the following should work:
print '\n%s %s' % (row[0].strftime('%Y-%m-%d'), row[1])
| Formatting SQL query output in Python/SQLite 3 | I use a simple SQL query in Python to grab records from a SQLite 3 database:
cursor.execute ("SELECT due, task FROM tasks WHERE due <> '' ORDER BY due ASC")
rows = cursor.fetchall()
for row in rows:
print '\n%s %s' % (row[0], row[1])
The due field in the database is set to DATE type, so the query returns the data in this field formatted as 2010-07-20 00:00:00.00 How can I remove the 00:00:00.00, so the result contains only the date? Thanks!
| [
"I think row[0] is a datetime object. So the following should work:\nprint '\\n%s %s' % (row[0].strftime('%Y-%m-%d'), row[1])\n\n"
] | [
3
] | [] | [] | [
"python",
"sql",
"sqlite"
] | stackoverflow_0003289317_python_sql_sqlite.txt |
Q:
How do I get mouse position relative to the parent widget in tkinter?
I need to get the mouse position relative to the tkinter window.
A:
Generally speaking you should never need to "get" this information because it is given to you as part of the event object that is passed in. You probably only need this information when responding to an event, and the event gives you this information.
Put more succinctly, to get the information you simply have to retrieve it from the event object.
Here's an example:
import Tkinter
class App:
def __init__(self, root):
f = Tkinter.Frame(width=100, height=100, background="bisque")
f.pack(padx=100, pady=100)
f.bind("<1>", self.OnMouseDown)
def OnMouseDown(self, event):
print "frame coordinates: %s/%s" % (event.x, event.y)
print "root coordinates: %s/%s" % (event.x_root, event.y_root)
root=Tkinter.Tk()
app = App(root)
root.mainloop()
A:
Get the screen coordinates of the mouse move event (x/y_root) and subtract the screen coordinates of the window (window.winfo_rootx()/y()).
| How do I get mouse position relative to the parent widget in tkinter? | I need to get the mouse position relative to the tkinter window.
| [
"Generally speaking you should never need to \"get\" this information because it is given to you as part of the event object that is passed in. You probably only need this information when responding to an event, and the event gives you this information. \nPut more succinctly, to get the information you simply have... | [
6,
3
] | [] | [] | [
"mouse_position",
"python",
"tkinter"
] | stackoverflow_0003288047_mouse_position_python_tkinter.txt |
Q:
functions in python query
def directionToVector(direction, speed = 1.0):
dx, dy = Actions._directions[direction]
return (dx * speed, dy * speed)
def getCostOfActions(self, actions):
"""
Returns the cost of a particular sequence of actions. If those actions
include an illegal move, return 999999. This is implemented for you.
"""
if actions == None: return 999999
x,y= self.startingPosition
for action in actions:
dx, dy = Actions.directionToVector(action)
x, y = int(x + dx), int(y + dy)
if self.walls[x][y]: return 999999
return len(actions)
def getCostOfActions(self, actions):
"""
actions: A list of actions to take
This method returns the total cost of a particular sequence of actions.
The sequence must be composed of legal moves
"""
File "in getCostOfActions
dx, dy = Actions.directionToVector(action)
File in directionToVector
dx, dy = Actions._directions[direction]
KeyError: 'N'
I am using the last function but the arguments are not accepted by the function. What should be the arguments here? What should their types be?
A:
The first argument, of course is self, since this is an instance method. This is passed implicitly.
According to the docstring, the argument the callers should provide is 'actions: A list of actions to take'.
E.g:
instance.getCostOfActions([North, East, South, West])
N.B: You have two lines thus:
def getCostOfActions(self, actions):
def getCostOfActions(self, actions):
The first is replaced by the second.
| functions in python query | def directionToVector(direction, speed = 1.0):
dx, dy = Actions._directions[direction]
return (dx * speed, dy * speed)
def getCostOfActions(self, actions):
"""
Returns the cost of a particular sequence of actions. If those actions
include an illegal move, return 999999. This is implemented for you.
"""
if actions == None: return 999999
x,y= self.startingPosition
for action in actions:
dx, dy = Actions.directionToVector(action)
x, y = int(x + dx), int(y + dy)
if self.walls[x][y]: return 999999
return len(actions)
def getCostOfActions(self, actions):
"""
actions: A list of actions to take
This method returns the total cost of a particular sequence of actions.
The sequence must be composed of legal moves
"""
File "in getCostOfActions
dx, dy = Actions.directionToVector(action)
File in directionToVector
dx, dy = Actions._directions[direction]
KeyError: 'N'
I am using the last function but the arguments are not accepted by the function. What should be the arguments here? What should their types be?
| [
"The first argument, of course is self, since this is an instance method. This is passed implicitly.\nAccording to the docstring, the argument the callers should provide is 'actions: A list of actions to take'. \nE.g:\ninstance.getCostOfActions([North, East, South, West])\n\nN.B: You have two lines thus:\ndef getCo... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0003289458_python.txt |
Q:
Improving performance of cgi
I have 5 python cgi pages. I can navigate from one page to another. All pages get their data from the same database table just that they use different queries.
The problem is that the application as a whole is slow. Though they connect to the same database, each page creates a new handle every time I visit it and handles are not shared by the pages.
I want to improve performance.
Can I do that by setting up sessions for the user?
Suggestions/Advices are welcome.
Thanks
A:
cgi requires a new interpreter to start up for each request, and then all the resources such as db connections to be acquired and released.
fastcgi or wsgi improve performance by allowing you to keep running the same process between requests
A:
Django and Pylons are both frameworks that solve this problem quite nicely, namely by abstracting the DB-frontend integration. They are worth considering.
| Improving performance of cgi | I have 5 python cgi pages. I can navigate from one page to another. All pages get their data from the same database table just that they use different queries.
The problem is that the application as a whole is slow. Though they connect to the same database, each page creates a new handle every time I visit it and handles are not shared by the pages.
I want to improve performance.
Can I do that by setting up sessions for the user?
Suggestions/Advices are welcome.
Thanks
| [
"cgi requires a new interpreter to start up for each request, and then all the resources such as db connections to be acquired and released.\nfastcgi or wsgi improve performance by allowing you to keep running the same process between requests\n",
"Django and Pylons are both frameworks that solve this problem qui... | [
2,
0
] | [] | [] | [
"cgi",
"python"
] | stackoverflow_0003289330_cgi_python.txt |
Q:
Web-ifing a python command line script?
This is my first questions here, so I hope it will be done correctly ;)
I've been assigned the task to give a web interface to some "home made" python script.
This script is used to check some web sites/applications availability, via curl commands. A very important aspect of this script is that it gives its results in real-time, writing line by line to the standard output.
By giving a web interface to this script, the main goal is that the script can be easily used from anywhere, for example via a smartphone. So the web interface must be quite basic, and work "plugin-free".
My problem is that most solutions I thought or found on the web (ajax, django, even a simple post) seem to be needing a full generation of the page before sending it to the browser, losing this important "real-time" aspect.
Any idea on how to do this properly ?
Thanks in advance.
A:
A sketch for a solution:
Create an HTML file which contains the layout for your web page, with a dedicated DIV for the output of the script:
<html>
<body>
<div id="scriptoutput"></div>
<script type="text/javascript" src="localhost:8000/runscript"/>
</body>
</html>
This HTML file can be served using any server you wish.
Now, write a simple http server which runs the script and converts each line to a javascript command (example in python):
import os
f = os.popen('ping 127.0.0.1')
for i in range(30):
ln = f.readline()
print "document.getElementById('scriptoutput').innerHTML += '<pre>%s</pre><br/>';" % ln
You can use any CGI/WSGI server for the task, or if performance is not crucial, even use Python's own BaseHTTPServer class.
This would do the trick, as most browsers parse and execute Javascript scripts as they are received (and not only when the request is completed) - note that no polling or server-side storage is needed!
A:
Your task sounds interesting. :-) A scenario that just came into mind: You continuosly scrape the resources with your home-brew scripts, and push the results into your persistent database and a caching system -- like Redis -- simultanously. Your caching system/layer serves as primary data source when serving client requests. Redis f.e. is a high-performant key-value-store that is capable to handle 100k connections per second. Though only the n latest (say f.e. 50k entries) matter the caching system will only hold these entries and let you solely focus on developing the server-side API (handling connections, processing requests, reading from Redis) and the frontend. The communication between frontend and backend-API could be driven by WebSocket connections. A pretty new part of the HTML5 spec. Though, however, already supported by many browser versions released these days. Alternatively you could fallback on some asynchronous Flash Socket-stuff. Websockets basically allow for persistent connections between a client and a server; you can register event listener that are called for every incoming data/-packet -- no endless polling or other stuff.
A:
I hope that I understand your need properly.
The idea behind Ajax is to update the content of the page without reloading the whole page. I think it should correspond to your need. You may have to modify your commands if you want to webify them. You may need to get their print logs "on the fly".
Here are some ideas:
Write a very simple page with the possibility to execute commands (menu, form ...)
When the user ask for a command execution, send an ajax query to the server which executes the command.
Your commands need to be modified in order to redirect the sys.stdout to something that stores the print logs into a database. You can do it by assigning to sys.stdout an object with a write function.
class MyDbLogger:
def __init__(self, ...):
"""Some initialization"""
...
def write(self, s):
"""write into the database"""
...
dbout = MyDbLogger(...)
sys.stdout = dbout
The client will poll the server regurlarly to get the content into the database and then write it into the page.
Comet is certainly the technology to investigate in order to have a real-time behavior. That'll avoid the client to poll the server on a regular basis. That can be an improvement to #4 but may be a little more difficult to implement.
I hope it helps
| Web-ifing a python command line script? | This is my first questions here, so I hope it will be done correctly ;)
I've been assigned the task to give a web interface to some "home made" python script.
This script is used to check some web sites/applications availability, via curl commands. A very important aspect of this script is that it gives its results in real-time, writing line by line to the standard output.
By giving a web interface to this script, the main goal is that the script can be easily used from anywhere, for example via a smartphone. So the web interface must be quite basic, and work "plugin-free".
My problem is that most solutions I thought or found on the web (ajax, django, even a simple post) seem to be needing a full generation of the page before sending it to the browser, losing this important "real-time" aspect.
Any idea on how to do this properly ?
Thanks in advance.
| [
"A sketch for a solution:\nCreate an HTML file which contains the layout for your web page, with a dedicated DIV for the output of the script:\n<html>\n<body>\n<div id=\"scriptoutput\"></div>\n<script type=\"text/javascript\" src=\"localhost:8000/runscript\"/>\n</body>\n</html>\n\nThis HTML file can be served using... | [
4,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0003289584_python.txt |
Q:
lists in python, with references
How do I copy the contents of a list and not just a reference to the list in Python?
A:
Look at the copy module, and notice the difference between shallow and deep copies:
The difference between shallow and deep copying is only relevant for compound objects (objects that contain other objects, like lists or class instances):
A shallow copy constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in the original.
A deep copy constructs a new compound object and then, recursively, inserts copies into it of the objects found in the original.
A:
Use a slice notation.
newlist = oldlist
This will assign a second name to the same list
newlist = oldlist[:]
This will duplicate each element of oldlist into a complete new list called newlist
A:
in addition to the slice notation mentioned by Lizard,
you can use list()
newlist = list(oldlist)
or copy
import copy
newlist = copy.copy(oldlist)
A:
The answes by Lizard and gnibbler are correct, though I'd like to add that all these ways give a shallow copy, i.e.:
l = [[]]
l2 = l[:] // or list(l) or copy.copy(l)
l2[0].append(1)
assert l[0] == [1]
For a deep copy, you need copy.deepcopy().
| lists in python, with references | How do I copy the contents of a list and not just a reference to the list in Python?
| [
"Look at the copy module, and notice the difference between shallow and deep copies:\n\nThe difference between shallow and deep copying is only relevant for compound objects (objects that contain other objects, like lists or class instances):\n\nA shallow copy constructs a new compound object and then (to the exten... | [
7,
5,
5,
2
] | [] | [] | [
"copy",
"list",
"python",
"reference"
] | stackoverflow_0003289822_copy_list_python_reference.txt |
Q:
Python decorator class to transform methods to dictionary items
I wonder if there is a reasonable easy way to allow for this code (with minor modifications) to work.
class Info(object):
@attr("Version")
def version(self):
return 3
info = Info()
assert info.version == 3
assert info["Version"] == 3
Ideally, the code would do some caching/memoising as well, e.g. employ lazy attributes, but I hope to figure that out myself.
Additional information:
The reason why I want provide two interfaces for accessing the same information is as follows.
I’d like to have a dict-like class which uses lazy keys. E.g. info["Version"] should call and cache another method and transparently return the result.
I don’t think that works with dicts alone, therefore I need to create new methods.
Methods alone won’t do either, because there are some attributes which are easier to define with pure dictionary syntax.
It probably is not the best idea anyway…
A:
If the attribute name (version) is always a lowercase version of the dict key ("Version"), then you could set it up this way:
class Info(object):
@property
def version(self):
return 3
def __getitem__(self,key):
if hasattr(self,key.lower()):
return getattr(self,key.lower())
If you wish the dict key to be arbitrary, then its still possible, though more complicated:
def attrcls(cls):
cls._attrdict={}
for methodname in cls.__dict__:
method=cls.__dict__[methodname]
if hasattr(method,'_attr'):
cls._attrdict[getattr(method,'_attr')]=methodname
return cls
def attr(key):
def wrapper(func):
class Property(object):
def __get__(self,inst,instcls):
return func(inst)
def __init__(self):
self._attr=key
return Property()
return wrapper
@attrcls
class Info(object):
@attr("Version")
def version(self):
return 3
def __getitem__(self,key):
if key in self._attrdict:
return getattr(self,self._attrdict[key])
I guess the larger question is, Is it a good interface? Why provide two syntaxes (with two different names) for the same thing?
A:
Not trivially. You could use a metaclass to detect decorated methods and wrap __*attr__() and __*item__() appropriately.
| Python decorator class to transform methods to dictionary items | I wonder if there is a reasonable easy way to allow for this code (with minor modifications) to work.
class Info(object):
@attr("Version")
def version(self):
return 3
info = Info()
assert info.version == 3
assert info["Version"] == 3
Ideally, the code would do some caching/memoising as well, e.g. employ lazy attributes, but I hope to figure that out myself.
Additional information:
The reason why I want provide two interfaces for accessing the same information is as follows.
I’d like to have a dict-like class which uses lazy keys. E.g. info["Version"] should call and cache another method and transparently return the result.
I don’t think that works with dicts alone, therefore I need to create new methods.
Methods alone won’t do either, because there are some attributes which are easier to define with pure dictionary syntax.
It probably is not the best idea anyway…
| [
"If the attribute name (version) is always a lowercase version of the dict key (\"Version\"), then you could set it up this way:\nclass Info(object):\n @property\n def version(self):\n return 3\n def __getitem__(self,key):\n if hasattr(self,key.lower()):\n return getattr(self,key.l... | [
1,
0
] | [] | [] | [
"decorator",
"properties",
"python"
] | stackoverflow_0003289064_decorator_properties_python.txt |
Q:
Help with a custom GUI in wxpython
I'm new to wxPython, so bear with me. I'm creating a custom GUI set up and need to get two attributes. Firstly I want to create an inner boarder of a different color (The single dark boarder looks too plain). Secondly, I need to bind the dragging attribute so that only the label will allow dragging as opposed to the whole frame.
Also does anyone have a good tutorial on wxPython geometry handling?
import wx
def GetRoundBitmap( w, h, r ):
maskColor = wx.Color(0,0,0)
shownColor = wx.Color(5,5,5)
b = wx.EmptyBitmap(w,h)
dc = wx.MemoryDC(b)
dc.SetBrush(wx.Brush(maskColor))
dc.DrawRectangle(0,0,w,h)
dc.SetBrush(wx.Brush(shownColor))
dc.SetPen(wx.Pen(shownColor))
dc.DrawRoundedRectangle(0,0,w,h,r)
dc.SelectObject(wx.NullBitmap)
b.SetMaskColour(maskColor)
return b
def GetRoundShape( w, h, r ):
return wx.RegionFromBitmap( GetRoundBitmap(w,h,r) )
class FancyFrame(wx.Frame):
def __init__(self):
style = ( wx.CLIP_CHILDREN | wx.STAY_ON_TOP | wx.FRAME_NO_TASKBAR |
wx.NO_BORDER | wx.FRAME_SHAPED )
wx.Frame.__init__(self, None, title='Fancy', style = style)
self.SetSize( (250, 40) )
self.SetPosition( (500,500) )
self.SetTransparent( 160 )
self.Bind(wx.EVT_KEY_UP, self.On_Esc)
self.Bind(wx.EVT_MOTION, self.OnMouse)
self.Bind(wx.EVT_PAINT, self.OnPaint)
if wx.Platform == '__WXGTK__':
self.Bind(wx.EVT_WINDOW_CREATE, self.SetRoundShape)
else:
self.SetRoundShape()
self.Show(True)
geo = wx.GridBagSizer()
self.label = wx.StaticText(self,-1,label=u'Hello !')
geo.Add(self.label, (0,2))
def SetRoundShape(self, event=None):
w, h = self.GetSizeTuple()
self.SetShape(GetRoundShape( w,h, 10 ) )
def OnPaint(self, event):
dc = wx.PaintDC(self)
dc = wx.GCDC(dc)
w, h = self.GetSizeTuple()
r = 10
dc.SetPen( wx.Pen("#000000", width = 4 ) )
dc.SetBrush( wx.Brush("#9e9e9e") )
dc.DrawRoundedRectangle( 0,0,w,h,r )
def On_Esc(self, event):
"""quit if user press Esc"""
if event.GetKeyCode() == 27 : #27 is Esc
self.Close(force=True)
else:
event.Skip()
def OnMouse(self, event):
"""implement dragging"""
if not event.Dragging():
self._dragPos = None
return
self.CaptureMouse()
if not self._dragPos:
self._dragPos = event.GetPosition()
else:
pos = event.GetPosition()
displacement = self._dragPos - pos
self.SetPosition( self.GetPosition() - displacement )
app = wx.App()
f = FancyFrame()
app.MainLoop()
A:
I'm not sure what border you want to change. Are you talking about the border of the selected object? As for dragging objects around, I would recommend looking at Whyteboard, a wxPython drawing program. It should how to select and drag objects around quite nicely and work on Windows and Linux. I'm not sure about Mac...
Edit: Forgot to include a link: http://whyteboard.org/
Mike Driscoll
Blog: http://blog.pythonlibrary.org
| Help with a custom GUI in wxpython | I'm new to wxPython, so bear with me. I'm creating a custom GUI set up and need to get two attributes. Firstly I want to create an inner boarder of a different color (The single dark boarder looks too plain). Secondly, I need to bind the dragging attribute so that only the label will allow dragging as opposed to the whole frame.
Also does anyone have a good tutorial on wxPython geometry handling?
import wx
def GetRoundBitmap( w, h, r ):
maskColor = wx.Color(0,0,0)
shownColor = wx.Color(5,5,5)
b = wx.EmptyBitmap(w,h)
dc = wx.MemoryDC(b)
dc.SetBrush(wx.Brush(maskColor))
dc.DrawRectangle(0,0,w,h)
dc.SetBrush(wx.Brush(shownColor))
dc.SetPen(wx.Pen(shownColor))
dc.DrawRoundedRectangle(0,0,w,h,r)
dc.SelectObject(wx.NullBitmap)
b.SetMaskColour(maskColor)
return b
def GetRoundShape( w, h, r ):
return wx.RegionFromBitmap( GetRoundBitmap(w,h,r) )
class FancyFrame(wx.Frame):
def __init__(self):
style = ( wx.CLIP_CHILDREN | wx.STAY_ON_TOP | wx.FRAME_NO_TASKBAR |
wx.NO_BORDER | wx.FRAME_SHAPED )
wx.Frame.__init__(self, None, title='Fancy', style = style)
self.SetSize( (250, 40) )
self.SetPosition( (500,500) )
self.SetTransparent( 160 )
self.Bind(wx.EVT_KEY_UP, self.On_Esc)
self.Bind(wx.EVT_MOTION, self.OnMouse)
self.Bind(wx.EVT_PAINT, self.OnPaint)
if wx.Platform == '__WXGTK__':
self.Bind(wx.EVT_WINDOW_CREATE, self.SetRoundShape)
else:
self.SetRoundShape()
self.Show(True)
geo = wx.GridBagSizer()
self.label = wx.StaticText(self,-1,label=u'Hello !')
geo.Add(self.label, (0,2))
def SetRoundShape(self, event=None):
w, h = self.GetSizeTuple()
self.SetShape(GetRoundShape( w,h, 10 ) )
def OnPaint(self, event):
dc = wx.PaintDC(self)
dc = wx.GCDC(dc)
w, h = self.GetSizeTuple()
r = 10
dc.SetPen( wx.Pen("#000000", width = 4 ) )
dc.SetBrush( wx.Brush("#9e9e9e") )
dc.DrawRoundedRectangle( 0,0,w,h,r )
def On_Esc(self, event):
"""quit if user press Esc"""
if event.GetKeyCode() == 27 : #27 is Esc
self.Close(force=True)
else:
event.Skip()
def OnMouse(self, event):
"""implement dragging"""
if not event.Dragging():
self._dragPos = None
return
self.CaptureMouse()
if not self._dragPos:
self._dragPos = event.GetPosition()
else:
pos = event.GetPosition()
displacement = self._dragPos - pos
self.SetPosition( self.GetPosition() - displacement )
app = wx.App()
f = FancyFrame()
app.MainLoop()
| [
"I'm not sure what border you want to change. Are you talking about the border of the selected object? As for dragging objects around, I would recommend looking at Whyteboard, a wxPython drawing program. It should how to select and drag objects around quite nicely and work on Windows and Linux. I'm not sure about M... | [
0
] | [] | [] | [
"python",
"user_interface",
"wxpython"
] | stackoverflow_0003285296_python_user_interface_wxpython.txt |
Q:
python time problem
I am using the exif.py library. After calling
tags=exif.process_file(...)
i want to retrieve the time the image was captured. so i continue with
t =tags['Image DateTime'] if tags.has_key('Image DateTime') else time.time()
now i want to store t in django's database. For that t must be in the form 2010-07-20 14:37:12 but apparently exif delivers 2010:07:20 14:37:12 however when i go
type(t)
it returns 'instance' as opposed to float which is the result of
type(time.time())
or 'str' which is the type of string. How can I parse the value EXIF gave me to stuff it into the django model?
A:
Use time.strptime() to parse the str() value, than format the time tuple to any desired form.
An example, using the 'Image DateTime' attribute returned by EXIF.
>>> e1['Image DateTime']
(0x0132) ASCII=2007:09:06 06:37:51 @ 176
>>> str(e1['Image DateTime'])
'2007:09:06 06:37:51'
>>>
>>> tag = time.strptime(str(e1['Image DateTime']),"%Y:%m:%d %H:%M:%S")
>>> tag
time.struct_time(tm_year=2007, tm_mon=9, tm_mday=6, tm_hour=6, tm_min=37, tm_sec=51,tm_wday=3, tm_yday=249, tm_isdst=-1)
>>> time.strftime("%Y-%m-%d %H:%M:%S", tag)
'2007-09-06 06:37:51'
>>>
A:
Django works best with datetime objects. Strings can be converted to datetime, but you should not focus on strings. You should focus on creating a proper datetime object.
Choice 1. Figure out what actual class the exif time is. Instead of type(t), do t.__class__ to see what it really is. Also, so dir(t) to see what methods it has. It may have methods which will create a proper float value or time.struct_time value.
Choice 2. Parse the time string with datetime.datetime.strptime to create a proper datetime object. Read this: http://docs.python.org/library/datetime.html#datetime.datetime.strptime
A:
It looks like exif.py returns an instance of IFD_Tag. The values you want may be in t.values. You can also use datetime.strptime() to parse the string you get from the exif data.
A:
Assuming that tags['Image DateTime'], if present, returns a string like "2010:07:20 14:37:12" then you can use:
if tags.has_key('Image DateTime'):
t = tags['Image DateTime'].replace(':', '-' , 2)
else:
t = time.strftime('%Y-%m-%d %H:%M:%S')
replace fixes the time-string from exif:
>>> '2010:07:20 14:37:12'.replace(':', '-', 2)
'2010-07-20 14:37:12'
If you want GMT rather than local time use
time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime())
| python time problem | I am using the exif.py library. After calling
tags=exif.process_file(...)
i want to retrieve the time the image was captured. so i continue with
t =tags['Image DateTime'] if tags.has_key('Image DateTime') else time.time()
now i want to store t in django's database. For that t must be in the form 2010-07-20 14:37:12 but apparently exif delivers 2010:07:20 14:37:12 however when i go
type(t)
it returns 'instance' as opposed to float which is the result of
type(time.time())
or 'str' which is the type of string. How can I parse the value EXIF gave me to stuff it into the django model?
| [
"Use time.strptime() to parse the str() value, than format the time tuple to any desired form.\nAn example, using the 'Image DateTime' attribute returned by EXIF.\n>>> e1['Image DateTime']\n(0x0132) ASCII=2007:09:06 06:37:51 @ 176\n>>> str(e1['Image DateTime'])\n'2007:09:06 06:37:51'\n>>> \n>>> tag = time.strptime(... | [
2,
1,
0,
0
] | [] | [] | [
"django_models",
"exif",
"python",
"time"
] | stackoverflow_0003289969_django_models_exif_python_time.txt |
Q:
Python Beautiful soup tag for table td
Python Beautiful soup tag for table td
<td class="result" valign="top" colspan="3">
At the moment, the following does not work:
for header in soup('table', 'td .result'):
Getting error:
HTMLParser.HTMLParseError: malformed start tag
A:
As noted on their website, HTMLParser is quite fragile. You should use SGMLParser instead, as it's more robust against malformed HTML.
Unfortunately, Python 3.0 has removed SGMLParser from the standard library. See the links above for suggested workarounds, such as using html5lib.
| Python Beautiful soup tag for table td | Python Beautiful soup tag for table td
<td class="result" valign="top" colspan="3">
At the moment, the following does not work:
for header in soup('table', 'td .result'):
Getting error:
HTMLParser.HTMLParseError: malformed start tag
| [
"As noted on their website, HTMLParser is quite fragile. You should use SGMLParser instead, as it's more robust against malformed HTML. \nUnfortunately, Python 3.0 has removed SGMLParser from the standard library. See the links above for suggested workarounds, such as using html5lib.\n"
] | [
1
] | [] | [] | [
"beautifulsoup",
"python"
] | stackoverflow_0003290062_beautifulsoup_python.txt |
Q:
reddit get_comments action, can someone clarify what is going on here?
I'm trying to understand reddit's source, and I am looking at the get_comments action method of front.py
This is the action that displays a story:
http://code.reddit.com/browser/r2/r2/controllers/front.py#L139
Specifically, what is the top part of the method doing where there is a @Validate marker?
And on the bottom near the return, it is sending objects to the view page.
Which viewpage is being called here?
211 res = LinkInfoPage(link = article, comment = comment,
212 content = displayPane,
213 subtitle = _("comments"),
214 nav_menus = [CommentSortMenu(default = sort),
215 NumCommentsMenu(article.num_comments,
216 default=num_comments)],
217 infotext = infotext).render()
218 return res
A:
Specifically, what is the top part of the method doing where there is a @Validate marker?
@validate is validation decorator, used to validate and process parameters from request.
You can see its sources at http code.reddit.com/browser/r2/r2/controllers/validator/validator.py#L129
And on the bottom near the return, it is sending objects to the view page.
Which viewpage is being called here?
It does not use 'view page', it uses widgets there. LinkInfoPage which contains PaneStack (http code.reddit.com/browser/r2/r2/lib/pages/pages.py#L1317)
So res = LinkInfoPage(...).render() is already generated html, in Pylons response form. It recursively calls .render() on underlying widgets.
P.S. you need to add :// to links, since it does not let to post more than one link.
| reddit get_comments action, can someone clarify what is going on here? | I'm trying to understand reddit's source, and I am looking at the get_comments action method of front.py
This is the action that displays a story:
http://code.reddit.com/browser/r2/r2/controllers/front.py#L139
Specifically, what is the top part of the method doing where there is a @Validate marker?
And on the bottom near the return, it is sending objects to the view page.
Which viewpage is being called here?
211 res = LinkInfoPage(link = article, comment = comment,
212 content = displayPane,
213 subtitle = _("comments"),
214 nav_menus = [CommentSortMenu(default = sort),
215 NumCommentsMenu(article.num_comments,
216 default=num_comments)],
217 infotext = infotext).render()
218 return res
| [
"\nSpecifically, what is the top part of the method doing where there is a @Validate marker?\n\n@validate is validation decorator, used to validate and process parameters from request.\nYou can see its sources at http code.reddit.com/browser/r2/r2/controllers/validator/validator.py#L129\n\nAnd on the bottom near th... | [
2
] | [] | [] | [
"pylons",
"python",
"reddit"
] | stackoverflow_0003283157_pylons_python_reddit.txt |
Q:
Good apps I could use to store a page locally?
I really need to find a reliable way in order to store a web page locally, with all it's dependencies e.g. html, css stylesheets, javascript, etc...
A python library would be awesome, a CLI would be great too. Also would this type of app/library have a standardized name?
Any suggestions guys? =)
A:
I have used HTTrack in the past to good effect (available for Windows, Linux, & OS X). It has a C API and there is also a third-party Python wrapper available.
Also see this question: Any Python Script to Save Websites Like Firefox?
A:
you can try Scrapy which is fairly simple and efficient:
it is a bit more than a python library...
| Good apps I could use to store a page locally? | I really need to find a reliable way in order to store a web page locally, with all it's dependencies e.g. html, css stylesheets, javascript, etc...
A python library would be awesome, a CLI would be great too. Also would this type of app/library have a standardized name?
Any suggestions guys? =)
| [
"I have used HTTrack in the past to good effect (available for Windows, Linux, & OS X). It has a C API and there is also a third-party Python wrapper available.\nAlso see this question: Any Python Script to Save Websites Like Firefox?\n",
"you can try Scrapy which is fairly simple and efficient:\nit is a bit more... | [
1,
0
] | [] | [] | [
"caching",
"html",
"linux",
"python",
"screen_scraping"
] | stackoverflow_0003289816_caching_html_linux_python_screen_scraping.txt |
Q:
Method logging in Python
I'd like something equivalent to
calling method: $METHOD_NAME
args: $ARGS
output: $OUTPUT
to be automatically logged to a file (via the logging module, possibly) for every (user-defined) method call. The best solution I can come up with is to write a decorator that will do this, and then add it to every function. Is there a better way?
Thanks
A:
You could look at the trace module in the standard library, which
allows you to trace program execution, generate annotated statement coverage listings, print caller/callee relationships and list functions executed during a program run. It can be used in another program or from the command line.
You can also log to disk:
import sys
import trace
# create a Trace object, telling it what to ignore, and whether to
# do tracing or line-counting or both.
tracer = trace.Trace(
ignoredirs=[sys.prefix, sys.exec_prefix],
trace=0,
count=1)
# run the new command using the given tracer
tracer.run('main()')
# make a report, placing output in /tmp
r = tracer.results()
r.write_results(show_missing=True, coverdir="/tmp")
A:
One approach that might simplify things a bit would be to use a metaclass to automatically apply your decorator for you. It'd cut down on the typing at the expense of requiring you to delve into the arcane and mysterious world of metaclass programming.
A:
It depends how exactly are you going to use it.
Most generic approach would be to follow stdlib's 'profile' module path and therefore have control over each call, but its somewhat slow.
If you know which modules you need to track before giving them control, I'd go with iterating over all their members and wrapping with tracking decorator. This way tracked code stays clean and it doesn't take too much coding to implement.
A:
A decorator would be a simple approach for a smaller project, however with decorators you have to be careful about passing arguments to make sure that they don't get mangled on their way through. A metaclass would probably be more of the "right" way to do it without having to worry about adding decorators to every new method.
| Method logging in Python | I'd like something equivalent to
calling method: $METHOD_NAME
args: $ARGS
output: $OUTPUT
to be automatically logged to a file (via the logging module, possibly) for every (user-defined) method call. The best solution I can come up with is to write a decorator that will do this, and then add it to every function. Is there a better way?
Thanks
| [
"You could look at the trace module in the standard library, which \n\nallows you to trace program execution, generate annotated statement coverage listings, print caller/callee relationships and list functions executed during a program run. It can be used in another program or from the command line.\n\nYou can als... | [
6,
2,
1,
1
] | [] | [] | [
"logging",
"python"
] | stackoverflow_0003290586_logging_python.txt |
Q:
Memory not released by python cherrypy application on linux
I have a long running process that will fetch 100k rows from the db genrate a web page and then release all the small objets (list, tuples and dicts). On windows, after each request the memory is freed. Howerver, on linux, the memory of the server keeps growing.
The following posts describes what the problem is and one possible solution.
http://pushingtheweb.com/2010/06/python-and-tcmalloc/
Is there any other way to get around this problem without having to compile my own python version which uses tcmalloc. That option is going to be very difficult to do, since python is controlled by the sys admin.
A:
You may be able to compile Python in your own working directory rather than try to have the sysadmin replace the system Python.
First you should confirm that the tcmalloc solution solves your problem and does not impact performance too much for your application
| Memory not released by python cherrypy application on linux | I have a long running process that will fetch 100k rows from the db genrate a web page and then release all the small objets (list, tuples and dicts). On windows, after each request the memory is freed. Howerver, on linux, the memory of the server keeps growing.
The following posts describes what the problem is and one possible solution.
http://pushingtheweb.com/2010/06/python-and-tcmalloc/
Is there any other way to get around this problem without having to compile my own python version which uses tcmalloc. That option is going to be very difficult to do, since python is controlled by the sys admin.
| [
"You may be able to compile Python in your own working directory rather than try to have the sysadmin replace the system Python.\nFirst you should confirm that the tcmalloc solution solves your problem and does not impact performance too much for your application\n"
] | [
0
] | [] | [] | [
"cherrypy",
"memory",
"python",
"tcmalloc"
] | stackoverflow_0003290754_cherrypy_memory_python_tcmalloc.txt |
Q:
Running subprocess.call to run a Cocoa command-line application
I have one piece of Cocoa code I wrote that takes in an XML file containing bounding boxes that are then drawn on top of a video (each box has an associated frame). The Cocoa program is meant to be run from the command line (and takes in all its parameters as command line arguments)
I can run program just fine with any XML document. However, I run into problems when I try to run the program from within a Python script. For example:
with file("test.xml") as temp:
temp.write(doc.toprettyxml())
# cval is my cocoa program to call, the other arguments are given to the Python script and parsed with optparser
command = ["./cval", "-o", options.output, "-i", str(options.interval), "-s", "%dx%d" % (options.width, options.height), "-f", str(options.frames), "-x", temp.name]
subprocess.call(command)
Sometimes this will cause my 'cval' to fail, other times not (changing one number in the XML document can change its behavior). I can also verify it's breaking when trying to read an XML element that isn't there. Only, I can open up 'test.xml', and verify the element does in fact exist.
However, if I then run 'cval' myself (outside of the Python script) with 'test.xml', it works fine. This leads me to believe that there is something strange happening when I do 'subprocess.call', but I'm not sure what it could be. I have other Cocoa/Python mixes that do completely different tasks (i.e. not using XML) that also arbitrarily exhibit weird behavior, but are more complex in nature.
I was hoping someone might have run into this problem as well, or might know the next step in debugging this weirdness.
A:
Because the code originally used temporary files, I couldn't close the file before passing it to the subprocess. However, what I should have done instead is to flush the file before subprocess.call was invoked. The inconsistent behavior likely resulted from the size of input causing automatic flushing at different thresholds.
The code should read:
with file("test.xml") as temp:
temp.write(doc.toprettyxml())
temp.flush()
command = ["./cval", "-o", options.output, "-i", str(options.interval), "-s", "%dx%d" % (options.width, options.height), "-f", str(options.frames), "-x", temp.name]
subprocess.call(command)
A:
Perhaps try placing a "print command" statement in there, when the return code of subprocess.call indicates an error. On failure, see if there's any difference between what's being executed by subprocess and what you might run from the command line. Also, try calling subprocess.call(command, shell=True), so your command is being executed as it would in the shell (with string formatting, etc).
| Running subprocess.call to run a Cocoa command-line application | I have one piece of Cocoa code I wrote that takes in an XML file containing bounding boxes that are then drawn on top of a video (each box has an associated frame). The Cocoa program is meant to be run from the command line (and takes in all its parameters as command line arguments)
I can run program just fine with any XML document. However, I run into problems when I try to run the program from within a Python script. For example:
with file("test.xml") as temp:
temp.write(doc.toprettyxml())
# cval is my cocoa program to call, the other arguments are given to the Python script and parsed with optparser
command = ["./cval", "-o", options.output, "-i", str(options.interval), "-s", "%dx%d" % (options.width, options.height), "-f", str(options.frames), "-x", temp.name]
subprocess.call(command)
Sometimes this will cause my 'cval' to fail, other times not (changing one number in the XML document can change its behavior). I can also verify it's breaking when trying to read an XML element that isn't there. Only, I can open up 'test.xml', and verify the element does in fact exist.
However, if I then run 'cval' myself (outside of the Python script) with 'test.xml', it works fine. This leads me to believe that there is something strange happening when I do 'subprocess.call', but I'm not sure what it could be. I have other Cocoa/Python mixes that do completely different tasks (i.e. not using XML) that also arbitrarily exhibit weird behavior, but are more complex in nature.
I was hoping someone might have run into this problem as well, or might know the next step in debugging this weirdness.
| [
"Because the code originally used temporary files, I couldn't close the file before passing it to the subprocess. However, what I should have done instead is to flush the file before subprocess.call was invoked. The inconsistent behavior likely resulted from the size of input causing automatic flushing at different... | [
1,
0
] | [] | [] | [
"cocoa",
"python",
"subprocess"
] | stackoverflow_0003283773_cocoa_python_subprocess.txt |
Q:
python , how to find class object from child entity?
my code is following in python.
class A(object):
b = B()
def d(self):
print "Hi"
class B():
def C(self):
self.__self__.d()#edit ::: i need to call d() method here. i know __self__ is wrong
# do knowledge for B being variable inside object A needed ? i.e
# passing parent object via init is needed as shown in some answer ?
# i search and found im_self __self__ etc...
temp = A()
temp.b.C()#should print hi ?
How do i do this ? i.e. access parent class object's method inside child's method ?
basically I want to send some signal to the parent class from one sibling object to call some method from another sibling object ( not shown in above code ) . I hope i do not sound too much confusing.
A:
See this previous answer. It's with a derived class instead, but it might be helpful to look into.
You could have A pass itself to B in the init method or as a separate method. As long as that was called before you had a call to B.c() it would work fine. It's not a perfect solution, but it works.
class B():
def __init__(self, someA):
self.parent = someA
def C(self):
self.parent.d()
class A(object):
def __init__(self):
self.b = B(self)
def d(self):
print "Hi"
A:
You have to pass the instance and store it in a member variable:
class B(object):
def __init__(self, a):
self.a = a
def c(self):
self.a.d()
class A(object):
def __init__(self):
self.b = B(self)
def d(self):
print "Hi"
Note that your code will give lots of errors due to missing self parameters.
| python , how to find class object from child entity? | my code is following in python.
class A(object):
b = B()
def d(self):
print "Hi"
class B():
def C(self):
self.__self__.d()#edit ::: i need to call d() method here. i know __self__ is wrong
# do knowledge for B being variable inside object A needed ? i.e
# passing parent object via init is needed as shown in some answer ?
# i search and found im_self __self__ etc...
temp = A()
temp.b.C()#should print hi ?
How do i do this ? i.e. access parent class object's method inside child's method ?
basically I want to send some signal to the parent class from one sibling object to call some method from another sibling object ( not shown in above code ) . I hope i do not sound too much confusing.
| [
"See this previous answer. It's with a derived class instead, but it might be helpful to look into.\nYou could have A pass itself to B in the init method or as a separate method. As long as that was called before you had a call to B.c() it would work fine. It's not a perfect solution, but it works.\nclass B():\n ... | [
2,
1
] | [] | [] | [
"class",
"object",
"python"
] | stackoverflow_0003290950_class_object_python.txt |
Q:
Plone content type works as folder but not as event
I have been trying to create a new content type for Plone based on the event type. I followed this tutorial for making content types and successfully created this code for my own content type called "Multimedia". My code works, however the type is based on the folder type.
My attempts to change this to be based on the event type:
Lines 6, 14 and 40 all contain instances of folder or ATFolder
Looking on the plone site I found that the event type is event and ATEvent, I think.
I replaced all the occurrences of folder with event(I had previously replaced all occurrences of base with folder and it worked)
Unfortunately this just throws a huge stack error that I cant find the relevance to my script in, I looked also in the error log but there is no reference to any lines in Multimedia.py so I am stuck.
If anyone knows how to change my current code to correct code that would make Multimedia be based on the event type I would be very greatful for you help.
Regards
Luke
A:
You can't extend ATEvent in that way and will have to use SchemaExtender to do so
| Plone content type works as folder but not as event | I have been trying to create a new content type for Plone based on the event type. I followed this tutorial for making content types and successfully created this code for my own content type called "Multimedia". My code works, however the type is based on the folder type.
My attempts to change this to be based on the event type:
Lines 6, 14 and 40 all contain instances of folder or ATFolder
Looking on the plone site I found that the event type is event and ATEvent, I think.
I replaced all the occurrences of folder with event(I had previously replaced all occurrences of base with folder and it worked)
Unfortunately this just throws a huge stack error that I cant find the relevance to my script in, I looked also in the error log but there is no reference to any lines in Multimedia.py so I am stuck.
If anyone knows how to change my current code to correct code that would make Multimedia be based on the event type I would be very greatful for you help.
Regards
Luke
| [
"You can't extend ATEvent in that way and will have to use SchemaExtender to do so\n"
] | [
1
] | [] | [] | [
"plone",
"python"
] | stackoverflow_0003125077_plone_python.txt |
Q:
Is there a Perl alternative to YSlow?
I'd like to have a tool in Perl to gather useful statistics for page loads (eg, download time/speed, CDN information, headers, dns lookups, compressions)
Does anyone know if one exists or if there's a place to learn about how to make one?
A:
You might want to try WWW::Mechanize::Timed, which extends the WWW::Mechanize module. The ::Timed features will allow you to collect information on how long your requests take. The underlying ::Mechanize module, which is itself a subclass of LWP::UserAgent, would give you access to your response, including headers, body content, and images. From these you could compute total page "weight", number of requests, etc. This doesn't cover everything YSlow does (exposing the DNS internals underlying gethostbyname would be a good trick!) but I hope it's a place to start, if I've understood your question properly.
A:
You could have the perl CGI (or any perl program) run a few times under the profiler, and scan for commonalities. I haven't seen a web-based interface like this, but if you have control over the perl side of things, the documentation is here:
http://www.perl.com/pub/a/2004/06/25/profiling.html
It basically boils down to running your perl program with -d:DProf and then, after it finishes, running dprofpp in the same directory:
# perl -d:DProf ./foo.pl
# dprofpp
Update:
Yes, this is not the same thing as protocol profiling, as duly noted below, but there aren't may alternatives for perl. If you are trying to find where the perl portion of the slowness is coming from, profiling perl is a good place to start. Products like YSlow will track the pure protocol aspects of it, whether the CGI is perl or php or python.
Personally, I use it to profile my django site, which is in python and flash, and I profile those separately from the protocol portion of the system, which I also use YSlow for.
Also, there are perl plugins for "ddd" which will at least make it graphical:
http://www.gnu.org/software/ddd/
Sorry if this doesn't solve the exact problem, I would like to know if there's a perl interface to collate this as well, but I know this is where I would start looking...
| Is there a Perl alternative to YSlow? | I'd like to have a tool in Perl to gather useful statistics for page loads (eg, download time/speed, CDN information, headers, dns lookups, compressions)
Does anyone know if one exists or if there's a place to learn about how to make one?
| [
"You might want to try WWW::Mechanize::Timed, which extends the WWW::Mechanize module. The ::Timed features will allow you to collect information on how long your requests take. The underlying ::Mechanize module, which is itself a subclass of LWP::UserAgent, would give you access to your response, including headers... | [
1,
0
] | [] | [] | [
"firefox",
"perl",
"python",
"yslow"
] | stackoverflow_0003175611_firefox_perl_python_yslow.txt |
Q:
xml parsing and reading the values in python
I want to know how to read and store the xml data in an array.I m not sure which method to use or class
Can anyone tell which xml lib to use for reading the xml
A:
That's quite a wide topic, and the best library depends on quite a few things, so it's not easy to answer this very meaningfully with so little details.
I'd suggest you look into xml.dom.minidom and see if it suits your needs.
A:
BeautifulSoup or xml
A:
If you're using Python 2.5+, xml.etree.ElementTree is probably the easiest API to use in the stdlib.
A:
According to #python channel on FreeNode:
When parsing XML or HTML, use the lxml library
| xml parsing and reading the values in python | I want to know how to read and store the xml data in an array.I m not sure which method to use or class
Can anyone tell which xml lib to use for reading the xml
| [
"That's quite a wide topic, and the best library depends on quite a few things, so it's not easy to answer this very meaningfully with so little details.\nI'd suggest you look into xml.dom.minidom and see if it suits your needs.\n",
"BeautifulSoup or xml\n",
"If you're using Python 2.5+, xml.etree.ElementTree i... | [
0,
0,
0,
0
] | [] | [] | [
"python",
"xml"
] | stackoverflow_0002326601_python_xml.txt |
Q:
BaseHTTPServer not recognizing CSS files
I'm writing a pretty basic webserver (well, trying) and while it's now serving HTML fine, my CSS files don't seem to be recognized at all. I have Apache2 running on my machine as well, and when I copy my files to the docroot, the pages are served correctly. I've also checked permissions and they seems to be fine. Here's the code I have so far:
class MyHandler(BaseHTTPRequestHandler):
def do_GET(self):
try:
if self.path == "/":
self.path = "/index.html"
if self.path == "favico.ico":
return
if self.path.endswith(".html"):
f = open(curdir+sep+self.path)
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
self.wfile.write(f.read())
f.close()
return
return
except IOError:
self.send_error(404)
def do_POST(self):
...
Is there anything special I need to be doing in order to serve CSS files?
Thanks!
A:
You could add this to your if clause
elif self.path.endswith(".css"):
f = open(curdir+sep+self.path)
self.send_response(200)
self.send_header('Content-type', 'text/css')
self.end_headers()
self.wfile.write(f.read())
f.close()
return
Alternatively
import os
from mimetypes import types_map
class MyHandler(BaseHTTPRequestHandler):
def do_GET(self):
try:
if self.path == "/":
self.path = "/index.html"
if self.path == "favico.ico":
return
fname,ext = os.path.splitext(self.path)
if ext in (".html", ".css"):
with open(os.path.join(curdir,self.path)) as f:
self.send_response(200)
self.send_header('Content-type', types_map[ext])
self.end_headers()
self.wfile.write(f.read())
return
except IOError:
self.send_error(404)
A:
You need to add a case that handles css files. Try changing:
if self.path.endswith(".html") or self.path.endswith(".css"):
| BaseHTTPServer not recognizing CSS files | I'm writing a pretty basic webserver (well, trying) and while it's now serving HTML fine, my CSS files don't seem to be recognized at all. I have Apache2 running on my machine as well, and when I copy my files to the docroot, the pages are served correctly. I've also checked permissions and they seems to be fine. Here's the code I have so far:
class MyHandler(BaseHTTPRequestHandler):
def do_GET(self):
try:
if self.path == "/":
self.path = "/index.html"
if self.path == "favico.ico":
return
if self.path.endswith(".html"):
f = open(curdir+sep+self.path)
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
self.wfile.write(f.read())
f.close()
return
return
except IOError:
self.send_error(404)
def do_POST(self):
...
Is there anything special I need to be doing in order to serve CSS files?
Thanks!
| [
"You could add this to your if clause\n elif self.path.endswith(\".css\"):\n f = open(curdir+sep+self.path)\n self.send_response(200)\n self.send_header('Content-type', 'text/css')\n self.end_headers()\n self.wfile.write(f.re... | [
7,
0
] | [] | [] | [
"python"
] | stackoverflow_0003291120_python.txt |
Q:
Dynamic Importing in Python (Dotted statments)
I'm having trouble with the following code:
def get_module(mod_path):
mod_list = mod_path.split('.')
mod = __import__(mod_list.pop(0))
while mod_list:
mod = getattr(mod, mod_list.pop(0))
return mod
When I do get_module('qmbpmn.common.db_parsers') I get the error message:
AttributeError: 'module' object has no attribute 'db_parsers'.
However: import qmbpmn.common.db_parsers works perfectly fine.
A:
When using __import__ to import submodules, you must pass the parent package as the fromlist argument:
>>> __import__("os.path")
<module 'os' from '/usr/lib/python2.6/os.pyc'>
>>> __import__("os.path", fromlist=["os"])
<module 'posixpath' from '/usr/lib/python2.6/posixpath.pyc'>
A:
__import__ works with the dotted module path, so this should work
def get_module(mod_path):
return __import__(mod_path)
or more simply
get_module = __import__
Perhaps I am misunderstanding the problem
importing a package does not automatically import all the submodules into it's namespace. For example
import qmbpmn
does not mean that
qmbpmn.common.db_parsers
will automatically resolve
| Dynamic Importing in Python (Dotted statments) | I'm having trouble with the following code:
def get_module(mod_path):
mod_list = mod_path.split('.')
mod = __import__(mod_list.pop(0))
while mod_list:
mod = getattr(mod, mod_list.pop(0))
return mod
When I do get_module('qmbpmn.common.db_parsers') I get the error message:
AttributeError: 'module' object has no attribute 'db_parsers'.
However: import qmbpmn.common.db_parsers works perfectly fine.
| [
"When using __import__ to import submodules, you must pass the parent package as the fromlist argument:\n>>> __import__(\"os.path\")\n<module 'os' from '/usr/lib/python2.6/os.pyc'>\n>>> __import__(\"os.path\", fromlist=[\"os\"])\n<module 'posixpath' from '/usr/lib/python2.6/posixpath.pyc'>\n\n",
"__import__ works... | [
3,
1
] | [] | [] | [
"python"
] | stackoverflow_0003291204_python.txt |
Q:
Pass QuerySet object in template. Django
How can i pass QuerySet object in to template. And then Iterate through it in tempalte. If ican do it....?
Example
queryset =MyModel.objects.all()
return render_to_response('template.html',{'queryset':queryset})
How it'll looks in template?
Can I show field of foreigne key object in this template?
A:
{% for each_model in model %}
#Do Something with model
{{each_model.name}}
{% endfor %}
| Pass QuerySet object in template. Django | How can i pass QuerySet object in to template. And then Iterate through it in tempalte. If ican do it....?
Example
queryset =MyModel.objects.all()
return render_to_response('template.html',{'queryset':queryset})
How it'll looks in template?
Can I show field of foreigne key object in this template?
| [
"{% for each_model in model %}\n #Do Something with model\n {{each_model.name}}\n{% endfor %}\n\n"
] | [
7
] | [] | [] | [
"django_templates",
"python"
] | stackoverflow_0003291469_django_templates_python.txt |
Q:
Shared memory and comunication between programs
I read this: python singleton into multiprocessing but I didn't find the solution of my problem. I have to run the same program (not process) many times in one time. Programs work in the same electronic devices. I must synchronized this programs. Only one program can use device in the moment.
Have you got any suggestions how I can resolve this problem?
A:
You could use lockfiles in the filesystem.
| Shared memory and comunication between programs | I read this: python singleton into multiprocessing but I didn't find the solution of my problem. I have to run the same program (not process) many times in one time. Programs work in the same electronic devices. I must synchronized this programs. Only one program can use device in the moment.
Have you got any suggestions how I can resolve this problem?
| [
"You could use lockfiles in the filesystem.\n"
] | [
0
] | [] | [] | [
"python",
"shared_memory",
"synchronization"
] | stackoverflow_0003289040_python_shared_memory_synchronization.txt |
Q:
Multiple assignments under 'if' statement
Why can't I make multiple assignments under an if statement in python? Is there some syntax I am missing?
I want to do this:
files = ["file1", "file2", "file3"]
print "\nThe following files are available: \n"
i = 0
for file in files:
i = i + 1
print i, file
choice = int(raw_input("\Enter a file number: "))
if choice ==1:
file = np.genfromtxt(files[0], usecols = (1,2,3), dtype = (float), delimiter = '\t')
time = np.genfromtxt(files[0], usecols = (0), dtype = (str), delimiter = '\t')
print time
Time is defined outside of my if statement, so it doesn't change as choice changes...what the heck?
A:
Both variables file and time must be defined at an higher block level than your if statement.
Be careful with "time", as it is the name of a python module. You should use a variation of this name (time_ for example).
A:
You are not using any other choice except for 1 and it will give error if choice is not 1, you code should be something like this
choice = int(raw_input("\Enter a file number: "))
choice -= 1 # array index is from 0
if choice < 0 or > 2:
print "Enter correct choice"
sys.exit()
file = np.genfromtxt(files[choice], usecols = (1,2,3), dtype = (float), delimiter = '\t')
time = np.genfromtxt(files[choice], usecols = (0), dtype = (str), delimiter = '\t')
| Multiple assignments under 'if' statement | Why can't I make multiple assignments under an if statement in python? Is there some syntax I am missing?
I want to do this:
files = ["file1", "file2", "file3"]
print "\nThe following files are available: \n"
i = 0
for file in files:
i = i + 1
print i, file
choice = int(raw_input("\Enter a file number: "))
if choice ==1:
file = np.genfromtxt(files[0], usecols = (1,2,3), dtype = (float), delimiter = '\t')
time = np.genfromtxt(files[0], usecols = (0), dtype = (str), delimiter = '\t')
print time
Time is defined outside of my if statement, so it doesn't change as choice changes...what the heck?
| [
"Both variables file and time must be defined at an higher block level than your if statement.\nBe careful with \"time\", as it is the name of a python module. You should use a variation of this name (time_ for example).\n",
"You are not using any other choice except for 1 and it will give error if choice is not ... | [
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0003291997_python.txt |
Q:
Django mod_wsgi PicklingError while saving object
Do you know any solution to this:
[Thu Jul 08 19:15:38 2010] [error] [client 79.162.31.162] mod_wsgi (pid=3072): Exception occurred processing WSGI script '/home/www/shop/django.wsgi'., referer: http://shop.domain.com/accounts/checkout/?
[Thu Jul 08 19:15:38 2010] [error] [client 79.162.31.162] Traceback (most recent call last):, referer: http://shop.domain.com/accounts/checkout/?
[Thu Jul 08 19:15:38 2010] [error] [client 79.162.31.162] File "/usr/lib/python2.5/site-packages/django/core/handlers/wsgi.py", line 245, in __call__, referer: http://shop.domain.com/accounts/checkout/?
[Thu Jul 08 19:15:38 2010] [error] [client 79.162.31.162] response = middleware_method(request, response), referer: http://shop.domain.com/accounts/checkout/?
[Thu Jul 08 19:15:38 2010] [error] [client 79.162.31.162] File "/usr/lib/python2.5/site-packages/django/contrib/sessions/middleware.py", line 36, in process_response, referer: http://shop.domain.com/accounts/checkout/?
[Thu Jul 08 19:15:38 2010] [error] [client 79.162.31.162] request.session.save(), referer: http://shop.domain.com/accounts/checkout/?
[Thu Jul 08 19:15:38 2010] [error] [client 79.162.31.162] File "/usr/lib/python2.5/site-packages/django/contrib/sessions/backends/db.py", line 57, in save, referer: http://shop.domain.com/accounts/checkout/?
[Thu Jul 08 19:15:38 2010] [error] [client 79.162.31.162] session_data = self.encode(self._get_session(no_load=must_create)),, referer: http://shop.domain.com/accounts/checkout/?
[Thu Jul 08 19:15:38 2010] [error] [client 79.162.31.162] File "/usr/lib/python2.5/site-packages/django/contrib/sessions/backends/base.py", line 88, in encode, referer: http://shop.domain.com/accounts/checkout/?
[Thu Jul 08 19:15:38 2010] [error] [client 79.162.31.162] pickled = pickle.dumps(session_dict, pickle.HIGHEST_PROTOCOL), referer: http://shop.domain.com/accounts/checkout/?
[Thu Jul 08 19:15:38 2010] [error] [client 79.162.31.162] PicklingError: Can't pickle <class 'decimal.Decimal'>: it's not the same object as decimal.Decimal, referer: http://shop.domain.com/accounts/checkout/?
It occures sometimes while saving model instance with DecimalField :/.
views.py:
def checkout_authenticated(request):
order = get_order(request)
user = request.user
if request.method == 'POST':
form = OrderCheckoutForm(request.POST, instance = order)
if form.is_valid():
form.save()
...
forms.py:
class OrderCheckoutForm(forms.ModelForm):
class Meta:
model = Order
exclude = ('status',
'user')
models.py:
class Shipping(models.Model):
name = models.CharField(max_length = 256)
price = models.DecimalField(max_digits = 10, decimal_places = 2)
description = models.TextField(blank = True, null = True)
cash_on_delivery = models.BooleanField(default = False)
class Order(models.Model):
date = models.DateField(editable = False, auto_now_add=True)
status = models.CharField(max_length = 1, choices = STATUS, default = Status.NEW)
shipping = models.ForeignKey(Shipping, related_name = 'orders', null = True)
address = models.ForeignKey(Address, related_name = 'address_order', null = True)
invoice = models.BooleanField(default = False)
company = models.ForeignKey(Company, related_name = 'company_order', blank = True, null = True)
I think the reason is:
price = models.DecimalField(max_digits = 10, decimal_places = 2)
Thanks in advance,
Etam.
A:
See this answer. Does that help?
EDIT (responding to your comment):
I'm afraid I don't know either django or your code well enough to give you a fix. I do have a clearer idea of the underlying error, though: Before this error occurred, an instance of decimal.Decimal was created, and then for some reason the class decimal.Decimal was re-defined. The pickle class doesn't work when it can't locate, by name, the class definition for a given object.
Here's an interpreter session showing a similar problem:
>>> import cPickle
>>> class Foo(object):
... pass
...
>>> f = Foo()
>>> s = cPickle.dumps(f)
>>>
>>> # Redefine class Foo
>>> class Foo(object):
... pass
...
>>> # Now attempt to pickle the same object that was created with the old Foo class
>>> s = cPickle.dumps(f)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
cPickle.PicklingError: Can't pickle <class '__main__.Foo'>: it's not the same object as __main__.Foo
>>>
>>> # Create an object with the new Foo class, and try to pickle it (this works)
>>> f2 = Foo()
>>> s = cPickle.dumps(f2)
| Django mod_wsgi PicklingError while saving object | Do you know any solution to this:
[Thu Jul 08 19:15:38 2010] [error] [client 79.162.31.162] mod_wsgi (pid=3072): Exception occurred processing WSGI script '/home/www/shop/django.wsgi'., referer: http://shop.domain.com/accounts/checkout/?
[Thu Jul 08 19:15:38 2010] [error] [client 79.162.31.162] Traceback (most recent call last):, referer: http://shop.domain.com/accounts/checkout/?
[Thu Jul 08 19:15:38 2010] [error] [client 79.162.31.162] File "/usr/lib/python2.5/site-packages/django/core/handlers/wsgi.py", line 245, in __call__, referer: http://shop.domain.com/accounts/checkout/?
[Thu Jul 08 19:15:38 2010] [error] [client 79.162.31.162] response = middleware_method(request, response), referer: http://shop.domain.com/accounts/checkout/?
[Thu Jul 08 19:15:38 2010] [error] [client 79.162.31.162] File "/usr/lib/python2.5/site-packages/django/contrib/sessions/middleware.py", line 36, in process_response, referer: http://shop.domain.com/accounts/checkout/?
[Thu Jul 08 19:15:38 2010] [error] [client 79.162.31.162] request.session.save(), referer: http://shop.domain.com/accounts/checkout/?
[Thu Jul 08 19:15:38 2010] [error] [client 79.162.31.162] File "/usr/lib/python2.5/site-packages/django/contrib/sessions/backends/db.py", line 57, in save, referer: http://shop.domain.com/accounts/checkout/?
[Thu Jul 08 19:15:38 2010] [error] [client 79.162.31.162] session_data = self.encode(self._get_session(no_load=must_create)),, referer: http://shop.domain.com/accounts/checkout/?
[Thu Jul 08 19:15:38 2010] [error] [client 79.162.31.162] File "/usr/lib/python2.5/site-packages/django/contrib/sessions/backends/base.py", line 88, in encode, referer: http://shop.domain.com/accounts/checkout/?
[Thu Jul 08 19:15:38 2010] [error] [client 79.162.31.162] pickled = pickle.dumps(session_dict, pickle.HIGHEST_PROTOCOL), referer: http://shop.domain.com/accounts/checkout/?
[Thu Jul 08 19:15:38 2010] [error] [client 79.162.31.162] PicklingError: Can't pickle <class 'decimal.Decimal'>: it's not the same object as decimal.Decimal, referer: http://shop.domain.com/accounts/checkout/?
It occures sometimes while saving model instance with DecimalField :/.
views.py:
def checkout_authenticated(request):
order = get_order(request)
user = request.user
if request.method == 'POST':
form = OrderCheckoutForm(request.POST, instance = order)
if form.is_valid():
form.save()
...
forms.py:
class OrderCheckoutForm(forms.ModelForm):
class Meta:
model = Order
exclude = ('status',
'user')
models.py:
class Shipping(models.Model):
name = models.CharField(max_length = 256)
price = models.DecimalField(max_digits = 10, decimal_places = 2)
description = models.TextField(blank = True, null = True)
cash_on_delivery = models.BooleanField(default = False)
class Order(models.Model):
date = models.DateField(editable = False, auto_now_add=True)
status = models.CharField(max_length = 1, choices = STATUS, default = Status.NEW)
shipping = models.ForeignKey(Shipping, related_name = 'orders', null = True)
address = models.ForeignKey(Address, related_name = 'address_order', null = True)
invoice = models.BooleanField(default = False)
company = models.ForeignKey(Company, related_name = 'company_order', blank = True, null = True)
I think the reason is:
price = models.DecimalField(max_digits = 10, decimal_places = 2)
Thanks in advance,
Etam.
| [
"See this answer. Does that help?\nEDIT (responding to your comment):\nI'm afraid I don't know either django or your code well enough to give you a fix. I do have a clearer idea of the underlying error, though: Before this error occurred, an instance of decimal.Decimal was created, and then for some reason the clas... | [
2
] | [] | [] | [
"django",
"django_models",
"pickle",
"python"
] | stackoverflow_0003292383_django_django_models_pickle_python.txt |
Q:
lapack import error with NumPy
Trying to import numpy in Python 2.6 I run into:
from numpy.linalg import lapack_lite
ImportError: libmkl_lapack.so: cannot open shared object file: No such file or directory
There are multiple instances of Intel's Math Kernel Library on the machine providing libmkl_lapack.so and I'm pointing at them with every relevant or semi-relevant environmental variable I can think of (most notably, I guess, $LD_LIBRARY_PATH and $PYTHONPATH). I don't have permission to run ldconfig.
This is on a well-used machine and there are multiple Python and NumPy installs. Python2.6 is in my /home/me/usr/ but there is an older installation of Python2.4 in /usr/ which will import lapack_lite without issue. So I'm not sure where to go from here.
Thanks for anything!
A:
you can try
strace python your_script.py
to see what it is trying.
That will trace all syscalls, therefore showing you the underlying open made by python.
| lapack import error with NumPy | Trying to import numpy in Python 2.6 I run into:
from numpy.linalg import lapack_lite
ImportError: libmkl_lapack.so: cannot open shared object file: No such file or directory
There are multiple instances of Intel's Math Kernel Library on the machine providing libmkl_lapack.so and I'm pointing at them with every relevant or semi-relevant environmental variable I can think of (most notably, I guess, $LD_LIBRARY_PATH and $PYTHONPATH). I don't have permission to run ldconfig.
This is on a well-used machine and there are multiple Python and NumPy installs. Python2.6 is in my /home/me/usr/ but there is an older installation of Python2.4 in /usr/ which will import lapack_lite without issue. So I'm not sure where to go from here.
Thanks for anything!
| [
"you can try \nstrace python your_script.py\n\nto see what it is trying.\nThat will trace all syscalls, therefore showing you the underlying open made by python.\n"
] | [
1
] | [] | [] | [
"linux",
"python"
] | stackoverflow_0003292396_linux_python.txt |
Q:
Sending email from my domain vs from the admin google account?
I have a domain xyz.com and right now it is pointing to my app in appspot. I want to send email alerts to users for various events. However, appengine restricts email sender to admin email address which was used to create the google app engine account.
Can I send emails on behalf of user@xyz.com using app engine? If not, is there a simple workaround to do this?
A:
According to the documentation about sending mail from within Google App Engine, the email sender has to be either:
the email address of an admin account associated with the application OR
the Google Account email address of the current signed-in user OR
a valid app email address (string @ appid.appspotmail.com, see here for more info)
So if your user is logged in with his/her Google Account while using the app, you will be able to send the mail with sender user@xyz.com.
If not, you will have to use an admin account's email, an app email address or create a separate Google Account (which you make an admin of the app) to use for this purpose as is suggested as a workaround in the documentation.
A:
When sending email, you can designate the sender as either the currently logged in user or any registered administrator. It does not have to be the administrator who created the app.
Also note that you can add any email address as an administrator on your app (from the permissions tab in the admin console). It does not need to be a Gmail or Google Apps account; any email account that you can access to click on the confirmation link will work.
| Sending email from my domain vs from the admin google account? | I have a domain xyz.com and right now it is pointing to my app in appspot. I want to send email alerts to users for various events. However, appengine restricts email sender to admin email address which was used to create the google app engine account.
Can I send emails on behalf of user@xyz.com using app engine? If not, is there a simple workaround to do this?
| [
"According to the documentation about sending mail from within Google App Engine, the email sender has to be either:\n\nthe email address of an admin account associated with the application OR\nthe Google Account email address of the current signed-in user OR\na valid app email address (string @ appid.appspotmail.c... | [
2,
2
] | [] | [] | [
"email",
"google_app_engine",
"python"
] | stackoverflow_0003292238_email_google_app_engine_python.txt |
Q:
uploading data using Numpy.genfromtxt with multiple formats
I have a file with a time stamp as a column, and numbers in all the rest. I can either load one or the other correctly, but not both. Frustrating the heck out of me...
This is what I am doing:
import numpy as np
file = np.genfromtxt('myfile.dat', skip_header = 1, usecols = (0,1,2,3), dtype = (str, float), delimiter = '\t')
So column 0 is the timestamp, and I want to read it in as a string. The rest I want to read in as floats. Does anyone know how to do this? I tried fooling around with names and dtypes, but I cannot get anything to work.
Thanks.
A:
Perhaps try this:
import numpy as np
data = np.genfromtxt('myfile.dat',
skiprows=1,
usecols = (0,1,2,3),
dtype = '|S10,<f8,<f8,<f8',
delimiter = '\t')
print(data)
# [('2010-1-1', 1.2, 2.2999999999999998, 3.3999999999999999)
# ('2010-2-1', 4.5, 5.5999999999999996, 6.7000000000000002)]
print(data.dtype)
# [('f0', '|S10'), ('f1', '<f8'), ('f2', '<f8'), ('f3', '<f8')]
print(data.shape)
# (2,)
A:
If I have a tab-delimited file that looks like:
# Header Stuff
12:53:16 1.1111 2.2222 3.3333 4.4444
12:53:17 5.5555 6.6666 7.7777 8.8888
12:53:18 9.9999 10.0000 11.1111 12.1212
I think you can get what you're looking for by either specifying the dtype as None (so numpy chooses the dtypes for you):
file = np.genfromtxt('myfile.dat', skip_header = 1, usecols = (0,1,2,3,4),\
dtype = None, delimiter = '\t')
or you can set the dtypes explicitly:
file = np.genfromtxt('myfile.dat', skip_header = 1, usecols = (0,1,2,3,4), \
dtype=[('mytime','S8'),('myfloat1','f8'),('myfloat2','f8'),('myfloat3','f8')], \
delimiter = '\t')
| uploading data using Numpy.genfromtxt with multiple formats | I have a file with a time stamp as a column, and numbers in all the rest. I can either load one or the other correctly, but not both. Frustrating the heck out of me...
This is what I am doing:
import numpy as np
file = np.genfromtxt('myfile.dat', skip_header = 1, usecols = (0,1,2,3), dtype = (str, float), delimiter = '\t')
So column 0 is the timestamp, and I want to read it in as a string. The rest I want to read in as floats. Does anyone know how to do this? I tried fooling around with names and dtypes, but I cannot get anything to work.
Thanks.
| [
"Perhaps try this:\nimport numpy as np\n\ndata = np.genfromtxt('myfile.dat',\n skiprows=1,\n usecols = (0,1,2,3),\n dtype = '|S10,<f8,<f8,<f8',\n delimiter = '\\t')\nprint(data)\n# [('2010-1-1', 1.2, 2.2999999999999998, 3.39999999999999... | [
3,
2
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0003291670_numpy_python.txt |
Q:
How to get accurate window information (dimensions, etc.) in Linux (X)?
How can I get accurate window information in Linux? I know that I can use wmctrl to get a window's size, but the actual size of the window can vary due to window decorations. I need the following information and methods:
precise window dimensions
precise available screen space (excluding panels like gnome-panel)
the ability to set a window to be a certain size, including decorations
What would be the best way to do this? I am interested in working with Python so something with a python module would be preferred.
Thanks in advance!
A:
The best way is to use X11/xlib directly (Documentation: http://tronche.com/gui/x/xlib/ )
Beginning from the Root you can walk through a tree via XQueryTree() and get the window Attributes via XGetWindowAttributes () / XGetGeometry ().
Ok, this is a C-Library, but there is also a Python Port: http://python-xlib.sourceforge.net/?page=documentation
| How to get accurate window information (dimensions, etc.) in Linux (X)? | How can I get accurate window information in Linux? I know that I can use wmctrl to get a window's size, but the actual size of the window can vary due to window decorations. I need the following information and methods:
precise window dimensions
precise available screen space (excluding panels like gnome-panel)
the ability to set a window to be a certain size, including decorations
What would be the best way to do this? I am interested in working with Python so something with a python module would be preferred.
Thanks in advance!
| [
"The best way is to use X11/xlib directly (Documentation: http://tronche.com/gui/x/xlib/ )\nBeginning from the Root you can walk through a tree via XQueryTree() and get the window Attributes via XGetWindowAttributes () / XGetGeometry ().\nOk, this is a C-Library, but there is also a Python Port: http://python-xlib.... | [
2
] | [] | [] | [
"linux",
"python",
"xserver"
] | stackoverflow_0003233660_linux_python_xserver.txt |
Q:
.NET equivalents of Some Python Functions
I am trying to port some Python code to .NET, and I was wondering if there were equivalents of the following Python functions in .NET, or some code snippets that have the same functionality.
os.path.split()
os.path.basename()
Edit
os.path.basename() in Python returns the tail of os.path.split, not the result of System.IO.Path.GetPathRoot(path)
I think the following method creates a suitable port of the os.path.split function, any tweaks are welcome. It follows the description of os.path.split from http://docs.python.org/library/os.path.html as much as possible I believe.
public static string[] PathSplit(string path)
{
string head = string.Empty;
string tail = string.Empty;
if (!string.IsNullOrEmpty(path))
{
head = Path.GetDirectoryName(path);
tail = path.Replace(head + "\\", "");
}
return new[] { head, tail };
}
I'm unsure about the way I'm returning the head and tail, as I didn't really want to pass out the head and tail via parameters to the method.
A:
You're looking for the System.IO.Path Class.
It has many functions you can use to get the same functionality.
Path.GetDirectoryName(string)
For split, you'll probably want to use String.Split(...) on the actual path name. You can get the OS Dependant seperator by Path.PathSeparator.
In the case that im missing the point about os.path.split and you want the file name, use Path.GetFileName(string).
Please Note: You can explore all the members of the System.IO namespace by using the Object Browser (Ctrl+Alt+J) in Visual Studio. From here you go mscorlib -> System.IO and all the classes will be discoverable there.
It's like Intellisense on crack :)
A:
os.path.basename()
The alternative is System.IO.Path.GetPathRoot(path);:
System.IO.Path.GetPathRoot("C:\\Foo\\Bar.xml") // Equals C:\\
Edit: The above returned the first path of the path, where basename should return the tail of the path. See the code below for an example of how this could be achieved.
os.path.split()
Unfortunately there's no alternative to this as there's no .Net equivalent. The closest you can find is System.IO.Path.GetDirectoryName(path), however if your path was C:\Foo, then GetDirectoryName would give you C:\Foo instead of C: and Foo. This would only work if you wanted to get the Directory Name of an actual file path.
So you'll have to write some code like the following to break these down for you:
public void EquivalentSplit(string path, out string head, out string tail)
{
// Get the directory separation character (i.e. '\').
string separator = System.IO.Path.DirectorySeparatorChar.ToString();
// Trim any separators at the end of the path
string lastCharacter = path.Substring(path.Length - 1);
if (separator == lastCharacter)
{
path = path.Substring(0, path.Length - 1);
}
int lastSeparatorIndex = path.LastIndexOf(separator);
head = path.Substring(0, lastSeparatorIndex);
tail = path.Substring(lastSeparatorIndex + separator.Length,
path.Length - lastSeparatorIndex - separator.Length);
}
A:
Path.GetFileName
Path.GetDirectoryName
http://msdn.microsoft.com/en-us/library/beth2052.aspx
Should help
A:
Why not just use IronPython and get the best of both worlds?
| .NET equivalents of Some Python Functions | I am trying to port some Python code to .NET, and I was wondering if there were equivalents of the following Python functions in .NET, or some code snippets that have the same functionality.
os.path.split()
os.path.basename()
Edit
os.path.basename() in Python returns the tail of os.path.split, not the result of System.IO.Path.GetPathRoot(path)
I think the following method creates a suitable port of the os.path.split function, any tweaks are welcome. It follows the description of os.path.split from http://docs.python.org/library/os.path.html as much as possible I believe.
public static string[] PathSplit(string path)
{
string head = string.Empty;
string tail = string.Empty;
if (!string.IsNullOrEmpty(path))
{
head = Path.GetDirectoryName(path);
tail = path.Replace(head + "\\", "");
}
return new[] { head, tail };
}
I'm unsure about the way I'm returning the head and tail, as I didn't really want to pass out the head and tail via parameters to the method.
| [
"You're looking for the System.IO.Path Class.\nIt has many functions you can use to get the same functionality.\n\nPath.GetDirectoryName(string)\nFor split, you'll probably want to use String.Split(...) on the actual path name. You can get the OS Dependant seperator by Path.PathSeparator.\nIn the case that im missi... | [
7,
1,
0,
0
] | [] | [] | [
"c#",
"porting",
"python"
] | stackoverflow_0003291970_c#_porting_python.txt |
Q:
My function takes negative time to complete. What in the world happened?
I'm posing this question mostly out of curiosity. I've written some code that is doing some very time intensive work. So, before executing my workhorse function, I wrapped it up in a couple of calls to time.clock(). It looks something like this:
t1 = time.clock()
print this_function_takes_forever(how_long_parameter = 20)
t2 = time.clock()
print t2 - t1
This worked fine. My function returned correctly and t2 - t1 gave me a result of 972.29, or about 16 minutes.
However, when I changed my code to this
t1 = time.clock()
print this_function_takes_forever(how_long_parameter = 80)
t2 = time.clock()
print t2 - t1
My function still returned fine, but the result of t2 - t1 was:
None
-1741
I'm curious as to what implementation detail causes this. Both the None, and the negative number are perplexing to me. Does it have something to do with a signed type? How does this explain the None?
A:
The Python docs say:
On Unix, return the current processor time as a floating point number expressed in seconds. The precision, and in fact the very definition of the meaning of “processor time”, depends on that of the C function of the same name
The manpage of the referenced C function then explains the issue:
Note that the time can wrap around. On a 32-bit system where CLOCKS_PER_SEC equals 1000000 this function will
return the same value approximately every 72 minutes.
A:
A quick guess... Looks like an overflow. The default data type is probably a signed data type (putting the first bit to 1 on a signed integer gives a negative number).
Try putting the result of the substraction in a variable (double), and then printing that.
If it still prints like that, you can try converting it from double to string, and then using 'print' function on the string.
A:
The None has a very simple answer, your function does not return a value. Actually I gather that is does under normal circumstances, but not when how_long_parameter = 80. Because your function seems to be returning early (probably because execution reaches the end of the function where there is an implicit return None in Python) the negative time might be because your function takes almost no time to complete in this case? So look for the bug in your function and correct it.
The actual answer as to why you get a negative time depends on the operating system you are using, because clock() is implemented differently on different platforms. On Windows it uses QueryPerformanceCounter(), on *nix it uses the C function clock().
| My function takes negative time to complete. What in the world happened? | I'm posing this question mostly out of curiosity. I've written some code that is doing some very time intensive work. So, before executing my workhorse function, I wrapped it up in a couple of calls to time.clock(). It looks something like this:
t1 = time.clock()
print this_function_takes_forever(how_long_parameter = 20)
t2 = time.clock()
print t2 - t1
This worked fine. My function returned correctly and t2 - t1 gave me a result of 972.29, or about 16 minutes.
However, when I changed my code to this
t1 = time.clock()
print this_function_takes_forever(how_long_parameter = 80)
t2 = time.clock()
print t2 - t1
My function still returned fine, but the result of t2 - t1 was:
None
-1741
I'm curious as to what implementation detail causes this. Both the None, and the negative number are perplexing to me. Does it have something to do with a signed type? How does this explain the None?
| [
"The Python docs say:\n\nOn Unix, return the current processor time as a floating point number expressed in seconds. The precision, and in fact the very definition of the meaning of “processor time”, depends on that of the C function of the same name\n\nThe manpage of the referenced C function then explains the iss... | [
17,
2,
1
] | [] | [] | [
"python",
"time",
"timing"
] | stackoverflow_0003292865_python_time_timing.txt |
Q:
define *struct in ctypes
I need to convert regexitem *regex to ctype variable, any ideas?
C function expects func(regexitem *regex)
char *regex1Groups[] = { "a","b","x","s" ,NULL};
char *regex2Groups[] = { "l" ,NULL};
regexitem regex[] = {
{"bla", regex1Groups,4 },
{"bla2",regex2Groups,1 }
};
First i defined
class regexitem(Structure):
_fields = ("regex",c_char_p), ("groups",c_char_p*size), ("groupsize",c_int)
and ran into first problem, declaring array of regexitem because size of groups is not known in advance.
A:
Structs can only contain variable-length arrays at their ends, and on top of that when you assign an array variable to something you aren't copying it, you're assigning the memory location of the first element of the array. So I'm betting that your regexitem struct contains a pointer to the array of char pointers rather than containing the array of char pointers itself. If that's the case, this might work:
class regexItem(Structure):
_fields_ = [("regex", c_char_p),
("groups", POINTER(c_char_p)),
("groupsize", c_int),
]
(You can keep the assignment to _fields_ as a tuple of tuples rather than a list of tuples if you want to.)
Oh, for your regex groups, it'd be something like this:
regex1Groups = (c_char_p * 5)("a", "b", "x", "s", None)
regex2Groups = (c_char_p * 2)("l", None)
And then your array of regexitems would be like so:
regex = (regexItem * 2)(("bla", regex1Groups, 4),
("bla2", regex2Groups, 1))
Look through the ctypes documentation if you want to know more.
http://docs.python.org/library/ctypes.html
| define *struct in ctypes | I need to convert regexitem *regex to ctype variable, any ideas?
C function expects func(regexitem *regex)
char *regex1Groups[] = { "a","b","x","s" ,NULL};
char *regex2Groups[] = { "l" ,NULL};
regexitem regex[] = {
{"bla", regex1Groups,4 },
{"bla2",regex2Groups,1 }
};
First i defined
class regexitem(Structure):
_fields = ("regex",c_char_p), ("groups",c_char_p*size), ("groupsize",c_int)
and ran into first problem, declaring array of regexitem because size of groups is not known in advance.
| [
"Structs can only contain variable-length arrays at their ends, and on top of that when you assign an array variable to something you aren't copying it, you're assigning the memory location of the first element of the array. So I'm betting that your regexitem struct contains a pointer to the array of char pointers ... | [
2
] | [] | [] | [
"ctypes",
"python"
] | stackoverflow_0003292840_ctypes_python.txt |
Q:
python dbus problem
I have a problem with dbus and python. Running python from the command line, telling it import dbus and then systembus = dbus.SystemBus() results in no errors, nor does running a program written by a friend which also uses the exact same code. However, when running a program I'm trying to write, I get this error:
Traceback (most recent call last):
File "dbtest.py", line 26, in <module>
a = getDevs()
File "dbtest.py", line 7, in getDevs
bus = dbus.SystemBus()
AttributeError: 'module' object has no attribute 'SystemBus'
Any ideas as to what I'm doing wrong? I don't think I fully understand the error returned. The code I have so far is:
#!/usr/bin/env python
import dbus
def getDevs():
bus = dbus.SystemBus()
if __name__ == "__main__":
a = getDevs()
A:
The obvious problem is that when you are importing dbus, it is not getting all the methods with it.
In both your program and your friend's, do print dbus.__file__. This will show what .pyc it is using. If they are different, you are not importing the correct dbus module.
I'm going to guess that you are actually importing some random file called dbus.py in your local directory. Or, if your script name is "dbus.py", you are just importing itself and luckily python doesn't import recursively. The easiest solution in this case is to rename the offending file to something else.
| python dbus problem | I have a problem with dbus and python. Running python from the command line, telling it import dbus and then systembus = dbus.SystemBus() results in no errors, nor does running a program written by a friend which also uses the exact same code. However, when running a program I'm trying to write, I get this error:
Traceback (most recent call last):
File "dbtest.py", line 26, in <module>
a = getDevs()
File "dbtest.py", line 7, in getDevs
bus = dbus.SystemBus()
AttributeError: 'module' object has no attribute 'SystemBus'
Any ideas as to what I'm doing wrong? I don't think I fully understand the error returned. The code I have so far is:
#!/usr/bin/env python
import dbus
def getDevs():
bus = dbus.SystemBus()
if __name__ == "__main__":
a = getDevs()
| [
"The obvious problem is that when you are importing dbus, it is not getting all the methods with it.\nIn both your program and your friend's, do print dbus.__file__. This will show what .pyc it is using. If they are different, you are not importing the correct dbus module.\nI'm going to guess that you are actually... | [
10
] | [] | [] | [
"dbus",
"python"
] | stackoverflow_0003293172_dbus_python.txt |
Q:
Accessing only part of a dictionary in a for using Python
My example dictionary is this
data_dictionary = {1:'blue',2:'green',3:'red',4:'orange',5:'purple',6:'mauve'}
The data_dictionary can have more elements depending on the incoming data . The first value is what we call a payload_index. I always get payload_index 1 to 4 .
I need to assemble a list from this. Pretty easy:
for payload_index in data_dictionary :
assembled_packet.append(data_dictionary[payload_index])
My problem is I need to always skip the 3rd element. I guess I could do an if but that would be inefficient:
for payload_index in data_dictionary :
if payload_index <> 3:
assembled_packet.append(data_dictionary[payload_index])
I could do it in two steps and do the first three elements but the problem is I cannot figure out how to get the rest since the number of elements after the 3rd varies. I tried using an impossibly high index (below) but that obviously fails:
#get element 1 and two
for index in range(0,3):
assembled_packet.append(data_dictionary[index])
#get element 1 and two
for index in range(4,999):
assembled_packet.append(data_dictionary[index])
Any ideas? Thanks!
A:
inefficient? That seems like a premature optimisation! Just use normal code:
for payload_index in data_dictionary:
if payload_index != 3:
assembled_packet.append(data_dictionary[payload_index])
or even better:
assembled_packet = [data_dictionary[index] for index in data_dictionary if index != 3]
Of course, you could just simply do:
>>> d = {1:'blue',2:'green',3:'red',4:'orange',5:'purple',6:'mauve'}
>>> d.pop(3)
'red'
>>> list(d.values()) # in py3k; in python-2.x d.values() would do
['blue', 'green', 'orange', 'purple', 'mauve']
P.S. <> is long since deprecated.
A:
To make those for loops work you can do this:
# Get the remaining elements
size = len(data_dictionary)
for index in range(4,size):
assembled_packet.append(data_dictionary[index])
A:
The best way i can think of is :
output = [elem for elem in data_dictionary.items() if elem[0]!=3]
A:
from you answer is not obvious if you want to skip firts three items or just the 3rd item.
if the former is the case, and you are not sure, that your keys are always 1, 2, 3, you can do something like this:
keys = list(sorted(data_dictionary.keys()))[3:]
for payload_index in keys:
assembled_packet.append(data_dictionary[payload_index])
A:
My problem is I need to always skip the 3rd element. I guess I could do an if but that would be inefficient:
This is even more inefficient:
for payload_index in data_dictionary :
...
assembled_packet.append(data_dictionary[payload_index])
I'd do it this way (Python >= 2.5):
assembled.extend(color for (number, color) in data.iteritems() if number != 3)
For Python 3.x change iteritems to items.
And don't encode type names/descriptions in variable names. It's evil.
| Accessing only part of a dictionary in a for using Python | My example dictionary is this
data_dictionary = {1:'blue',2:'green',3:'red',4:'orange',5:'purple',6:'mauve'}
The data_dictionary can have more elements depending on the incoming data . The first value is what we call a payload_index. I always get payload_index 1 to 4 .
I need to assemble a list from this. Pretty easy:
for payload_index in data_dictionary :
assembled_packet.append(data_dictionary[payload_index])
My problem is I need to always skip the 3rd element. I guess I could do an if but that would be inefficient:
for payload_index in data_dictionary :
if payload_index <> 3:
assembled_packet.append(data_dictionary[payload_index])
I could do it in two steps and do the first three elements but the problem is I cannot figure out how to get the rest since the number of elements after the 3rd varies. I tried using an impossibly high index (below) but that obviously fails:
#get element 1 and two
for index in range(0,3):
assembled_packet.append(data_dictionary[index])
#get element 1 and two
for index in range(4,999):
assembled_packet.append(data_dictionary[index])
Any ideas? Thanks!
| [
"inefficient? That seems like a premature optimisation! Just use normal code:\nfor payload_index in data_dictionary:\n if payload_index != 3:\n assembled_packet.append(data_dictionary[payload_index])\n\nor even better:\nassembled_packet = [data_dictionary[index] for index in data_dictionary if index != 3]... | [
6,
1,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0003292509_python.txt |
Q:
django forms into database
hey guys, im trying to make a volunteer form, that takes info such as name, last name, etc. and i want to save that info into my database (MySQL), so that it can be retrieved later on .
A:
So first you'll need to define a model that will hold this information, in the models.py file something like:
class Volunteer(models.Model):
def __unicode__(self):
return self.fname + self.lname
fname = models.CharField(max_length=200)
lname = models.CharField(max_length=200)
bio = models.TextField(max_length=400)
number = models.CharField(max_length=15)
email = modesl.CharField(max_length=255)
And then a view to receive the POST data from the form, in views.py:
def volunteer_create(request):
if request.method == 'POST'and request.POST['fname'] and request.POST['lname'] and request.POST['email'] (ETC...):
v = Volunteer()
v.fname = request.POST['fname']
v.fname = request.POST['lname']
v.fname = request.POST['email']
v.fname = request.POST['number']
...
v.save()
return HttpResponse("Thank you!") #success!
else
return HttpResponseRedirect("/volunteer_form/") #take them back to the form to fill out missed info
Then you'll need to set up your urls.py to point the form target to this view.
| django forms into database | hey guys, im trying to make a volunteer form, that takes info such as name, last name, etc. and i want to save that info into my database (MySQL), so that it can be retrieved later on .
| [
"So first you'll need to define a model that will hold this information, in the models.py file something like:\nclass Volunteer(models.Model):\n def __unicode__(self):\n return self.fname + self.lname\n fname = models.CharField(max_length=200)\n lname = models.CharField(max_length=200)\n bio = mo... | [
2
] | [] | [] | [
"django",
"django_forms",
"python"
] | stackoverflow_0003293316_django_django_forms_python.txt |
Q:
Command Line in R code
Let me start by saying I am new to programming.
I am hoping to run a python script from the command line within an R script. I am running windows xp but also have a machine that runs Windows 7. I can run the following code without error for the dos-prompt.
cd C:\Documents and Settings\USER\workspace\UGA - Website
python test1.py
I have tried all sorts of different attempts in R using ?system, but am hoping someone can point me to what I am doing wrong. For example, here is just one attempt (it was recommended to use absolute paths)
cmd.1 <- shQuote("C:Python26/python.exe C:/Documents and Settings/USER/Desktop/UGA New Website", type="cmd")
system(cmd.1)
Any guidance will be very much appreciated
A:
Thanks for the help everyone. My issue was a combination of things, but this chunk of code worked.
shell(paste("python", shQuote("C:\\Documents and Settings\\USER\\Desktop\\UGA New Website\\metrics_get.py")))
Many thanks
A:
Add a / after C:, which would make it look like this:
cmd.1 <- shQuote("C:Python26/python.exe C:/Documents and Settings/USER/Desktop/UGA New Website", type="cmd")
system(cmd.1)
A:
Not tested but try this:
cmd.1 <- shQuote('C:\\Python26\\python.exe "C:\\Documents and Settings\\USER\\Desktop\\UGA New Website"', type="cmd")
system(cmd.1)
If this doesn't work, try variations on \, \\ and /, and where you put your quotes.
You could also try a system cd command to change the directory, so you don't need an absolute path.
| Command Line in R code | Let me start by saying I am new to programming.
I am hoping to run a python script from the command line within an R script. I am running windows xp but also have a machine that runs Windows 7. I can run the following code without error for the dos-prompt.
cd C:\Documents and Settings\USER\workspace\UGA - Website
python test1.py
I have tried all sorts of different attempts in R using ?system, but am hoping someone can point me to what I am doing wrong. For example, here is just one attempt (it was recommended to use absolute paths)
cmd.1 <- shQuote("C:Python26/python.exe C:/Documents and Settings/USER/Desktop/UGA New Website", type="cmd")
system(cmd.1)
Any guidance will be very much appreciated
| [
"Thanks for the help everyone. My issue was a combination of things, but this chunk of code worked.\nshell(paste(\"python\", shQuote(\"C:\\\\Documents and Settings\\\\USER\\\\Desktop\\\\UGA New Website\\\\metrics_get.py\")))\n\nMany thanks\n",
"Add a / after C:, which would make it look like this:\ncmd.1 <- shQu... | [
2,
1,
1
] | [] | [] | [
"command_line",
"python",
"r"
] | stackoverflow_0003284301_command_line_python_r.txt |
Q:
Python utf-8 handling
I am using Python 2.6.1 and am having utf-8 related problem with my code. This problem is reproducible with this code:
# -*- coding: utf-8 -*-
import os, sys
import string, time
import codecs, re
bDATA='"Domenick Lombardozzi","Eddie Marsan","Isaach De Bankolé","John Hawkes"'
print (bDATA)
fileObj = codecs.open("btvresp1.txt", "r", "utf-8")
data = fileObj.read()
print (data)
The first print of bDATA works just fine. However, if the same data is in the file btcresp1.txt file, python complains as follows:
cat btvresp2.txt
"Domenick Lombardozzi","Eddie Marsan","Isaach De Bankol?","John Hawkes"
python
Python 2.6.1 (r261:67515, Feb 11 2010, 00:51:29)
[GCC 4.2.1 (Apple Inc. build 5646)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> # -*- coding: utf-8 -*-
...
>>> import os, sys
>>> import string, time
>>> import codecs, re
>>> bDATA='"Domenick Lombardozzi","Eddie Marsan","Isaach De Bankol","John Hawkes"'
>>> print (bDATA)
"Domenick Lombardozzi","Eddie Marsan","Isaach De Bankol","John Hawkes"
>>> fileObj = codecs.open("btvresp2.txt", "r", "utf-8")
>>> data = fileObj.read()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/codecs.py", line 666, in read
return self.reader.read(size)
File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/codecs.py", line 472, in read
newchars, decodedbytes = self.decode(data, self.errors)
UnicodeDecodeError: 'utf8' codec can't decode bytes in position 55-57: invalid data
I am not sure as to why the same data when read from a file causes problems. Can someone shed light as to why this behavior and how I can resolve this?
Thanks in advance!
A:
It looks like the contents of your file are not encoded in UTF-8. Are you sure you didn't save it in some other encoding? When you cat the file, the terminal displays a ? instead of the é, which would also hint at an encoding problem in the file, since your terminal seems to use UTF-8.
Also you have two files, btvresp1.txt and btvresp2.txt. Are you using the correct one?
A:
codecs.open returns an object whose read method returns a unicode string, not an encoded byte string -- that's the whole point of the codecs.open function. So, your print (data), if and when you get to it, will be entirely, drastically different from your working print (bDATA): the latter is printing utf-8 encoded byte strings, the latter will be trying to print unicode objects (which may or may not work depending on your environment -- but, you should be fine on a Terminal.app set to use utf-8 encoding).
However your problems come much earlier: the codecs-produced file-like object asserts that bytes 55 to 57 are not a valid utf-8 encoding. The way to check this is something like...:
>>> f = open("btvresp2.txt", "rb")
>>> print repr(f.read()[50:65])
where I'm also showing a few bytes before and after, for context. If you do that and edit your question to show us the results, we might be able to guess what encoding your file is actually in (the only certainty, at this point, is that it's not in utf-8 encoding).
| Python utf-8 handling | I am using Python 2.6.1 and am having utf-8 related problem with my code. This problem is reproducible with this code:
# -*- coding: utf-8 -*-
import os, sys
import string, time
import codecs, re
bDATA='"Domenick Lombardozzi","Eddie Marsan","Isaach De Bankolé","John Hawkes"'
print (bDATA)
fileObj = codecs.open("btvresp1.txt", "r", "utf-8")
data = fileObj.read()
print (data)
The first print of bDATA works just fine. However, if the same data is in the file btcresp1.txt file, python complains as follows:
cat btvresp2.txt
"Domenick Lombardozzi","Eddie Marsan","Isaach De Bankol?","John Hawkes"
python
Python 2.6.1 (r261:67515, Feb 11 2010, 00:51:29)
[GCC 4.2.1 (Apple Inc. build 5646)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> # -*- coding: utf-8 -*-
...
>>> import os, sys
>>> import string, time
>>> import codecs, re
>>> bDATA='"Domenick Lombardozzi","Eddie Marsan","Isaach De Bankol","John Hawkes"'
>>> print (bDATA)
"Domenick Lombardozzi","Eddie Marsan","Isaach De Bankol","John Hawkes"
>>> fileObj = codecs.open("btvresp2.txt", "r", "utf-8")
>>> data = fileObj.read()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/codecs.py", line 666, in read
return self.reader.read(size)
File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/codecs.py", line 472, in read
newchars, decodedbytes = self.decode(data, self.errors)
UnicodeDecodeError: 'utf8' codec can't decode bytes in position 55-57: invalid data
I am not sure as to why the same data when read from a file causes problems. Can someone shed light as to why this behavior and how I can resolve this?
Thanks in advance!
| [
"It looks like the contents of your file are not encoded in UTF-8. Are you sure you didn't save it in some other encoding? When you cat the file, the terminal displays a ? instead of the é, which would also hint at an encoding problem in the file, since your terminal seems to use UTF-8.\nAlso you have two files, bt... | [
2,
1
] | [] | [] | [
"python",
"python_2.x",
"unicode",
"utf_8"
] | stackoverflow_0003293055_python_python_2.x_unicode_utf_8.txt |
Q:
How to walk a tar.gz file that contains zip files without extraction
I have a large tar.gz file to analyze using a python script. The tar.gz file contains a number of zip files which might embed other .gz files in it. Before extracting the file, I would like to walk through the directory structure within the compressed files to see if certain files or directories are present. By looking at tarfile and zipfile module I don't see any existing function that allow me to get a table of content of a zip file within a tar.gz file.
Appreciate your help,
A:
You can't get at it without extracting the file. However, you don't need to extract it to disk if you don't want to. You can use the tarfile.TarFile.extractfile method to get a file-like object that you can then pass to tarfile.open as the fileobj argument. For example, given these nested tarfiles:
$ cat bar/baz.txt
This is bar/baz.txt.
$ tar cvfz bar.tgz bar
bar/
bar/baz.txt
$ tar cvfz baz.tgz bar.tgz
bar.tgz
You can access files from the inner one like so:
>>> import tarfile
>>> baz = tarfile.open('baz.tgz')
>>> bar = tarfile.open(fileobj=baz.extractfile('bar.tgz'))
>>> bar.extractfile('bar/baz.txt').read()
'This is bar/baz.txt.\n'
and they're only ever extracted to memory.
A:
I suspect that this is not possible and that you'll have to program it manually.
.tar.gz files are first tar'd then gzipped with what is essentially two different applications, in succession. To access the tar file, you're probably going to have to un-gzip it, first.
Also, once you do have access to the tar file after ungzipping it, it does not do random-access well. There is no central repository in the tar file that lists the contents.
| How to walk a tar.gz file that contains zip files without extraction | I have a large tar.gz file to analyze using a python script. The tar.gz file contains a number of zip files which might embed other .gz files in it. Before extracting the file, I would like to walk through the directory structure within the compressed files to see if certain files or directories are present. By looking at tarfile and zipfile module I don't see any existing function that allow me to get a table of content of a zip file within a tar.gz file.
Appreciate your help,
| [
"You can't get at it without extracting the file. However, you don't need to extract it to disk if you don't want to. You can use the tarfile.TarFile.extractfile method to get a file-like object that you can then pass to tarfile.open as the fileobj argument. For example, given these nested tarfiles:\n$ cat bar/baz.... | [
6,
1
] | [] | [] | [
"python"
] | stackoverflow_0003293809_python.txt |
Q:
algorithm design in python
I need to know about the uniform cost search algorithm. In the uniform cost solution, we find a node that has the lowest cost. But there can be other nodes that have less cost than the previous one.Do we need use some buffer to keep the lowest value in that , so that we can get the lowest cost from the whole tree??I need some pseducode to implement this algorithm.
A:
You can use the built in function min()
>>min([3, 2, 4, 1])
1
A:
How is tree built, is lowest cost some function of traversing the tree or only dependent of leaf values? Example input and output would be nice.
This Guido's document could be good starting point:
http://python.org/doc/essays/graphs.html
A:
http://en.wikipedia.org/wiki/Uniform-cost_search
See ref for how to use a priority queue.
| algorithm design in python | I need to know about the uniform cost search algorithm. In the uniform cost solution, we find a node that has the lowest cost. But there can be other nodes that have less cost than the previous one.Do we need use some buffer to keep the lowest value in that , so that we can get the lowest cost from the whole tree??I need some pseducode to implement this algorithm.
| [
"You can use the built in function min()\n>>min([3, 2, 4, 1])\n1\n\n",
"How is tree built, is lowest cost some function of traversing the tree or only dependent of leaf values? Example input and output would be nice.\nThis Guido's document could be good starting point:\nhttp://python.org/doc/essays/graphs.html\n"... | [
3,
0,
0
] | [] | [] | [
"algorithm",
"python"
] | stackoverflow_0003293686_algorithm_python.txt |
Q:
Problem with nested for loops
I have to read two csv file, combine the row and write the result in a third csv file.
first csv file have five row with user name in the first colunm.( 25 colunm in total)
second csv file have five row with user name in the first colunm and user id in second colunm.(only 2 colunm)
the third csv file will contain username+useridand all remaining 24 column of first file.
data = open(os.path.join("c:\\transales","AccountID+ContactID-source1.csv"),"rb").read().replace(";",",").replace("\0","")
data2 = open(os.path.join("c:\\transales","AccountID+ContactID-source2.csv"),"rb").read().replace(";",",").replace("\0","")
i = 0
j = 0
Info_Client_source1=StringIO.StringIO(data)
Info_Client_source2=StringIO.StringIO(data2)
for line in csv.reader(Info_Client_source1):
name= line[1]
i=i+1
print "i= ",i
for line2 in csv.reader(Info_Client_source2):
print "j = :",j
j=j+1
if line[1] == line2[2]:
continue
the result:
i= 1
j = : 0
j = : 1
j = : 2
j = : 3
j = : 4
j = : 5
j = : 6
i= 2
i= 3
i= 4
i= 5
i= 6
i= 7
why after i=2 the seconf for loop do nothing ??
I expect to have i=2, j=0 to 6, i=3 j=0 ro 6 ,...
A:
It's because you read off the entire contents of your StringIO object in the first pass, leaving the cursor at the end of the string. On the second pass, there's nothing left to read, so you end up with an empty reader.
Also, it's probably not a great idea to call csv.reader() for every inner iteration of your loop. Let me rephrase your code and then explain my changes:
data = open(os.path.join("c:\\transales","AccountID+ContactID-source1.csv"),"rb").read().replace(";",",").replace("\0","")
data2 = open(os.path.join("c:\\transales","AccountID+ContactID-source2.csv"),"rb").read().replace(";",",").replace("\0","")
source1 = csv.reader(data)
source2 = csv.reader(data2)
for line in source1:
name= line[1]
i=i+1
print "i= ",i
data2.seek(0)
for line2 in source2:
print "j = :",j
j=j+1
if line[1] == line2[2]:
continue
Changes:
I've removed the extraneous step of creating a StringIO object; you can just pass a standard file handle to csv.reader() and it'll work fine. (If there's a reason for creating those StringIO objects, feel free to add that back in...)
I've moved the initialization of the readers outside the for loop. While it'd be alright for source1 to be initialized in the outer loop, having source2 initialized in the inner loop is pretty inefficient.
Most importantly, calling data2.seek(0) resets the cursor on the underlying file handle, which will allow you to read from data2 repeatedly.
Here's a similar question on SO, which might better illustrate the idea:
StackOverflow: Reading from CSVs in Python repeatedly?
Hope it helps. :)
A:
Because once the csv.reader reaches the end of the file, it will never execute any more.
For a small dataset like this you can easily read your data into a list or dictionary and iterate over that.
A:
More pythonic would be:
filename1 = os.path.join('c:\\transales', 'AccountID+ContactID-source1.csv')
filename2 = os.path.join('c:\\transales', 'AccountID+ContactID-source2.csv')
with open(filename1, 'rb') as file1, open(filename2, 'rb') as file2:
csv1 = csv.reader(file1, delimiter=';')
csv2 = csv.reader(file2, delimiter=';')
lookup = { line[0] : line[1:] for line in csv1 }
joined = [ [uname, uid] + lookup[uname] for (uname, uid) in csv2 ]
print joined
(assuming Python version 2.7)
BTW: first column has index 0, not 1.
A:
It could be an easy fix...try moving your declaration for Info_Client_source2 into the first loop:
Info_Client_source1=StringIO.StringIO(data)
for line in csv.reader(Info_Client_source1):
Info_Client_source2=StringIO.StringIO(data2)
name= line[1]
i=i+1
print "i= ",i
for line2 in csv.reader(Info_Client_source2):
print "j = :",j
j=j+1
if line[1] == line2[2]:
continue
| Problem with nested for loops | I have to read two csv file, combine the row and write the result in a third csv file.
first csv file have five row with user name in the first colunm.( 25 colunm in total)
second csv file have five row with user name in the first colunm and user id in second colunm.(only 2 colunm)
the third csv file will contain username+useridand all remaining 24 column of first file.
data = open(os.path.join("c:\\transales","AccountID+ContactID-source1.csv"),"rb").read().replace(";",",").replace("\0","")
data2 = open(os.path.join("c:\\transales","AccountID+ContactID-source2.csv"),"rb").read().replace(";",",").replace("\0","")
i = 0
j = 0
Info_Client_source1=StringIO.StringIO(data)
Info_Client_source2=StringIO.StringIO(data2)
for line in csv.reader(Info_Client_source1):
name= line[1]
i=i+1
print "i= ",i
for line2 in csv.reader(Info_Client_source2):
print "j = :",j
j=j+1
if line[1] == line2[2]:
continue
the result:
i= 1
j = : 0
j = : 1
j = : 2
j = : 3
j = : 4
j = : 5
j = : 6
i= 2
i= 3
i= 4
i= 5
i= 6
i= 7
why after i=2 the seconf for loop do nothing ??
I expect to have i=2, j=0 to 6, i=3 j=0 ro 6 ,...
| [
"It's because you read off the entire contents of your StringIO object in the first pass, leaving the cursor at the end of the string. On the second pass, there's nothing left to read, so you end up with an empty reader.\nAlso, it's probably not a great idea to call csv.reader() for every inner iteration of your lo... | [
6,
1,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0003292563_python.txt |
Q:
How to insert dynamic string in wxpython html window? (wx.html.htmlwindow)
I am making a html window in wxpython and want to print it. Before that I need to enter user input (such as his name or such things ) in the html page. How to do that nicely?
Thanks in advance,
A:
Use Jinja2.
Create an HTML template with variables in the places where you need to display user-entered data. Then render the template with a dictionary containing that data.
Here, I'll write you a helper module.
# templates.py
import jinja2 as jinja
def create_env():
loader = jinja.FileSystemLoader(PATH_TO_YOUR_TEMPLATES)
env = jinja.Environment(loader=loader)
return env
env = create_env()
def render(name, context=None):
context = context or {}
return env.get_template(name).render(context)
# my_module.py
import templates
data = {
'first_name': 'John',
'last_name': 'Smith',
}
html = templates.render('my_template.html', data)
# do something with html string
# my_template.html
<p>Hello, {{ first_name }} {{ last_name }}. This is a template.</p>
A:
There are a couple of approaches that come to my mind. If it's like a form letter where only specific parts will be replaced, then you can just should that to the user and have some text controls for them to fill in. Something like this:
Dear #NAME,
Thank you for contacting #COMPANY, blah blah blah
And then have a text control for each of the replaceable parts. The other method would be to use the RichTextCtrl's Save As HTML functionality. See the wxPython Demo application for an example.
| How to insert dynamic string in wxpython html window? (wx.html.htmlwindow) | I am making a html window in wxpython and want to print it. Before that I need to enter user input (such as his name or such things ) in the html page. How to do that nicely?
Thanks in advance,
| [
"Use Jinja2.\nCreate an HTML template with variables in the places where you need to display user-entered data. Then render the template with a dictionary containing that data.\nHere, I'll write you a helper module.\n# templates.py\nimport jinja2 as jinja\n\ndef create_env():\n loader = jinja.FileSystemLoader(P... | [
1,
0
] | [] | [] | [
"python",
"tags",
"wxpython"
] | stackoverflow_0003287455_python_tags_wxpython.txt |
Q:
Multiple select() syscalls from one thread in Python
I'm using a couple of Python libraries, and they both use a select() syscall. I was wondering if it was safe to have two select() syscalls from within the same thread (assuming there are no shared descriptors between them)?
A:
Well, within a single thread you can't really have "two select() syscalls", because the first call has to end before you can start the second call. But yes, it's perfectly safe, even if they do share descriptors: both calls create new objects to return, there's no variable re-use that might affect them (like it might with static variables in C.)
Even if you had multiple threads it would be fine, as the select module is careful to hold the GIL until the actual select call. In that case you do have to avoid sharing descriptors, though.
A:
It seems unlikely to me that this is going to work well, but it depends on the libraries, and what you need them to do. Some thoughts:
The libraries might provide APIs to open up the select loop, either by letting you plug into their select loop with your own file descriptors, or by providing APIs that return their own selectors (so that you can wire them into your own select loop), or both. I'd look into whether these libraries have such APIs.
Assuming no such APIs exist, then:
If either of the libraries implements the select loop such that it never returns from the loop, then you're totally out of luck -- you'll never be able to go one that library's select loop into the other library's select loop.
If either of the libraries call select() without a timeout value, you're probably not going to get good results. Without a timeout, the library can (and probably will) cause the thread to block indefinitely.
If either library provides services that work best with low latency (for example, GUIs generally need to respond quickly to events), then having both libraries on the same thread is probably not a good idea.
The libraries may provide APIs that you can use to send messages that they'd pick up within the select loop. If they do, then this makes multi-threading that much easier to implement. If they don't, it may make even single-threading that much harder to manage. (Are you sure that multi-threading isn't an option?)
Are you sure that your choice of libraries is appropriate for your app? If they're custom (or open source) libraries, can they be redesigned to make them more select-friendly?
| Multiple select() syscalls from one thread in Python | I'm using a couple of Python libraries, and they both use a select() syscall. I was wondering if it was safe to have two select() syscalls from within the same thread (assuming there are no shared descriptors between them)?
| [
"Well, within a single thread you can't really have \"two select() syscalls\", because the first call has to end before you can start the second call. But yes, it's perfectly safe, even if they do share descriptors: both calls create new objects to return, there's no variable re-use that might affect them (like it ... | [
2,
0
] | [] | [] | [
"python",
"select",
"system_calls"
] | stackoverflow_0003294349_python_select_system_calls.txt |
Q:
Reading files and writing to database in django
I have a Django app that opens a file, continuously reads it, and at the same time writes data to a Postgres database. My issue is that whenever I open a file,
file = open(filename, 'r')
I am unable to also create new things in the database,
Message.objects.create_message(sys, msg)
That should create a database entry with two strings. However, nothing seems to happen and I am presented with no errors :( If I decide to close the file, file.close(), before I write to the database everything is fine. My problem is that I need that file open to create my objects. Does anyone have a solution for this? Thanks.
EDIT
Here's some more of my code. Basically I have the following snippet following the end of a file and then writing to the database as it gets information.
file.seek(0,2)
while True:
line = file.readline()
if not line:
time.sleep(1)
continue
Message.objects.create_message(sys, line)
EDIT 2
Got this to work finally but I'm not sure why. I'd love to understand why this worked:
str1ng = line[0:len(line)-1]
Message.objects.create_message(sys, str1ng)
Some how there is a difference between that string and the string gathered from file.readline().
Any ideas?
A:
try this:
file = open(filename, 'r')
fileContents = file.read()
file.close()
A:
Have you tried linecache? Something like this might work (not tested).
import linecache
i = 0
go = True
file = ...
while (go == True):
out = linecache.getline(file,i)
...process out...
i = i+1
if i % 100 == 0:
# check for cache update every 100 lines
linecache.checkcache(file)
if ( some eof condition):
go = False
linecache.clearcache()
| Reading files and writing to database in django | I have a Django app that opens a file, continuously reads it, and at the same time writes data to a Postgres database. My issue is that whenever I open a file,
file = open(filename, 'r')
I am unable to also create new things in the database,
Message.objects.create_message(sys, msg)
That should create a database entry with two strings. However, nothing seems to happen and I am presented with no errors :( If I decide to close the file, file.close(), before I write to the database everything is fine. My problem is that I need that file open to create my objects. Does anyone have a solution for this? Thanks.
EDIT
Here's some more of my code. Basically I have the following snippet following the end of a file and then writing to the database as it gets information.
file.seek(0,2)
while True:
line = file.readline()
if not line:
time.sleep(1)
continue
Message.objects.create_message(sys, line)
EDIT 2
Got this to work finally but I'm not sure why. I'd love to understand why this worked:
str1ng = line[0:len(line)-1]
Message.objects.create_message(sys, str1ng)
Some how there is a difference between that string and the string gathered from file.readline().
Any ideas?
| [
"try this:\nfile = open(filename, 'r')\nfileContents = file.read()\nfile.close()\n\n",
"Have you tried linecache? Something like this might work (not tested).\nimport linecache\n\ni = 0\ngo = True\nfile = ...\nwhile (go == True):\n out = linecache.getline(file,i)\n ...process out...\n i = i+1\n if i % 100... | [
3,
2
] | [] | [] | [
"database",
"django",
"file",
"file_io",
"python"
] | stackoverflow_0003293951_database_django_file_file_io_python.txt |
Q:
Facebook Connect via Javascript doesn't close and doesn't pass session id
I'm trying to authenticate users via Facebook Connect using a custom Javascript button:
<form>
<input type="button" value="Connect with Facebook" onclick="window.open('http://www.facebook.com/login.php?api_key=XXXXX&extern=1&fbconnect=1&req_perms=publish_stream,email&return_session=0&v=1.0&next=http%3A%2F%2Fwww.example.com%2Fxd_receiver.htm&fb_connect=1&cancel_url=http%3A%2F%2Fwww.example.com%2Fregister%2Fcancel', '_blank', 'top=442,width=480,height=460,resizable=yes', true)" onlogin='window.location="/register/step2"' />
</form>
I am able to authenticate users. However after authentication, the popup window just stays open and the main window is not directed anywhere. In fact, it is the popup window that goes to "/register/step2"
How can I get the login window to close as expected, and to pass the facebook session id to /register/step2?
Thanks!
A:
Looks like you might be using the old JS SDK (your code sample is confusing, but the onlogin handler makes me think you are using some SDK). Do yourself a favor and switch to the new JS SDK. Then use XFBML and the <fb:login-button>:
<fb:login-button perms="read_stream"></fb:login-button>
It will make your life much easier and do most of the hard work for you.
A:
Are your Facebook application's settings set to redirect back to a Django-enabled URL? For example, in my URLconf I have:
url(r'^facebook/setup/$', facebook_complete_reg, name="facebook_setup"),
The 'facebook_complete_reg' view looks something like the 'setup' view in django-facebookconnect's source. I would use that file to make sure that your "return from Facebook" view does the correct action.
Finally, make sure that your templates load the correct JavaSript. In my main template I have the following loaded:
{% load facebook_tags %}
{% facebook_js %}
{% initialize_facebook_connect %}
This would enable you to use the template tag 'show_connect_button', which is what I assume you are doing.
The only other possibility I can think of is that you are using a JavaScript blocker or some similar browser plugin. Can you post some code?
Ryan
A:
The thing is that, you've to close the popup window and reload the main window yourself by coding.
There is a step by step tutorial to do this.
A:
you can use xd_receiver.html file with following code :
<script src="http://static.ak.connect.facebook.com/js/api_lib/v0.4/XdCommReceiver.js" type="text/javascript"></script>
put it in template folder and then put this code where you want the button should be in your app page :
<script src="http://static.ak.facebook.com/js/api_lib/v0.4/FeatureLoader.js.php/en_US" type="text/javascript">
</script>
<script type="text/javascript">
FB.init("API_KEY", "/xd_receiver.html",{ permsToRequestOnConnect : "email,publish_stream,photo_upload,offline_access" });
function facebook_login() {
window.location ="/register/step2"
}
</script>
<fb:login-button onlogin="facebook_login();"></fb:login-button>
and add one url to get xd_receiver and create view for it as well
hope this will help you
Thanks
Ansh J
| Facebook Connect via Javascript doesn't close and doesn't pass session id | I'm trying to authenticate users via Facebook Connect using a custom Javascript button:
<form>
<input type="button" value="Connect with Facebook" onclick="window.open('http://www.facebook.com/login.php?api_key=XXXXX&extern=1&fbconnect=1&req_perms=publish_stream,email&return_session=0&v=1.0&next=http%3A%2F%2Fwww.example.com%2Fxd_receiver.htm&fb_connect=1&cancel_url=http%3A%2F%2Fwww.example.com%2Fregister%2Fcancel', '_blank', 'top=442,width=480,height=460,resizable=yes', true)" onlogin='window.location="/register/step2"' />
</form>
I am able to authenticate users. However after authentication, the popup window just stays open and the main window is not directed anywhere. In fact, it is the popup window that goes to "/register/step2"
How can I get the login window to close as expected, and to pass the facebook session id to /register/step2?
Thanks!
| [
"Looks like you might be using the old JS SDK (your code sample is confusing, but the onlogin handler makes me think you are using some SDK). Do yourself a favor and switch to the new JS SDK. Then use XFBML and the <fb:login-button>:\n<fb:login-button perms=\"read_stream\"></fb:login-button>\n\nIt will make your li... | [
1,
0,
0,
0
] | [] | [] | [
"facebook",
"javascript",
"python"
] | stackoverflow_0002715826_facebook_javascript_python.txt |
Q:
Using csv modele to extract specific lines of text from a larger file
So I'm extracting the lines that I want from this larger file using this program:
import csv
name = ['NAMETHEFIRST,' 'NAMEANOTHERNAME ']
data = csv.reader(open('C:\\bigfile.csv'))
with open('C:\\smalldataset.xcl','w') as outf:
csv.writer(outf).writerows(l for l in data if l[0] in name)
The program runs. However I am only getting the line of data from NAMETHEFIRST and I get no data from NAMETHEOTHERNAME written to my small dataset file. This works exactly as I want printing all relevant info from the large data set of the line of data for NAME THE FIRST but i get no information from the second nametheother name written to the smaller file. Why isn't this working?
A:
This is a list with one string:
['NAMETHEFIRST,' 'NAMEANOTHERNAME ']
This is a list with two strings:
['NAMETHEFIRST', 'NAMEANOTHERNAME ']
Note the placement of the comma.
Also note that your second string has a space at the end.
A:
This line of code
name = ['NAMETHEFIRST,' 'NAMEANOTHERNAME ']
is equivalent to
name = ['NAMETHEFIRST,NAMEANOTHERNAME ']
because Python follows C in concatenating adjacent string constants at compile time.
You say """I am only getting the line of data from NAMETHEFIRST and I get no data from NAMETHEOTHERNAME written to my small dataset file""" -- however the code that you show will NOT produce that result; it will select only lines that start with
"NAMETHEFIRST,NAMEANOTHERNAME ",
You will get the stated result only if that line is actually:
name = ['NAMETHEFIRST', 'NAMEANOTHERNAME ']
and that is presumably because the second name in the file doesn't have a trailing space as above.
Other problems:
csv.writer(outf).writerows(l for l in data if l[0] in name) is trying to be a bit too clever. If you break it down into bite-size chunks, you can much more easily use a debugger or just print statements to show you what is actually happening.
Try this:
print len(name), name
data = csv.reader(open('C:\\bigfile.csv', 'rb')) # ALWAYS open csv files in BINARY mode
with open('C:\\smalldataset.xcl','wb') as outf: # ALWAYS open csv files in BINARY mode
writer = csv.writer(outf)
for row_index, row in enumerate (data): # don't use 'l' as a variable name
print row_index + 1, row
if row[0] in name:
writer.writerow(row)
| Using csv modele to extract specific lines of text from a larger file | So I'm extracting the lines that I want from this larger file using this program:
import csv
name = ['NAMETHEFIRST,' 'NAMEANOTHERNAME ']
data = csv.reader(open('C:\\bigfile.csv'))
with open('C:\\smalldataset.xcl','w') as outf:
csv.writer(outf).writerows(l for l in data if l[0] in name)
The program runs. However I am only getting the line of data from NAMETHEFIRST and I get no data from NAMETHEOTHERNAME written to my small dataset file. This works exactly as I want printing all relevant info from the large data set of the line of data for NAME THE FIRST but i get no information from the second nametheother name written to the smaller file. Why isn't this working?
| [
"This is a list with one string:\n['NAMETHEFIRST,' 'NAMEANOTHERNAME ']\n\nThis is a list with two strings:\n['NAMETHEFIRST', 'NAMEANOTHERNAME ']\n\nNote the placement of the comma.\nAlso note that your second string has a space at the end.\n",
"This line of code\nname = ['NAMETHEFIRST,' 'NAMEANOTHERNAME ']\n\nis ... | [
1,
1
] | [] | [] | [
"csv",
"python"
] | stackoverflow_0003292488_csv_python.txt |
Q:
simulate private variables in python
Possible Duplicate:
private members in python
I've got few variables I really want to hide because they do not belong outside my class. Also all such non-documented variables render inheritance useless.
How do you hide such variables you don't want to show outside your object?
To clarify why I need private variables, first one example where inability to hide variables is just an inconvenience, then another that's really a problem:
class MyObject(object):
def __init__(self, length):
self.length = length
def __len__(self):
return length
item = MyObject(5)
item.length
len(item)
So I've got two ways to access 'length' of the item here. It's only an inconvenience and nothing horrible.
from wares import ImplementationSpecific
class MyThing(object):
def __init__(self):
self.__no_access_even_if_useful = ImplementationSpecific()
def restricted_access(self):
return self.__no_access_even_if_useful.mutable_value
thing = MyThing()
thing.restricted_access()
thing._MyThing__no_access_even_if_useful.something_useful_for_someone()
So say I want to change the implementation some day.. The chances are it'll break something unless I've really buried the implementation specifics.
I'll take it as anyone could program. That 'anyone' can find an useful thing from my implementation specifics and use it, even if I'd have strongly discouraged of doing so! It'd be much easier to just say: "no, it's not there, try something else."
A:
Private variables is covered in the Python documentation:
9.6. Private Variables
“Private” instance variables that cannot be accessed except from inside an object don’t exist in Python. However, there is a convention that is followed by most Python code: a name prefixed with an underscore (e.g. _spam) should be treated as a non-public part of the API (whether it is a function, a method or a data member). It should be considered an implementation detail and subject to change without notice.
Summary: use an underscore before the name.
A:
From the Python docs:
“Private” instance variables that cannot be accessed except from inside an object don’t exist in Python. However, there is a convention that is followed by most Python code: a name prefixed with an underscore (e.g. _spam) should be treated as a non-public part of the API (whether it is a function, a method or a data member). It should be considered an implementation detail and subject to change without notice.
| simulate private variables in python |
Possible Duplicate:
private members in python
I've got few variables I really want to hide because they do not belong outside my class. Also all such non-documented variables render inheritance useless.
How do you hide such variables you don't want to show outside your object?
To clarify why I need private variables, first one example where inability to hide variables is just an inconvenience, then another that's really a problem:
class MyObject(object):
def __init__(self, length):
self.length = length
def __len__(self):
return length
item = MyObject(5)
item.length
len(item)
So I've got two ways to access 'length' of the item here. It's only an inconvenience and nothing horrible.
from wares import ImplementationSpecific
class MyThing(object):
def __init__(self):
self.__no_access_even_if_useful = ImplementationSpecific()
def restricted_access(self):
return self.__no_access_even_if_useful.mutable_value
thing = MyThing()
thing.restricted_access()
thing._MyThing__no_access_even_if_useful.something_useful_for_someone()
So say I want to change the implementation some day.. The chances are it'll break something unless I've really buried the implementation specifics.
I'll take it as anyone could program. That 'anyone' can find an useful thing from my implementation specifics and use it, even if I'd have strongly discouraged of doing so! It'd be much easier to just say: "no, it's not there, try something else."
| [
"Private variables is covered in the Python documentation:\n\n9.6. Private Variables\n“Private” instance variables that cannot be accessed except from inside an object don’t exist in Python. However, there is a convention that is followed by most Python code: a name prefixed with an underscore (e.g. _spam) should b... | [
15,
11
] | [] | [] | [
"oop",
"private",
"python"
] | stackoverflow_0003294764_oop_private_python.txt |
Q:
Display custom labels for values in the Django Admin Site
One of my models has a 'status' field which is only ever modified in code. It is an integer from 1 to 6 (although this may change in the future).
However, in the Admin site, I would like to display a label for this data. So, instead of displaying '5', I would like it to say 'Error'. This means I would be able to easily filter the objects in the database that have the status 'Error' and also my colleagues who don't know what each status means as they are not involved in coding, can use the admin site to its full.
I don't know if I am going the right way about this or if it is even possible, but I would appreciate any help you can give. I would rather not change how the status is stored as it would require a big re-write of some parts of our system. In hindsight I guess it was a bad way to do it, but I didn't think the field would matter as much as it does.
A:
Consider to use choices. Anyway you can customize lots of things in django-admin, just read the docs:
http://docs.djangoproject.com/en/1.2/ref/contrib/admin/#django.contrib.admin.ModelAdmin.list_display
http://docs.djangoproject.com/en/1.2/ref/contrib/admin/#django.contrib.admin.ModelAdmin.form
A:
You could create a custom field type that overrides to_python and get_prep_value to store integers in the db but use string values within Python:
http://docs.djangoproject.com/en/dev/howto/custom-model-fields/#django.db.models.django.db.models.Field
| Display custom labels for values in the Django Admin Site | One of my models has a 'status' field which is only ever modified in code. It is an integer from 1 to 6 (although this may change in the future).
However, in the Admin site, I would like to display a label for this data. So, instead of displaying '5', I would like it to say 'Error'. This means I would be able to easily filter the objects in the database that have the status 'Error' and also my colleagues who don't know what each status means as they are not involved in coding, can use the admin site to its full.
I don't know if I am going the right way about this or if it is even possible, but I would appreciate any help you can give. I would rather not change how the status is stored as it would require a big re-write of some parts of our system. In hindsight I guess it was a bad way to do it, but I didn't think the field would matter as much as it does.
| [
"Consider to use choices. Anyway you can customize lots of things in django-admin, just read the docs:\nhttp://docs.djangoproject.com/en/1.2/ref/contrib/admin/#django.contrib.admin.ModelAdmin.list_display\nhttp://docs.djangoproject.com/en/1.2/ref/contrib/admin/#django.contrib.admin.ModelAdmin.form\n",
"You could ... | [
4,
0
] | [] | [] | [
"django",
"django_admin",
"django_models",
"python"
] | stackoverflow_0003294855_django_django_admin_django_models_python.txt |
Q:
Browser-based MMO best-practice
I am developing an online browser game, based on google maps, with Django backend, and I am getting close to the point where I need to make a decision on how to implement the (backend) timed events - i.e. NPC possession quantity raising (e.g. city population should grow based on some variables - city size, application speed).
The possible solutions I found are:
Putting the queued actions in a table and processing them along with every request.
Problems: huge overhead, harder to implement
Using cron or something similar
Problem: this is an external tool, and I want as little external tools as possible.
Any other solutions?
A:
Running a scheduled task to perform updates in your game, at any interval, will give you a spike of heavy database use. If your game logic relies on all of those database values to be up to date at the same time (which is very likely, if you're running an interval based update), you'll have to have scheduled downtime for as long as that cronjob is running. When that time becomes longer, as your player base grows, this becomes extremely annoying.
If you're trying to reduce database overhead, you should store values with their last update time and growth rates, and only update those rows when the quantity or rate of growth changes.
For example, a stash of gold, that grows at 5 gold per minute, only updates when a player withdraws gold from it. When you need to know the current amount, it is calculated based on the last update time, the current time, the amount stored at the last update, and the rate of growth.
Data that changes over time, without requiring interaction, does not belong in the database. It belongs in the logic end of your game. When a player performs an activity you need to remember, or a calculation becomes too cumbersome to generate again, that's when you store it.
A:
If I understand your question correct, you should look at Celery which is a distributed task queue. http://ask.github.com/celery/
| Browser-based MMO best-practice | I am developing an online browser game, based on google maps, with Django backend, and I am getting close to the point where I need to make a decision on how to implement the (backend) timed events - i.e. NPC possession quantity raising (e.g. city population should grow based on some variables - city size, application speed).
The possible solutions I found are:
Putting the queued actions in a table and processing them along with every request.
Problems: huge overhead, harder to implement
Using cron or something similar
Problem: this is an external tool, and I want as little external tools as possible.
Any other solutions?
| [
"Running a scheduled task to perform updates in your game, at any interval, will give you a spike of heavy database use. If your game logic relies on all of those database values to be up to date at the same time (which is very likely, if you're running an interval based update), you'll have to have scheduled downt... | [
5,
2
] | [] | [] | [
"cron",
"django",
"python"
] | stackoverflow_0003294682_cron_django_python.txt |
Q:
Calling a python function over the web using AJAX?
I want to send a string to a python function I have written and want to display the return value of that function on a web page. After some initial research, WSGI sounds like the way to go. Preferably, I don't want to use any fancy frameworks. I'm pretty sure some one has done this before. Need some reassurance. Thanks!
A:
You can try Flask, it's a framework, but tiny and 100% WSGI 1.0 compliant.
from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello():
return "Hello World!"
if __name__ == "__main__":
app.run()
Note: Flask sits on top of Werkzeug and may need other libraries like sqlalchemy for DB work or jinja2 for templating.
A:
You can use cgi...
#!/usr/bin/env python
import cgi
def myMethod(some_parameter):
// do stuff
return something
form = cgi.FieldStorage()
my_passed_in_param = form.getvalue("var_passed_in")
my_output = myMethod(my_passed_in_param)
print "Content-Type: text/html\n"
print my_output
This is just a very simple example. Also, your content-type may be json or plain text... just wanted to show an example.
A:
In addition to Flask, bottle is also simple and WSGI compliant:
from bottle import route, run
@route('/hello/:name')
def hello(name):
return 'Hello, %s' % name
run(host='localhost', port=8080)
# --> http://localhost:8080/hello/world
| Calling a python function over the web using AJAX? | I want to send a string to a python function I have written and want to display the return value of that function on a web page. After some initial research, WSGI sounds like the way to go. Preferably, I don't want to use any fancy frameworks. I'm pretty sure some one has done this before. Need some reassurance. Thanks!
| [
"You can try Flask, it's a framework, but tiny and 100% WSGI 1.0 compliant.\nfrom flask import Flask\napp = Flask(__name__)\n\n@app.route(\"/\")\ndef hello():\n return \"Hello World!\"\n\nif __name__ == \"__main__\":\n app.run()\n\nNote: Flask sits on top of Werkzeug and may need other libraries like sqlalche... | [
5,
3,
3
] | [] | [] | [
"ajax",
"python",
"wsgi"
] | stackoverflow_0003294929_ajax_python_wsgi.txt |
Q:
modwsgi - Precompiled Binaries for Python 2.4?
I'm trying to install Django using Apache and modwsgi on Windows XP. The problem is our whole development environment uses Python 2.4.
This page explains how to install modwsgi on Windows but it doesn't link to any precompiled binaries for Python 2.4.
Anyone know of anything, or a workaround?
A:
Follow the instructions in that page about compiling from source code. Simply copy the makefile for 'win32-ap22py26.mk', calling it 'win32-ap22py24.mk' and make changes to paths to the compiler. This is required as Python 2.4 requires an ancient version of Microsoft C/C++ compiler (VS2003 I think). If you don't already have that compiler you will be out of luck as free express version for that no longer available (if it ever was).
Hopefully that will be enough for it to work, if not and compiler complains about unknown options, you may have to tweak the makefile compiler flags.
If you get it working, please submit back via mod_wsgi issue tracker the modified makefile for possible inclusion in future mod_wsgi version.
| modwsgi - Precompiled Binaries for Python 2.4? | I'm trying to install Django using Apache and modwsgi on Windows XP. The problem is our whole development environment uses Python 2.4.
This page explains how to install modwsgi on Windows but it doesn't link to any precompiled binaries for Python 2.4.
Anyone know of anything, or a workaround?
| [
"Follow the instructions in that page about compiling from source code. Simply copy the makefile for 'win32-ap22py26.mk', calling it 'win32-ap22py24.mk' and make changes to paths to the compiler. This is required as Python 2.4 requires an ancient version of Microsoft C/C++ compiler (VS2003 I think). If you don't al... | [
1
] | [] | [] | [
"apache",
"django",
"mod_wsgi",
"python",
"windows_xp"
] | stackoverflow_0003293194_apache_django_mod_wsgi_python_windows_xp.txt |
Q:
color plot animation with play, pause, stop cabability using Tkinter with pylab/matplotlib embedding: can't update figure/canvas?
I've looked but didn't find previous questions specific enough, so sorry if this is repeated.
Goal: GUI to continuously update figure with different matrix data plotted by pylab's pcolor such that there is a running animation. But user should be able to play, pause, stop animation by Tkinter widget buttons.
Before I get an answer for matplotlib using set_array(), draw(), and canvas.manager.after() ..., I have working code that enables me to start animation, but i can't figure out how to stop or pause it, when just using matplotlib capabilities, so I decided to use Tkinter straigt up instead of matplotlib's Tcl/Tk wrapper. Here is working code just for kicks though in case someone has any ideas. But continue for real question.
# mouse click the "Play" button widget to play animation
# PROBLEMS:
# 1. can't pause or stop animation. once loop starts it cant be broken
# 2. set_array attribute for pcolor PolyCollection object only updates the matrix
# C of pcolor, however for my actual application, I will be using pcolor(x,y,C)
# and will have new x,y, and C per plot. Unlike line object, where set_xdata and
# set_ydata are used, I can't find an analogy to pcolor. If I were updating an
# image I could use set_data(x,y,C), but i am not importing an image. I assume
# pcolor is still my best bet unless (as in Matlab) there is an equivalent
# image(x,y,C) function?
import time as t
from pylab import *
from matplotlib.widgets import Button
ion()
def pressPlay(event):
#fig=figure()
ax = subplot(111)
subplots_adjust(bottom=0.2)
c=rand(5,5)
cplot=pcolor(c)
draw()
for i in range(5):
c=rand(5,5)
cplot.set_array(c.ravel())
cplot.autoscale()
title('Ionosphere '+str(i+1))
t.sleep(3)
draw()
axPlay = axes([0.7, 0.05, 0.1, 0.075])
bPlay = Button(axPlay, 'Play')
bPlay.on_clicked(pressPlay)
Btw: in importing pylab the TkAgg backend is automatically set for use in matplotlib... i think. Or somehow I automatically use TkAgg. I am running Linux, Python 2.6.4, Ipython 0.10.
I manipulated code found from Daniweb IT Discussion Community so that using Tkinter and the update_idletasks() function I can play, plause, stop the changing colors of a label widget. This can be run on python alone as long as Tkinter is installed. No matplotlib or pylab used. This is working code and the backbone of the final code I question.
# This is meant to draw Start and Stop buttons and a label
# The Start button should start a loop in which the label
# is configured to change color by looping through a color list.
# At each pass through the loop the variable self.stop is checked:
# if True the loop terminates.
# The Stop button terminates the loop by setting the
# variable self.stop to True.
# The Start button restarts the animation from the beginning
# if Stop was hit last, or restarts the animation from where it left off
# if pause was hit last.
# The loop also terminates on the last color of the list, as if stop were hit
from Tkinter import *
colors = ['red','green','blue','orange','brown','black','white','purple','violet']
numcol=len(colors)
class SGWidget(Frame):
def __init__(self, parent=None):
Frame.__init__(self, parent)
self.top_frame = Frame(bg='green')
self.top_frame.grid()
# enter event loop until all idle callbacks have been called.
self.top_frame.update_idletasks()
self.makeToolbar()
# construct a label widget with the parent frame top_frame
self.label = Label(self.top_frame,text = 'Text',bg='orange')
self.label.grid()
# initialize (time index t)
self.t=0
def makeToolbar(self):
self.toolbar_text = ['Play','Pause','Stop']
self.toolbar_length = len(self.toolbar_text)
self.toolbar_buttons = [None] * self.toolbar_length
for toolbar_index in range(self.toolbar_length):
text = self.toolbar_text[toolbar_index]
bg = 'yellow'
button_id = Button(self.top_frame,text=text,background=bg)
button_id.grid(row=0, column=toolbar_index)
self.toolbar_buttons[toolbar_index] = button_id
def toolbar_button_handler(event, self=self, button=toolbar_index):
return self.service_toolbar(button)
# bind mouse click on start or stop to the toolbar_button_handler
button_id.bind("<Button-1>", toolbar_button_handler)
# call blink() if start and set stop when stop
def service_toolbar(self, toolbar_index):
if toolbar_index == 0:
self.stop = False
print self.stop
self.blink()
elif toolbar_index == 1:
self.stop = True
print self.stop
elif toolbar_index == 2:
self.stop = True
print self.stop
self.t=0
# while in start, check if stop is clicked, if not, call blink recursivly
def blink(self):
if not self.stop:
print 'looping',self.stop
self.label.configure(bg=colors[self.t])
self.t += 1
if self.t == numcol: # push stop button
self.service_toolbar(2)
self.label.update_idletasks()
self.after(500, self.blink)
if __name__ == '__main__':
SGWidget().mainloop()
Then, with help from matplotlib example embedding_in_tk.html, http://matplotlib.sourceforge.net/examples/user_interfaces/embedding_in_tk.html, I manipulated the previous code to animate a canvas connected to the pcolor figure. However, updating the canvas with canvas.get_tk_widget() doesn't do the trick I assume because of the command before it that re-plots pcolor(). So I'm guessing I have to reconnect the canvas with the figure every time I re-plot? But I don't know how. I hope I'm even on the right track using update_idletasks()???
So, with the following code, all I see is the same plot when the code is looping through Play, instead of an updated figure? This is my main problem and question.
from pylab import *
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from Tkinter import *
colors=[None]*10
for i in range(len(colors)):
colors[i]=rand(5,5)
#colors = ['red','green','blue','orange','brown','black','white','purple','violet']
numcol=len(colors)
class App(Frame):
def __init__(self,parent=None):
Frame.__init__(self,parent)
self.top=Frame()
self.top.grid()
self.top.update_idletasks()
self.makeWidgets()
self.makeToolbar()
def makeWidgets(self):
# figsize (w,h tuple in inches) dpi (dots per inch)
#f = Figure(figsize=(5,4), dpi=100)
self.f = Figure()
self.a = self.f.add_subplot(111)
self.a.pcolor(rand(5,5))
# a tk.DrawingArea
self.canvas = FigureCanvasTkAgg(self.f, master=self.top)
self.canvas.get_tk_widget().grid(row=3,column=0,columnspan=3)
self.bClose = Button(self.top, text='Close',command=self.top.destroy)
self.bClose.grid()
#self.label = Label(self.top, text = 'Text',bg='orange')
#self.label.grid()
# initialize (time index t)
self.t=0
def makeToolbar(self):
self.toolbar_text = ['Play','Pause','Stop']
self.toolbar_length = len(self.toolbar_text)
self.toolbar_buttons = [None] * self.toolbar_length
for toolbar_index in range(self.toolbar_length):
text = self.toolbar_text[toolbar_index]
bg = 'yellow'
button_id = Button(self.top,text=text,background=bg)
button_id.grid(row=0, column=toolbar_index)
self.toolbar_buttons[toolbar_index] = button_id
def toolbar_button_handler(event, self=self, button=toolbar_index):
return self.service_toolbar(button)
button_id.bind("<Button-1>", toolbar_button_handler)
# call blink() if start and set stop when stop
def service_toolbar(self, toolbar_index):
if toolbar_index == 0:
self.stop = False
print self.stop
self.blink()
elif toolbar_index == 1:
self.stop = True
print self.stop
elif toolbar_index == 2:
self.stop = True
print self.stop
self.t=0
# while in start, check if stop is clicked, if not, call blink recursivly
def blink(self):
if not self.stop:
print 'looping',self.stop
self.a.pcolor(colors[self.t])
#draw()
#self.label.configure(bg=colors[self.t])
self.t += 1
if self.t == numcol: # push stop button
self.service_toolbar(2)
self.canvas.get_tk_widget().update_idletasks()
#self.label.update_idletasks()
self.after(500, self.blink)
#root = Tk()
app=App()
app.mainloop()
Thanks for the help!
A:
In your blink function, add a self.canvas.show() before calling idle tasks:
self.canvas.show() # insert this line
self.canvas.get_tk_widget().update_idletasks()
| color plot animation with play, pause, stop cabability using Tkinter with pylab/matplotlib embedding: can't update figure/canvas? | I've looked but didn't find previous questions specific enough, so sorry if this is repeated.
Goal: GUI to continuously update figure with different matrix data plotted by pylab's pcolor such that there is a running animation. But user should be able to play, pause, stop animation by Tkinter widget buttons.
Before I get an answer for matplotlib using set_array(), draw(), and canvas.manager.after() ..., I have working code that enables me to start animation, but i can't figure out how to stop or pause it, when just using matplotlib capabilities, so I decided to use Tkinter straigt up instead of matplotlib's Tcl/Tk wrapper. Here is working code just for kicks though in case someone has any ideas. But continue for real question.
# mouse click the "Play" button widget to play animation
# PROBLEMS:
# 1. can't pause or stop animation. once loop starts it cant be broken
# 2. set_array attribute for pcolor PolyCollection object only updates the matrix
# C of pcolor, however for my actual application, I will be using pcolor(x,y,C)
# and will have new x,y, and C per plot. Unlike line object, where set_xdata and
# set_ydata are used, I can't find an analogy to pcolor. If I were updating an
# image I could use set_data(x,y,C), but i am not importing an image. I assume
# pcolor is still my best bet unless (as in Matlab) there is an equivalent
# image(x,y,C) function?
import time as t
from pylab import *
from matplotlib.widgets import Button
ion()
def pressPlay(event):
#fig=figure()
ax = subplot(111)
subplots_adjust(bottom=0.2)
c=rand(5,5)
cplot=pcolor(c)
draw()
for i in range(5):
c=rand(5,5)
cplot.set_array(c.ravel())
cplot.autoscale()
title('Ionosphere '+str(i+1))
t.sleep(3)
draw()
axPlay = axes([0.7, 0.05, 0.1, 0.075])
bPlay = Button(axPlay, 'Play')
bPlay.on_clicked(pressPlay)
Btw: in importing pylab the TkAgg backend is automatically set for use in matplotlib... i think. Or somehow I automatically use TkAgg. I am running Linux, Python 2.6.4, Ipython 0.10.
I manipulated code found from Daniweb IT Discussion Community so that using Tkinter and the update_idletasks() function I can play, plause, stop the changing colors of a label widget. This can be run on python alone as long as Tkinter is installed. No matplotlib or pylab used. This is working code and the backbone of the final code I question.
# This is meant to draw Start and Stop buttons and a label
# The Start button should start a loop in which the label
# is configured to change color by looping through a color list.
# At each pass through the loop the variable self.stop is checked:
# if True the loop terminates.
# The Stop button terminates the loop by setting the
# variable self.stop to True.
# The Start button restarts the animation from the beginning
# if Stop was hit last, or restarts the animation from where it left off
# if pause was hit last.
# The loop also terminates on the last color of the list, as if stop were hit
from Tkinter import *
colors = ['red','green','blue','orange','brown','black','white','purple','violet']
numcol=len(colors)
class SGWidget(Frame):
def __init__(self, parent=None):
Frame.__init__(self, parent)
self.top_frame = Frame(bg='green')
self.top_frame.grid()
# enter event loop until all idle callbacks have been called.
self.top_frame.update_idletasks()
self.makeToolbar()
# construct a label widget with the parent frame top_frame
self.label = Label(self.top_frame,text = 'Text',bg='orange')
self.label.grid()
# initialize (time index t)
self.t=0
def makeToolbar(self):
self.toolbar_text = ['Play','Pause','Stop']
self.toolbar_length = len(self.toolbar_text)
self.toolbar_buttons = [None] * self.toolbar_length
for toolbar_index in range(self.toolbar_length):
text = self.toolbar_text[toolbar_index]
bg = 'yellow'
button_id = Button(self.top_frame,text=text,background=bg)
button_id.grid(row=0, column=toolbar_index)
self.toolbar_buttons[toolbar_index] = button_id
def toolbar_button_handler(event, self=self, button=toolbar_index):
return self.service_toolbar(button)
# bind mouse click on start or stop to the toolbar_button_handler
button_id.bind("<Button-1>", toolbar_button_handler)
# call blink() if start and set stop when stop
def service_toolbar(self, toolbar_index):
if toolbar_index == 0:
self.stop = False
print self.stop
self.blink()
elif toolbar_index == 1:
self.stop = True
print self.stop
elif toolbar_index == 2:
self.stop = True
print self.stop
self.t=0
# while in start, check if stop is clicked, if not, call blink recursivly
def blink(self):
if not self.stop:
print 'looping',self.stop
self.label.configure(bg=colors[self.t])
self.t += 1
if self.t == numcol: # push stop button
self.service_toolbar(2)
self.label.update_idletasks()
self.after(500, self.blink)
if __name__ == '__main__':
SGWidget().mainloop()
Then, with help from matplotlib example embedding_in_tk.html, http://matplotlib.sourceforge.net/examples/user_interfaces/embedding_in_tk.html, I manipulated the previous code to animate a canvas connected to the pcolor figure. However, updating the canvas with canvas.get_tk_widget() doesn't do the trick I assume because of the command before it that re-plots pcolor(). So I'm guessing I have to reconnect the canvas with the figure every time I re-plot? But I don't know how. I hope I'm even on the right track using update_idletasks()???
So, with the following code, all I see is the same plot when the code is looping through Play, instead of an updated figure? This is my main problem and question.
from pylab import *
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from Tkinter import *
colors=[None]*10
for i in range(len(colors)):
colors[i]=rand(5,5)
#colors = ['red','green','blue','orange','brown','black','white','purple','violet']
numcol=len(colors)
class App(Frame):
def __init__(self,parent=None):
Frame.__init__(self,parent)
self.top=Frame()
self.top.grid()
self.top.update_idletasks()
self.makeWidgets()
self.makeToolbar()
def makeWidgets(self):
# figsize (w,h tuple in inches) dpi (dots per inch)
#f = Figure(figsize=(5,4), dpi=100)
self.f = Figure()
self.a = self.f.add_subplot(111)
self.a.pcolor(rand(5,5))
# a tk.DrawingArea
self.canvas = FigureCanvasTkAgg(self.f, master=self.top)
self.canvas.get_tk_widget().grid(row=3,column=0,columnspan=3)
self.bClose = Button(self.top, text='Close',command=self.top.destroy)
self.bClose.grid()
#self.label = Label(self.top, text = 'Text',bg='orange')
#self.label.grid()
# initialize (time index t)
self.t=0
def makeToolbar(self):
self.toolbar_text = ['Play','Pause','Stop']
self.toolbar_length = len(self.toolbar_text)
self.toolbar_buttons = [None] * self.toolbar_length
for toolbar_index in range(self.toolbar_length):
text = self.toolbar_text[toolbar_index]
bg = 'yellow'
button_id = Button(self.top,text=text,background=bg)
button_id.grid(row=0, column=toolbar_index)
self.toolbar_buttons[toolbar_index] = button_id
def toolbar_button_handler(event, self=self, button=toolbar_index):
return self.service_toolbar(button)
button_id.bind("<Button-1>", toolbar_button_handler)
# call blink() if start and set stop when stop
def service_toolbar(self, toolbar_index):
if toolbar_index == 0:
self.stop = False
print self.stop
self.blink()
elif toolbar_index == 1:
self.stop = True
print self.stop
elif toolbar_index == 2:
self.stop = True
print self.stop
self.t=0
# while in start, check if stop is clicked, if not, call blink recursivly
def blink(self):
if not self.stop:
print 'looping',self.stop
self.a.pcolor(colors[self.t])
#draw()
#self.label.configure(bg=colors[self.t])
self.t += 1
if self.t == numcol: # push stop button
self.service_toolbar(2)
self.canvas.get_tk_widget().update_idletasks()
#self.label.update_idletasks()
self.after(500, self.blink)
#root = Tk()
app=App()
app.mainloop()
Thanks for the help!
| [
"In your blink function, add a self.canvas.show() before calling idle tasks:\nself.canvas.show() # insert this line\nself.canvas.get_tk_widget().update_idletasks()\n\n"
] | [
2
] | [] | [] | [
"ipython",
"matplotlib",
"python",
"tkinter"
] | stackoverflow_0003294989_ipython_matplotlib_python_tkinter.txt |
Q:
How to do this (PHP) in python or ruby?
My app takes a loooong list of urls, and split it in X (where X = $threads) so then I can start a thread.php and calculate the urls for it. Then it does GET and POST request to retrieve data
I am using this:
for($x=1;$x<=$threads;$x++){
$pid[] = exec("/path/bin/php thread.php <options> > /dev/null & echo \$!");
}
For "threading" (I know its not really threading, is it forking or what?), I save the pids into a file for later checking if N thread is running and to stop them.
Now I want to move out from php, I was thinking about using python because I'd like to learn more about it.
How can I achieve this kind of "threading" with python? (or ruby)
Or is there a better way to launch multiple background threads in python or ruby that runs in parallel (at the same time)?
The threads doesn't need to communicate between each other or with a main thread, they are independent, they do http request and interact with a mysql db, they may need to access/modify the same table entries (I haven't tought about this or how I will solve it yet).
The app works with "projects", each project has a "max threads" variable and I use a web interface to control it (so I could still use php for the interface [starting/stopping threads] in the new app).
I wanted to use
from threading import Thread
in python, but I've been told those threads wont run in parallel but once at a time.
The app is intended to run on linux web servers.
Any suggestion will be appreciated.
A:
You don't want threading. You want a work queue like Gearman that you can send jobs to asynchronously.
It's worth noting that this is a cross-platform, cross-language solution. There are bindings for many languages (including Python and PHP) provided officially, and many more unofficially with a bit of work with Google.
The original intent is effectively load balancing, but it works just as well with only one machine. Basically, you can create one or more Workers that listen for Jobs. You can control the number of Workers and the types of Jobs they can listen for.
If you insert five Jobs into the queue at the same time, and there happen to be five Workers waiting, each Worker will be handed one of the Jobs. If there are more Jobs than Workers, the Jobs get handled sequentially. Your Client (the thing that submits Jobs) can either wait for all of the Jobs it's created to complete, or it can simply place them in the queue and continue on.
A:
For Python 2.6+, consider the multiprocessing module:
multiprocessing is a package that supports spawning processes using an API similar to the threading module. The multiprocessing package offers both local and remote concurrency, effectively side-stepping the Global Interpreter Lock by using subprocesses instead of threads. Due to this, the multiprocessing module allows the programmer to fully leverage multiple processors on a given machine. It runs on both Unix and Windows
For Python 2.5, the same functionality is available via pyprocessing.
In addition to the example at the links above, here are some additional links to get you started:
multiprocessing Basics
Communication between processes with multiprocessing
| How to do this (PHP) in python or ruby? | My app takes a loooong list of urls, and split it in X (where X = $threads) so then I can start a thread.php and calculate the urls for it. Then it does GET and POST request to retrieve data
I am using this:
for($x=1;$x<=$threads;$x++){
$pid[] = exec("/path/bin/php thread.php <options> > /dev/null & echo \$!");
}
For "threading" (I know its not really threading, is it forking or what?), I save the pids into a file for later checking if N thread is running and to stop them.
Now I want to move out from php, I was thinking about using python because I'd like to learn more about it.
How can I achieve this kind of "threading" with python? (or ruby)
Or is there a better way to launch multiple background threads in python or ruby that runs in parallel (at the same time)?
The threads doesn't need to communicate between each other or with a main thread, they are independent, they do http request and interact with a mysql db, they may need to access/modify the same table entries (I haven't tought about this or how I will solve it yet).
The app works with "projects", each project has a "max threads" variable and I use a web interface to control it (so I could still use php for the interface [starting/stopping threads] in the new app).
I wanted to use
from threading import Thread
in python, but I've been told those threads wont run in parallel but once at a time.
The app is intended to run on linux web servers.
Any suggestion will be appreciated.
| [
"You don't want threading. You want a work queue like Gearman that you can send jobs to asynchronously. \nIt's worth noting that this is a cross-platform, cross-language solution. There are bindings for many languages (including Python and PHP) provided officially, and many more unofficially with a bit of work w... | [
1,
1
] | [] | [] | [
"multithreading",
"php",
"python",
"ruby"
] | stackoverflow_0003294917_multithreading_php_python_ruby.txt |
Q:
How to install Bazaar to a shared server via SSH?
If I have SSH access to a shared server (running centOS) and I want to install Bazaar. I do not have root access, but Python is already installed on the server, so that shouldn't be a problem.
I really don't know where to begin after logging into the server. I'm assuming the first step is to copy the Bazaar application files onto the server... but I don't know where to put them.
If it helps, I will be using the shared server as a repository - I won't be doing any checkouts or anything with it.
A:
From the Installation FAQ:
Install in home directory
You can install Bazaar into home directory, in ~/bin. This method requires that ~/bin is in your $PATH and that ~/lib/python is in your $PYTHONPATH.
% python setup.py install --home $HOME
However, if you are truly only using it as a repository, there's no need to install Bazaar. This how-to explains how to set up a Bazaar repository on a server that only has SSH but no Bazaar. It won't get you quite as good performance as bzr+ssh, but you would actually need to run a Bazaar server to get bzr+ssh anyway; you may not have that right on your shared server.
| How to install Bazaar to a shared server via SSH? | If I have SSH access to a shared server (running centOS) and I want to install Bazaar. I do not have root access, but Python is already installed on the server, so that shouldn't be a problem.
I really don't know where to begin after logging into the server. I'm assuming the first step is to copy the Bazaar application files onto the server... but I don't know where to put them.
If it helps, I will be using the shared server as a repository - I won't be doing any checkouts or anything with it.
| [
"From the Installation FAQ:\n\nInstall in home directory\nYou can install Bazaar into home directory, in ~/bin. This method requires that ~/bin is in your $PATH and that ~/lib/python is in your $PYTHONPATH.\n% python setup.py install --home $HOME\n\n\nHowever, if you are truly only using it as a repository, there's... | [
2
] | [] | [] | [
"bazaar",
"installation",
"python"
] | stackoverflow_0003295678_bazaar_installation_python.txt |
Q:
Create an instance that represents the average of multiple instances
I have a Review Model like the one defined below (I removed a bunch of the fields in REVIEW_FIELDS). I want to find the average of a subset of the attributes and populate a ModelForm with the computed information.
REVIEW_FIELDS = ['noise']
class Review(models.Model):
notes = models.TextField(null=True, blank=True)
CHOICES = ((1, u'Quiet'), (2, u'Kinda Quiet'), (3, u'Loud'))
noise = models.models.IntegerField('Noise Level', blank-True, null=True, choices=CHOICES)
class ReviewForm(ModelForm):
class Meta:
model = Review
fields = REVIEW_FIELDS
I can easily add more fields to the model, and then add them to the REVIEW_FIELDS list. Then I can easily iterate over them in javascript, etc. In my view, I want to compute the average of a bunch of the integer fields and populate a ReviewForm with the attribute values. How can I do something like this?
stats = {}
for attr in REVIEW_FIELDS:
val = reviews.aggregate(Avg(attr)).values()[0]
if val:
stats[attr] = int(round(val,0))
r.attr = stats[attr]
r = Review()
f = ReviewForm(r)
How can I create a ReviewForm with the average values without hard-coding the attribute values? I'd like to be able to add the field, add the value to the list, and have it automatically added to the set of statistics computed.
If I'm doing something fundamentally wrong, please let me know. I'm relatively new to django, so I might be re-inventing functionality that already exists.
A:
After looking at the docs, I pass a dictionary to the ReviewForm when instantiating it:
f = ReviewForm(stats)
It seems to work pretty well! If anyone has any suggestions on a better way to do this, I'm all ears!
| Create an instance that represents the average of multiple instances | I have a Review Model like the one defined below (I removed a bunch of the fields in REVIEW_FIELDS). I want to find the average of a subset of the attributes and populate a ModelForm with the computed information.
REVIEW_FIELDS = ['noise']
class Review(models.Model):
notes = models.TextField(null=True, blank=True)
CHOICES = ((1, u'Quiet'), (2, u'Kinda Quiet'), (3, u'Loud'))
noise = models.models.IntegerField('Noise Level', blank-True, null=True, choices=CHOICES)
class ReviewForm(ModelForm):
class Meta:
model = Review
fields = REVIEW_FIELDS
I can easily add more fields to the model, and then add them to the REVIEW_FIELDS list. Then I can easily iterate over them in javascript, etc. In my view, I want to compute the average of a bunch of the integer fields and populate a ReviewForm with the attribute values. How can I do something like this?
stats = {}
for attr in REVIEW_FIELDS:
val = reviews.aggregate(Avg(attr)).values()[0]
if val:
stats[attr] = int(round(val,0))
r.attr = stats[attr]
r = Review()
f = ReviewForm(r)
How can I create a ReviewForm with the average values without hard-coding the attribute values? I'd like to be able to add the field, add the value to the list, and have it automatically added to the set of statistics computed.
If I'm doing something fundamentally wrong, please let me know. I'm relatively new to django, so I might be re-inventing functionality that already exists.
| [
"After looking at the docs, I pass a dictionary to the ReviewForm when instantiating it:\nf = ReviewForm(stats)\n\nIt seems to work pretty well! If anyone has any suggestions on a better way to do this, I'm all ears!\n"
] | [
2
] | [] | [] | [
"django",
"django_forms",
"python"
] | stackoverflow_0003295843_django_django_forms_python.txt |
Q:
Any good recursive tutorials? Python?
Wondering if anyone could point me towards a good recursion tutorial. I am a bit rusty on it as I learned about it in my Data Structures class first semester. Would like to brush up on my recursion...any help?
A:
Consider this.
More seriously…
Recursion is a way of solving problems that have a clearly defined base case (or cases, btu I'm keeping it simple here.)
For examples, the commonly cited factorial problem is a great one.
What does factorial do? Let's see some examples:
factorial(0) = 1
factorial(1) = 1
factorial(2) = 2
factorial(3) = 6
factorial(4) = 24
The factorial of a number is that number multiplied by the factorial of the number that comes before it, unless (now, this is the base case) the number is 0. The factorial of 0 is 1. (You can't take the factorial of a negative number; only positive integers.)
So we have our clearly defined base case. And we know what to do with numbers that aren't our base case (we multiply them times the factorial of the number one less than it.) We're ready to write our function.
def factorial(x):
if x == 0: # this is our base case
return 1 # and this is what we do when we see it
else: # this is what we do with all other numbers
return x * factorial(x-1)
So you
Clearly define your base case.
Find a way to reduce your problem from a non-base case to the base case.
Formally express that in a function that (when it's simple!) looks like
function:
if base case:
this
else:
something + function(something closer to the base case)
If you want something more advanced, Google's got a lot of info.
A:
I would highly recommend watching MIT's intro to programming course.
Lecture 4 talks about recursion.
| Any good recursive tutorials? Python? | Wondering if anyone could point me towards a good recursion tutorial. I am a bit rusty on it as I learned about it in my Data Structures class first semester. Would like to brush up on my recursion...any help?
| [
"Consider this.\nMore seriously…\nRecursion is a way of solving problems that have a clearly defined base case (or cases, btu I'm keeping it simple here.)\nFor examples, the commonly cited factorial problem is a great one. \nWhat does factorial do? Let's see some examples: \nfactorial(0) = 1\nfactorial(1) = 1\nfact... | [
11,
5
] | [] | [] | [
"c++",
"python",
"recursion"
] | stackoverflow_0003295817_c++_python_recursion.txt |
Q:
Is there a way to fix vim not-noticing python if statements that have comments?
Consider the following block of code-
if (1==1):#Go forever
print "Wooo."
Vim doesn't see the :, due to the comment, so it insists that the print should be at the same indent level as the "if"
using http://www.vim.org/scripts/script.php?script_id=974
Any thoughts would be appreciated.
A:
Find this in the .vim file:
" If the previous line ended with a colon, indent relative to
" statement start.
if pline =~ ':\s*$'
change it to...
" If the previous line ended with a colon, indent relative to
" statement start.
if pline =~ ':\s*\(#.*\)\?$'
That will make it also match lines that end with a colon followed by a comment.
| Is there a way to fix vim not-noticing python if statements that have comments? | Consider the following block of code-
if (1==1):#Go forever
print "Wooo."
Vim doesn't see the :, due to the comment, so it insists that the print should be at the same indent level as the "if"
using http://www.vim.org/scripts/script.php?script_id=974
Any thoughts would be appreciated.
| [
"Find this in the .vim file:\n\" If the previous line ended with a colon, indent relative to\n\" statement start.\nif pline =~ ':\\s*$'\n\nchange it to...\n\" If the previous line ended with a colon, indent relative to\n\" statement start.\nif pline =~ ':\\s*\\(#.*\\)\\?$'\n\nThat will make it also match lines that... | [
1
] | [] | [] | [
"python",
"vim"
] | stackoverflow_0003296104_python_vim.txt |
Q:
Improve performance of self join in sqlite
I have a table with 21 columns (all integers) id, c1 , c2 ... c20 and what to fetch ids for rows that have the same values in the columns ...
so row 1 will match row 10 if row 1 c1 = row 10 c1 and row 1 c2 = row 10 c2 ... and so on.
This is what the query looks like:
select r1.id, r2.id
from tbl r1, tbl r2
where 1=1 and r1.c1=r2.c1 and r1.c2=r2.c2 and
..... r1.c20=r2.c20 and not r1.id=r2.id
I am currently using self join, but this is way too slow (20 secs for 10000 rows).
I have setup indexes on the columns (?)
I have ~ 1 million rows
Thanks
A:
Have you tried a single index on all 20 columns?
A:
You may want to create an extra column, where you can store a hash of all the values in the row. Then simply index that column and filter the rows that match the hash of the 20 values you are searching for.
| Improve performance of self join in sqlite | I have a table with 21 columns (all integers) id, c1 , c2 ... c20 and what to fetch ids for rows that have the same values in the columns ...
so row 1 will match row 10 if row 1 c1 = row 10 c1 and row 1 c2 = row 10 c2 ... and so on.
This is what the query looks like:
select r1.id, r2.id
from tbl r1, tbl r2
where 1=1 and r1.c1=r2.c1 and r1.c2=r2.c2 and
..... r1.c20=r2.c20 and not r1.id=r2.id
I am currently using self join, but this is way too slow (20 secs for 10000 rows).
I have setup indexes on the columns (?)
I have ~ 1 million rows
Thanks
| [
"Have you tried a single index on all 20 columns?\n",
"You may want to create an extra column, where you can store a hash of all the values in the row. Then simply index that column and filter the rows that match the hash of the 20 values you are searching for.\n"
] | [
1,
1
] | [] | [] | [
"python",
"sqlite"
] | stackoverflow_0003296511_python_sqlite.txt |
Q:
Rich text to be stored using django
If csv file has rich text in it. Using csv.reader() can the same format stored in the Mysql database using django and retrieved back to html pages?
Thanks..
A:
Text or data has no color or creed.
If you have data as text, just store it in text field, if it is binary store it as a blob. It doesn't matter what that data represents, it can be richtext, pdf, a flash file etc database doesn't care.
| Rich text to be stored using django | If csv file has rich text in it. Using csv.reader() can the same format stored in the Mysql database using django and retrieved back to html pages?
Thanks..
| [
"Text or data has no color or creed.\nIf you have data as text, just store it in text field, if it is binary store it as a blob. It doesn't matter what that data represents, it can be richtext, pdf, a flash file etc database doesn't care.\n"
] | [
0
] | [] | [] | [
"django",
"django_models",
"django_views",
"python"
] | stackoverflow_0003296268_django_django_models_django_views_python.txt |
Q:
Convert a Python snippet to PHP?
Can anyone translate my small Python snippet to PHP? I'm not a familiar with both languages. :(
matches = re.compile("\"cap\":\"(.*?)\"")
totalrewards = re.findall(matches, contents)
print totalrewards
Thank you for those who'd help! :(
A:
This is a direct translation of the code above, with "contents" populated for demonstration purposes:
<?php
$contents = '"cap":"foo" "cap":"wahey"';
if (preg_match_all('/"cap":"(.*?)"/', $contents, $matches, PREG_SET_ORDER)) {
var_dump($matches);
}
The output:
array(2) {
[0]=>
array(2) {
[0]=>
string(11) ""cap":"foo""
[1]=>
string(3) "foo"
}
[1]=>
array(2) {
[0]=>
string(13) ""cap":"wahey""
[1]=>
string(5) "wahey"
}
}
If you want to actually do something with the result, for e.g. list it, try:
<?php
$contents = '"cap":"foo" "cap":"wahey"';
if (preg_match_all('/"cap":"(.*?)"/', $contents, $matches, PREG_SET_ORDER)) {
foreach ($matches as $match) {
// array index 1 corresponds to the first set of brackets (.*?)
// we also add a newline to the end of the item we output as this
// happens automatically in PHP, but not in python.
echo $match[1] . "\n";
}
}
| Convert a Python snippet to PHP? | Can anyone translate my small Python snippet to PHP? I'm not a familiar with both languages. :(
matches = re.compile("\"cap\":\"(.*?)\"")
totalrewards = re.findall(matches, contents)
print totalrewards
Thank you for those who'd help! :(
| [
"This is a direct translation of the code above, with \"contents\" populated for demonstration purposes:\n<?php\n$contents = '\"cap\":\"foo\" \"cap\":\"wahey\"';\nif (preg_match_all('/\"cap\":\"(.*?)\"/', $contents, $matches, PREG_SET_ORDER)) {\n var_dump($matches);\n}\n\nThe output:\narray(2) {\n [0]=>\n arra... | [
1
] | [] | [] | [
"code_snippets",
"php",
"python"
] | stackoverflow_0003296592_code_snippets_php_python.txt |
Q:
GAE WSGIApplication and multiple request
In dev_appserver
class MainPage(webapp.RequestHandler):
def get(self):
self.response.out.write("Hello MainPage")
class TestPage(webapp.RequestHandler):
def get(self):
# 10 seconds
i = 1
while True:
if i == 10:
break
time.sleep(1)
i = i + 1
application = webapp.WSGIApplication([
('/', MainPage)
('/test10', TestPage),
], debug=True)
I don't understand. I go to http://localhost:8080/test10 and go to http://localhost:8080/, but MainPage not execute. After 10 seconds, MainPage return "Hello MainPage". GAE server not support multiple request?
A:
The actual GAE web servers on Google's servers in the clouds support multiple requests easily (indeed their scalability is one of their strengths!), typically by using multiple processes and possibly multiple computers to divide up the load during periods of time in which many requests are coming in fast and furious.
The SDK running on your local computer, intended strictly to help you develop (definitely not to actually serve production traffic!-), serves requests one after the other instead, to make it easier for you to debug (directly, via the logs, etc, etc).
If you want to serve GAE apps yourself (from your own computer or data center), not for development purposes but for production, consider alternative implementations of the GAE APIs, such as appscale (probably more suitable if you have many servers available for the purpose, and the sysadm skill to deal with them) and typhoonae (probably more suitable if you have one or just a few servers to use and want less sysadm workload).
A:
You haven't included a main() method, or the 'magic' stanza that causes the first request to be handled correctly. Add the following to the end of your module:
def main():
run_wsgi_app(application)
if __name__ == "__main__":
main()
A:
@Nick Johnson: You test it? Of course! My code included "run_wsgi_app" and "main" functions.
http://groups.google.com/group/google-appengine-python/browse_thread/thread/102d76f04ecc5155
| GAE WSGIApplication and multiple request | In dev_appserver
class MainPage(webapp.RequestHandler):
def get(self):
self.response.out.write("Hello MainPage")
class TestPage(webapp.RequestHandler):
def get(self):
# 10 seconds
i = 1
while True:
if i == 10:
break
time.sleep(1)
i = i + 1
application = webapp.WSGIApplication([
('/', MainPage)
('/test10', TestPage),
], debug=True)
I don't understand. I go to http://localhost:8080/test10 and go to http://localhost:8080/, but MainPage not execute. After 10 seconds, MainPage return "Hello MainPage". GAE server not support multiple request?
| [
"The actual GAE web servers on Google's servers in the clouds support multiple requests easily (indeed their scalability is one of their strengths!), typically by using multiple processes and possibly multiple computers to divide up the load during periods of time in which many requests are coming in fast and furio... | [
1,
1,
0
] | [] | [] | [
"google_app_engine",
"python",
"request"
] | stackoverflow_0003284196_google_app_engine_python_request.txt |
Q:
Why do I get an error in python saying that a method cannot be found even though I previously defined the method?
index = 0
def changeColor():
global index
if index%2==0:
label.configure(bg = "purple")
else:
label.configure(bg = "blue")
index+=1
label.after(1000, changeColor)
def Start (self): # command when start button is clicked in GUI
self.root = Tk()
self.root.geometry("500x300")
mainContainer = Frame (self.root)
label = Label(mainContainer, text = "")
label.pack(side = LEFT, ipadx = 5, ipady = 5)
mainContainer.pack()
label.after(1000, changeColor)
self.root.mainloop()
I get an error saying: NameError: global name 'changeColor' is not defined. Why does this occur and how would I fix it?
A:
It looks to me like the problem might be what's not in the snippet. Are both of these functions part of a class definition? From the use of self as an argument in Start, and label in changeColor, it looks like it might be.
If so, let's say it's class Foo, then changeColor is really Foo.changeColor. To use it, you'd pull it outside of the class, or pass it as self.changeColor from Start.
EDIT: Three other things you should do to clean up the style:
Make changeColor take self as an argument, so it's a proper method of the class.
Make label a member of the object; i.e. make it self.label, so changeColor can access it.
Get rid of the global index. Instead, query the label's current color (self.label['bg']) to figure out what state it's in.
A:
try this
index = 0
def changeColor(self):
global index
if index%2==0:
self.label.configure(bg = "purple")
else:
self.label.configure(bg = "blue")
index+=1
def Start (self): # command when start button is clicked in GUI
self.root = Tk()
self.root.geometry("500x300")
mainContainer = Frame (self.root)
label = Label(mainContainer, text = "")
label.pack(side = LEFT, ipadx = 5, ipady = 5)
mainContainer.pack()
label.after(1000, self.changeColor)
# above should really be lambda: changeColor()
self.root.mainloop()
working example
>>> def f(): print f
...
>>> def h(f): f()
...
>>> def g(): h(f)
...
>>> g()
<function f at 0x7f2262a8c8c0>
| Why do I get an error in python saying that a method cannot be found even though I previously defined the method? | index = 0
def changeColor():
global index
if index%2==0:
label.configure(bg = "purple")
else:
label.configure(bg = "blue")
index+=1
label.after(1000, changeColor)
def Start (self): # command when start button is clicked in GUI
self.root = Tk()
self.root.geometry("500x300")
mainContainer = Frame (self.root)
label = Label(mainContainer, text = "")
label.pack(side = LEFT, ipadx = 5, ipady = 5)
mainContainer.pack()
label.after(1000, changeColor)
self.root.mainloop()
I get an error saying: NameError: global name 'changeColor' is not defined. Why does this occur and how would I fix it?
| [
"It looks to me like the problem might be what's not in the snippet. Are both of these functions part of a class definition? From the use of self as an argument in Start, and label in changeColor, it looks like it might be.\nIf so, let's say it's class Foo, then changeColor is really Foo.changeColor. To use it, you... | [
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0003296609_python.txt |
Q:
many-to-one attributes in Storm
My schema looks something like this:
CREATE TABLE plans (
id SERIAL PRIMARY KEY,
description text
);
CREATE TABLE projects (
id SERIAL PRIMARY KEY,
project_id character varying(240) UNIQUE,
plan_id integer REFERENCES plans(id) ON DELETE CASCADE
);
And I want to do Storm queries along the lines of
plan = store.find(Plan, Plan.project_id == "alpha")
# should translate to something like
# SELECT p.* from plans p LEFT JOIN projects proj ON p.id = proj.plan_id
# WHERE proj.project_id = 'alpha';
(Note that projects.plan_id is not unique.)
How do I set this up?
A:
For the given SQL, there isn't much reason to use a left join, since your where clause won't match any rows where there isn't a corresponding project. You could get the results with:
result = store.find(Plan, Plan.id == Project.plan_id, Project.project_id == "alpha")
This will give you a ResultSet object. Given your schema, it looks like you're expecting a single row, so you can access that with:
plan = result.one()
Or tie them both together with:
plan = store.find(Plan, Plan.id == Project.plan_id, Project.project_id == "alpha").one()
If you really need to do a left join, the syntax for that would be something like this:
result = store.using(LeftJoin(Plan, Project, Plan.id == Project.plan_id)).find(
Plan, Project.project_id == "alpha")
| many-to-one attributes in Storm | My schema looks something like this:
CREATE TABLE plans (
id SERIAL PRIMARY KEY,
description text
);
CREATE TABLE projects (
id SERIAL PRIMARY KEY,
project_id character varying(240) UNIQUE,
plan_id integer REFERENCES plans(id) ON DELETE CASCADE
);
And I want to do Storm queries along the lines of
plan = store.find(Plan, Plan.project_id == "alpha")
# should translate to something like
# SELECT p.* from plans p LEFT JOIN projects proj ON p.id = proj.plan_id
# WHERE proj.project_id = 'alpha';
(Note that projects.plan_id is not unique.)
How do I set this up?
| [
"For the given SQL, there isn't much reason to use a left join, since your where clause won't match any rows where there isn't a corresponding project. You could get the results with:\nresult = store.find(Plan, Plan.id == Project.plan_id, Project.project_id == \"alpha\")\n\nThis will give you a ResultSet object. ... | [
2
] | [] | [] | [
"python",
"storm_orm"
] | stackoverflow_0003294975_python_storm_orm.txt |
Q:
Python: How to call unbound method with other type parameter?
Python 2.6.4 (r264:75706, Dec 7 2009, 18:45:15)
[GCC 4.4.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> class A(object):
... def f(self):
... print self.k
...
>>> class B(object):pass
...
>>> a=A()
>>> b=B()
>>> a.k="a.k"
>>> b.k="b.k"
>>> a.f()
a.k
>>> A.f(a)
a.k
>>> A.f(b)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unbound method f() must be called with A instance as first argument (got B instance instead)
>>>
How can I do this?
Edited:this example is more clear
A:
Use the im_func attribute of the method.
A.f.im_func(b)
| Python: How to call unbound method with other type parameter? | Python 2.6.4 (r264:75706, Dec 7 2009, 18:45:15)
[GCC 4.4.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> class A(object):
... def f(self):
... print self.k
...
>>> class B(object):pass
...
>>> a=A()
>>> b=B()
>>> a.k="a.k"
>>> b.k="b.k"
>>> a.f()
a.k
>>> A.f(a)
a.k
>>> A.f(b)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unbound method f() must be called with A instance as first argument (got B instance instead)
>>>
How can I do this?
Edited:this example is more clear
| [
"Use the im_func attribute of the method.\nA.f.im_func(b)\n\n"
] | [
9
] | [] | [] | [
"methods",
"python"
] | stackoverflow_0003296993_methods_python.txt |
Q:
Python: Xlib -- How can I raise(bring to top) windows?
I've tried using:
win.configure(stack_mode=X.TopIf)
win.set_input_focus(X.RevertToParent, X.CurrentTime)
However even without any focus loss prevention on my window manager this does not work, does anyone know of another way to do this? Xlib or not.
A:
There is a command-line tool called wmctrl which allows you to interact with EWMH/NetWM-compatible X window managers.
For example,
wmctrl -l
lists all the windows managed by the window manager, and
wmctrl -a Mozilla
makes active the first window in the list which has the string "Mozilla" in its title.
There are other ways to select windows; the above is just an example.
wmctrl enables you to move and resize windows too.
A:
Try this:
window=Display().screen().root.query_pointer().child
window.set_input_focus(X.RevertToParent, X.CurrentTime)
window.configure(stack_mode=X.Above)
A:
Perhaps this is the solution:
[Xlib] Force Raise/Map/Focus a given Window
A solution given (follow the thread) involves using wnck, which in Python is a part of the Gtk+ bindings.
| Python: Xlib -- How can I raise(bring to top) windows? | I've tried using:
win.configure(stack_mode=X.TopIf)
win.set_input_focus(X.RevertToParent, X.CurrentTime)
However even without any focus loss prevention on my window manager this does not work, does anyone know of another way to do this? Xlib or not.
| [
"There is a command-line tool called wmctrl which allows you to interact with EWMH/NetWM-compatible X window managers.\nFor example,\nwmctrl -l\n\nlists all the windows managed by the window manager, and\nwmctrl -a Mozilla \n\nmakes active the first window in the list which has the string \"Mozilla\" in its title.\... | [
3,
3,
1
] | [] | [] | [
"linux",
"python",
"xlib"
] | stackoverflow_0001616628_linux_python_xlib.txt |
Q:
Where can I find getLevel()?
In the code below is using getLevel(). where can I find it (it is about sound, and it run with pyaudio library)
# this is the threshold that determines whether or not sound is detected
THRESHOLD = 0
#open your audio stream
# wait until the sound data breaks some level threshold
while True:
data = stream.read(chunk)
# check level against threshold, you'll have to write getLevel()
if getLevel(data) > THRESHOLD:
break
# record for however long you want
# close the stream
A:
You could have a look at https://docs.python.org/library/audioop.html
This is another python module to handle audio, but that one does seem to have a method to get the audio level ( max(fragment, width) ).
A:
Look at the imports that have been executed. You'll either find from someModule import getLevel, or from someModule import *.
| Where can I find getLevel()? | In the code below is using getLevel(). where can I find it (it is about sound, and it run with pyaudio library)
# this is the threshold that determines whether or not sound is detected
THRESHOLD = 0
#open your audio stream
# wait until the sound data breaks some level threshold
while True:
data = stream.read(chunk)
# check level against threshold, you'll have to write getLevel()
if getLevel(data) > THRESHOLD:
break
# record for however long you want
# close the stream
| [
"You could have a look at https://docs.python.org/library/audioop.html\nThis is another python module to handle audio, but that one does seem to have a method to get the audio level ( max(fragment, width) ).\n",
"Look at the imports that have been executed. You'll either find from someModule import getLevel, or f... | [
2,
0
] | [] | [] | [
"pyaudio",
"python"
] | stackoverflow_0003297354_pyaudio_python.txt |
Q:
Audio waveform visualisation in Python/Django
I've looked around Stack Overflow for an answer to this, but nowhere seems to give the correct answer or direction...
My project will allow a user to upload a WAV, which ultimately will be converted to a low quality MP3 using FFmpeg on the server and it'll all be stored and served on Amazon S3. The next obstacle is working out how to extract a reliable waveform visualisation from this uploaded sound. I'm using Python and Django on Linux Ubuntu 10 on a VPS for this project...
I'm, at the vert least, needing some sort of direction... I'm at a lost of where to start to look for such a tool?
A:
This one (uses audiolab, PIL and numpy) is decent: http://www.freesound.org/blog/?p=10
A:
To make a graph or plot of the waveform, the usual Python appoach is to get the waveform into a numpy array, and then use matplotlib to make the plot.
The easiest way to read the data into a numpy array is to use scipy.io.wavfile.read, though if you prefer not to use scipy (it's a big package), it's not difficult to read and convert the data using Python's wav module.
A:
Not trying to answer my own question here, but it's a suggestion that may help others clearly when seeing this quesion...
After lots of searching around, I found this solution... It seems well done, but does anyone else know anything about it?
Seems to do the lot!
http://code.google.com/p/timeside/
| Audio waveform visualisation in Python/Django | I've looked around Stack Overflow for an answer to this, but nowhere seems to give the correct answer or direction...
My project will allow a user to upload a WAV, which ultimately will be converted to a low quality MP3 using FFmpeg on the server and it'll all be stored and served on Amazon S3. The next obstacle is working out how to extract a reliable waveform visualisation from this uploaded sound. I'm using Python and Django on Linux Ubuntu 10 on a VPS for this project...
I'm, at the vert least, needing some sort of direction... I'm at a lost of where to start to look for such a tool?
| [
"This one (uses audiolab, PIL and numpy) is decent: http://www.freesound.org/blog/?p=10\n",
"To make a graph or plot of the waveform, the usual Python appoach is to get the waveform into a numpy array, and then use matplotlib to make the plot. \nThe easiest way to read the data into a numpy array is to use scipy... | [
8,
6,
3
] | [] | [] | [
"audio",
"django",
"python",
"visualization",
"waveform"
] | stackoverflow_0003290054_audio_django_python_visualization_waveform.txt |
Q:
Appengine and GWT - feeding the python some java
I realize this is a dated question since appengine now comes in java, but I have a python appengine app that I want to access via GWT. Python is just better for server-side text processing (using pyparsing of course!). I have tried to interpret GWT's client-side RPC and that is convoluted since there is no python counterpart (python-gwt-rpc is out of date). I just tried using JSON and RequestBuilder, but that fails when using SSL. Does anyone have a good solution for putting a GWT frontend on a python appengine app?
A:
The only alternative (if you can call it that) that I'm familiar with is Pyjamas. Obviously, this is more of a GWT replacement than a GWT-RPC replacement. Beyond that, I think you would be stuck with writing your own communications layer using some sort of REST-type protocol.
A:
You can maybe have a look at the GWT JSON RPC example.
If that fails, there are always several XML parser implementations in Python AND Java :)
A:
I agree with your evaluation of Python's text processing and GWT's quality. Have you considered using Jython? Googling "pyparsing jython" gives some mixed reviews, but it seems there has been some success with recent versions of Jython.
A:
I know I am late to this question...
Have you seen this project?
http://code.google.com/p/python-gwt-rpc/
It might be useful as a starting point.
| Appengine and GWT - feeding the python some java | I realize this is a dated question since appengine now comes in java, but I have a python appengine app that I want to access via GWT. Python is just better for server-side text processing (using pyparsing of course!). I have tried to interpret GWT's client-side RPC and that is convoluted since there is no python counterpart (python-gwt-rpc is out of date). I just tried using JSON and RequestBuilder, but that fails when using SSL. Does anyone have a good solution for putting a GWT frontend on a python appengine app?
| [
"The only alternative (if you can call it that) that I'm familiar with is Pyjamas. Obviously, this is more of a GWT replacement than a GWT-RPC replacement. Beyond that, I think you would be stuck with writing your own communications layer using some sort of REST-type protocol.\n",
"You can maybe have a look at ... | [
1,
0,
0,
0
] | [] | [] | [
"google_app_engine",
"gwt",
"java",
"python"
] | stackoverflow_0001186155_google_app_engine_gwt_java_python.txt |
Q:
basic http authentication with django-piston
I'm a newb to this. I've seen the code snippet at the official site (pasted below).
The problem is how do I deploy this to the server ? Where do I set the username and password credentials ? In the httpd.conf file for Apache ?
from django.conf.urls.defaults import *
from piston.resource import Resource
from piston.authentication import HttpBasicAuthentication
from myapp.handlers import BlogPostHandler, ArbitraryDataHandler
auth = HttpBasicAuthentication(realm="My Realm")
ad = { 'authentication': auth }
blogpost_resource = Resource(handler=BlogPostHandler, **ad)
arbitrary_resource = Resource(handler=ArbitraryDataHandler, **ad)
urlpatterns += patterns('',
url(r'^posts/(?P<post_slug>[^/]+)/$', blogpost_resource),
url(r'^other/(?P<username>[^/]+)/(?P<data>.+)/$', arbitrary_resource),
)
A:
By default piston.authenticate.HttpBasicAuthentication uses
django.contrib.auth.authenticate to check credentials.
In other words: you "set username and password credentials" simply by creating normal Django Users.
| basic http authentication with django-piston | I'm a newb to this. I've seen the code snippet at the official site (pasted below).
The problem is how do I deploy this to the server ? Where do I set the username and password credentials ? In the httpd.conf file for Apache ?
from django.conf.urls.defaults import *
from piston.resource import Resource
from piston.authentication import HttpBasicAuthentication
from myapp.handlers import BlogPostHandler, ArbitraryDataHandler
auth = HttpBasicAuthentication(realm="My Realm")
ad = { 'authentication': auth }
blogpost_resource = Resource(handler=BlogPostHandler, **ad)
arbitrary_resource = Resource(handler=ArbitraryDataHandler, **ad)
urlpatterns += patterns('',
url(r'^posts/(?P<post_slug>[^/]+)/$', blogpost_resource),
url(r'^other/(?P<username>[^/]+)/(?P<data>.+)/$', arbitrary_resource),
)
| [
"By default piston.authenticate.HttpBasicAuthentication uses \ndjango.contrib.auth.authenticate to check credentials.\nIn other words: you \"set username and password credentials\" simply by creating normal Django Users.\n"
] | [
3
] | [] | [] | [
"django",
"django_piston",
"python"
] | stackoverflow_0003297125_django_django_piston_python.txt |
Q:
What's the equivalent of C#'s GetBytes() in Python?
I have
byte[] request = UTF8Encoding.UTF8.GetBytes(requestParams);
in a C# AES encryption only class that I'm converting to Python. Can anyone tell me the Python 2.5 equivalent(I'm using this on google app engine?
Example inputs:
request_params: &r=p&playerid=6263017 (or a combination of query strings)
dev_key: GK1FzK12iPYKE9Kt
dev_iv: E2I21NEwsC9RdSN2
dev_id: 12
Python function:
def Encrypt(self, request_params, dev_key, dev_iv, dev_id):
data_bytes = request_params.encode("utf-8")
block_size = 16
mode = AES.MODE_CBC
assert len(dev_key) == block_size and len(dev_iv) == block_size
pad_char = '0'
pad_length = block_size - len(data_bytes) % block_size
padded_data_bytes = data_bytes + pad_length * pad_char
encrypted_bytes = dev_iv + AES.new(dev_key, mode, dev_iv).encrypt(padded_data_bytes)
base64_encrypted_string = base64.urlsafe_b64encode(str(encrypted_bytes))
request_uri = "http://api.blackoutrugby.com/?d=" + dev_id + "&er=" + base64_encrypted_string
#http://api.blackoutrugby.com/?d=19&er=RTJJNTFORXdzQzNSZFNObNerdsGhiNoeue6c3mzed4Ty1YE-gTlVJVXHz05uPT-8
# output from this Python code, it's incorrect
#http://api.blackoutrugby.com/?d=19&er=16t2waGI2h657pzebN53hPr4kEjOzgsOEZiycDwPXR4=
# correct output from C# code
return request_uri
C# Class:
using System;
using System.Security.Cryptography;
using System.Text;
using System.IO;
using System.Net;
using System.Xml;
using Newtonsoft.Json;
namespace BlackoutRugbyPOC.Controllers {
public class BlackoutRugbyAPI {
public static string Request(string requestParams, string devKey, string devIV, string devID) {
// Create an unencrypted request as an array of bytes
byte[] request = UTF8Encoding.UTF8.GetBytes(requestParams);
byte[] key = UTF8Encoding.UTF8.GetBytes(devKey);
byte[] iv = UTF8Encoding.UTF8.GetBytes(devIV);
AesCryptoServiceProvider aes = new AesCryptoServiceProvider();
aes.Key = key;
aes.IV = iv;
aes.Mode = CipherMode.CBC;
aes.Padding = PaddingMode.Zeros;
// Get the transformer from the AES Encryptor
ICryptoTransform cTransform = aes.CreateEncryptor();
// Use the transformer to encrypt our request
byte[] result = cTransform.TransformFinalBlock(request, 0, request.Length);
aes.Clear();
// Encode to base64
string encryptedRequest = Convert.ToBase64String(result, 0, result.Length);
// Send request to API
string requestUri = "http://api.blackoutrugby.com/?d=" + devID + "&er=" + encryptedRequest;
string xmlResponse = getWebResponse(requestUri);
return XmlToJson(xmlResponse);
}
private static string getWebResponse(string url) {
string html = "";
WebRequest request = HttpWebRequest.Create(url);
WebResponse response = request.GetResponse();
using (StreamReader reader = new StreamReader(response.GetResponseStream())) {
html = reader.ReadToEnd();
}
return html;
}
public static string XmlToJson(string xml) {
if (string.IsNullOrEmpty(xml))
throw new ArgumentNullException("XML Input");
XmlDocument doc = new XmlDocument();
try {
doc.LoadXml(xml);
} catch {
throw new ArgumentNullException("Input could not be loaded into XML Document");
}
return JsonConvert.SerializeXmlNode(doc, Newtonsoft.Json.Formatting.Indented);
}
}
}
Thanks,
Denis
A:
Don't know where you got the following code from
data_bytes = str.encode(request_params)
key_bytes = str.encode(dev_key)
iv_bytes = str.encode(dev_iv)
but you should know that it is equivalent to the following:
data_bytes = request_params.encode("ascii")
key_bytes = dev_key.encode("ascii")
iv_bytes = dev_iv.encode("ascii")
which means that non-ASCII characters in any of the three variables will cause an error (I hope you don't make up an AES key of ASCII characters only?).
In Python 2.x, str objects (byte[] in C#) are bytes and unicode objects (string in C#) are for text. This confusing fact was changed in Python 3.x, by the way.
That means if request_params is a Unicode object, you should encode it as UTF-8, and if it's a str object, you should assume (or check) that it is already encoded as UTF-8. So it might be something like:
if isinstance(request_params, unicode):
data_bytes = request_params.encode("utf-8")
else:
request_params.decode("utf-8") # optional check whether it is correct UTF-8
data_bytes = request_params
As for key/IV, they will always be binary data (e.g. 16 bytes for AES-128), not text. So they don't have a character encoding. Remove those two lines of code and probably replace them with
assert len(dev_key) == block_size and len(dev_iv) == block_size
| What's the equivalent of C#'s GetBytes() in Python? | I have
byte[] request = UTF8Encoding.UTF8.GetBytes(requestParams);
in a C# AES encryption only class that I'm converting to Python. Can anyone tell me the Python 2.5 equivalent(I'm using this on google app engine?
Example inputs:
request_params: &r=p&playerid=6263017 (or a combination of query strings)
dev_key: GK1FzK12iPYKE9Kt
dev_iv: E2I21NEwsC9RdSN2
dev_id: 12
Python function:
def Encrypt(self, request_params, dev_key, dev_iv, dev_id):
data_bytes = request_params.encode("utf-8")
block_size = 16
mode = AES.MODE_CBC
assert len(dev_key) == block_size and len(dev_iv) == block_size
pad_char = '0'
pad_length = block_size - len(data_bytes) % block_size
padded_data_bytes = data_bytes + pad_length * pad_char
encrypted_bytes = dev_iv + AES.new(dev_key, mode, dev_iv).encrypt(padded_data_bytes)
base64_encrypted_string = base64.urlsafe_b64encode(str(encrypted_bytes))
request_uri = "http://api.blackoutrugby.com/?d=" + dev_id + "&er=" + base64_encrypted_string
#http://api.blackoutrugby.com/?d=19&er=RTJJNTFORXdzQzNSZFNObNerdsGhiNoeue6c3mzed4Ty1YE-gTlVJVXHz05uPT-8
# output from this Python code, it's incorrect
#http://api.blackoutrugby.com/?d=19&er=16t2waGI2h657pzebN53hPr4kEjOzgsOEZiycDwPXR4=
# correct output from C# code
return request_uri
C# Class:
using System;
using System.Security.Cryptography;
using System.Text;
using System.IO;
using System.Net;
using System.Xml;
using Newtonsoft.Json;
namespace BlackoutRugbyPOC.Controllers {
public class BlackoutRugbyAPI {
public static string Request(string requestParams, string devKey, string devIV, string devID) {
// Create an unencrypted request as an array of bytes
byte[] request = UTF8Encoding.UTF8.GetBytes(requestParams);
byte[] key = UTF8Encoding.UTF8.GetBytes(devKey);
byte[] iv = UTF8Encoding.UTF8.GetBytes(devIV);
AesCryptoServiceProvider aes = new AesCryptoServiceProvider();
aes.Key = key;
aes.IV = iv;
aes.Mode = CipherMode.CBC;
aes.Padding = PaddingMode.Zeros;
// Get the transformer from the AES Encryptor
ICryptoTransform cTransform = aes.CreateEncryptor();
// Use the transformer to encrypt our request
byte[] result = cTransform.TransformFinalBlock(request, 0, request.Length);
aes.Clear();
// Encode to base64
string encryptedRequest = Convert.ToBase64String(result, 0, result.Length);
// Send request to API
string requestUri = "http://api.blackoutrugby.com/?d=" + devID + "&er=" + encryptedRequest;
string xmlResponse = getWebResponse(requestUri);
return XmlToJson(xmlResponse);
}
private static string getWebResponse(string url) {
string html = "";
WebRequest request = HttpWebRequest.Create(url);
WebResponse response = request.GetResponse();
using (StreamReader reader = new StreamReader(response.GetResponseStream())) {
html = reader.ReadToEnd();
}
return html;
}
public static string XmlToJson(string xml) {
if (string.IsNullOrEmpty(xml))
throw new ArgumentNullException("XML Input");
XmlDocument doc = new XmlDocument();
try {
doc.LoadXml(xml);
} catch {
throw new ArgumentNullException("Input could not be loaded into XML Document");
}
return JsonConvert.SerializeXmlNode(doc, Newtonsoft.Json.Formatting.Indented);
}
}
}
Thanks,
Denis
| [
"Don't know where you got the following code from\ndata_bytes = str.encode(request_params)\nkey_bytes = str.encode(dev_key)\niv_bytes = str.encode(dev_iv)\n\nbut you should know that it is equivalent to the following:\ndata_bytes = request_params.encode(\"ascii\")\nkey_bytes = dev_key.encode(\"ascii\")\niv_bytes = ... | [
2
] | [
" buffer = file.read(bytes)\n\n"
] | [
-1
] | [
"aes",
"c#",
"encryption",
"python"
] | stackoverflow_0003297030_aes_c#_encryption_python.txt |
Q:
File upload with django
What is wrong with the following code for file uploading.The request.FILES['file'] looks empty
Models:
from django.db import models
from django import forms
class UploadFileForm(forms.Form):
title = forms.CharField(max_length=50)
file = forms.FileField(label="Your file")
Views:
def index(request):
if request.method == 'POST':
a=request.POST
logging.debug(a["title"])
logging.debug(a["file"])
form = UploadFileForm()
form = UploadFileForm(request.POST, request.FILES)
handle_uploaded_file(request.FILES['file'])
if form.is_valid():
handle_uploaded_file(request.FILES['file'])
return HttpResponseRedirect('/Files/')
else:
form = UploadFileForm()
return render_to_response('Files/index.html', {'form': form})
def handle_uploaded_file(f):
logging.debug("here1")
#destination = open('some/file/name.txt', 'wb+')
destination = open('/tmp', 'wb+')
for chunk in f.chunks():
destination.write(chunk)
destination.close()
Templates:
<form name="lang" action="/test/" method="post">
<table>
<tr><td>
<b> {{ form.file.label_tag }}</b> {{ form.file}}
</td></tr>
<tr><td>
<input type="hidden" value="title" name="title" id="title" />
<input type="submit" value="Save" id="Save"/>
</td></tr>
</table>
</form>
A:
You need to set enctype attribute on your form:
<form enctype="multipart/form-data" method="post" action="/foo/">
Like they say in the docs.
| File upload with django | What is wrong with the following code for file uploading.The request.FILES['file'] looks empty
Models:
from django.db import models
from django import forms
class UploadFileForm(forms.Form):
title = forms.CharField(max_length=50)
file = forms.FileField(label="Your file")
Views:
def index(request):
if request.method == 'POST':
a=request.POST
logging.debug(a["title"])
logging.debug(a["file"])
form = UploadFileForm()
form = UploadFileForm(request.POST, request.FILES)
handle_uploaded_file(request.FILES['file'])
if form.is_valid():
handle_uploaded_file(request.FILES['file'])
return HttpResponseRedirect('/Files/')
else:
form = UploadFileForm()
return render_to_response('Files/index.html', {'form': form})
def handle_uploaded_file(f):
logging.debug("here1")
#destination = open('some/file/name.txt', 'wb+')
destination = open('/tmp', 'wb+')
for chunk in f.chunks():
destination.write(chunk)
destination.close()
Templates:
<form name="lang" action="/test/" method="post">
<table>
<tr><td>
<b> {{ form.file.label_tag }}</b> {{ form.file}}
</td></tr>
<tr><td>
<input type="hidden" value="title" name="title" id="title" />
<input type="submit" value="Save" id="Save"/>
</td></tr>
</table>
</form>
| [
"You need to set enctype attribute on your form:\n<form enctype=\"multipart/form-data\" method=\"post\" action=\"/foo/\">\n\nLike they say in the docs.\n"
] | [
7
] | [] | [] | [
"django",
"django_models",
"django_templates",
"django_views",
"python"
] | stackoverflow_0003298176_django_django_models_django_templates_django_views_python.txt |
Q:
Forcing a variable to be an integer
errors = int(0)
for i in range(len(expectedData)):
if data[i] != expectedData[i]:
errors += int(binary_compare(data[i], expectedData[i]))
return errors
I have the above code which I am trying to use to calculate some integer (number of errors) for some data. I have casted everything I can see possible as an integer, yet the line "errors += ..." still appends the value, rather than adds it.
For example, if my answer should be 7, I might get 500002. (5 + 0 + 0 + .. + 2). I have never run into this before. The function binary_compare is returning an integer as well, but I'm completely in the dark as to why this isn't working.
A:
python is not javascript
it's no way to get concatenated strings instead of math sum, when you do count += value starting with count = 0. if you try to add a string to integer, exception is raised:
>>> x = 0
>>> x += "1"
TypeError: unsupported operand type(s) for +=: 'int' and 'str'
to compare values of which you don't know whether they are strings or integers, i'd use
str(data[i]).strip() == str(expectedData[i]).strip()
for noninteger-proof math sum, you might want to do something like this
try:
value = int(expectedData[i])
except:
value = 0
count += value
A:
I think the error is outside of your code, but anyway, in Python, list operations are seldom done with loops, as this focuses on the implementation rather on the purpose. List comprehension, generators etc are preferred, and there are also many built-in and standard library functions for common tasks.
In your case, I would write the function as
return sum(binary_compare(x, y) for x, y in zip(data, expectedData) if x != y)
If you are using Python 2.x, itertools.izip should be used instead of zip.
| Forcing a variable to be an integer | errors = int(0)
for i in range(len(expectedData)):
if data[i] != expectedData[i]:
errors += int(binary_compare(data[i], expectedData[i]))
return errors
I have the above code which I am trying to use to calculate some integer (number of errors) for some data. I have casted everything I can see possible as an integer, yet the line "errors += ..." still appends the value, rather than adds it.
For example, if my answer should be 7, I might get 500002. (5 + 0 + 0 + .. + 2). I have never run into this before. The function binary_compare is returning an integer as well, but I'm completely in the dark as to why this isn't working.
| [
"python is not javascript\nit's no way to get concatenated strings instead of math sum, when you do count += value starting with count = 0. if you try to add a string to integer, exception is raised:\n>>> x = 0\n>>> x += \"1\"\nTypeError: unsupported operand type(s) for +=: 'int' and 'str'\n\nto compare values of w... | [
4,
2
] | [] | [] | [
"python"
] | stackoverflow_0003292718_python.txt |
Q:
trickle down unit tests
If I'm writing a library in C that includes a Python interface, is it OK to just write unit tests for the functions, etc in the Python interface? Assuming the Python interface is complete, it should imply the C code works.
Mostly I'm being lazy in that the Python unit test thing takes almost zero effort to use.
thanks,
-nick
A:
Tests through the Python interface will be valuable acceptance tests for your library. They will not however be unit tests.
Unit tests are written by the same coders, in the same language, on the same platform as the unit which they test. These should be written too!
You're right, though, unit testing in Python is far easier than C++ (or even C, which is what you said!).
A:
If you only care if the Python library works, then test that. This will give you significant confirmation that the C library is robust, but the maxim "if you didn't test it, it doesn't work" still mostly applies and I wouldn't export the library without the test harness.
You could, in theory, test that the processor microcode is doing its job properly but one usually doesn't.
A:
Ideally, you'd write unit tests for each.
Your Python library calls probably (hopefully?) don't have a one-to-one correspondence to your C library calls, because that wouldn't be a very Pythonic interface, so if you only unit test your Python interface, there would be variations and sequences of C library calls that weren't tested.
A:
I see two mains restrictions to unit testing thru the Python interface. Whether it is OK to testing with those restrictions or not depends on what the library does, how it is implemented, and on the alignment of the Python interface on the interface of the C library.
the library can only be exercised the way the Python library is using it. This is not a problem as far as the Python interface is the only client of the C library.
the Python unit tests do not have access to the internals of the C library as unit tests written in C would have: only what is exposed via the Python interface is reachable. Therefore
if a problem arises after 10 calls to the Python interface, 10 calls will be needed to reproduce it, while a unit test written in C could create the fixture directly, without the 10 calls. This can make Python tests slower.
the Python unit tests couldn't be as isolated as C unit tests could be as they may not been able to reset the internals of the library
| trickle down unit tests | If I'm writing a library in C that includes a Python interface, is it OK to just write unit tests for the functions, etc in the Python interface? Assuming the Python interface is complete, it should imply the C code works.
Mostly I'm being lazy in that the Python unit test thing takes almost zero effort to use.
thanks,
-nick
| [
"Tests through the Python interface will be valuable acceptance tests for your library. They will not however be unit tests.\nUnit tests are written by the same coders, in the same language, on the same platform as the unit which they test. These should be written too!\nYou're right, though, unit testing in Python ... | [
5,
1,
0,
0
] | [] | [] | [
"c",
"python",
"unit_testing"
] | stackoverflow_0003294526_c_python_unit_testing.txt |
Q:
How do I get a windows border like this in Tkinter?
Is there any way to get a border like this in Tkinter? Notice how it lacks the buttons on the top right. Also I don't want this program to show in the task bar.
This is in windows 7, btw.
A:
Tk (and thus, Tkinter) has a command for removing all window manager decoration. This command in tkinter is the "wm_overrideredirect" method of toplevel windows. Pass it a parameter of True to remove the window manager decorations. You can then draw whatever borders you want, usually by packing a canvas over the entire window and drawing on the canvas.
However, when I experiment with this on my Mac, the window appears properly but won't take focus. Perhaps this is a bug in Tkinter. I don't see the same problem with identical code in Tcl.
A:
The WS_DLGFRAME window style should give you a window without a titlebar and WS_EX_TOOLWINDOW is normally also used for a window like this so it is not visible in the taskbar (Or with a hidden parent window like control panel dialogs before Vista) You can figure out the exact window styles with a tool like Spy++ (Visual Studio) or WinSpy++
| How do I get a windows border like this in Tkinter? | Is there any way to get a border like this in Tkinter? Notice how it lacks the buttons on the top right. Also I don't want this program to show in the task bar.
This is in windows 7, btw.
| [
"Tk (and thus, Tkinter) has a command for removing all window manager decoration. This command in tkinter is the \"wm_overrideredirect\" method of toplevel windows. Pass it a parameter of True to remove the window manager decorations. You can then draw whatever borders you want, usually by packing a canvas over the... | [
2,
1
] | [] | [] | [
"python",
"tkinter",
"user_interface",
"windows_7"
] | stackoverflow_0003295659_python_tkinter_user_interface_windows_7.txt |
Q:
sort a dictionary according to their values in python
Possible Duplicate:
Sort by key of dictionary inside a dictionary in Python
I have a dictionary:
d={'abc.py':{'map':'someMap','distance':11},
'x.jpg':{'map':'aMap','distance':2},....}
Now what I need is: I need to sort d according to their distances?
I tried sorted(d.items(),key=itemgetter(1,2), but it's not working.
How can it be done?
A:
You cannot (really) influence the order in which your dict keys appear. If you want to iterate over the sorted keys, you could for instance use
sorted(d.keys(), key=lambda x: d[x]['distance'])
A:
A dictonary can't be sorted. So you have to convert your data to a list and sort this list.
Maybe you convert your dict to a list of tuples (key, value) and sort then.
A:
You can do it like this:
sorted(d.items(), key=lambda x:x[1]['distance'])
| sort a dictionary according to their values in python |
Possible Duplicate:
Sort by key of dictionary inside a dictionary in Python
I have a dictionary:
d={'abc.py':{'map':'someMap','distance':11},
'x.jpg':{'map':'aMap','distance':2},....}
Now what I need is: I need to sort d according to their distances?
I tried sorted(d.items(),key=itemgetter(1,2), but it's not working.
How can it be done?
| [
"You cannot (really) influence the order in which your dict keys appear. If you want to iterate over the sorted keys, you could for instance use\nsorted(d.keys(), key=lambda x: d[x]['distance'])\n\n",
"A dictonary can't be sorted. So you have to convert your data to a list and sort this list.\nMaybe you convert y... | [
4,
3,
1
] | [] | [] | [
"dictionary",
"key",
"python",
"sorting"
] | stackoverflow_0003298629_dictionary_key_python_sorting.txt |
Q:
Delete an item from a list
Hey, I was trying to delete an item form a list (without using set):
list1 = []
for i in range(2,101):
for j in range(2,101):
list1.append(i ** j)
list1.sort()
for k in range(1,len(list1) - 1):
if (list1[k] == list1[k - 1]):
list1.remove(list1[k])
print "length = " + str(len(list1))
The set function works fine, but i want to apply this method. Except I get:
IndexError: list index out of range
on the statement:
if (list1[k] == list1[k - 1]):
Edited to add
(Thanks to Ned Batchelder) the working code is:
list1 = []
for i in range(2,101):
for j in range(2,101):
list1.append(i ** j)
list1.sort()
k = 0
while k < len(list1) - 1: # while loop instead of for loop because "The range function is evaluated once before the loop is entered"
k += 1
if (list1[k] == list1[k - 1]):
list1.remove(list1[k])
list1.sort()
k -= 1 # "If you find a duplicate, you don't want to move onto the next iteration, since you'll miss potential runs of more than two duplicates"
print "length = " + str(len(list1))
A:
Your code doesn't work because in your loop, you are iterating over all the indexes in the original list, but shortening the list as you go. At the end of the iteration, you will be accessing indexes that no longer exist:
for k in range(1,len(list1) - 1):
if (list1[k] == list1[k - 1]):
list1.remove(list1[k])
The range function is evaluated once before the loop is entered, creating a list of all the indexes in the list. Each call to remove shortens the list by one, so if you remove any elements, you're guaranteed to get your error at the end of the list.
If you want to use a loop like this, try:
k = 1
while k < len(list1):
if list1[k] == list1[k-1]:
del list1[k]
else:
k += 1
I fixed a few other things:
You don't need parentheses around the condition in Python if statements.
If you find a duplicate, you don't want to move onto the next iteration, since you'll miss potential runs of more than two duplicates.
You want to start from index 1, not zero, since k=0 will access list1[-1].
A:
It looks as if you're trying to uniquify a list (clarification would be awesome) so take a look here: http://www.peterbe.com/plog/uniqifiers-benchmark
There is also this question here on SO: In Python, what is the fastest algorithm for removing duplicates from a list so that all elements are unique *while preserving order*?
A:
Instead of removing items Write a list comprehension of the things you want in the new list:
list1[:] = [list1[k] for k in range(1,len(list1) - 1)
if not list1[k] == list1[k - 1] ]
Your method breaks because you remove items from the list. When you do that, the list becomes shorter and the next loop iteration has skipped a item. Say you look at k=0 and L = [1,2,3]. You delete the first item, so L = [2,3] and the next k=1. So you look at L[1] which is 3 -- you skipped the 2!
So: Never change the list you iterate on
A:
You can use del :
l = [1, 2, 3, 4]
del l[2]
print l
[1, 2, 4]
| Delete an item from a list | Hey, I was trying to delete an item form a list (without using set):
list1 = []
for i in range(2,101):
for j in range(2,101):
list1.append(i ** j)
list1.sort()
for k in range(1,len(list1) - 1):
if (list1[k] == list1[k - 1]):
list1.remove(list1[k])
print "length = " + str(len(list1))
The set function works fine, but i want to apply this method. Except I get:
IndexError: list index out of range
on the statement:
if (list1[k] == list1[k - 1]):
Edited to add
(Thanks to Ned Batchelder) the working code is:
list1 = []
for i in range(2,101):
for j in range(2,101):
list1.append(i ** j)
list1.sort()
k = 0
while k < len(list1) - 1: # while loop instead of for loop because "The range function is evaluated once before the loop is entered"
k += 1
if (list1[k] == list1[k - 1]):
list1.remove(list1[k])
list1.sort()
k -= 1 # "If you find a duplicate, you don't want to move onto the next iteration, since you'll miss potential runs of more than two duplicates"
print "length = " + str(len(list1))
| [
"Your code doesn't work because in your loop, you are iterating over all the indexes in the original list, but shortening the list as you go. At the end of the iteration, you will be accessing indexes that no longer exist:\nfor k in range(1,len(list1) - 1):\n if (list1[k] == list1[k - 1]):\n list1.remove... | [
5,
3,
2,
1
] | [] | [] | [
"list",
"python",
"unique"
] | stackoverflow_0003299128_list_python_unique.txt |
Q:
Django admin style application for Java
I'm looking for a web framework or an application in Java that does what Django admin does - provides a friendly user interface for editing data in a relational database. I know it's possible to run Django on Jython and that way achieve a somewhat Java-based solution, but I'd prefer something pure-Java to keep the higher-ups happy.
A:
Try Grails. It's a framework modeled after Django, written in Groovy. Groovy is a JVM based language, source-compatible with Java.
To get a Django-like admin interface, you write your models, let Grails generate all the rest (controllers and views), and you're done.
Some resources:
Quick Start Tutorial
Screencast showing Scaffolding
A:
Spring ROO is probably what you are looking for - it's a pure Java solution.
A:
What you mean is CRUD generating (CRUD: create, read, update, delete = typical admin interface). For example Rife can do this.
| Django admin style application for Java | I'm looking for a web framework or an application in Java that does what Django admin does - provides a friendly user interface for editing data in a relational database. I know it's possible to run Django on Jython and that way achieve a somewhat Java-based solution, but I'd prefer something pure-Java to keep the higher-ups happy.
| [
"Try Grails. It's a framework modeled after Django, written in Groovy. Groovy is a JVM based language, source-compatible with Java.\nTo get a Django-like admin interface, you write your models, let Grails generate all the rest (controllers and views), and you're done.\nSome resources:\n\nQuick Start Tutorial\nScree... | [
4,
4,
0
] | [] | [] | [
"django",
"java",
"python"
] | stackoverflow_0000706405_django_java_python.txt |
Q:
How do I make a nasty C++ program scriptable with Python and/or Lua?
I'm confronted with the task of making a C++ app scriptable by users. The app has been in development for several years with no one wasting a thought on this before. It contains all sorts of niceties like multithreading, template wizardry and multiple inheritance. As the scripting language, Python is preferred, but Lua might be accepted if it is significantly easier to implement.
Question 1
From what I have learned so far, there are broadly speaking two ways to integrate Python/Lua with C++ : "extending" and "embedding".
In this case, it looks like I need both. The scripting language need access to objects, methods and data from the app but needs to be called by the app once the user has written the script - without restarting anything.
How is this usually done in the real world?
Question 2
There seems to be a bewildering array of of manual solutions and binding generators out there, all of them less than perfect.
swig, pyste, Py++, ctypes, Boost.Python sip, PyCXX, pybindgen, robin, (Cython/Pyrex, Weave)
CppLua, Diluculum, Luabind, Luabridge, LuaCpp, Luna/LunaWrapper, MLuaBind, MultiScript, OOLua, SLB, Sweet Lua, lux
(this list from the lua wiki)
CPB, tolua, tolua++, toLuaxx, luna and again swig
Most commments on these found on the web are a little out of date. For example, swig is said to be difficult in non-trivial cases and to generate incomprehensible code. OTOH, it has recently gone to v2.0.
Some of the above use pygccxml to let gcc analyze the C++ code and then genarate the binding. I find this idea appealing, as gcc probably understands the code better than i do :-). Does this work well?
Testing them all might easily cost me half of the time allocated for the whole project.
So, which ones do you recommend?
A:
I wouldn't recommend swig as it's hard to get it to generate satisfactory binding in complex situations: been there, done that. I had to write a horrible script that "parsed" the original C++ code to generate some acceptable C++ code that swig could chew and generate acceptable bindings. So, in general: avoid ANY solution that relies on parsing the original C++ program.
Between Lua and Python: I have found Lua MUCH, MUCH better documented and more cleanly implemented. Python has a GIL (global lock), whereas with Lua, you can have an interpreter instance in each thread, for example.
So, if you can choose, I'd recommend Lua. It is smaller language, easier to comprehend, easier to embed (much cleaner and smaller API, with excellent documentation). I have used luabind for a small project of mine and found it easy to use.
A:
Regarding Question 1 - yes, you need to do both.
You would expose your applications scripting interface to an embedded interpreter, which then runs the user script in question.
The Python manuals section on embedding includes a section Extending Embedded Python and there are tutorials for similar things for Lua, see e.g. this article. Of course there are probably easier ways to be found when you have decided with what scripting language and binding mechanism you want to go.
A:
Some of the above use pygccxml to let gcc analyze the C++ code and then genarate the binding. I find this idea appealing, as gcc probably understands the code better than i do :-). Does this work well?
A similar approach is used in the Lua Qt binding - lqt. It uses cpptoxml to generate an XML file containing all classes and methods with parameters, and generated binding C++ code according to that.
It works really well, the generator is able to bind almost all Qt classes and methods, including virtual methods, overloaded operators, selected template classes, signal/slot mechanism etc.
Although it was created specially for Qt, it has a "noqt" mode, in which it can serve as a generic binder, unfortunately I have no experience with it, so I cannot tell how much work it would be to bind your code.
A:
My experience may not be much, but I figure it's at least worth what you paid for it ;)
I've done some basic "hello world" python modules, and I couldn't really get into swig - it seemed like a lot of overhead for what I was doing. Of course it's also possible that it's just the right amount for your needs.
A:
Try Boost::Python, it has somewhat of a learning curve associated with it but it is the best tool for the job in my view, we have a huge real time system and developed the scripting library for the QA in Boost::Python.
| How do I make a nasty C++ program scriptable with Python and/or Lua? | I'm confronted with the task of making a C++ app scriptable by users. The app has been in development for several years with no one wasting a thought on this before. It contains all sorts of niceties like multithreading, template wizardry and multiple inheritance. As the scripting language, Python is preferred, but Lua might be accepted if it is significantly easier to implement.
Question 1
From what I have learned so far, there are broadly speaking two ways to integrate Python/Lua with C++ : "extending" and "embedding".
In this case, it looks like I need both. The scripting language need access to objects, methods and data from the app but needs to be called by the app once the user has written the script - without restarting anything.
How is this usually done in the real world?
Question 2
There seems to be a bewildering array of of manual solutions and binding generators out there, all of them less than perfect.
swig, pyste, Py++, ctypes, Boost.Python sip, PyCXX, pybindgen, robin, (Cython/Pyrex, Weave)
CppLua, Diluculum, Luabind, Luabridge, LuaCpp, Luna/LunaWrapper, MLuaBind, MultiScript, OOLua, SLB, Sweet Lua, lux
(this list from the lua wiki)
CPB, tolua, tolua++, toLuaxx, luna and again swig
Most commments on these found on the web are a little out of date. For example, swig is said to be difficult in non-trivial cases and to generate incomprehensible code. OTOH, it has recently gone to v2.0.
Some of the above use pygccxml to let gcc analyze the C++ code and then genarate the binding. I find this idea appealing, as gcc probably understands the code better than i do :-). Does this work well?
Testing them all might easily cost me half of the time allocated for the whole project.
So, which ones do you recommend?
| [
"I wouldn't recommend swig as it's hard to get it to generate satisfactory binding in complex situations: been there, done that. I had to write a horrible script that \"parsed\" the original C++ code to generate some acceptable C++ code that swig could chew and generate acceptable bindings. So, in general: avoid ... | [
12,
1,
1,
0,
0
] | [] | [] | [
"binding",
"c++",
"lua",
"python",
"scriptable"
] | stackoverflow_0003299067_binding_c++_lua_python_scriptable.txt |
Q:
adding 2 1/2 hours to a time object in python
I need to be able to convert time on an time object I recieve from a sql database into python. Here is the current python code I am using without any conversions. I need to add 2 and 1/2 hours to the time.
def getLastReport(self, sql):
self.connectDB()
cursor.execute(sql)
lastReport = cursor.fetchall()
date = lastReport[0][0].strftime('%Y-%m-%d %H:%M UTC')
dataset_id = int(lastReport[0][1])
cursor.close()
DATABASE.close()
return date, dataset_id
A:
Have you looked at the datetime module? http://docs.python.org/library/datetime.html
Convert your SQL time into a datetime, and make a timedelta object of 2.5 hours. Then add the two.
from datetime import datetime
dt = datetime.strptime( date, '%Y-%m-%d %H:%M' )
dt_plus_25 = dt + datetime.timedelta( 0, 2*60*60 + 30*60 )
A:
Add datetime.timedelta(0, 2.5*60*60).
A:
Try this (switch sqlite3 with whatever db interface you are using):
f= lastReport[0][0]
newtime = sqlite3.Time(f.hour + 2, f.minute + 30, f.second, f.microsecond)
I thought that adding datetime.timedelta(0, 2.5*60*60) like Igancio suggests would be the best solution, but I get:
'unsupported operand type(s) for +: 'datetime.time' and 'datetime.timedelta'.
A:
I usually use the 3rd party module, dateutil, for this sort of thing. It makes this sort of time-shifting much easier to do and understand:
http://labix.org/python-dateutil
| adding 2 1/2 hours to a time object in python | I need to be able to convert time on an time object I recieve from a sql database into python. Here is the current python code I am using without any conversions. I need to add 2 and 1/2 hours to the time.
def getLastReport(self, sql):
self.connectDB()
cursor.execute(sql)
lastReport = cursor.fetchall()
date = lastReport[0][0].strftime('%Y-%m-%d %H:%M UTC')
dataset_id = int(lastReport[0][1])
cursor.close()
DATABASE.close()
return date, dataset_id
| [
"Have you looked at the datetime module? http://docs.python.org/library/datetime.html\nConvert your SQL time into a datetime, and make a timedelta object of 2.5 hours. Then add the two.\nfrom datetime import datetime\n\ndt = datetime.strptime( date, '%Y-%m-%d %H:%M' )\ndt_plus_25 = dt + datetime.timedelta( 0, 2*6... | [
3,
1,
1,
0
] | [] | [] | [
"mysql",
"python",
"time"
] | stackoverflow_0003298935_mysql_python_time.txt |
Q:
how to move all those imports to standalone file
Imagine situation:
I have view directory with tons of different views. all views have about 6 lines with imports - in the beginning of the file. it's pretty damn hard copy paste those 6 lines every time I create new view.
I usually using all those imports.
from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required, user_passes_test
from django.core.files.base import ContentFile
from django.core.urlresolvers import reverse
from django.core import paginator
from django.db import connection
from django.db.models import Q
from django.http import HttpResponseRedirect, Http404, HttpResponse, HttpResponseForbidden
from django.shortcuts import render_to_response, get_object_or_404
from django.template import loader, Context, RequestContext
from django.utils.translation import ugettext as _
things like that..
SO QUESTION IS:
HOW to move all those imports to standalone file, so that I could include that file in every view i create. instead of tones imports I would have one file with imports for all views. I don't think that this would kill perfomance of application or smtng. I would use that file just for most common imports or smtng like that.. maybe it's damn php logic still with me, I know that includes in python is bad practise.. but I need a workaround for this situation.. it's getting on my nerves
A:
You could put them in a module, say imports.py, and then do this in your views:
from imports import *
But I think most Python programmers would argue (and I'd agree) that it's probably better to list your imports at the top of the module file where you actually use them, like you're already doing. It may seem a bit verbose, but it's a lot easier to track down external modules when they're conveniently listed at the top of the file. It also makes it more explicit what you're importing.
A:
If you're doing the same things over and over and over, then you should do them in a separate module and just import that module.
| how to move all those imports to standalone file | Imagine situation:
I have view directory with tons of different views. all views have about 6 lines with imports - in the beginning of the file. it's pretty damn hard copy paste those 6 lines every time I create new view.
I usually using all those imports.
from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required, user_passes_test
from django.core.files.base import ContentFile
from django.core.urlresolvers import reverse
from django.core import paginator
from django.db import connection
from django.db.models import Q
from django.http import HttpResponseRedirect, Http404, HttpResponse, HttpResponseForbidden
from django.shortcuts import render_to_response, get_object_or_404
from django.template import loader, Context, RequestContext
from django.utils.translation import ugettext as _
things like that..
SO QUESTION IS:
HOW to move all those imports to standalone file, so that I could include that file in every view i create. instead of tones imports I would have one file with imports for all views. I don't think that this would kill perfomance of application or smtng. I would use that file just for most common imports or smtng like that.. maybe it's damn php logic still with me, I know that includes in python is bad practise.. but I need a workaround for this situation.. it's getting on my nerves
| [
"You could put them in a module, say imports.py, and then do this in your views:\nfrom imports import *\n\nBut I think most Python programmers would argue (and I'd agree) that it's probably better to list your imports at the top of the module file where you actually use them, like you're already doing. It may seem ... | [
2,
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0003300568_django_python.txt |
Q:
SQLAlchemy truncating Column=(Integer)
weird issue here:
I have a reflected SQL alchemy class that looks like this:
class Install(Base):
__tablename__ = 'install'
id = Column(Integer, primary_key=True)
ip_address = Column(Integer)
I convert the string representation ("1.2.3.4") to int using:
struct.unpack('!L', socket.inet_aton(ip_address))[0]
This does work, I've made sure it's converting IPs right. However, when I look at the database, most of them have been truncated to "2147483647"
2147483647
I can't find out how to stop this truncation, I know that MySQL can handle this, why is SQLAlchemy doing this to my integers?
Thanks in advance!
A:
Fixed it!
For MySQL:
Make sure you are using unsigned INTs, and then use the mysql.MSInteger(unsigned=True) type:
from sqlalchemy.databases import mysql
[..]
class Install(Base):
__tablename__ = 'install'
id = Column(Integer, primary_key=True)
ip_address = Column(mysql.MSInteger(unsigned=True))
| SQLAlchemy truncating Column=(Integer) | weird issue here:
I have a reflected SQL alchemy class that looks like this:
class Install(Base):
__tablename__ = 'install'
id = Column(Integer, primary_key=True)
ip_address = Column(Integer)
I convert the string representation ("1.2.3.4") to int using:
struct.unpack('!L', socket.inet_aton(ip_address))[0]
This does work, I've made sure it's converting IPs right. However, when I look at the database, most of them have been truncated to "2147483647"
2147483647
I can't find out how to stop this truncation, I know that MySQL can handle this, why is SQLAlchemy doing this to my integers?
Thanks in advance!
| [
"Fixed it!\nFor MySQL:\nMake sure you are using unsigned INTs, and then use the mysql.MSInteger(unsigned=True) type:\nfrom sqlalchemy.databases import mysql\n[..]\nclass Install(Base):\n __tablename__ = 'install'\n id = Column(Integer, primary_key=True)\n ip_address = Column(mysql.MSInteger(unsigned=True))... | [
3
] | [] | [] | [
"integer",
"mysql",
"python",
"sqlalchemy"
] | stackoverflow_0003300406_integer_mysql_python_sqlalchemy.txt |
Q:
How do I set a breakpoint in a module other than the one I am running in Python IDLE?
If I edit two modules, eggs and ham, and module eggs imports ham, how do I run module eggs such that IDLE stops at breakpoints set in ham? So far, I have only been able to get IDLE to recognize breakpoints set in the module actually being run, not those being imported.
A:
start IDLE
open eggs, open ham
set desired breakpoints in both files
go to IDLE's shell, select Debug=>Debugger
go back to eggs and to run.
You should stop at break points in each file. (It works, I just tested it.)
| How do I set a breakpoint in a module other than the one I am running in Python IDLE? | If I edit two modules, eggs and ham, and module eggs imports ham, how do I run module eggs such that IDLE stops at breakpoints set in ham? So far, I have only been able to get IDLE to recognize breakpoints set in the module actually being run, not those being imported.
| [
"\nstart IDLE\nopen eggs, open ham\nset desired breakpoints in both files\ngo to IDLE's shell, select Debug=>Debugger\ngo back to eggs and to run.\n\nYou should stop at break points in each file. (It works, I just tested it.)\n"
] | [
8
] | [] | [] | [
"python",
"python_idle"
] | stackoverflow_0003300665_python_python_idle.txt |
Q:
Mapping python tuple and R list with rpy2?
I'm having some trouble to understand the mapping with rpy2 object and python object.
I have a function(x) which return a tuple object in python, and i want to map this tuple object with R object list or vector.
First, i'm trying to do this :
# return a python tuple into this r object tlist
robjects.r.tlist = get_max_ticks(x)
#Convert list into dataframe
r('x <- as.data.frame(tlist,row.names=c("seed","ticks"))')
FAIL with error :
rinterface.RRuntimeError: Error in eval(expr, envir, enclos) : object 'tlist' not found
So i'm trying an other strategy :
robjects.r["tlist"] = get_max_ticks(x)
r('x <- as.data.frame(tlist,row.names=c("seed","ticks"))')
FAIL with this error :
TypeError: 'R' object does not support item assignment
Could you help me to understand ?
Thanks a lot !!
A:
Use globalEnv:
import rpy2.robjects as ro
r=ro.r
def get_max_ticks():
return (1,2)
ro.globalEnv['tlist'] = ro.FloatVector(get_max_ticks())
r('x <- as.data.frame(tlist,row.names=c("seed","ticks"))')
print(r['x'])
# tlist
# seed 1
# ticks 2
It may be possible to access symbols in the R namespace with this type of notation: robjects.r.tlist, but you can not assign values this way. The way to assign symbol is to use robject.globalEnv.
Moreover, some symbols in R may contain a period, such as data.frame. You can not access such symbols in Python using notation similar to robjects.r.data.frame, since Python interprets the period differently than R. So I'd suggest avoiding this notation entirely, and instead use
robjects.r['data.frame'], since this notation works no matter what the symbol name is.
A:
You could also avoid the assignment in R all together:
import rpy2.robjects as ro
tlist = ro.FloatVector((1,2))
keyWordArgs = {'row.names':ro.StrVector(("seed","ticks"))}
x = ro.r['as.data.frame'](tlist,**keyWordArgs)
ro.r['print'](x)
| Mapping python tuple and R list with rpy2? | I'm having some trouble to understand the mapping with rpy2 object and python object.
I have a function(x) which return a tuple object in python, and i want to map this tuple object with R object list or vector.
First, i'm trying to do this :
# return a python tuple into this r object tlist
robjects.r.tlist = get_max_ticks(x)
#Convert list into dataframe
r('x <- as.data.frame(tlist,row.names=c("seed","ticks"))')
FAIL with error :
rinterface.RRuntimeError: Error in eval(expr, envir, enclos) : object 'tlist' not found
So i'm trying an other strategy :
robjects.r["tlist"] = get_max_ticks(x)
r('x <- as.data.frame(tlist,row.names=c("seed","ticks"))')
FAIL with this error :
TypeError: 'R' object does not support item assignment
Could you help me to understand ?
Thanks a lot !!
| [
"Use globalEnv:\nimport rpy2.robjects as ro\nr=ro.r\n\ndef get_max_ticks():\n return (1,2)\nro.globalEnv['tlist'] = ro.FloatVector(get_max_ticks())\nr('x <- as.data.frame(tlist,row.names=c(\"seed\",\"ticks\"))')\nprint(r['x'])\n# tlist\n# seed 1\n# ticks 2\n\nIt may be possible to access symbols i... | [
3,
0
] | [] | [] | [
"mapping",
"python",
"r",
"rpy2",
"tuples"
] | stackoverflow_0003300671_mapping_python_r_rpy2_tuples.txt |
Q:
Have well-defined, narrowly-focused classes ... now how do I get anything done in my program?
I'm coding a poker hand evaluator as my first programming project. I've made it through three classes, each of which accomplishes its narrowly-defined task very well:
HandRange = a string-like object (e.g. "AA"). getHands() returns a list of tuples for each specific hand within the string:
[(Ad,Ac),(Ad,Ah),(Ad,As),(Ac,Ah),(Ac,As),(Ah,As)]
Translation = a dictionary that maps the return list from getHands to values that are useful for a given evaluator (yes, this can probably be refactored into another class).
{'As':52, 'Ad':51, ...}
Evaluator = takes a list from HandRange (as translated by Translator), enumerates all possible hand matchups and provides win % for each.
My question: what should my "domain" class for using all these classes look like, given that I may want to connect to it via either a shell UI or a GUI? Right now, it looks like an assembly line process:
user_input = HandRange()
x = Translation.translateList(user_input)
y = Evaluator.getEquities(x)
This smells funny in that it feels like it's procedural when I ought to be using OO.
In a more general way: if I've spent so much time ensuring that my classes are well defined, narrowly focused, orthogonal, whatever ... how do I actually manage work flow in my program when I need to use all of them in a row?
Thanks,
Mike
A:
Don't make a fetish of object orientation -- Python supports multiple paradigms, after all! Think of your user-defined types, AKA classes, as building blocks that gradually give you a "language" that's closer to your domain rather than to general purpose language / library primitives.
At some point you'll want to code "verbs" (actions) that use your building blocks to perform something (under command from whatever interface you'll supply -- command line, RPC, web, GUI, ...) -- and those may be module-level functions as well as methods within some encompassing class. You'll surely want a class if you need multiple instances, and most likely also if the actions involve updating "state" (instance variables of a class being much nicer than globals) or if inheritance and/or polomorphism come into play; but, there is no a priori reason to prefer classes to functions otherwise.
If you find yourself writing static methods, yearning for a singleton (or Borg) design pattern, writing a class with no state (just methods) -- these are all "code smells" that should prompt you to check whether you really need a class for that subset of your code, or rather whether you may be overcomplicating things and should use a module with functions for that part of your code. (Sometimes after due consideration you'll unearth some different reason for preferring a class, and that's allright too, but the point is, don't just pick a class over a module w/functions "by reflex", without critically thinking about it!).
A:
You could create a Poker class that ties these all together and intialize all of that stuff in the __init__() method:
class Poker(object):
def __init__(self, user_input=HandRange()):
self.user_input = user_input
self.translation = Translation.translateList(user_input)
self.evaluator = Evaluator.getEquities(x)
# and so on...
p = Poker()
# etc, etc...
| Have well-defined, narrowly-focused classes ... now how do I get anything done in my program? | I'm coding a poker hand evaluator as my first programming project. I've made it through three classes, each of which accomplishes its narrowly-defined task very well:
HandRange = a string-like object (e.g. "AA"). getHands() returns a list of tuples for each specific hand within the string:
[(Ad,Ac),(Ad,Ah),(Ad,As),(Ac,Ah),(Ac,As),(Ah,As)]
Translation = a dictionary that maps the return list from getHands to values that are useful for a given evaluator (yes, this can probably be refactored into another class).
{'As':52, 'Ad':51, ...}
Evaluator = takes a list from HandRange (as translated by Translator), enumerates all possible hand matchups and provides win % for each.
My question: what should my "domain" class for using all these classes look like, given that I may want to connect to it via either a shell UI or a GUI? Right now, it looks like an assembly line process:
user_input = HandRange()
x = Translation.translateList(user_input)
y = Evaluator.getEquities(x)
This smells funny in that it feels like it's procedural when I ought to be using OO.
In a more general way: if I've spent so much time ensuring that my classes are well defined, narrowly focused, orthogonal, whatever ... how do I actually manage work flow in my program when I need to use all of them in a row?
Thanks,
Mike
| [
"Don't make a fetish of object orientation -- Python supports multiple paradigms, after all! Think of your user-defined types, AKA classes, as building blocks that gradually give you a \"language\" that's closer to your domain rather than to general purpose language / library primitives.\nAt some point you'll want... | [
3,
1
] | [] | [] | [
"oop",
"python"
] | stackoverflow_0003300575_oop_python.txt |
Q:
@StaticMethod or @ClassMethod decoration on magic methods
I am trying to decorate the magic method __getitem__ to be a classmethod on the class. Here is a sample of what I tried. I don't mind using either classmethod or staticmethod decoration, but I am not too sure how to do it. Here is what I tried:
import ConfigParser
class Settings(object):
_env = None
_config = None
def __init__(self, env='dev'):
_env = env
# find the file
filePath = "C:\\temp\\app.config"
#load the file
_config = ConfigParser.ConfigParser()
_config.read(filePath)
@classmethod
def __getitem__(cls, key):
return cls._config.get(cls._env, key)
@classmethod
def loadEnv(cls, env):
cls._env = env
However, when I try to call Settings['database'] I get the following error.
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: expected Array[Type], got str
Can anyone tell me what I am doing wrong. Also, could someone suggest if there is better way to do this? I even tried using MetaClasses, but with little success (as I don't know python too well).
class Meta(type):
def __getitem__(*args):
return type.__getitem__(*args)
class Settings(object):
__metaclass__ = Meta
Thanks in advance.
A:
Python always looks up __getitem__ and other magic methods on the class, not on the instance. So, for example, defining a __getitem__ in a metaclass means that you can index the class (but you can't define it by delegating to a non-existent __getitem__ in type -- just as you can never define anything by delegating to other non-existent methods, of course;-).
So, if you need to index a class such as Settings, your custom metaclass must indeed define __getitem__, but it must define it with explicit code that performs the action you desire -- the return cls._config.get you want.
Edit: let me give a simplified example...:
>>> class MyMeta(type):
... def __getitem__(cls, k):
... return cls._config.get(k)
...
>>> class Settings(metaclass=MyMeta):
... _config = dict(foo=23, bar=45)
...
>>> print(Settings['foo'])
23
Of course, if that was all there was to it, it would be silly to architect this code as "indexing a class" -- a class had better have instances with states and methods, too, otherwise you should just code a module instead;-). And why the "proper" access should be by indexing the whole class rather than a specific instance, etc, is far from clear. But I'll pay you the compliment of assuming you have a good design reason for wanting to structure things this way, and just show you how to implement such a structure;-).
A:
Apart from Alex's (entirely correct) answer, it isn't clear what you actually want to do here. Right now you are trying to load the config when you instantiate the class. If you were to assign that _config to the class object, that would mean all instance of the class share the same config (and creating another instance would change all existing instances to point to the latest config.) Why are you trying to use the class to access this configuration, instead of a particular instance of the class? Even if you only ever have one configuration, it's much more convenient (and understandable!) to use an instance of the class. You can even store this instance in a module-global and call it 'Settings' if you like:
class _Settings(object):
def __init__(self, fname):
self._config = ...
...
Settings = _Settings('/path/to/config.ini')
| @StaticMethod or @ClassMethod decoration on magic methods | I am trying to decorate the magic method __getitem__ to be a classmethod on the class. Here is a sample of what I tried. I don't mind using either classmethod or staticmethod decoration, but I am not too sure how to do it. Here is what I tried:
import ConfigParser
class Settings(object):
_env = None
_config = None
def __init__(self, env='dev'):
_env = env
# find the file
filePath = "C:\\temp\\app.config"
#load the file
_config = ConfigParser.ConfigParser()
_config.read(filePath)
@classmethod
def __getitem__(cls, key):
return cls._config.get(cls._env, key)
@classmethod
def loadEnv(cls, env):
cls._env = env
However, when I try to call Settings['database'] I get the following error.
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: expected Array[Type], got str
Can anyone tell me what I am doing wrong. Also, could someone suggest if there is better way to do this? I even tried using MetaClasses, but with little success (as I don't know python too well).
class Meta(type):
def __getitem__(*args):
return type.__getitem__(*args)
class Settings(object):
__metaclass__ = Meta
Thanks in advance.
| [
"Python always looks up __getitem__ and other magic methods on the class, not on the instance. So, for example, defining a __getitem__ in a metaclass means that you can index the class (but you can't define it by delegating to a non-existent __getitem__ in type -- just as you can never define anything by delegating... | [
6,
1
] | [] | [] | [
"decorator",
"magic_methods",
"python",
"static_methods"
] | stackoverflow_0003301220_decorator_magic_methods_python_static_methods.txt |
Q:
Using Web2Py in Making a blog in Python (Google App Engine)? Is it a good Idea?
I know there are tons of blogging platforms out there (Wordpress,Drupal,etc) but I want to make my own blog engine or blog platform from scratch using python as a learning tool. The idea of using Google App Engine solves the issues in hosting. Blogs relatively consumes less amount of disk space and If it scales then there's no problem of migrations and other things related to that. I chose web2py as a framework cause I don't need to tweak the framework so that it would work with Google App Engine.
What do you think will the problems that I have to face in using GAE's Data Store? Will it be better if I use RDBMS instead of Google App Engine? What are the PROS and CONS if I use google app engine?
A:
You can use this to build a blogging platform on Google App Engine with web2py. You may want to customize the layout using this.
A:
Learning exercises, like the one you want to undertake, are just about the only good reason to reinvent the wheel -- and using a very lightweight framework can be more instructive than using a rich one such as Django, which does a lot for you under the covers. As a very lightweight framework for GAE apps, I recommend tipfy, but I guess tastes do differ;-).
The only real "pro" is that you'll learn a lot and learning is always a good thing. The "con" is that it will take a lot of work that you could save by reusing existing blogging frameworks, but of course then you would miss out on a lot of the learning experience you're after!-)
| Using Web2Py in Making a blog in Python (Google App Engine)? Is it a good Idea? | I know there are tons of blogging platforms out there (Wordpress,Drupal,etc) but I want to make my own blog engine or blog platform from scratch using python as a learning tool. The idea of using Google App Engine solves the issues in hosting. Blogs relatively consumes less amount of disk space and If it scales then there's no problem of migrations and other things related to that. I chose web2py as a framework cause I don't need to tweak the framework so that it would work with Google App Engine.
What do you think will the problems that I have to face in using GAE's Data Store? Will it be better if I use RDBMS instead of Google App Engine? What are the PROS and CONS if I use google app engine?
| [
"You can use this to build a blogging platform on Google App Engine with web2py. You may want to customize the layout using this.\n",
"Learning exercises, like the one you want to undertake, are just about the only good reason to reinvent the wheel -- and using a very lightweight framework can be more instructive... | [
5,
2
] | [] | [] | [
"blogs",
"google_app_engine",
"python",
"web2py"
] | stackoverflow_0003276194_blogs_google_app_engine_python_web2py.txt |
Q:
How to check for EOF when using pipe file descriptors in Python?
I have 2 threads, Thread A and Thread B.
Thread A takes data from either sys.stdin or from the read end of a pipe (using os.pipe()). Whatever data gets read (from either sys.stdin or from the read end of the pipe) gets sent out on a TCP socket. Thread A uses select.select() to determine whether it should read from sys.stdin or from the read end of the pipe, and select.select() is using a 1 second timeout to periodically check and make sure that the socket connection is still there.
Thread B holds the write end of the pipe, and will typically just write 1 really long string to the pipe, and then close the write end.
How can Thread A check for an EOF on the pipe? Basically, I want Thread A to close the pipe when it's no longer being used. But, I can't risk blocking on read() from the pipe, because then data that is available on sys.stdin would be unnecessarily blocked.
Any help would be greatly appreciated. Thank you!
A:
The only way to check for EOF on the pipe is to read from it. In fact, when you close the write-end of the pipe, select.select() will say the socket is ready for reading, even if there's no actual data to be read. When you read from the read-end, the empty string ('') will indicate EOF. This won't block your read even if the pipe is in blocking mode.
That said, it's probably a good idea to not use blocking reads altogether. You can set the pipes non-blocking using fcntl.fcntl(). And you can just avoid using two threads by sending directly to the socket from thread B, forgoing the seemingly useless gateway thread. If you have multiple sockets you need to manage, or even multiple producer threads, Twisted is a good way of managing the sockets and other communication.
| How to check for EOF when using pipe file descriptors in Python? | I have 2 threads, Thread A and Thread B.
Thread A takes data from either sys.stdin or from the read end of a pipe (using os.pipe()). Whatever data gets read (from either sys.stdin or from the read end of the pipe) gets sent out on a TCP socket. Thread A uses select.select() to determine whether it should read from sys.stdin or from the read end of the pipe, and select.select() is using a 1 second timeout to periodically check and make sure that the socket connection is still there.
Thread B holds the write end of the pipe, and will typically just write 1 really long string to the pipe, and then close the write end.
How can Thread A check for an EOF on the pipe? Basically, I want Thread A to close the pipe when it's no longer being used. But, I can't risk blocking on read() from the pipe, because then data that is available on sys.stdin would be unnecessarily blocked.
Any help would be greatly appreciated. Thank you!
| [
"The only way to check for EOF on the pipe is to read from it. In fact, when you close the write-end of the pipe, select.select() will say the socket is ready for reading, even if there's no actual data to be read. When you read from the read-end, the empty string ('') will indicate EOF. This won't block your read ... | [
7
] | [] | [] | [
"linux",
"python"
] | stackoverflow_0003301253_linux_python.txt |
Q:
PyDev Setting breakpoints in doctests
Is it possible to set breakpoints in doctests, using PyDev (i.e. eclipse)? I found that while I am seemingly able to do so, the breakpoints do not work at all.
To have some code in the question, and to clarify, say I have
def funct():
"""
>>> funct()
Whatever
"""
print "Whatever"
and that I set a breakpoint at the funct() call in the doctest. Can I do that?
PS: I know I can do
>>> import pdb; pdb.set_trace()
to have a prompt in a doctest, but I would prefer not inserting such lines.
A:
I don't think you can set breakpoints in strings.
doctest is a module for automated testing. If you need to debug your doctest code, why not run it normally and verify the output, then once you know it works, throw it into a docstring?
| PyDev Setting breakpoints in doctests | Is it possible to set breakpoints in doctests, using PyDev (i.e. eclipse)? I found that while I am seemingly able to do so, the breakpoints do not work at all.
To have some code in the question, and to clarify, say I have
def funct():
"""
>>> funct()
Whatever
"""
print "Whatever"
and that I set a breakpoint at the funct() call in the doctest. Can I do that?
PS: I know I can do
>>> import pdb; pdb.set_trace()
to have a prompt in a doctest, but I would prefer not inserting such lines.
| [
"I don't think you can set breakpoints in strings. \ndoctest is a module for automated testing. If you need to debug your doctest code, why not run it normally and verify the output, then once you know it works, throw it into a docstring?\n"
] | [
0
] | [] | [] | [
"breakpoints",
"doctest",
"eclipse",
"pydev",
"python"
] | stackoverflow_0003301514_breakpoints_doctest_eclipse_pydev_python.txt |
Q:
Verifying constructor parameters in Python
What is the best-practice method for verifying constructor params in Python?
I am new to the language, and am using raise:
class Breakfast(object):
def __init__(self, spam=None, eggs=0):
if not spam:
raise Error("Error: no spam")
Is this stupid, or what?
Thanks!
A:
If you are just trying to make sure that required parameters are passed, just leave off the default value. Python will then automatically throw a TypeError if a parameter is missing.
def __init__( self, spam, eggs=0 )
A:
If the argument isn't optional, why are you providing a default argument for it? The Python interpreter automatically raises an error if an argument without a default value isn't passed one.
A:
In your specific example it would be simplest to not give spam a default value -- Python will then diagnose the problem for you if the user forgets to pass that argument. (However, passing False, 0, [], ... as spam would be OK for Python, so if you have requirements against them you might have to additionally specify your own semantics checks).
If you do have to perform any diagnosis, raising an exception if it fails is sensible. However it should be the proper exception -- e.g., ValueError if the value is of an acceptable type but not acceptable as its specific value -- and with a clear, complete message. So, summarizing:
class Breakfast(object):
def __init__(self, spam, eggs=0):
if not spam:
raise ValueError("falsish spam %r not acceptable" % (spam,))
(You do need to wrap spam in a single-item tuple (spam,) here, else passing an empty tuple as spam would result in a complicated, confusing error;-).
A:
In this special case, don't make spam a keyword:
class Breakfast(object):
def __init__(self, spam, eggs=0):
"""Spam may not be none.
"""
# This is just validation of parameters which you can either
# do or leave. spam is part of the contract now and you documented
# that it may not be None
if not spam:
raise Error("Error: spam may not be None")
A:
First of all I think you mean
if spam is None:
as Breakfast(0) would be boolean True for not spam as would be an argument of [], 0.0, '', u'', etc.
Secondly, the Error raised is both of an uninformative generic class instead of a more typical ValueError. Finally, exception text could be more informative and guide the caller to a fix.
And, as others have noted, you sacrificed automatic checking by setting a default for which there isn't one.
| Verifying constructor parameters in Python | What is the best-practice method for verifying constructor params in Python?
I am new to the language, and am using raise:
class Breakfast(object):
def __init__(self, spam=None, eggs=0):
if not spam:
raise Error("Error: no spam")
Is this stupid, or what?
Thanks!
| [
"If you are just trying to make sure that required parameters are passed, just leave off the default value. Python will then automatically throw a TypeError if a parameter is missing.\ndef __init__( self, spam, eggs=0 )\n\n",
"If the argument isn't optional, why are you providing a default argument for it? The P... | [
4,
3,
3,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0003301745_python.txt |
Q:
best scripting language to develop rational clearcase plugin to extract some functionalities
I just want to know about clearcase. Basically i want to write some application which will extract some files from clearcase vobs. Right now i am not getting any clue that which scripting language like python or perl i should use. basically i am looking for perl scripting for that. I also want to know is there any proper document or book available for clearcase exposed api list and documentation.
Thanks in advance,
Abhijit
A:
The official API is cleartool, the command line interface which contains all ClearCase commands.
You can call cleartool commands from a Perl script (like in this question)
An example of a Perl library able to call cleartool command is here.
The other scripting interface is ClearCase Automation Library (CAL).
See this question for an example of CAL script based on Perl.
Note that in any case, you will need ClearCase views (snapshot or dynamic ones) to access Vobs elements (versioned files or directories).
| best scripting language to develop rational clearcase plugin to extract some functionalities | I just want to know about clearcase. Basically i want to write some application which will extract some files from clearcase vobs. Right now i am not getting any clue that which scripting language like python or perl i should use. basically i am looking for perl scripting for that. I also want to know is there any proper document or book available for clearcase exposed api list and documentation.
Thanks in advance,
Abhijit
| [
"The official API is cleartool, the command line interface which contains all ClearCase commands.\nYou can call cleartool commands from a Perl script (like in this question)\nAn example of a Perl library able to call cleartool command is here.\nThe other scripting interface is ClearCase Automation Library (CAL).\nS... | [
1
] | [] | [] | [
"clearcase",
"perl",
"python"
] | stackoverflow_0003301579_clearcase_perl_python.txt |
Q:
Python cached list
I have a module which supports creation of geographic objects using a company-standard interface. After these objects are created, the update_db() method is called, and all objects are updated into a database.
It is important to have all objects inserted in one session, in order to keep counters and statistics before updating a production database.
The problem is that sometimes there are just too many objects, and the memory gets full.
Is there a way to create a cached list in Python, in order to handle lists that does not fit into memory?
My general thought was:
class CachedList(object):
def __init__(self, max_memory_size, directory)
def get_item(index)
def set_item(index)
def del_item(index)
def append(item)
An ordinary list would be created upon initialization. When the list's size exceeds max_memory_size, the list elements are pickled and stored at a file in directory. get_item(), set_item() and del_item() would handle the data stored in memory, or 'swap' it from disk to access it.
Is this a good design? Are there any standard alternatives?
How can I force garbage collection after pickle-ing parts of the list?
Thanks,
Adam
A:
Use shelve. Your keys are the indices to your list.
A:
I think your first question is answered. On the second, forcing GC: use gc.collect. http://docs.python.org/library/gc.html.
| Python cached list | I have a module which supports creation of geographic objects using a company-standard interface. After these objects are created, the update_db() method is called, and all objects are updated into a database.
It is important to have all objects inserted in one session, in order to keep counters and statistics before updating a production database.
The problem is that sometimes there are just too many objects, and the memory gets full.
Is there a way to create a cached list in Python, in order to handle lists that does not fit into memory?
My general thought was:
class CachedList(object):
def __init__(self, max_memory_size, directory)
def get_item(index)
def set_item(index)
def del_item(index)
def append(item)
An ordinary list would be created upon initialization. When the list's size exceeds max_memory_size, the list elements are pickled and stored at a file in directory. get_item(), set_item() and del_item() would handle the data stored in memory, or 'swap' it from disk to access it.
Is this a good design? Are there any standard alternatives?
How can I force garbage collection after pickle-ing parts of the list?
Thanks,
Adam
| [
"Use shelve. Your keys are the indices to your list. \n",
"I think your first question is answered. On the second, forcing GC: use gc.collect. http://docs.python.org/library/gc.html. \n"
] | [
5,
2
] | [] | [] | [
"caching",
"data_structures",
"list",
"python"
] | stackoverflow_0003301789_caching_data_structures_list_python.txt |
Q:
Import module CairoPlot fails in Python
I'm using cairo plot to draw charts with python. I followed the instruction as stated on the website to install Cairplot, http://linil.wordpress.com/2008/09/16/cairoplot-11/ :
sudo apt-get install bzr
bzr branch lp:cairoplot/1.1
The installation completes successfully.
I then try to import the modules in python:
>>> import CairoPlot Traceback (most recent call last): File "<stdin>",
line 1, in <module> ImportError: No
module named CairoPlot
>>> import cairo
>>>
Importing cairo is fine, but I can't figure out why I am not able to import CairoPlot.
A:
bzr branch lp:cairoplot/1.1 creates a directory called 1.1 in your current working directory. Inside you'll find CairoPlot.py. Move CairoPlot.py into a directory which is listed in your PYTHONPATH, or edit your PYTHONPATH to include (the unfortunately named) 1.1.
A:
Is the directory where CairoPlot is installed in your $PYTHONPATH? Do you need to run any setup scripts, like setuptools?
The repository appears to include a setup.py file, so you likely need to run setuptools to fully install the module.
| Import module CairoPlot fails in Python | I'm using cairo plot to draw charts with python. I followed the instruction as stated on the website to install Cairplot, http://linil.wordpress.com/2008/09/16/cairoplot-11/ :
sudo apt-get install bzr
bzr branch lp:cairoplot/1.1
The installation completes successfully.
I then try to import the modules in python:
>>> import CairoPlot Traceback (most recent call last): File "<stdin>",
line 1, in <module> ImportError: No
module named CairoPlot
>>> import cairo
>>>
Importing cairo is fine, but I can't figure out why I am not able to import CairoPlot.
| [
"bzr branch lp:cairoplot/1.1 creates a directory called 1.1 in your current working directory. Inside you'll find CairoPlot.py. Move CairoPlot.py into a directory which is listed in your PYTHONPATH, or edit your PYTHONPATH to include (the unfortunately named) 1.1.\n",
"Is the directory where CairoPlot is installe... | [
2,
0
] | [] | [] | [
"cairoplot",
"python"
] | stackoverflow_0003301846_cairoplot_python.txt |
Q:
Using Python property() inside a method
Assuming you know about Python builtin property: http://docs.python.org/library/functions.html#property
I want to re-set a object property in this way but, I need to do it inside a method to be able to pass to it some arguments, currently all the web examples of property() are defining the property outside the methods, and trying the obvious...
def alpha(self, beta):
self.x = property(beta)
...seems not to work, I'm glad if you can show me my concept error or other alternative solutions without subclassing the code (actually my code is already over-subclassed) or using decorators (this is the solution I'll use if there is no other).
Thanks.
A:
Properties work using the descriptor protocol, which only works on attributes of a class object. The property object has to be stored in a class attribute. You can't "override" it on a per-instance basis.
You can, of course, provide a property on the class that gets an instance attribute or falls back to some default:
class C(object):
_default_x = 5
_x = None
@property
def x(self):
return self._x or self._default_x
def alpha(self, beta):
self._x = beta
A:
In this case all you need to do in your alpha() is self.x = beta. Use property when you want to implement getters and setters for an attribute, for example:
class Foo(object):
@property
def foo(self):
return self._dblookup('foo')
@foo.setter
def foo(self, value):
self._dbwrite('foo', value)
And then be able to do
f = Foo()
f.foo
f.foo = bar
| Using Python property() inside a method | Assuming you know about Python builtin property: http://docs.python.org/library/functions.html#property
I want to re-set a object property in this way but, I need to do it inside a method to be able to pass to it some arguments, currently all the web examples of property() are defining the property outside the methods, and trying the obvious...
def alpha(self, beta):
self.x = property(beta)
...seems not to work, I'm glad if you can show me my concept error or other alternative solutions without subclassing the code (actually my code is already over-subclassed) or using decorators (this is the solution I'll use if there is no other).
Thanks.
| [
"Properties work using the descriptor protocol, which only works on attributes of a class object. The property object has to be stored in a class attribute. You can't \"override\" it on a per-instance basis.\nYou can, of course, provide a property on the class that gets an instance attribute or falls back to some d... | [
5,
1
] | [] | [] | [
"decorator",
"properties",
"python"
] | stackoverflow_0003302020_decorator_properties_python.txt |
Q:
Anjuta IDE - Simple Python Question
I'm new to Linux, Python and the Anjuta IDE.
I have created a new file called hello.py. This is the contents of that file:
#!/usr/bin/env python
print "Hello World!"
All I want to do is run this in the terminal. I go to Run > Execute but I get the following error message:
Program 'home/joe/Programming/Python//hello.py' does not have execution permission
How do I get this really simple program to run?
Thanks,
A:
open a shell, cd to the folder where the file is located and execute chmod +x hello.py.
A:
ZeissS' solution will work and is generally preferred to this, but for the sake of completeness, you could also open a shell, cd to the appropriate directory, and type:
python hello.py
| Anjuta IDE - Simple Python Question | I'm new to Linux, Python and the Anjuta IDE.
I have created a new file called hello.py. This is the contents of that file:
#!/usr/bin/env python
print "Hello World!"
All I want to do is run this in the terminal. I go to Run > Execute but I get the following error message:
Program 'home/joe/Programming/Python//hello.py' does not have execution permission
How do I get this really simple program to run?
Thanks,
| [
"open a shell, cd to the folder where the file is located and execute chmod +x hello.py.\n",
"ZeissS' solution will work and is generally preferred to this, but for the sake of completeness, you could also open a shell, cd to the appropriate directory, and type:\n\npython hello.py\n\n"
] | [
4,
2
] | [] | [] | [
"linux",
"permissions",
"python",
"ubuntu"
] | stackoverflow_0003302071_linux_permissions_python_ubuntu.txt |
Q:
Foreign key relationships missing when reflecting db in SqlAlchemy
I am attempting to use SqlAlchemy (0.5.8) to interface with a legacy database declaratively and using reflection. My test code looks like this:
from sqlalchemy import *
from sqlalchemy.orm import create_session
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
engine = create_engine('oracle://schemaname:pwd@SID')
meta = MetaData(bind=engine)
class CONSTRUCT(Base):
__table__ = Table('CONSTRUCT', meta, autoload=True)
class EXPRESSION(Base):
__table__ = Table('EXPRESSION', meta, autoload=True)
session = create_session(bind=engine)
Now when I attempt to run a query using the join between these two tables (defined by a foreign key constraint in the underlying oracle schema):
print session.query(EXPRESSION).join(PURIFICATION)
... no joy:
sqlalchemy.exc.ArgumentError: Can't find any foreign key relationships between 'EXPRESSION' and 'PURIFICATION'
However:
>>> EXPRESSION.epiconstruct_pkey.property.columns
[Column(u'epiconstruct_pkey', OracleNumeric(precision=10, scale=2, asdecimal=True,
length=None), ForeignKey(u'construct.pkey'), table=<EXPRESSION>, nullable=False)]
>>> CONSTRUCT.pkey.property.columns
[Column(u'pkey', OracleNumeric(precision=38, scale=0, asdecimal=True, length=None),
table=<CONSTRUCT>, primary_key=True, nullable=False)]
Which clearly indicates that the reflection picked up the foreign key.
Where am I going wrong?
A:
After debugging the script + SqlAlchemy code with Eclipse, I found that the list of tables/columns is kept internally in lower case. As such, there was never any possibility of a match between EXPRESSION.foreignkey and expression.foreignkey. Hence the error message.
Digging deep into the SqlAlchemy documentation ( http://www.sqlalchemy.org/docs/reference/dialects/oracle.html#identifier-casing ) I then found the following:
"In Oracle, the data dictionary represents all case insensitive identifier names using UPPERCASE text. SQLAlchemy on the other hand considers an all-lower case identifier name to be case insensitive. The Oracle dialect converts all case insensitive identifiers to and from those two formats during schema level communication, such as reflection of tables and indexes. Using an UPPERCASE name on the SQLAlchemy side indicates a case sensitive identifier, and SQLAlchemy will quote the name - this will cause mismatches against data dictionary data received from Oracle, so unless identifier names have been truly created as case sensitive (i.e. using quoted names), all lowercase names should be used on the SQLAlchemy side."
So my code works if it looks like this (differences are case-changes only):
from sqlalchemy import *
from sqlalchemy.orm import create_session
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
engine = create_engine('oracle://EPIGENETICS:sgc04lab@ELN')
meta = MetaData(bind=engine)
class construct(Base):
__table__ = Table('construct', meta, autoload=True)
class expression(Base):
__table__ = Table('expression', meta, autoload=True)
class purification(Base):
__table__ = Table('purification', meta, autoload=True)
session = create_session(bind=engine)
print session.query(expression).join(purification,expression)
... which spits out:
SELECT expression.pkey AS expression_pkey, expression.cellline AS expression_cellline, expression.epiconstruct_pkey AS expression_epiconstruct_pkey, expression.elnexp AS expression_elnexp, expression.expression_id AS expression_expression_id, expression.expressioncomments AS expression_expressioncomments, expression.cellmass AS expression_cellmass, expression.datestamp AS expression_datestamp, expression.person AS expression_person, expression.soluble AS expression_soluble, expression.semet AS expression_semet, expression.scale AS expression_scale, expression.purtest AS expression_purtest, expression.nmrlabelled AS expression_nmrlabelled, expression.yield AS expression_yield
FROM expression JOIN purification ON expression.pkey = purification.epiexpression_pkey JOIN expression ON expression.pkey = purification.epiexpression_pkey
Case closed.
| Foreign key relationships missing when reflecting db in SqlAlchemy | I am attempting to use SqlAlchemy (0.5.8) to interface with a legacy database declaratively and using reflection. My test code looks like this:
from sqlalchemy import *
from sqlalchemy.orm import create_session
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
engine = create_engine('oracle://schemaname:pwd@SID')
meta = MetaData(bind=engine)
class CONSTRUCT(Base):
__table__ = Table('CONSTRUCT', meta, autoload=True)
class EXPRESSION(Base):
__table__ = Table('EXPRESSION', meta, autoload=True)
session = create_session(bind=engine)
Now when I attempt to run a query using the join between these two tables (defined by a foreign key constraint in the underlying oracle schema):
print session.query(EXPRESSION).join(PURIFICATION)
... no joy:
sqlalchemy.exc.ArgumentError: Can't find any foreign key relationships between 'EXPRESSION' and 'PURIFICATION'
However:
>>> EXPRESSION.epiconstruct_pkey.property.columns
[Column(u'epiconstruct_pkey', OracleNumeric(precision=10, scale=2, asdecimal=True,
length=None), ForeignKey(u'construct.pkey'), table=<EXPRESSION>, nullable=False)]
>>> CONSTRUCT.pkey.property.columns
[Column(u'pkey', OracleNumeric(precision=38, scale=0, asdecimal=True, length=None),
table=<CONSTRUCT>, primary_key=True, nullable=False)]
Which clearly indicates that the reflection picked up the foreign key.
Where am I going wrong?
| [
"After debugging the script + SqlAlchemy code with Eclipse, I found that the list of tables/columns is kept internally in lower case. As such, there was never any possibility of a match between EXPRESSION.foreignkey and expression.foreignkey. Hence the error message.\nDigging deep into the SqlAlchemy documentation ... | [
6
] | [] | [] | [
"oracle10g",
"python",
"sqlalchemy"
] | stackoverflow_0003301139_oracle10g_python_sqlalchemy.txt |
Q:
Writing file line to Django model field
I can't seem to write a line from a file to a field of a Django model. The field is described in the model as:
text = models.TextField(null=True, blank=True, help_text='A status message.')
However, when I attempt to create a new object I cannot fill this field using the readline function:
file = open(filename, 'r')
str = file.readline()
When I attempt to use str for the text field I don't seem to be able to read or write to the database. I'm not given any error so I'm assuming its an encoding problem. Any advice? Thanks.
edit
The database is a postgres database and the field type is "text".
The code I'm using to create the object is:
Message.objects.create_message(sys, str)
and
def create_message(self, system, msg):
"""Create a message for the given system."""
m = Message.objects.create(system=system,
text=msg)
return m
A:
Don't create variable names which conflict with python built in types. "str" is the string type.Python interpreter:
>> str
<type 'str'>
A:
I think you're not calling the create_message method properly. Shouldn't you just call it like this
create_message(sys, str)
instead of this
Message.objects.create_message(sys, str)
?
| Writing file line to Django model field | I can't seem to write a line from a file to a field of a Django model. The field is described in the model as:
text = models.TextField(null=True, blank=True, help_text='A status message.')
However, when I attempt to create a new object I cannot fill this field using the readline function:
file = open(filename, 'r')
str = file.readline()
When I attempt to use str for the text field I don't seem to be able to read or write to the database. I'm not given any error so I'm assuming its an encoding problem. Any advice? Thanks.
edit
The database is a postgres database and the field type is "text".
The code I'm using to create the object is:
Message.objects.create_message(sys, str)
and
def create_message(self, system, msg):
"""Create a message for the given system."""
m = Message.objects.create(system=system,
text=msg)
return m
| [
"Don't create variable names which conflict with python built in types. \"str\" is the string type.Python interpreter:\n>> str\n<type 'str'>\n\n",
"I think you're not calling the create_message method properly. Shouldn't you just call it like this\ncreate_message(sys, str)\n\ninstead of this\nMessage.objects.crea... | [
2,
0
] | [] | [] | [
"database",
"django",
"file",
"file_io",
"python"
] | stackoverflow_0003301988_database_django_file_file_io_python.txt |
Q:
reordering list of dicts arbitrarily in python
I have a list of 4 dicts (always 4) that look something like this:
[{'id':'1','name':'alfa'},{'id':'2','name':'bravo'},{'id':'3','name':'charlie'},{'id':'4','name':'delta'}]
I know exactly the order I want them in, which is:
2, 3, 1, 4
what's the simplest way of reordering them?
A:
If it's always four, and you always know the order, just simply like this:
lst = [{...},{...},{...},{...}]
ordered = [lst[1],lst[2],lst[0],lst[3]]
If you meant to sort them by 'id', in that order:
ordered = sorted(lst, key=lambda d: [2,3,1,4].index(int(d['id'])))
Note that index() is O(n) but doesn't require you to build a dictionary. So for small inputs, this may actually be faster. In your case, there are four elements, ten comparisons are guaranteed. Using timeit, this snippet runs 10% faster than the dictionary based solution by tokland... but it doesn't really matter since neither will likely be significant.
A:
Here's a pretty general function to impose a wanted order (any key value not in the wanted order is placed at the end of the resulting list, in arbitrary sub-order):
def ordered(somelist, wantedorder, keyfunction):
orderdict = dict((y, x) for x, y in enumerate(wantedorder))
later = len(orderdict)
def key(item):
return orderdict.get(keyfunction(item), later)
return sorted(somelist, key=key)
You'd be using it as
import operator
sortedlist = ordered(dictlist, ('2', '3', '1', '4'),
operator.itemgetter('id'))
A:
the_list.sort(key=lambda x: (3, 1, 2, 4)[int(x["id"])-1])
Update0
A new much simpler answer
the_list = [the_list[i - 1] for i in (2, 3, 1, 4)]
This way the OP can see his desired ordering, and there's no silliness with sorting, which is not required here. It's probably fast too.
A:
A non-generalized solution:
lst = [{'id':'1','name':'alfa'},{'id':'2','name':'bravo'},{'id':'3','name':'charlie'},{'id':'4','name':'delta'}]
order = ["2", "3", "1", "4"]
indexes = dict((idfield, index) for (index, idfield) in enumerate(order))
print sorted(lst, key=lambda d: indexes[d["id"]])
# [{'id': '2', 'name': 'bravo'}, {'id': '3', 'name': 'charlie'}, {'id': '1', 'name': 'alfa'}, {'id': '4', 'name': 'delta'}]
And here generalized:
def my_ordered(it, wanted_order, key):
indexes = dict((value, index) for (index, value) in enumerate(wanted_order))
return sorted(it, key=lambda x: indexes[key(x)])
import operator
print my_ordered(lst, order, operator.itemgetter("id"))
A:
If you want to re-order without regard for content of the dicts:
>>> order = 2, 3, 1, 4
>>> d = [{'id':'1','name':'alfa'},{'id':'2','name':'bravo'},{'id':'3','name':'charlie'},{'id':'4','name':'delta'}]
>>> index = dict(enumerate(dd))
>>> [index[i-1] for i in order]
[{'id': '2', 'name': 'bravo'}, {'id': '3', 'name': 'charlie'}, {'id': '1', 'name': 'alfa'}, {'id': '4', 'name': 'delta'}]
If you want to base your sorting on the 'id' of the dicts:
>>> sorted(d, key=lambda x: order.index(int(x['id'])))
[{'id': '2', 'name': 'bravo'}, {'id': '3', 'name': 'charlie'}, {'id': '1', 'name': 'alfa'}, {'id': '4', 'name': 'delta'}]
| reordering list of dicts arbitrarily in python | I have a list of 4 dicts (always 4) that look something like this:
[{'id':'1','name':'alfa'},{'id':'2','name':'bravo'},{'id':'3','name':'charlie'},{'id':'4','name':'delta'}]
I know exactly the order I want them in, which is:
2, 3, 1, 4
what's the simplest way of reordering them?
| [
"If it's always four, and you always know the order, just simply like this:\nlst = [{...},{...},{...},{...}]\nordered = [lst[1],lst[2],lst[0],lst[3]]\n\nIf you meant to sort them by 'id', in that order:\nordered = sorted(lst, key=lambda d: [2,3,1,4].index(int(d['id'])))\n\nNote that index() is O(n) but doesn't requ... | [
4,
3,
2,
2,
0
] | [] | [] | [
"list",
"python"
] | stackoverflow_0003301406_list_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.