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:
wxPython: how to make taskbar icon respond to left-click
Using wxPython, I created a taskbar icon and menu.
Everything works fine (in Windows at least) upon right-click of the icon: i.e., the menu is displayed, and automatically hidden when you click somewhere else, like on Windows' taskbar.
Now I do want to have the menu appear when the icon is left-clicked as well.
So I inserted a Bind() to a left-click in the Frame class wrapper, calling the CreatePopupMenu() of the taskbar icon:
import wx
class BibTaskBarIcon(wx.TaskBarIcon):
def __init__(self, frame):
wx.TaskBarIcon.__init__(self)
self.frame = frame
icon = wx.Icon('test_icon.ico', wx.BITMAP_TYPE_ICO)
self.SetIcon(icon, "title")
def CreatePopupMenu(self):
self.menu = wx.Menu()
self.menu.Append(wx.NewId(), "dummy menu ")
self.menu.Append(wx.NewId(), "dummy menu 2")
return self.menu
class TaskBarFrame(wx.Frame):
def __init__(self, parent, title):
wx.Frame.__init__(self, parent, style=wx.FRAME_NO_TASKBAR)
...
self.tbicon = BibTaskBarIcon(self)
wx.EVT_TASKBAR_LEFT_UP(self.tbicon, self.OnTaskBarLeftClick)
...
def OnTaskBarLeftClick(self, evt):
self.PopupMenu(self.tbicon.CreatePopupMenu())
...
def main(argv=None):
app = wx.App(False)
TaskBarFrame(None, "testing frame")
app.MainLoop()
This works fine, except that the menu does not disappear automatically when you click somewhere else on your screen. In fact, left-clicking multiple times on the icon creates multiple menus. The only way to hide the menu(s) is to click on one of its items (which you don't always want). I've looked at the available methods of TaskbarIcon, but I failed to be clear about which one to use to hide the menu (.Destroy() didn't work). Moreover, I don't know which event to bind it to (there is a EVT_SET_FOCUS, but I couldn't find any EVT_LOOSE_FOCUS or similar).
So, how to hide the menu upon losing focus?
EDIT: I've inserted a bit more code, to make it more clear
A:
Ah, I've discovered what went wrong. In the statement
self.PopupMenu(self.tbicon.CreatePopupMenu())
I had bound the popup menu to the frame, instead of to the taskbar icon.
By changing it to:
self.tbicon.PopupMenu(self.tbicon.CreatePopupMenu())
all is working well now.
Thanks for all remarks
A:
I think the problem here is that the PopupMenu is usually used in a program's context, not a little icon in the system tray. What that means is that in a normal frame, the popup menu would detect the click the you clicked off of it. Here, you are clicking outside of the wxPython program. Also, the PopupMenu is usually used with EVT_CONTEXT_MENU, not this taskbar event.
You can try wx.EVT_KILL_FOCUS and see if that works since it should theoretically fire when you click off the menu. Or you could ask on the official wxPython forum here: http://groups.google.com/group/wxpython-users/topics
Mike Driscoll
Blog: http://blog.pythonlibrary.org
| wxPython: how to make taskbar icon respond to left-click | Using wxPython, I created a taskbar icon and menu.
Everything works fine (in Windows at least) upon right-click of the icon: i.e., the menu is displayed, and automatically hidden when you click somewhere else, like on Windows' taskbar.
Now I do want to have the menu appear when the icon is left-clicked as well.
So I inserted a Bind() to a left-click in the Frame class wrapper, calling the CreatePopupMenu() of the taskbar icon:
import wx
class BibTaskBarIcon(wx.TaskBarIcon):
def __init__(self, frame):
wx.TaskBarIcon.__init__(self)
self.frame = frame
icon = wx.Icon('test_icon.ico', wx.BITMAP_TYPE_ICO)
self.SetIcon(icon, "title")
def CreatePopupMenu(self):
self.menu = wx.Menu()
self.menu.Append(wx.NewId(), "dummy menu ")
self.menu.Append(wx.NewId(), "dummy menu 2")
return self.menu
class TaskBarFrame(wx.Frame):
def __init__(self, parent, title):
wx.Frame.__init__(self, parent, style=wx.FRAME_NO_TASKBAR)
...
self.tbicon = BibTaskBarIcon(self)
wx.EVT_TASKBAR_LEFT_UP(self.tbicon, self.OnTaskBarLeftClick)
...
def OnTaskBarLeftClick(self, evt):
self.PopupMenu(self.tbicon.CreatePopupMenu())
...
def main(argv=None):
app = wx.App(False)
TaskBarFrame(None, "testing frame")
app.MainLoop()
This works fine, except that the menu does not disappear automatically when you click somewhere else on your screen. In fact, left-clicking multiple times on the icon creates multiple menus. The only way to hide the menu(s) is to click on one of its items (which you don't always want). I've looked at the available methods of TaskbarIcon, but I failed to be clear about which one to use to hide the menu (.Destroy() didn't work). Moreover, I don't know which event to bind it to (there is a EVT_SET_FOCUS, but I couldn't find any EVT_LOOSE_FOCUS or similar).
So, how to hide the menu upon losing focus?
EDIT: I've inserted a bit more code, to make it more clear
| [
"Ah, I've discovered what went wrong. In the statement\nself.PopupMenu(self.tbicon.CreatePopupMenu())\n\nI had bound the popup menu to the frame, instead of to the taskbar icon.\nBy changing it to:\nself.tbicon.PopupMenu(self.tbicon.CreatePopupMenu())\n\nall is working well now.\nThanks for all remarks\n",
"I thi... | [
4,
0
] | [] | [] | [
"python",
"taskbar",
"wxpython"
] | stackoverflow_0003235408_python_taskbar_wxpython.txt |
Q:
How can I use python to load a browser session that posts values to a url?
I have a python script that takes a number of variables. I also have a html page that can receive post values.
How can I start a browser from python and point it to the html page I have above and send those post variables to the html url?
The problem I have is that if I use urllib/urllib2 to do the post, it doesn't load the browser window. And if I want to load a browser window I cannot send a post to the url.
This is how you can do a POST to a url but it doesn't open up a browser, instead it can receive back values like so. But I do not need to read back values, I need to open a Internet browser, point it to a specific url and post the variables to that url.
data = urllib.urlencode({"fileTitle" : "ThisFileName", "findtype" : "t", "etc" : "etc"})
f = urllib.urlopen("http://www.domain.com/someurl/", data)
# Read the results back.
s = f.read()
s.close()
A:
Do the values have to be supplied via HTTP POST? Could you supply the parameters as part of the URL and use a GET instead?
e.g. Build a URL similar to the following:
http://somehost/somefile.html?param1=value1¶m2=value2&...
A:
"... it doesn't load the browser window."
Sorry, I don't fully understand what you try to do. But maybe Selenium Remote Control (RC) is interesting for you. You can write scripts to remote controll a browser. It's used for automated testing. Python is supported as well. You can make the browser to submit forms or click on links eg. to PHP scripts or whatever.
A:
This seems to be the only way to get what I want done.
You can use urllib to call a page on the server that stores the data (either in sql table or in a temporary file) and returns an unique id. Then you can use the unique id to fetch that data from its known source.
The python code will look something like this:
import urllib
data = urllib.urlencode({"postField1" : "postValue1", "postField2" : "postValue2", "etc" : "etc"})
f = urllib.urlopen("http://www.domain.com/storePostData.php", data)
# At this point your storePostData.php file stores all the post
# info in either an sql DB or temporary file so this can accessed later on and
# an uuid is passed back which we now read below. In may case I store all post
# fields in a sql DB and each column represents each post field.
uuid = f.read()
# the uuid is the sql table id field which is auto_incremented.
# SO now we load the default browser below and send it the uuid so the php script
# can access the sql data. Once it has been accessed and the form fields have been
# received then we delete that row as the information is useless to us now that we
# have filled in the forms fields
import webbrowser
webbrowser.open_new("http://www.domain.com/someOtherUrl?uuid=" + uuid)
All the rest of the work is done by PHP scripting, where it stores the info, and then retrieves the info based on the uuid. I'm not going to put an example of the code up here as that's just general knowledge and all I'm trying to do is get the concept through here.
I hope this helps someone.
Cheers
| How can I use python to load a browser session that posts values to a url? | I have a python script that takes a number of variables. I also have a html page that can receive post values.
How can I start a browser from python and point it to the html page I have above and send those post variables to the html url?
The problem I have is that if I use urllib/urllib2 to do the post, it doesn't load the browser window. And if I want to load a browser window I cannot send a post to the url.
This is how you can do a POST to a url but it doesn't open up a browser, instead it can receive back values like so. But I do not need to read back values, I need to open a Internet browser, point it to a specific url and post the variables to that url.
data = urllib.urlencode({"fileTitle" : "ThisFileName", "findtype" : "t", "etc" : "etc"})
f = urllib.urlopen("http://www.domain.com/someurl/", data)
# Read the results back.
s = f.read()
s.close()
| [
"Do the values have to be supplied via HTTP POST? Could you supply the parameters as part of the URL and use a GET instead?\ne.g. Build a URL similar to the following:\nhttp://somehost/somefile.html?param1=value1¶m2=value2&...\n",
"\"... it doesn't load the browser window.\"\nSorry, I don't fully understand ... | [
0,
0,
0
] | [] | [] | [
"html",
"php",
"post",
"python"
] | stackoverflow_0003263350_html_php_post_python.txt |
Q:
Python API C++ : "Static variable" for a Type Object
I have a small question about static variable and TypeObjects.
I use the API C to wrap a c++ object (let's call it Acpp) that has a static variable called x.
Let's call my TypeObject A_Object :
typedef struct {
PyObject_HEAD
Acpp* a;
} A_Object;
The TypeObject is attached to my python module "myMod" as "A". I have defined getter and setters (tp_getset) so that I can access and modify the static variable of Acpp from python :
>>> import myMod
>>> myA1 = myMod.A(some args...)
>>> myA1.x = 34 # using the setter to set the static variable of Acpp
>>> myA2 = myMod.A(some other args...)
>>> print myA2.x
34
>>> # Ok it works !
This solution works but it's not really "clean". I would like to access the static variable in python by using the TypeObject and not the instances :
>>> import myMod
>>> myMod.A.x = 34 # what I wish...
Does anybody have an idea to help me ?
Thanks in advance.
A:
Essentially, what you're trying to do is define a "static property". That is, you want a function to be called when you get/set an attribute of the class.
With that in mind, you might find this thread interesting. It only talks about Python-level solutions to this problem, not C extension types, but it covers the basic principles.
To implement the solution proposed in that thread for a C extension type, I think you'd have to initialize tp_dict and add to it an entry for "x" whose value is an object that implements __get__ appropriately.
A:
You could add a dummy 'x' field in the A_Object and create a pair of set/get methods. When you access the dummy 'x' field, the method would redirect the call to the static 'x' field.
| Python API C++ : "Static variable" for a Type Object | I have a small question about static variable and TypeObjects.
I use the API C to wrap a c++ object (let's call it Acpp) that has a static variable called x.
Let's call my TypeObject A_Object :
typedef struct {
PyObject_HEAD
Acpp* a;
} A_Object;
The TypeObject is attached to my python module "myMod" as "A". I have defined getter and setters (tp_getset) so that I can access and modify the static variable of Acpp from python :
>>> import myMod
>>> myA1 = myMod.A(some args...)
>>> myA1.x = 34 # using the setter to set the static variable of Acpp
>>> myA2 = myMod.A(some other args...)
>>> print myA2.x
34
>>> # Ok it works !
This solution works but it's not really "clean". I would like to access the static variable in python by using the TypeObject and not the instances :
>>> import myMod
>>> myMod.A.x = 34 # what I wish...
Does anybody have an idea to help me ?
Thanks in advance.
| [
"Essentially, what you're trying to do is define a \"static property\". That is, you want a function to be called when you get/set an attribute of the class.\nWith that in mind, you might find this thread interesting. It only talks about Python-level solutions to this problem, not C extension types, but it covers... | [
1,
0
] | [] | [] | [
"api",
"c++",
"python",
"static",
"wrapper"
] | stackoverflow_0003265592_api_c++_python_static_wrapper.txt |
Q:
HTML form data to recursive json dict
I would like to convert flat form data to recursive JSON data in python or javascript. This JSON data can later be interpreted by a template engine (google for tempest, it has django like syntax). There are plenty examples to convert flat data to recursive data, but the problem is it can't be a dict or list only.
I tried to do it in many ways, but didn't succeed yet. So after scratching my head for at least two weeks, I decided to ask a question here.
The formdata is like this (key names may be different):
formdata = [
{"formname": "name", "formvalue": "Roel Kramer"},
{"formname": "email", "formvalue": "blaat@blaat.nl"},
{"formname": "paragraph-0.title", "formvalue": "test titel 1"},
{"formname": "paragraph-0.body", "formvalue": "bla bla body 1"},
{"formname": "paragraph-0.image-0.src", "formvalue": "src 1"},
{"formname": "paragraph-0.image-1.src", "formvalue": "src 2"},
{"formname": "paragraph-1.title", "formvalue": "test titel 2"},
{"formname": "paragraph-1.body", "formvalue": "bla bla body 2"},
{"formname": "paragraph-1.image-0.src", "formvalue": "src 3"},
{"formname": "paragraph-1.image-1.src", "formvalue": "src 4"},
{"formname": "paragraph-1.image-2.src", "formvalue": "src 5"},
{"formname": "paragraph-2.title", "formvalue": "test titel 3"},
{"formname": "paragraph-2.body", "formvalue": "bla bla body 3"},
{"formname": "paragraph-2.image-0.src", "formvalue": "src 6"},
{"formname": "paragraph-2.image-1.src", "formvalue": "src 7"},
]
I would like to convert it to this format:
{'paragraph':
[
{
'image': [{'src': 'src 1'}, {'src': 'src 2'}],
'body': 'body 2',
'title': 'titel 2'
},
{
'image': [{'src': 'src 3'}, {'src': 'src 4'}, {'src': 'src 5'}],
'body': 'body 2',
'title': 'titel 2'
},
{
'image': [{'src': 'src 6'}, {'src': 'src 7'},
'body': 'body 3',
'title': 'titel 3'
},
],
}
As you can see I mix dicts with lists, which makes it a bit harder. In my last attempt I got to the point where the script figures out where to add lists and where to add dicts. This results in this:
{'paragraph': [{'image': []}, {'image': []}, {'image': []}]}
But when I add data the result is not what I expected.
{
"paragraph": [{
"body": "bla bla body 1",
"image": {
"src": "src 7"
},
"title": "test titel 1"
}, {
"body": "bla bla body 2",
"image": {
"src": "src 5"
},
"title": "test titel 2"
}, {
"body": "bla bla body 3",
"image": {
"src": "src 3"
},
"title": "test titel 3"
}, {
"image": {
"src": "src 6"
}
}],
"name": "Roel Kramer",
"email": "contact@roelkramer.nl"
}
The total script can be seen at github gist. I know it can be much cleaner, but I will refactor it when it works.
What am I doing wrong? Am I totally missing something?
Thanks a lot!
A:
Well, if you know the format will be consistent then something like this will work:
def add_data(node, name, value):
if '-' not in name:
node[name] = value
else:
key = name[:name.index('-')]
node_index = int(name[len(key) + 1:name.index('.')])
node.setdefault(key, [])
if node_index >= len(node[key]):
node[key].append({})
add_data(node[key][node_index],
name[name.index('.') + 1:],
value)
Then to use it, just do something like this:
root_node = {}
for data in formdata:
add_data(root_node, data['formname'], data['formvalue'])
The function makes the following assumptions:
The - character is used to specify which node of a particular node type, and is followed
by a number.
The . character separates nodes in the tree, and always follows the index number.
The form data will always go in order. (paragraph-0, paragraph-1, paragraph-2) instead of (paragraph-1, paragraph-0, paragraph-3).
So, here's the code with comments explaining it:
def add_data(node, name, value):
# We're at a parent node (ex: paragraph-0), so we need to drill down until
# we find a leaf node
if '-' in name:
key = name[:name.index('-')]
node_index = int(name[len(key) + 1:name.index('.')])
# Initialize the parent node if needed by giving it a dict to store it's
# information nodes
node.setdefault(key, [])
if node_index >= len(node[key]):
node[key].append({})
# Drill down the tree by calling this function again, making this
# parent node the root
add_data(node[key][node_index],
name[name.index('.') + 1:],
value)
# We're at a leaf node, so just add it to the parent node's information
# ex: The first formdata item would make the root_node dict look like
# { 'name': 'Roel Kramer' }
else:
node[name] = value
Here's a working example: http://pastebin.com/wpMPXs1r
| HTML form data to recursive json dict | I would like to convert flat form data to recursive JSON data in python or javascript. This JSON data can later be interpreted by a template engine (google for tempest, it has django like syntax). There are plenty examples to convert flat data to recursive data, but the problem is it can't be a dict or list only.
I tried to do it in many ways, but didn't succeed yet. So after scratching my head for at least two weeks, I decided to ask a question here.
The formdata is like this (key names may be different):
formdata = [
{"formname": "name", "formvalue": "Roel Kramer"},
{"formname": "email", "formvalue": "blaat@blaat.nl"},
{"formname": "paragraph-0.title", "formvalue": "test titel 1"},
{"formname": "paragraph-0.body", "formvalue": "bla bla body 1"},
{"formname": "paragraph-0.image-0.src", "formvalue": "src 1"},
{"formname": "paragraph-0.image-1.src", "formvalue": "src 2"},
{"formname": "paragraph-1.title", "formvalue": "test titel 2"},
{"formname": "paragraph-1.body", "formvalue": "bla bla body 2"},
{"formname": "paragraph-1.image-0.src", "formvalue": "src 3"},
{"formname": "paragraph-1.image-1.src", "formvalue": "src 4"},
{"formname": "paragraph-1.image-2.src", "formvalue": "src 5"},
{"formname": "paragraph-2.title", "formvalue": "test titel 3"},
{"formname": "paragraph-2.body", "formvalue": "bla bla body 3"},
{"formname": "paragraph-2.image-0.src", "formvalue": "src 6"},
{"formname": "paragraph-2.image-1.src", "formvalue": "src 7"},
]
I would like to convert it to this format:
{'paragraph':
[
{
'image': [{'src': 'src 1'}, {'src': 'src 2'}],
'body': 'body 2',
'title': 'titel 2'
},
{
'image': [{'src': 'src 3'}, {'src': 'src 4'}, {'src': 'src 5'}],
'body': 'body 2',
'title': 'titel 2'
},
{
'image': [{'src': 'src 6'}, {'src': 'src 7'},
'body': 'body 3',
'title': 'titel 3'
},
],
}
As you can see I mix dicts with lists, which makes it a bit harder. In my last attempt I got to the point where the script figures out where to add lists and where to add dicts. This results in this:
{'paragraph': [{'image': []}, {'image': []}, {'image': []}]}
But when I add data the result is not what I expected.
{
"paragraph": [{
"body": "bla bla body 1",
"image": {
"src": "src 7"
},
"title": "test titel 1"
}, {
"body": "bla bla body 2",
"image": {
"src": "src 5"
},
"title": "test titel 2"
}, {
"body": "bla bla body 3",
"image": {
"src": "src 3"
},
"title": "test titel 3"
}, {
"image": {
"src": "src 6"
}
}],
"name": "Roel Kramer",
"email": "contact@roelkramer.nl"
}
The total script can be seen at github gist. I know it can be much cleaner, but I will refactor it when it works.
What am I doing wrong? Am I totally missing something?
Thanks a lot!
| [
"Well, if you know the format will be consistent then something like this will work:\ndef add_data(node, name, value):\n if '-' not in name:\n node[name] = value\n else:\n key = name[:name.index('-')]\n node_index = int(name[len(key) + 1:name.index('.')])\n node.setdefault(key, [])... | [
1
] | [] | [] | [
"html",
"javascript",
"json",
"python",
"recursion"
] | stackoverflow_0003265218_html_javascript_json_python_recursion.txt |
Q:
Python over JavaScript? (Facts, please)
I recently learned JavaScript an all of the sudden I hear about Python...
Should I go learn Python or just stick with my basic JavaScript knowledge?
If you have some "facts" I would love to hear them! Like efficiency, difficultylevel and so on, an so on...
Thanks :)
A:
The two are generally used quite differently. Javascript is primarily used as a client side scripting language vs python which is a server based language. So in a website you could use both. But not sure if this is what you were wondering.
A:
If you're just learning a language, then there is none better than Python. It's an easy language to pick up. It's well documented. It's associated with a large, active, and friendly community. Since it's a scripting language, you can easily try stuff out and immediately see the results. You can also build up from programming basics, starting by learning functions and then moving into classes.
Javascript is the bane of many a programmer's existences. It's easy enough to learn, and is good for small scripts which is what is was designed for. But once you start making anything big, it becomes hard to keep track of. That's why language modifications like CoffeeScript, Typescript and Dart have emerged.
As noted by spinon, these programming languages were used in very different ways. Python is a general scripting language, which can sometimes be used to do server-side work. Javascript used to be solely used for building interactivity on web pages. Nowadays, however, it also becomes popular in server-side and desktop applications as Node.js.
A:
The key fact is that Javascript is very hard to ever change (because of billions of old implementations existing in browsers), so design errors made in early (and frantically hurried;-) stages are still with the language today. (See Crockford's Javascript: the good parts for a reasonable discussion by a JS expert and enthusiast about the good and bad parts thereof). This might change if something like a use strict; directive ever makes its way into ECMAscript (though programming in ways that support old, and often buggy, browsers, will still be like pulling teeth -- like writing Python code that runs unchanged all the way from Python 1.0 to 3.1 would be!-).
Python is deployed in more traditional ways, so gradual language changes have enhanced it over the years (it was also designed with less hurry, and [[arguably, not "a fact";-)]] ended up with a better design from the start, in many respects).
As a result, Javascript (so far) has not enjoyed much success "server side", where programmers get a choice (even though they still have to use JS for "browser side" code). But there's nothing intrinsic to that. JS is by far the most widely deployed language in the world (those billions of browsers...), huge investments are made in it by many companies and open source groups in competing implementations and supporting frameworks (Python's no slouch at that either, but the difference is still there), practical improvements (speed, warnings) keep piling up on JS's side as a consequence (even though the language proper can't improve).
With strict self-imposed programming discipline (enforced e.g. by Crockfor's "lint" program for JS) and a good supporting framework (jQuery, Dojo, Closure, ...) and tools (Firefox has maybe the best add-ons for JS tracing and debugging, but other browsers are rushing in that direction too), JS has become usable in recent years. Probably one of these days a fast server-side implementation (probably with "use strict;" or the like enforced, once that's officially blessed;-) will start gaining a substantial foothold, just because so many web programmers already have some JS knowledge (they have to, to make good web apps).
Note that much of JS's bad rep (beyond the acknowledge "bad parts that can't be removed";-) comes from stuff that doesn't really "belong" to JS as a language: buggy implementations, the mess that the HTML DOM can often be (esp. with buggy browser impementations), etc. There is no reason a future server-side deployment should reproduce these maddening defects!-)
A:
Python’s a good second language to learn after JavaScript, as they have a reasonable number of similarities, e.g.
they’re both memory-managed
they have similar data structures — JavaScript’s objects and arrays are much like Python’s dictionaries and arrays
they’re both used quite a lot for web-related work — JavaScript in the browser and in server-side contexts like node.js, Python in web frameworks like Django.
However, Python’s object-oriented... stuff is quite different to JavaScript’s protoype-based object-oriented stuff.
If the only programming you do is manipulating web pages within the web browser, then Python won’t be of any direct use to you (only JavaScript runs in browsers at the moment). But learning another programming language generally gives you new ways to think about the languages you already know. Learning Python could help you write better JavaScript.
A:
Javascript is primarily for client-side ( browser ), Python is primarily used for server-side - so they serve different needs ( disregarding the Python to JS converters and all ).
I would recommend learning Python though, as it influenced ECMAScript and the syntax is very similar, both are object oriented, both are great languages.
2018 Update: I would still recommend learning Python over Javascript as a first language because it's just that much of a more beautiful, elegant language... although Javascript can now be used for both server-side and client-side thanks to node.js thus making it more useful all-around.
http://hg.toolness.com/python-for-js-programmers/raw-file/tip/PythonForJsProgrammers.html
A:
JavaScript is usually used as a client-side scripting language - that is, it gets downloaded and executed by your browser. Python, however, is usually not coupled to the web. it can be used as a server-side scripting language, and for scripts and applications of any kind. But it is not a client-side language, and is therefore not directly comparable to Javascript, which has an entirely different audience.
Looking at the language level, Javascript is terrible and dysfunctional (hard to debug, clumsy object-orientation) while Python is beautiful and expressive. This is, of course, subjective :-)
A:
IMO Python may be easier to learn (having taught both to intro classes).
Also, one major annoyance of JavaScript is that in runs in your browser. This inherently makes it much harder to debug problems.
In terms of a production-level language, Python is more of a general purpose programming language, while JavaScript is targeted at building dynamic web applications.
If you want to get into programming, you should definitely learn a more general purpose language such as Java or Python.
A:
For what purpose? Javascript is king in some circles (web development, for instance).
Javascript and Python are not mutually exclusive. Why not learn both?
A:
JavaScript and Python are both great languages that are geared toward different problems.
JavaScript knowledge is invaluable when dealing with the web, writing web pages, and poking around in html DOM.
Python is a scripting language that is great for a host of things on any machine.
A:
It depends.
Do you want to program in a language that specifically targets web browsers? Stick with Javascript
Do you want to write... well anything besides for web browsers? Learn Python.
Python is an excellent beginner language that's not just a beginner language. Google uses it, NASA uses it, and many, many other organizations use Python.
A:
Along with Python generally being server-side and JavaScript client-side, Python was designed to not only be easy to learn, but also easy to read, and to encourage a more productive environment.
| Python over JavaScript? (Facts, please) | I recently learned JavaScript an all of the sudden I hear about Python...
Should I go learn Python or just stick with my basic JavaScript knowledge?
If you have some "facts" I would love to hear them! Like efficiency, difficultylevel and so on, an so on...
Thanks :)
| [
"The two are generally used quite differently. Javascript is primarily used as a client side scripting language vs python which is a server based language. So in a website you could use both. But not sure if this is what you were wondering.\n",
"If you're just learning a language, then there is none better than P... | [
15,
12,
4,
3,
2,
2,
1,
1,
0,
0,
0
] | [
"If you need to ask, then I would say no since you don't have a need in mind for its usage.\n"
] | [
-2
] | [
"javascript",
"python"
] | stackoverflow_0003266223_javascript_python.txt |
Q:
What is the most efficient way to repeatedly use regular expressions in a Python loop?
When you're iterating over hundreds of lines in a file, what is the most (and least) efficient way to run regular expressions in Python?
Specifically, is the following bad form?
for line in file:
data = re.search('(\d+\.\d+)\|(-\d+\.\d+)\|(.*?)\|(.*?)\|(\d+:\d+\s+\w+)\sTO\s(.*?)',line)
one = data.group(1)
two = data.group(2)
three = data.group(3)
four = data.group(4)
five = data.group(5)
six = data.group(6)
# do the magic...
A:
If you're just using this same regex over and over again, you don't need to compile it directly. http://docs.python.org/release/2.6.5/library/re.html#re.compile
The compiled versions of the most recent patterns passed to re.match(), re.search() or re.compile() are cached, so programs that use only a few regular expressions at a time needn’t worry about compiling regular expressions.
However, I would very much recommend not doing the assignments below that as you are. Try something like this:
for line in file:
data = re.search('(\d+\.\d+)\|(-\d+\.\d+)\|(.*?)\|(.*?)\|(\d+:\d+\s+\w+)\sTO\s(.*?)',line)
groups = data.groups()
# do the magic...
MatchObject.groups() returns a tuple of all the groups in the match, with groups that don't participate in the match being assigned the value passed to groups() (said value defaults to None).
A:
Save the regex before the loop.
rx = re.compile( '(\d+\.\d+)\|(-\d+\.\d+)\|(.*?)\|(.*?)\|(\d+:\d+\s+\w+)\sTO\s(.*?)' )
for line in file:
data = re.search(rx,line)
one = data.group(1)
two = data.group(2)
three = data.group(3)
four = data.group(4)
five = data.group(5)
six = data.group(6)
A:
Unless the speed is an issue then you might want to just go with what you are comfortable reading, and which works.
| What is the most efficient way to repeatedly use regular expressions in a Python loop? | When you're iterating over hundreds of lines in a file, what is the most (and least) efficient way to run regular expressions in Python?
Specifically, is the following bad form?
for line in file:
data = re.search('(\d+\.\d+)\|(-\d+\.\d+)\|(.*?)\|(.*?)\|(\d+:\d+\s+\w+)\sTO\s(.*?)',line)
one = data.group(1)
two = data.group(2)
three = data.group(3)
four = data.group(4)
five = data.group(5)
six = data.group(6)
# do the magic...
| [
"If you're just using this same regex over and over again, you don't need to compile it directly. http://docs.python.org/release/2.6.5/library/re.html#re.compile\n\nThe compiled versions of the most recent patterns passed to re.match(), re.search() or re.compile() are cached, so programs that use only a few regular... | [
6,
3,
1
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0003266134_python_regex.txt |
Q:
Django boilerplate template code
I am a django newbie and in creating my first project I have come to realize that a lot of my boilerplate code (the lists on the side of my page). I have to recreate them in every view and I am trying to stick with DRY but I find myself rewriting the code every time. Is there a way to inherit from my base views and just modify a few objects?
Thanks,
James
A:
Yes, you'll want to look into template inheritance, which lets you share common elements between templates, and the {% include %} template tag, which lets you create reusable template "snippets" that can be included in other templates.
Edit: Re-reading the question, it sounds like you're talking about boilerplate code that you have in your view functions/methods that you're using to generate context shared by multiple templates. In that case, mipadi's answer is the right one: Look into context processors.
A:
You might want to use a context processor for this work.
A:
For the lists of recent articles etc, custom template tags are the thing you need. Whereas a context processor will populate your context with the lists automatically, a template tag can actually do that plus create the whole HTML markup for the column itself.
A:
For large blocks of static html that reappear consistently you can use the include template tag:
{% include 'static/some_file.html' %}
The includes are stored in your template file system, just like templates.
A:
If you don't decide to use context processor for some reasons (this solution looks reasonable here) you can always encapsulate some common logic into util functions and use them in your views.
You can also take a look at Generic views - this is a good way to 'stay DRY' with your code
| Django boilerplate template code | I am a django newbie and in creating my first project I have come to realize that a lot of my boilerplate code (the lists on the side of my page). I have to recreate them in every view and I am trying to stick with DRY but I find myself rewriting the code every time. Is there a way to inherit from my base views and just modify a few objects?
Thanks,
James
| [
"Yes, you'll want to look into template inheritance, which lets you share common elements between templates, and the {% include %} template tag, which lets you create reusable template \"snippets\" that can be included in other templates.\nEdit: Re-reading the question, it sounds like you're talking about boilerpla... | [
3,
3,
3,
1,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0003250463_django_python.txt |
Q:
Python: Obtain a URL
Because I cant get this working: Python: KeyError with form.getfirst
I have an alternative option, I have a function in DTML which needs to obtain a URL:
For example if the dtml webpage is located at
www.blah.com/foo/foo2?variable=55
How would i obtain the URL of this page using a python function?
The function is called by:
<dtml-var test>
The syntax for "test" is rite, the Zope documentation says so.
A:
for: http://www.blah.com/foo/foo2?job_ID=55555&test=1
<dtml-var URL> = http://www.blah.com/foo/foo2
<dtml-var QUERY_STRING> = job_ID=55555&test=1
<dtml-var "REQUEST['job_ID']"> = 55555
See: http://wiki.zope.org/zope2/REQUESTX
| Python: Obtain a URL | Because I cant get this working: Python: KeyError with form.getfirst
I have an alternative option, I have a function in DTML which needs to obtain a URL:
For example if the dtml webpage is located at
www.blah.com/foo/foo2?variable=55
How would i obtain the URL of this page using a python function?
The function is called by:
<dtml-var test>
The syntax for "test" is rite, the Zope documentation says so.
| [
"for: http://www.blah.com/foo/foo2?job_ID=55555&test=1\n<dtml-var URL> = http://www.blah.com/foo/foo2\n<dtml-var QUERY_STRING> = job_ID=55555&test=1\n<dtml-var \"REQUEST['job_ID']\"> = 55555\nSee: http://wiki.zope.org/zope2/REQUESTX\n"
] | [
1
] | [] | [] | [
"dtml",
"python",
"zope"
] | stackoverflow_0003251020_dtml_python_zope.txt |
Q:
Python: KeyError with form.getfirst
I have a dtml page, which calls a function, with this code:
<dtml-var public_blast(form.getfirst('job_ID'))>
But i get a key error? stating KeyError: "public_blast(form.getfirst('job_ID'))". I can see the job_ID variable at the top of the page. So i know it is being passed to the URL.
I cant see where im going wrong?
A:
It's been a very long time since I did any DTML, but I don't think you can call Python functions directly like that inside a DTML tag.
Instead I think you need to use the expr attribute:
<dtml-var expr="public_blast(form.getfirst('job_ID'))">
A:
Try <dtml-var "REQUEST['job_ID']">
| Python: KeyError with form.getfirst | I have a dtml page, which calls a function, with this code:
<dtml-var public_blast(form.getfirst('job_ID'))>
But i get a key error? stating KeyError: "public_blast(form.getfirst('job_ID'))". I can see the job_ID variable at the top of the page. So i know it is being passed to the URL.
I cant see where im going wrong?
| [
"It's been a very long time since I did any DTML, but I don't think you can call Python functions directly like that inside a DTML tag. \nInstead I think you need to use the expr attribute:\n<dtml-var expr=\"public_blast(form.getfirst('job_ID'))\">\n\n",
"Try <dtml-var \"REQUEST['job_ID']\">\n"
] | [
0,
0
] | [] | [] | [
"dtml",
"python"
] | stackoverflow_0003250572_dtml_python.txt |
Q:
PUT Variables Missing between Python and Tomcat
I'm trying to get a PUT request from Python into a servlet in Tomcat. The parameters are missing when I get into Tomcat.
The same code is happily working for POST requests, but not for PUT.
Here's the client:
lConnection = httplib.HTTPConnection('localhost:8080')
lHeaders = {"Content-type": "application/x-www-form-urlencoded",
"Accept": "text/plain"}
lParams = {'Username':'usr', 'Password':'password', 'Forenames':'First','Surname':'Last'}
lConnection.request("PUT", "/my/url/", urllib.urlencode(lParams), lHeaders)
Once in the server, a request.getParameter("Username") is returning null.
Has anyone got any clues as to where I'm losing the parameters?
A:
I tried your code and it seems that the parameters get to the server using that code. Tcpdump gives:
PUT /my/url/ HTTP/1.1
Host: localhost
Accept-Encoding: identity
Content-Length: 59
Content-type: application/x-www-form-urlencoded
Accept: text/plain
Username=usr&Password=password&Surname=Last&Forenames=First
So the request gets to the other side correctly, it must be something with either tomcat configuration or the code that is trying to read the parameters.
A:
I don't know what the Tomcat side of your code looks like, or how Tomcat processes and provides access to request parameters, but my guess is that Tomcat is not "automagically" parsing the body of your PUT request into nice request parameters for you.
I ran into the exact same problem using the built-in webapp framework (in Python) on App Engine. It did not parse the body of my PUT requests into request parameters available via self.request.get('param'), even though they were coming in as application/x-www-form-urlencoded.
You'll have to check on the Tomcat side to confirm this, though. You may end up having to access the body of the PUT request and parse out the parameters yourself.
Whether or not your web framework should be expected to automagically parse out application/x-www-form-urlencoded parameters in PUT requests (like it does with POST requests) is debatable.
A:
I'm guessing here, but I think the problem is that PUT isn't meant to be used that way. The intent of PUT is to store a single entity, contained in the request, into the resource named in the headers. What's all this stuff about user name and stuff?
Your Content Type is application/X-www-form-urlencoded, which is a bunch of field contents. What PUT wants is something like an encoded file. You know, a single bunch of data it can store somewhere.
| PUT Variables Missing between Python and Tomcat | I'm trying to get a PUT request from Python into a servlet in Tomcat. The parameters are missing when I get into Tomcat.
The same code is happily working for POST requests, but not for PUT.
Here's the client:
lConnection = httplib.HTTPConnection('localhost:8080')
lHeaders = {"Content-type": "application/x-www-form-urlencoded",
"Accept": "text/plain"}
lParams = {'Username':'usr', 'Password':'password', 'Forenames':'First','Surname':'Last'}
lConnection.request("PUT", "/my/url/", urllib.urlencode(lParams), lHeaders)
Once in the server, a request.getParameter("Username") is returning null.
Has anyone got any clues as to where I'm losing the parameters?
| [
"I tried your code and it seems that the parameters get to the server using that code. Tcpdump gives:\nPUT /my/url/ HTTP/1.1\nHost: localhost\nAccept-Encoding: identity\nContent-Length: 59\nContent-type: application/x-www-form-urlencoded\nAccept: text/plain\n\nUsername=usr&Password=password&Surname=Last&Forenames=F... | [
2,
2,
1
] | [] | [] | [
"http",
"put",
"python",
"tomcat"
] | stackoverflow_0003266997_http_put_python_tomcat.txt |
Q:
Is there a list of 3rd party Python 3 libraries?
More and more libraries are being ported to Python 3, and I suspect the changes will happen more and more rapidly as time goes on. However, as a non-newbie to Python, there are quite a few 3rd party libraries I use (matplotlib, pygame, pyGTK, Tkinter, among others). I know I should just be able to go to their site(s) to find out if they support python3k yet, but I'm wondering: is there a site anywhere that already has some type of list of 3rd party modules that work in Py3k?
Thanks
A:
On the side menu at pypi.python.org there is a link entitled "Python 3 packages":
http://pypi.python.org/pypi?:action=browse&c=533&show=all
| Is there a list of 3rd party Python 3 libraries? | More and more libraries are being ported to Python 3, and I suspect the changes will happen more and more rapidly as time goes on. However, as a non-newbie to Python, there are quite a few 3rd party libraries I use (matplotlib, pygame, pyGTK, Tkinter, among others). I know I should just be able to go to their site(s) to find out if they support python3k yet, but I'm wondering: is there a site anywhere that already has some type of list of 3rd party modules that work in Py3k?
Thanks
| [
"On the side menu at pypi.python.org there is a link entitled \"Python 3 packages\":\nhttp://pypi.python.org/pypi?:action=browse&c=533&show=all\n"
] | [
10
] | [] | [] | [
"python",
"python_3.x",
"reference"
] | stackoverflow_0003267805_python_python_3.x_reference.txt |
Q:
Recommendation for click/event tracking mechanisms (python, django, celery, mongo etc)
I'm looking into way to track events in a django application (events would generally be clicks tied to a specific unique user id).
These events would essentially contain an event type like "click" and then each click event would be assigned to a unique id (many events can go to one id) and each event would have a data set including items like referrer etc...
I have tried mixpanel, but for now the data api they are offering seems too limiting as I can't seem to find a way to get all of my data out by a unique id (apart from the event itself).
I'm looking into using django-eventracker, but curious about any others thought on the best way to do this. Mongo or CouchDb seem like a great choice here, but the celery/rabbitmq looks really attractive with mongo. Pumping these events into the existing applications db seems limiting at this point.
Anyways, this is just a thread to see what others thoughts are on this and how they have implemented something like this...
shoot
A:
I am not familiar with the pre-packaged solutions you mention. Were I to design this from scratch, I'd have a simple JS collecting info on clicks and posting it back to the server via Ajax (using whatever JS framework you're already using), and on the server side I'd simply append that info to a log file for later "offline" processing -- so that would be independent of django or other server-side framework, essentially.
Appending to a log file is a very light-weight action, while DBs for web use are generally way optimized for read-intensive (not write-intensive) operation, so I agree with you that force fitting that info (as it trickes in) into the existing app's DB is unlikely to offer good performance.
A:
You probably want to keep a flexible format for your logs to anticipate future needs or changes. In this sense, the schema-less document-oriented databases are nice. One advantage is that the structure of your data will be close to your application needs for whatever analyses you perform later (so, avoiding some of the inevitable parsing/data munging work).
If you're thinking about using mysql, postgresql or such, then you should look into something like rsyslog for buffering writes and avoiding the performance penalty with heavy logging. (I can't say much about celery and other queueing mechanisms for this type of thing, but they sound promising.)
Mongodb has a some nice features that make it amenable to logging such as capped collections. A summary can be found in this post.
A:
If by click, you mean a click on a link that loads a new page (or performs an AJAX request), then what you aim to do is fairly straightforward. Web servers tend to keep plain-text logs about requests - with information about the user, time/date, referrer, the page requested, etc. You could examine these logs and mine the statistics you need.
On the other hand, if you have a web application where clicks don't necessarily generate server requests, then collecting click information with javascript is your best bet.
| Recommendation for click/event tracking mechanisms (python, django, celery, mongo etc) | I'm looking into way to track events in a django application (events would generally be clicks tied to a specific unique user id).
These events would essentially contain an event type like "click" and then each click event would be assigned to a unique id (many events can go to one id) and each event would have a data set including items like referrer etc...
I have tried mixpanel, but for now the data api they are offering seems too limiting as I can't seem to find a way to get all of my data out by a unique id (apart from the event itself).
I'm looking into using django-eventracker, but curious about any others thought on the best way to do this. Mongo or CouchDb seem like a great choice here, but the celery/rabbitmq looks really attractive with mongo. Pumping these events into the existing applications db seems limiting at this point.
Anyways, this is just a thread to see what others thoughts are on this and how they have implemented something like this...
shoot
| [
"I am not familiar with the pre-packaged solutions you mention. Were I to design this from scratch, I'd have a simple JS collecting info on clicks and posting it back to the server via Ajax (using whatever JS framework you're already using), and on the server side I'd simply append that info to a log file for late... | [
5,
2,
1
] | [] | [] | [
"django",
"events",
"mongodb",
"python",
"tracking"
] | stackoverflow_0003267081_django_events_mongodb_python_tracking.txt |
Q:
Why aren't the Python 2.7 command-line tools located in `/usr/local/bin` on Mac OS X?
The Python 2.7 installer disk image for Mac OS X (python-2.7-macosx10.5.dmg) states:
The installer puts the applications in "Python 2.7" in your Applications folder, command-line tools in /usr/local/bin and the underlying machinery in /Library/Frameworks/Python.framework.
However, after installation there are no Python 2.7 files in /usr/local/bin/.
Are others seeing the same behavior?
I assume the solution is simply to create the equivalent symbolic links to /usr/local/bin as Python 2.6, or am I overlooking something?
A:
The python.org Python installer for OS X is a meta package with a set of several packages. You can see the packages by clicking on the Customize button during the installation process. The symlinks in /usr/local/bin are installed by the UNIX command-line tools package. For the 2.7 release, that package is no longer selected by default. You can install it and the symlinks by doing a custom install and selecting that package; if you've already installed 2.7, select just that package.
EDIT: That said, it is important to recognize that, with OS X Python framework builds, just having /usr/local/bin in your search path is generally not sufficient. The reason for that is that python scripts included in packages are, by default, installed into the bin directory of the Python directory, e.g. /Library/Frameworks/Python.framework/Versions/2.7/bin. This is true of just about anything that uses Distutils defaults or installation tools that wrap Distutils, like easy_install (Distribute or setuptools) or pip. This is why there is another installer package, Shell profile updater, that is enabled by default and attempts to modify your login profile to put the framework bin directory at the front of your shell search path, PATH. If that is done, the symlinks in /usr/local/bin are not required for python2.7 to be invoked.
A:
Steven Majewski's comment stating "I believe I had to explicitly select that option ( "install command line tools" ) in the installer" made me think that I overlooked something in the installer. Sure enough, I overlooked the Customize option. See below.
Optional Customize Python Install http://img.skitch.com/20100716-ede8ausmtch9cb6g4mqp4hcm84.jpg
Select UNIX Command-Line Tools http://img.skitch.com/20100716-817rjbyikr8c4y88xkfj6qeg1p.jpg
| Why aren't the Python 2.7 command-line tools located in `/usr/local/bin` on Mac OS X? | The Python 2.7 installer disk image for Mac OS X (python-2.7-macosx10.5.dmg) states:
The installer puts the applications in "Python 2.7" in your Applications folder, command-line tools in /usr/local/bin and the underlying machinery in /Library/Frameworks/Python.framework.
However, after installation there are no Python 2.7 files in /usr/local/bin/.
Are others seeing the same behavior?
I assume the solution is simply to create the equivalent symbolic links to /usr/local/bin as Python 2.6, or am I overlooking something?
| [
"The python.org Python installer for OS X is a meta package with a set of several packages. You can see the packages by clicking on the Customize button during the installation process. The symlinks in /usr/local/bin are installed by the UNIX command-line tools package. For the 2.7 release, that package is no long... | [
4,
2
] | [
"11:54 jsmith@upsidedown find /usr -name python2.7\n11:54 jsmith@upsidedown\n\nYeah, that sucks.\nI'd follow the pattern that the Python 2.6 (and, in my case, 2.5) installer did, and create the symlinks (as you're suspecting). The pattern stayed the same, at least:\n11:57 jsmith@upsidedown /Library/Frameworks/P... | [
-1
] | [
"installation",
"macos",
"python"
] | stackoverflow_0003266005_installation_macos_python.txt |
Q:
How can we properly implement Python bindings of subclassed C++ objects?
I'm having an issue with a rather intricate interaction of C++ and Python that I'm hoping the community can help me with. If my explanation doesn't make sense, let me know in the comments and I'll try to clarify.
Our C++ code base contains a parent classes called "IODevice" which is a parent to other classes such as "File" and "Socket" and so forth. We've done this so that in much of our code we can work generically with "IODevice" objects that might actually be files or sockets or whatever we originally constructed. This all works fine within the C++ code.
We've started to build Python bindings for some of our objects. We didn't want to modify the original "File" or "Socket" classes; we created "FilePy" and "SocketPy" subclasses of the "File" and "Socket" classes. These *Py classes contain the necessary Python binding code.
Here's where the problem starts. Let's say I have a "InputProcessorPy" C++ class that has the appropriate Python bindings. I would want to be able to construct it in my Python code and pass it a "FilePy" or "SocketPy" object that the "InputProcessorPy" is going to pull data from. The Python binding code from "InputProcessorPy" looks like this:
PyObject* InputProcessor::PyMake(PyObject* ignored, PyObject *args)
{
PyObject* cD_py;
IODevice* inputFile;
if (!PyArg_ParseTuple(args, "O", &cD_py))
return NULL;
inputFile = (IODevice*) cD_py;
inputFile->isReadable();
printf("------>>>> Done\n");
return (PyObject *) new CL_InputRenderer(*inputFile, InputProcessor::Type);
}
If I run this code, I get a segmentation error when I call the isReadable() method of inputFile, which is actually a method of the IODevice base class.
If instead I do this:
...
FilePy* inputFile;
...
inputFile = (FilePy*) cD_py;
inputFile->isReadable();
...
The code works fine in this case. This, however, is undesirable, as it assumes we are passing in a "FilePy" object, which will not be the case; it might be a "SocketPy" or "BufferPy" or "StringPy" or any other sort of "IODevice" subclass.
It seems as if the Python binding process is somehow not compatible with the C++ class inheritance structure that we're trying to use. Has anyone tried to solve an issue like this before? Are we doing our C++ inheritance wrong, or should we be doing something different in our Python bindings to make this work?
A:
Are your types FilePy and IODevice derived from PyObject? Otherwise, the C++ compiler will interpret:
inputFile = (IODevice*) cD_py;
as:
inputFile = reinterpret_cast<IODevice*> (cD_py);
rather than what you expected:
inputFile = dynamic_cast<IODevice*> (cD_py);
If the actual type passed is not PyObject, or IODevice is not related to PyObject via inheritance, there is no way for the C++ compiler or runtime to know how to find the proper vtable.
| How can we properly implement Python bindings of subclassed C++ objects? | I'm having an issue with a rather intricate interaction of C++ and Python that I'm hoping the community can help me with. If my explanation doesn't make sense, let me know in the comments and I'll try to clarify.
Our C++ code base contains a parent classes called "IODevice" which is a parent to other classes such as "File" and "Socket" and so forth. We've done this so that in much of our code we can work generically with "IODevice" objects that might actually be files or sockets or whatever we originally constructed. This all works fine within the C++ code.
We've started to build Python bindings for some of our objects. We didn't want to modify the original "File" or "Socket" classes; we created "FilePy" and "SocketPy" subclasses of the "File" and "Socket" classes. These *Py classes contain the necessary Python binding code.
Here's where the problem starts. Let's say I have a "InputProcessorPy" C++ class that has the appropriate Python bindings. I would want to be able to construct it in my Python code and pass it a "FilePy" or "SocketPy" object that the "InputProcessorPy" is going to pull data from. The Python binding code from "InputProcessorPy" looks like this:
PyObject* InputProcessor::PyMake(PyObject* ignored, PyObject *args)
{
PyObject* cD_py;
IODevice* inputFile;
if (!PyArg_ParseTuple(args, "O", &cD_py))
return NULL;
inputFile = (IODevice*) cD_py;
inputFile->isReadable();
printf("------>>>> Done\n");
return (PyObject *) new CL_InputRenderer(*inputFile, InputProcessor::Type);
}
If I run this code, I get a segmentation error when I call the isReadable() method of inputFile, which is actually a method of the IODevice base class.
If instead I do this:
...
FilePy* inputFile;
...
inputFile = (FilePy*) cD_py;
inputFile->isReadable();
...
The code works fine in this case. This, however, is undesirable, as it assumes we are passing in a "FilePy" object, which will not be the case; it might be a "SocketPy" or "BufferPy" or "StringPy" or any other sort of "IODevice" subclass.
It seems as if the Python binding process is somehow not compatible with the C++ class inheritance structure that we're trying to use. Has anyone tried to solve an issue like this before? Are we doing our C++ inheritance wrong, or should we be doing something different in our Python bindings to make this work?
| [
"Are your types FilePy and IODevice derived from PyObject? Otherwise, the C++ compiler will interpret:\ninputFile = (IODevice*) cD_py;\n\nas:\ninputFile = reinterpret_cast<IODevice*> (cD_py);\n\nrather than what you expected:\ninputFile = dynamic_cast<IODevice*> (cD_py);\n\nIf the actual type passed is not PyObjec... | [
4
] | [] | [] | [
"c++",
"inheritance",
"python"
] | stackoverflow_0003268230_c++_inheritance_python.txt |
Q:
Trouble with syntax - if/else and raw_input()
Okay, so the answer is probably obvious, but I don't know the correct way to get the program to respond differently depending on what the user types.
octopusList = {"first": ["red", "white"],
"second": ["green", "blue", "red"],
"third": ["green", "blue", "red"]}
squidList = ["first", "second", "third"]
squid = random.choice(squidList)
octopus = random.choice(octopusList[squid])
The lists and the squid and octopus generate a random phrase
resp = raw_input("Please Type Something")
while resp !=1:
if resp == octopusList:
print squid + " " +octopus
break
elif resp == "Something":
print "Elephants are pachyderms"
break
else:
print "That's another text to think about."
break
print "One More Comment"
This is supposed to print squid + " " +octopus if the user inputs anything on the octopusList. Or, if the user types "Something", it should return the phrase "Elephants are pachyderms". If the user types anything esle, it should return the phrase "That's another text to think about." Lastly it should print "One More Comment". What it actually does is skip strait to else no matter what the user types.
It goes strait to Else so there's something I'm not getting about the if and the elif... thanks for any light you can shine on this.
A:
Edit: After Ned Batchelder formatted the code, I re-read the question and see my guess as to what you want to do wasn't quite correct ... although it's still not 100% clear if you're trying to loop or not. If you only want to go through this once, there's no need for the while loop, just remove it. As for the test of the input against the values in the dictionary called octopusList, you could use an in test, but that only tests against the dict's keys. If you're looking for the values in the dict entries, you'll have to either make octopusList a true list (e.g. octopusList = ['red', 'white', 'blue', 'green'] and do an in test (e.g. if resp in octopusList:) or get a little more complicated in parsing the dict.
Original answer:
It seems you're trying to create a loop to get user input and print a string in response to that input. If that's the case, I see a few things in need of correction:
You do not want the break statements, as they cause the loop to exit.
As others have said, comparing the input to octopusList won't work, just compare it to your randomly generated octopus value.
If you're going to use 1 as an exit input, you need to test the input against the string form ('1'), not the integer form (1).
If my guess is correct about what you're doing, the raw_input needs to be inside the loop.
This isn't marked homework, so I've posted code to do what I think you want below. If you want the octopus value to remain unknown to the user, just delete the print octopus line, but I put it in so you know what value to enter for testing.
import random
octopusList = {"first": ["red", "white"],
"second": ["green", "blue", "red"],
"third": ["green", "blue", "red"]}
squidList = ["first", "second", "third"]
squid = random.choice(squidList)
octopus = random.choice(octopusList[squid])
print octopus # So we know what value to use - necessary for testing at least
resp = ''
while resp != '1':
resp = raw_input("Please Type Something: ")
if resp == octopus:
print squid + " " +octopus
elif resp == "Something":
print "Elephants are pachyderms"
else:
print "That's another text to think about."
print "One More Comment"
If my speculations & suggestions are off the mark please provide a better explanation as to what you're attempting to do.
A:
Comparing a string to a dictionary does not do anything useful (it will always be false, IIRC) -- did you maybe want 'if resp in octopusList'? I'm not sure why the second conditional never hits, perhaps you typed "something" instead of "Something"?
A:
You're comparing a string (resp) with a list. Did you want something like this:
if resp == octopus: # not octopusList!
# do something
else:
# ...
| Trouble with syntax - if/else and raw_input() | Okay, so the answer is probably obvious, but I don't know the correct way to get the program to respond differently depending on what the user types.
octopusList = {"first": ["red", "white"],
"second": ["green", "blue", "red"],
"third": ["green", "blue", "red"]}
squidList = ["first", "second", "third"]
squid = random.choice(squidList)
octopus = random.choice(octopusList[squid])
The lists and the squid and octopus generate a random phrase
resp = raw_input("Please Type Something")
while resp !=1:
if resp == octopusList:
print squid + " " +octopus
break
elif resp == "Something":
print "Elephants are pachyderms"
break
else:
print "That's another text to think about."
break
print "One More Comment"
This is supposed to print squid + " " +octopus if the user inputs anything on the octopusList. Or, if the user types "Something", it should return the phrase "Elephants are pachyderms". If the user types anything esle, it should return the phrase "That's another text to think about." Lastly it should print "One More Comment". What it actually does is skip strait to else no matter what the user types.
It goes strait to Else so there's something I'm not getting about the if and the elif... thanks for any light you can shine on this.
| [
"Edit: After Ned Batchelder formatted the code, I re-read the question and see my guess as to what you want to do wasn't quite correct ... although it's still not 100% clear if you're trying to loop or not. If you only want to go through this once, there's no need for the while loop, just remove it. As for the t... | [
3,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0003268154_python.txt |
Q:
Why does this Python (Django) code eat up memory?
Why does this code eat up memory? When I run it it slowly consumes more memory with every loop, and I have something like 300000 loops. I'm using Windows, and Python 2.6.
def LoadVotes(self):
old_votes=Votes.objects.all()
amount=old_votes.count()
print 'Amount of votes is: ' + str(amount)
c=0
for row in old_votes:
try:
new_id_user=LegacyUserId.objects.get(legacy_id=row._login)
except LegacyUserId.DoesNotExist:
string=" user with old id "+str(row._login)+" does not match new user id /n"
log=open('log_add_old_votes.txt','a')
log.write(string)
continue
try:
new_id_media=LegacyMedia.objects.get(legacy_id=row.media_file_id)
except new_id_media.DoesNotExist:
log_text='old media with ID:'+str(row.media_file_id)+' is not found in relation with new media \n'
log=open('log_add_old_votes.txt','a')
log.write(log_text)
continue
mo=MediaObject.objects.get(pk=new_id_media.object_id)
new_votes_item, created=Mark.objects.get_or_create(user=new_id_user.user, media_object=mo, defaults={'mark':int(row.rate)*2})
c=c+1
i=amount-c
print '\rRemain:',
stdout.write("%d" % i)
stdout.flush()
A:
If you run with DEBUG=True, django is storing all the queries in memory. Try changing to DEBUG=False in your settings.py file.
A:
I'm not sure what the Vote model looks like. But you're only interested in two attributes from Vote (_login and media_file_id). So you might consider using the values or values_list queryset API instead -- this way you only select the fields you need, and you don't create an object for each row.
Also, depending on how many more Votes you have than LegacyUserId or LegacyMedia rows, if you have a foreign key, you might just consider selecting those rows directly through a join, rather than iterating through votes and then issuing new queries when the id's exist.
Finally, this won't affect memory as much, but consider using python logging instead of the current method. (Or at least open the file once at the start of the function instead of every time you need to write.)
A:
You are never closing the files you open. You should be doing file access like this
with open('log_add_old_votes.txt','a') as log:
log.write(string)
This will automatically close the file object for you once you are done with it. You are also using the same file for each log message, so you could move the open to before the loop and use the same file object until you finish.
A:
Presumably because it's loading objects for every Vote in your database, and then iterating through those votes and loading LegacyUserIds for each one, and LegacyMedia objects for each one.
If the amount of data you have is large, or if these objects are large this will take a lot of memory.
I wouldn't be suprised if LegacyMedia was a pretty big object itself.
| Why does this Python (Django) code eat up memory? | Why does this code eat up memory? When I run it it slowly consumes more memory with every loop, and I have something like 300000 loops. I'm using Windows, and Python 2.6.
def LoadVotes(self):
old_votes=Votes.objects.all()
amount=old_votes.count()
print 'Amount of votes is: ' + str(amount)
c=0
for row in old_votes:
try:
new_id_user=LegacyUserId.objects.get(legacy_id=row._login)
except LegacyUserId.DoesNotExist:
string=" user with old id "+str(row._login)+" does not match new user id /n"
log=open('log_add_old_votes.txt','a')
log.write(string)
continue
try:
new_id_media=LegacyMedia.objects.get(legacy_id=row.media_file_id)
except new_id_media.DoesNotExist:
log_text='old media with ID:'+str(row.media_file_id)+' is not found in relation with new media \n'
log=open('log_add_old_votes.txt','a')
log.write(log_text)
continue
mo=MediaObject.objects.get(pk=new_id_media.object_id)
new_votes_item, created=Mark.objects.get_or_create(user=new_id_user.user, media_object=mo, defaults={'mark':int(row.rate)*2})
c=c+1
i=amount-c
print '\rRemain:',
stdout.write("%d" % i)
stdout.flush()
| [
"If you run with DEBUG=True, django is storing all the queries in memory. Try changing to DEBUG=False in your settings.py file.\n",
"I'm not sure what the Vote model looks like. But you're only interested in two attributes from Vote (_login and media_file_id). So you might consider using the values or values_li... | [
5,
2,
1,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0003268127_django_python.txt |
Q:
ObjectListView Flickers/Flashes when adding a new list object
When I update my objectListView list it flickers/flashes white, is this normal behaviour or can it be prevented. The list gets updated around every 1-5 seconds using the AddObject method if that makes any difference.
A:
I seem to have fixed it by using the FastObjectListView class instead...
A:
You might be able to alleviate some of the flickering by Freezing and Thawing the ObjectListView widget as well.
Mike Driscoll
Blog: http://blog.pythonlibrary.org
| ObjectListView Flickers/Flashes when adding a new list object | When I update my objectListView list it flickers/flashes white, is this normal behaviour or can it be prevented. The list gets updated around every 1-5 seconds using the AddObject method if that makes any difference.
| [
"I seem to have fixed it by using the FastObjectListView class instead...\n",
"You might be able to alleviate some of the flickering by Freezing and Thawing the ObjectListView widget as well. \n\nMike Driscoll\nBlog: http://blog.pythonlibrary.org\n"
] | [
0,
0
] | [] | [] | [
"objectlistview",
"python",
"user_interface",
"wxpython"
] | stackoverflow_0003268106_objectlistview_python_user_interface_wxpython.txt |
Q:
python dll swig help
First, I have never used SWIG, I dont know what it does...
We have a python library, that as far as I can tell uses SWIG, say when I want to use this library I have to put this in my python code:
import pylib
Now if I go open this vendor's pylib.py I see some classes, functions and this header:
# This file was automatically generated by SWIG (http://www.swig.org).
# Version 1.3.33
#
# Don't modify this file, modify the SWIG interface instead.
# This file is compatible with both classic and new-style classes.
import _pylib
import new
new_instancemethod = new.instancemethod
Next, in the same directory as pylib.py, there is a file called _pylib.pyd, that I think is a dll.
My problem is the following:
Many classes in pylib.py look like this:
class PersistentCache(_object):
__swig_setmethods__ = {}
__setattr__ = lambda self, name, value: _swig_setattr(self, PersistentCache, name, value)
__swig_getmethods__ = {}
__getattr__ = lambda self, name: _swig_getattr(self, PersistentCache, name)
__repr__ = _swig_repr
def __init__(self, *args):
this = _pylib.new_PersistentCache(*args)
try: self.this.append(this)
except: self.this = this
__swig_destroy__ = _pylib.delete_PersistentCache
__del__ = lambda self : None;
def setProperty(*args): return _pylib.PersistentCache_setProperty(*args)
def getProperty(*args): return _pylib.PersistentCache_getProperty(*args)
def clear(*args): return _pylib.PersistentCache_clear(*args)
def entries(*args): return _pylib.PersistentCache_entries(*args)
PersistentCache_swigregister = _pylib.PersistentCache_swigregister
PersistentCache_swigregister(PersistentCache)
Say I want to use this class or it's methods, with things like:
*args
as parameters, I cant know how many parameters I should pass nor what they should be, with what I have is it possible to find this out, so I can use the library?
A:
SWIG is a method of automatically wrapping up a C/C++ library so it can be accessed from Python. The library is actually a C library compiled as a DLL. The Python code is just pass-through code, all autogenerated by SWIG, and you're right that it's not very helpful.
If you want to know what arguments to pass, you should not look at the Python code, you should look at the C code it was generated from -- if you have it, or the documentation if not. If you don't have any code or documentation for that library, then I think you're going to have a very difficult time figuring it out... you should contact the vendor for documentation.
| python dll swig help | First, I have never used SWIG, I dont know what it does...
We have a python library, that as far as I can tell uses SWIG, say when I want to use this library I have to put this in my python code:
import pylib
Now if I go open this vendor's pylib.py I see some classes, functions and this header:
# This file was automatically generated by SWIG (http://www.swig.org).
# Version 1.3.33
#
# Don't modify this file, modify the SWIG interface instead.
# This file is compatible with both classic and new-style classes.
import _pylib
import new
new_instancemethod = new.instancemethod
Next, in the same directory as pylib.py, there is a file called _pylib.pyd, that I think is a dll.
My problem is the following:
Many classes in pylib.py look like this:
class PersistentCache(_object):
__swig_setmethods__ = {}
__setattr__ = lambda self, name, value: _swig_setattr(self, PersistentCache, name, value)
__swig_getmethods__ = {}
__getattr__ = lambda self, name: _swig_getattr(self, PersistentCache, name)
__repr__ = _swig_repr
def __init__(self, *args):
this = _pylib.new_PersistentCache(*args)
try: self.this.append(this)
except: self.this = this
__swig_destroy__ = _pylib.delete_PersistentCache
__del__ = lambda self : None;
def setProperty(*args): return _pylib.PersistentCache_setProperty(*args)
def getProperty(*args): return _pylib.PersistentCache_getProperty(*args)
def clear(*args): return _pylib.PersistentCache_clear(*args)
def entries(*args): return _pylib.PersistentCache_entries(*args)
PersistentCache_swigregister = _pylib.PersistentCache_swigregister
PersistentCache_swigregister(PersistentCache)
Say I want to use this class or it's methods, with things like:
*args
as parameters, I cant know how many parameters I should pass nor what they should be, with what I have is it possible to find this out, so I can use the library?
| [
"SWIG is a method of automatically wrapping up a C/C++ library so it can be accessed from Python. The library is actually a C library compiled as a DLL. The Python code is just pass-through code, all autogenerated by SWIG, and you're right that it's not very helpful.\nIf you want to know what arguments to pass, you... | [
2
] | [] | [] | [
"python"
] | stackoverflow_0003268371_python.txt |
Q:
python use __getitem__ for a method
is it possible to use getitem inside a method, ie
Class MyClass:
@property
def function(self):
def __getitem__():
...
So I can do
A = MyClass()
A.function[5]
A.function[-1]
A:
Everything is a first-class object in python, so the idea should work (the syntax is off), though I'd suggest making function its own class with properties in it, and then utilizing it in MyClass, unless you have a very good data-hiding reason to not do so...
I'd like to point out that I'm assuming you want to have function return a subscriptable thing, not have a subscriptable list of functions. That's a different implementation (also can be done, though.)
For example, a subscriptable thing (you could have made just a list, too):
# python
> class FooFunc(list):
> pass
> class Foo:
> foofunc = FooFunc()
> f = Foo()
> f.foofunc.append("bar")
> f.foofunc[0]
'bar'
A:
Nope, that will not work. Consider the underlying descriptor logic being called when you access an attribute that has been decorated as a @property. The get method needs to return a value that will be used as the computed property function. In this case, function doesn't return anything (implicit None value for the property). Your subscripting will then attempt to index None and boom.
You could return an object from function that supported the __getitem__ dunder method, though. That would syntactically "work" the same.
A:
If you try your code (after fixing the C in Class), you'll see it produces an error: "TypeError: 'NoneType' object is unsubscriptable".
I think your best bet is to create a class with a __getitem__, and set function to an instance of that class. Is there a reason it needs to be so complicated?
| python use __getitem__ for a method | is it possible to use getitem inside a method, ie
Class MyClass:
@property
def function(self):
def __getitem__():
...
So I can do
A = MyClass()
A.function[5]
A.function[-1]
| [
"Everything is a first-class object in python, so the idea should work (the syntax is off), though I'd suggest making function its own class with properties in it, and then utilizing it in MyClass, unless you have a very good data-hiding reason to not do so...\nI'd like to point out that I'm assuming you want to ha... | [
4,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0003268408_python.txt |
Q:
How to crop gtk pixbufs
I've got a gtk - pixbuf out of an svg and want to crop this to a specific size at specific coordinates.
Anyone has an easy possible solution for that ?
A:
solved it in a different way:
simply created a subpixbuf with the coodinates:
cropped_buffer=pixbuf.subpixbuf(x,y,width,height)
A:
svg has a viewbox attribute. You could use that one.
| How to crop gtk pixbufs | I've got a gtk - pixbuf out of an svg and want to crop this to a specific size at specific coordinates.
Anyone has an easy possible solution for that ?
| [
"solved it in a different way:\nsimply created a subpixbuf with the coodinates:\ncropped_buffer=pixbuf.subpixbuf(x,y,width,height)\n",
"svg has a viewbox attribute. You could use that one.\n"
] | [
4,
0
] | [] | [] | [
"gtk",
"python",
"svg"
] | stackoverflow_0003267981_gtk_python_svg.txt |
Q:
sets in python problem
can we remove a entry from the sets.
what are the commands to use for it?
like, my set conatins (6,5) , (6,7), (7,9)...I need to remove the second entry...what shud I do??
A:
my_set.remove((6, 7))
The remove() method can be used to remove items from a set.
A:
You can use remove():
>>> s = set([1, 2, 3])
>>> s.remove(2)
>>> s
set([1, 3])
A:
a -= set([(6, 7)])
:-)
A:
If you've got a list of those tuples you can clear it out like this:
l = [(1,2),(3,4),(5,6)]
[(1, 2), (3, 4), (5, 6)]
l.remove((3,4))
[(1, 2), (5, 6)]
| sets in python problem | can we remove a entry from the sets.
what are the commands to use for it?
like, my set conatins (6,5) , (6,7), (7,9)...I need to remove the second entry...what shud I do??
| [
"my_set.remove((6, 7))\n\nThe remove() method can be used to remove items from a set.\n",
"You can use remove():\n>>> s = set([1, 2, 3])\n>>> s.remove(2)\n>>> s\nset([1, 3])\n\n",
"a -= set([(6, 7)])\n:-)\n",
"If you've got a list of those tuples you can clear it out like this:\nl = [(1,2),(3,4),(5,6)]\n\n[(1... | [
3,
3,
2,
1
] | [] | [] | [
"python",
"set"
] | stackoverflow_0003268641_python_set.txt |
Q:
What's the best performing xml parsing for GAE (Python Version)?
I think we all know this page, but the benchmarks provided dated from more than two years ago. So, I would like to know if you could point out the best xml parser around. As I need just a xml parser, the more important thing to me is speed over everything else.
My objective is to process some xml feeds (about 25k) that are 4kb in size (this will be a daily task). As you probably know, I'm restricted by the 30 seconds request timeout. So, what's the best parser (Python only) that I can use?
Thanks for your anwsers.
Edit 01:
@Peter Recore
I'll. I'm writing some code now and plan to run some profiling in the near future. Regarding your question, the answer is no. Processing takes just a little time when compared with downloading the actual xml feed. But, I can't increase Google's Bandwidth, so I can only focus on this right now.
My only problem is that i need to do this as fastest as possible because my objective is to get a snapshot of a website status. And, as internet is live and people keep adding and changing it's data, i need the fastest method because any data insertion during the "downloading and processing" time span will actually mess with my statistical analisys.
I used to do it from my own computer and the process took 24 minutes back then, but now the website has 12 times more information.
A:
I know that this don't awnser my question directly, but id does what i just needed.
I remenbered that xml is not the only file type I could use, so instead of using a xml parser I choose to use json. About 2.5 times smaller in size. What means a decrease in download time. I used simplejson as my json libray.
I used from google.appengine.api import urlfetch to get the json feeds in parallel:
class GetEntityJSON(webapp.RequestHandler):
def post(self):
url = 'http://url.that.generates.the.feeds/'
if self.request.get('idList'):
idList = self.request.get('idList').split(',')
try:
asyncRequests = self._asyncFetch([url + id + '.json' for id in idList])
except urlfetch.DownloadError:
# Dealed with time out errors (#5) as these were very frequent
for result in asyncRequests:
if result.status_code == 200:
entityJSON = simplejson.loads(result.content)
# Filled a database entity with some json info. It goes like this:
# entity= Entity(
# name = entityJSON['name'],
# dateOfBirth = entityJSON['date_of_birth']
# ).put()
self.redirect('/')
def _asyncFetch(self, urlList):
rpcs = []
for url in urlList:
rpc = urlfetch.create_rpc(deadline = 10)
urlfetch.make_fetch_call(rpc, url)
rpcs.append(rpc)
return [rpc.get_result() for rpc in rpcs]
I tried getting 10 feeds at a time, but most of the times an individual feed raised the DownloadError #5 (Time out). Then, I increased the deadline to 10 seconds and started getting 5 feeds at a time.
But still, 25k feeds getting 5 at a time results in 5k calls. In a queue that can spawn 5 tasks a second, the total task time should be 17min in the end.
| What's the best performing xml parsing for GAE (Python Version)? | I think we all know this page, but the benchmarks provided dated from more than two years ago. So, I would like to know if you could point out the best xml parser around. As I need just a xml parser, the more important thing to me is speed over everything else.
My objective is to process some xml feeds (about 25k) that are 4kb in size (this will be a daily task). As you probably know, I'm restricted by the 30 seconds request timeout. So, what's the best parser (Python only) that I can use?
Thanks for your anwsers.
Edit 01:
@Peter Recore
I'll. I'm writing some code now and plan to run some profiling in the near future. Regarding your question, the answer is no. Processing takes just a little time when compared with downloading the actual xml feed. But, I can't increase Google's Bandwidth, so I can only focus on this right now.
My only problem is that i need to do this as fastest as possible because my objective is to get a snapshot of a website status. And, as internet is live and people keep adding and changing it's data, i need the fastest method because any data insertion during the "downloading and processing" time span will actually mess with my statistical analisys.
I used to do it from my own computer and the process took 24 minutes back then, but now the website has 12 times more information.
| [
"I know that this don't awnser my question directly, but id does what i just needed.\nI remenbered that xml is not the only file type I could use, so instead of using a xml parser I choose to use json. About 2.5 times smaller in size. What means a decrease in download time. I used simplejson as my json libray.\nI u... | [
1
] | [] | [] | [
"google_app_engine",
"parsing",
"python",
"xml"
] | stackoverflow_0003252070_google_app_engine_parsing_python_xml.txt |
Q:
Create a summary text file of a folder with filename and the first two lines out of each file
I have a directory with 260+ text files containing scoring information. I want to create a summary text file of all of these files containing filename and the first two lines of each file. My idea was to create two lists separately and 'zip' them. However, I can get the list of the filenames but I can't get the first two lines of the file into an a appended list. Here is my code so far:
# creating a list of filename
for f in os.listdir("../scores"):
(pdb, extension) = os.path.splitext(f)
name.append(pdb[1:5])
# creating a list of the first two lines of each file
for f in os.listdir("../scores"):
for line in open(f):
score.append(line)
b = f.nextline()
score.append(b)
I get an error the str had no attribute nextline. Please help, thanks in advance.
A:
The problem you're getting is a result of trying to take more than one line at a time from the scores file using a file iterator (for line in f). Here's a quick fix (one of several ways to do it, I'm sure):
# creating a list of the first two lines of each file
for f in os.listdir("../scores"):
with open(f) as fh:
score.append(fh.readline())
score.append(fh.readline())
The with statement takes care of closing the file for you after you're done, and it gives you a filehandle object (fh), which you can grab lines from manually.
A:
File objects have a next() method not nextline().
A:
Merging comment from David and answer from perimosocordiae:
from __future__ import with_statement
from itertools import islice
import os
NUM_LINES = 2
with open('../dir_summary.txt','w') as dir_summary:
for f in os.listdir('.'):
with open(f) as tf:
dir_summary.write('%s: %s\n' % (f, repr(', '.join(islice(tf,NUM_LINES)))))
A:
Here is my maybe more old fashioned version with redirected printing for easier newlines.
## written for Python 2.7, summarize filename and two first lines of files of given filetype
import os
extension = '.txt' ## replace with extension of desired files
os.chdir('.') ## '../scores') ## location of files
summary = open('summary.txt','w')
# creating a list of filenames with right extension
for fn in [fn for fn in os.listdir(os.curdir) if os.path.isfile(fn) and fn.endswith(extension)]:
with open(fn) as the_file:
print >>summary, '**'+fn+'**'
print >>summary, the_file.readline(), the_file.readline(),
print >>summary, '-'*60
summary.close()
## show resulta
print(open('summary.txt').read())
| Create a summary text file of a folder with filename and the first two lines out of each file | I have a directory with 260+ text files containing scoring information. I want to create a summary text file of all of these files containing filename and the first two lines of each file. My idea was to create two lists separately and 'zip' them. However, I can get the list of the filenames but I can't get the first two lines of the file into an a appended list. Here is my code so far:
# creating a list of filename
for f in os.listdir("../scores"):
(pdb, extension) = os.path.splitext(f)
name.append(pdb[1:5])
# creating a list of the first two lines of each file
for f in os.listdir("../scores"):
for line in open(f):
score.append(line)
b = f.nextline()
score.append(b)
I get an error the str had no attribute nextline. Please help, thanks in advance.
| [
"The problem you're getting is a result of trying to take more than one line at a time from the scores file using a file iterator (for line in f). Here's a quick fix (one of several ways to do it, I'm sure):\n# creating a list of the first two lines of each file\nfor f in os.listdir(\"../scores\"):\n with open(... | [
4,
1,
0,
0
] | [] | [] | [
"python",
"text_files"
] | stackoverflow_0003268246_python_text_files.txt |
Q:
making python programs "chat" via pipe
I'm trying to make two processes communicate using a pipe.
I did this in the parent process:
process = subprocess.Popen(test, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
process.stdin.write("4\n");
output = process.stdout.read()
print output
and in the child process:
inp = raw_input()
integer = int(inp)
print integer**2
while(True):
pass
I would expect the parent process to print 16... Unfortunately, it remains hanging without printing anything. Replacing the infinite loop by a sleep for 5 seconds makes the parent process be idle for 5 seconds and AFTER that print 16.
This shows that the parent process only gets the output from the child after it terminated execution.
I'd like to know if it's possible to get input before programs finishes.
My idea is to go passing information via this pipe, getting input, processing it, and outputting the result in the pipe, so that the other can continue with processing.
Any help?
Thanks,
Manuel
A:
I see a number of possible issues:
a) The child process never actually flushes its output and thus never actually sends its output to the parent.
b) The parent process runs its read() call before the child process has actually sent its output (flushed its output).
c) The parent process does a blocking read() which until EOF which effectively means it waits for the child to exit. The subprocess.Popen docs should mention whether this can be the case.
d) The parent process's read() call waits for a certain number of bytes (e.g. 1024) to arrive before it returns.
Probably having the parent do lots of read(1) calls and reassembling the bytes as they come in will fix the issue. Or using a higher level communication API, e.g. using datagrams instead of parsing byte streams.
A:
As suggested by ndim, do the folowing in the parent:
process.stdin.write("4\n")
process.stdin.flush()
output = process.stdout.readline()
print output
You will also need to change the child:
inp = sys.stdin.readline()
integer = int(inp)
sys.stdout.write("%d\n", (integer ** 2,))
sys.stdout.flush()
I used sys.stdin.readline and sys.stdout.write as a matter of style.
I wrote 2 test programs and they worked fine with python-2.6.4-27 on Fedora 13.
A:
You have to use select for this. Like in the communicate method of the subprocess.
There's a discussion about this in the python issue tracker.
A:
THE DEAL: http://code.activestate.com/recipes/440554/
| making python programs "chat" via pipe | I'm trying to make two processes communicate using a pipe.
I did this in the parent process:
process = subprocess.Popen(test, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
process.stdin.write("4\n");
output = process.stdout.read()
print output
and in the child process:
inp = raw_input()
integer = int(inp)
print integer**2
while(True):
pass
I would expect the parent process to print 16... Unfortunately, it remains hanging without printing anything. Replacing the infinite loop by a sleep for 5 seconds makes the parent process be idle for 5 seconds and AFTER that print 16.
This shows that the parent process only gets the output from the child after it terminated execution.
I'd like to know if it's possible to get input before programs finishes.
My idea is to go passing information via this pipe, getting input, processing it, and outputting the result in the pipe, so that the other can continue with processing.
Any help?
Thanks,
Manuel
| [
"I see a number of possible issues:\na) The child process never actually flushes its output and thus never actually sends its output to the parent.\nb) The parent process runs its read() call before the child process has actually sent its output (flushed its output).\nc) The parent process does a blocking read() wh... | [
4,
2,
0,
0
] | [] | [] | [
"multiprocessing",
"pipe",
"python",
"stdin",
"stdout"
] | stackoverflow_0003268410_multiprocessing_pipe_python_stdin_stdout.txt |
Q:
error: list objects are unhashable
closed = set() -here closed is a set
node is (5,5)
The error occurse at execution time.
Error is:
list objects are unhashable
the program is:
closed.add(node)
for val in closed:
print val
Node is the output of stack.
node = stack.pop() - it gives me...(5,5)
Traceback:
File "/home/", line 99, in depthFirstSearch
closed.add(node)
TypeError: list objects are unhashable
A:
Show the actual code that you executed, plus the full traceback. Use copy/paste, don't type from memory. You should always do this. Even better reason in this case is that that error can happen only if node is a list, not a tuple as you have said.
A:
I do not have a problem running the code if node is a tuple, as you indicate. When I make node a list, e.g., node = [5,5], then I receive the error.
I believe the reason is because a list is mutable, so it is not suitable for checking for uniqueness:
>>> a = [5,5]
>>> id(a)
140505526957552
>>> a.append(6)
>>> id(a)
140505526957552
Since a has the same id despite the change, it cannot be used in a set.
A:
Assuming node is a list, and given that tuples are hashable.
closed.add(tuple(node))
A:
No problem with that - are you sure it is this portion of code? Can you post the traceback?
>>> closed = set()
>>> node = (5,5)
>>> closed.add(node)
>>> closed
set([(5, 5)])
>>> for val in closed:
... print val
...
(5, 5)
A:
All your node object have to be hashable, see
http://docs.python.org/glossary.html#term-hashable
A:
Are you sure you didn't typed node = [5, 5] instead of node = (5,5) ? Looks like you node is really a list and it rightly refuse to add a list to a set (as it is unhashable).
Again: with some fonts parenthesis and square brackets are very similar. Or stacks contains other data and you didn't showed the right node. But you can get the answer by yourself. Just do:
print type(node)
If it is a list you are here. If it is a tuple, something really weird occurred.
A:
You can't hash a list because hashes must be immutable. The implementation of set requires this for efficiency. Since the elements of a list can be updated at any time, so would any hash value derived from the contents.
I think there's a mistake in your example, as it shows a tuple rather than a list.
| error: list objects are unhashable | closed = set() -here closed is a set
node is (5,5)
The error occurse at execution time.
Error is:
list objects are unhashable
the program is:
closed.add(node)
for val in closed:
print val
Node is the output of stack.
node = stack.pop() - it gives me...(5,5)
Traceback:
File "/home/", line 99, in depthFirstSearch
closed.add(node)
TypeError: list objects are unhashable
| [
"Show the actual code that you executed, plus the full traceback. Use copy/paste, don't type from memory. You should always do this. Even better reason in this case is that that error can happen only if node is a list, not a tuple as you have said.\n",
"I do not have a problem running the code if node is a tuple,... | [
2,
1,
0,
0,
0,
0,
0
] | [] | [] | [
"python",
"set"
] | stackoverflow_0003268966_python_set.txt |
Q:
Error building 'lxml.etree' extension
I'm trying to install lxml, on an Ubuntu server running Python 2.6 (in a virtualenv - the system Python is 2.5).
I've checked out via svn and as a result I've also install Cython, as per the instructions.
However, I get the following error when running python setup.py build:
Building lxml version 2.3.alpha1-76211.
Building with Cython 0.11.
Using build configuration of libxslt 1.1.22
Building against libxml2/libxslt in the following directory: /usr/lib
running build
running build_py
running build_ext
cythoning src/lxml/lxml.etree.pyx to src/lxml/lxml.etree.c
Error converting Pyrex file to C:
------------------------------------------------------------
...
c_child = _findChildForwards(c_node, 0)
while c_child is not NULL:
if c_child.type == tree.XML_ELEMENT_NODE:
for i in range(c_tag_count):
if _tagMatchesExactly(c_child, c_ns_tags[2*i], c_ns_tags[2*i+1]):
c_next = _findChildForwards(c_child, 0) or _nextElement(c_child)
^
------------------------------------------------------------
/home/admin/web/blink/lxml/src/lxml/cleanup.pxi:246:64: Cannot assign type 'int' to 'xmlNode *'
Error converting Pyrex file to C:
building 'lxml.etree' extension
gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC -I/usr/include/libxml2 -I/home/admin/python/2.6.5/include/python2.6 -c src/lxml/lxml.etree.c -o build/temp.linux-x86_64-2.6/src/lxml/lxml.etree.o -w
src/lxml/lxml.etree.c:1:2: error: #error Do not use this file, it is the result of a failed Cython compilation.
error: command 'gcc' failed with exit status 1
And very similar errors if i try python setup.py bdist_egg, python setup.py build_ext -i or make
Trying to install via easy_install or pip produces the same error - although the former just hangs indefinitely.
As far as I am aware, all of the various dependencies, such as python-dev are installed.
What am I missing / doing wrong?
A:
"I've checked out via svn" ...
"Building lxml version 2.3.alpha1-76211" ...
You appear to be on the bleeding edge. Suggestions: Use a released version of the lxml source. Consult with the lxml author/maintainer.
| Error building 'lxml.etree' extension | I'm trying to install lxml, on an Ubuntu server running Python 2.6 (in a virtualenv - the system Python is 2.5).
I've checked out via svn and as a result I've also install Cython, as per the instructions.
However, I get the following error when running python setup.py build:
Building lxml version 2.3.alpha1-76211.
Building with Cython 0.11.
Using build configuration of libxslt 1.1.22
Building against libxml2/libxslt in the following directory: /usr/lib
running build
running build_py
running build_ext
cythoning src/lxml/lxml.etree.pyx to src/lxml/lxml.etree.c
Error converting Pyrex file to C:
------------------------------------------------------------
...
c_child = _findChildForwards(c_node, 0)
while c_child is not NULL:
if c_child.type == tree.XML_ELEMENT_NODE:
for i in range(c_tag_count):
if _tagMatchesExactly(c_child, c_ns_tags[2*i], c_ns_tags[2*i+1]):
c_next = _findChildForwards(c_child, 0) or _nextElement(c_child)
^
------------------------------------------------------------
/home/admin/web/blink/lxml/src/lxml/cleanup.pxi:246:64: Cannot assign type 'int' to 'xmlNode *'
Error converting Pyrex file to C:
building 'lxml.etree' extension
gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC -I/usr/include/libxml2 -I/home/admin/python/2.6.5/include/python2.6 -c src/lxml/lxml.etree.c -o build/temp.linux-x86_64-2.6/src/lxml/lxml.etree.o -w
src/lxml/lxml.etree.c:1:2: error: #error Do not use this file, it is the result of a failed Cython compilation.
error: command 'gcc' failed with exit status 1
And very similar errors if i try python setup.py bdist_egg, python setup.py build_ext -i or make
Trying to install via easy_install or pip produces the same error - although the former just hangs indefinitely.
As far as I am aware, all of the various dependencies, such as python-dev are installed.
What am I missing / doing wrong?
| [
"\"I've checked out via svn\" ...\n\"Building lxml version 2.3.alpha1-76211\" ...\nYou appear to be on the bleeding edge. Suggestions: Use a released version of the lxml source. Consult with the lxml author/maintainer.\n"
] | [
1
] | [] | [] | [
"lxml",
"python",
"ubuntu"
] | stackoverflow_0003266111_lxml_python_ubuntu.txt |
Q:
Why does Twisted think I'm calling request.finish() twice when I am not?
This is an annoying problem I am having with Twisted.web. Basically, I have a class that inherits from twisted.web.resource.Resource and adds some default stuff to Mako templates:
from twisted.web.resource import Resource
from mako.lookup import TemplateLookup
from project.session import SessionData
from project.security import make_nonce
class Page(Resource):
template = ""
def display(self, request, **kwargs):
session = SessionData(request.getSession())
if self.template:
templates = TemplateLookup(directories=['templates'])
template = templates.get_template(self.template)
return template.render(user=session.user,
info=session.info,
current_path=request.path,
nonce=make_nonce(session),
**kwargs)
else:
return ""
Then, and I have narrowed the problem down to this small class (which I tested), I write a resource which inherits from Page:
class Test(pages.Page):
def render_GET(self, request):
return "<form method='post'><input type='submit'></form>"
def render_POST(self, request):
request.redirect("/test")
request.finish()
I'd like to note that, in every other case, if request.finish() isn't the last line in a function, then I return immediately after it.
Anyways, I add this class to the site at /test and when I navigate there, I get a submit button. I click the submit button, and in the console I get:
C:\Python26\lib\site-packages\twisted\web\server.py:200: UserWarning: Warning! request.finish called twice.
self.finish()
But, I get this ONLY the first time I submit the page. Every other time, it's fine. I would just ignore this, but it's been nagging at me, and I can't for the life of me figure out why it's doing this at all, and why only the first time the page is submitted. I can't seem to find anything online, and even dropping print statements and tracebacks in the request.finish() code didn't reveal anything.
edit
This morning I tried adding a second request.finish() line to the resource, and it still only gave me the error one time. I suppose it will only warn about it in a resource once -- maybe per run of the program, or per session, I'm not sure. In any case, I changed it to:
class Test(pages.Page):
def render_GET(self, request):
return "<form method='post'><input type='submit'></form>"
def render_POST(self, request):
request.redirect("/test")
request.finish()
request.finish()
and just got two messages, one time. I still have no idea why I can't redirect the request without it saying I finished it twice (because I can't redirect without request.finish()).
A:
Short Answer
It has to be:
request.redirect("/test")
request.finish()
return twisted.web.server.NOT_DONE_YET
Long Answer
I decided to go sifting through some Twisted source code. I first added a traceback to the area that prints the error if request.finish() is called twice:
def finish(self):
import traceback #here
"""
Indicate that all response data has been written to this L{Request}.
"""
if self._disconnected:
raise RuntimeError(
"Request.finish called on a request after its connection was lost; "
"use Request.notifyFinish to keep track of this.")
if self.finished:
warnings.warn("Warning! request.finish called twice.", stacklevel=2)
traceback.print_stack() #here
return
#....
...
File "C:\Python26\lib\site-packages\twisted\web\server.py", line 200, in render
self.finish()
File "C:\Python26\lib\site-packages\twisted\web\http.py", line 904, in finish
traceback.print_stack()
I went in and checked out render in twisted.web.server and found this:
if body == NOT_DONE_YET:
return
if type(body) is not types.StringType:
body = resource.ErrorPage(
http.INTERNAL_SERVER_ERROR,
"Request did not return a string",
"Request: " + html.PRE(reflect.safe_repr(self)) + "<br />" +
"Resource: " + html.PRE(reflect.safe_repr(resrc)) + "<br />" +
"Value: " + html.PRE(reflect.safe_repr(body))).render(self)
if self.method == "HEAD":
if len(body) > 0:
# This is a Bad Thing (RFC 2616, 9.4)
log.msg("Warning: HEAD request %s for resource %s is"
" returning a message body."
" I think I'll eat it."
% (self, resrc))
self.setHeader('content-length', str(len(body)))
self.write('')
else:
self.setHeader('content-length', str(len(body)))
self.write(body)
self.finish()
body is the result of rendering a resource, so once body is populated, in the example case given in my question, finish has already been called on this request object (since self is passed from this method to the resource's render method).
From looking at this code it becomes apparent that by returning NOT_DONE_YET I would avoid the warning.
I could have also changed the last line of that method to:
if not self.finished:
self.finish()
but, in the interest of not modifying the library, the short answer is:
after calling request.redirect() you must call request.finish() and then return twisted.web.server.NOT_DONE_YET
More
I found some documentation about this. It isn't related to redirecting a request, but instead rendering a resource, using request.write(). It says to call request.finish() and then return NOT_DONE_YET. From looking at the code in render() I can see why that is the case.
| Why does Twisted think I'm calling request.finish() twice when I am not? | This is an annoying problem I am having with Twisted.web. Basically, I have a class that inherits from twisted.web.resource.Resource and adds some default stuff to Mako templates:
from twisted.web.resource import Resource
from mako.lookup import TemplateLookup
from project.session import SessionData
from project.security import make_nonce
class Page(Resource):
template = ""
def display(self, request, **kwargs):
session = SessionData(request.getSession())
if self.template:
templates = TemplateLookup(directories=['templates'])
template = templates.get_template(self.template)
return template.render(user=session.user,
info=session.info,
current_path=request.path,
nonce=make_nonce(session),
**kwargs)
else:
return ""
Then, and I have narrowed the problem down to this small class (which I tested), I write a resource which inherits from Page:
class Test(pages.Page):
def render_GET(self, request):
return "<form method='post'><input type='submit'></form>"
def render_POST(self, request):
request.redirect("/test")
request.finish()
I'd like to note that, in every other case, if request.finish() isn't the last line in a function, then I return immediately after it.
Anyways, I add this class to the site at /test and when I navigate there, I get a submit button. I click the submit button, and in the console I get:
C:\Python26\lib\site-packages\twisted\web\server.py:200: UserWarning: Warning! request.finish called twice.
self.finish()
But, I get this ONLY the first time I submit the page. Every other time, it's fine. I would just ignore this, but it's been nagging at me, and I can't for the life of me figure out why it's doing this at all, and why only the first time the page is submitted. I can't seem to find anything online, and even dropping print statements and tracebacks in the request.finish() code didn't reveal anything.
edit
This morning I tried adding a second request.finish() line to the resource, and it still only gave me the error one time. I suppose it will only warn about it in a resource once -- maybe per run of the program, or per session, I'm not sure. In any case, I changed it to:
class Test(pages.Page):
def render_GET(self, request):
return "<form method='post'><input type='submit'></form>"
def render_POST(self, request):
request.redirect("/test")
request.finish()
request.finish()
and just got two messages, one time. I still have no idea why I can't redirect the request without it saying I finished it twice (because I can't redirect without request.finish()).
| [
"Short Answer\n\nIt has to be:\nrequest.redirect(\"/test\")\nrequest.finish()\nreturn twisted.web.server.NOT_DONE_YET\n\nLong Answer\n\nI decided to go sifting through some Twisted source code. I first added a traceback to the area that prints the error if request.finish() is called twice:\ndef finish(self):\n i... | [
11
] | [] | [] | [
"python",
"twisted.web"
] | stackoverflow_0003254965_python_twisted.web.txt |
Q:
How to match string with database fields in Django?
I have a database with a name column having data like
'Very big News'
'News'
'something else'
'New Nes'
'Fresh News'
'Something else'
Now given a string of words, how can I find if any of the words in the given string is contained in the name field?
For example:
I have a string 'super very news'. I need to look in my database to see if I have any record such that the name field contains either 'super' or 'very' or 'news' or 'super very' or 'very news'.
A:
Update based on comments. See the query set docs here.
your_search_query = 'super very news'
qset = Q()
for term in your_search_query.split():
qset |= Q(name__contains=term)
matching_results = YourModel.objects.filter(qset)
This creates the equivalent of:
matching_result = YourModel.objects.filter(Q(name__contains='super') |
Q(name__contains='very') |
Q(name__contains='news'))
which produces (roughly) the following SQL in a single query:
select * from your_model where name like '%super%' or name like '%very%' or name like '%news%'
A:
If your word list is small and simple you can write your own lookup table and indexer, otherwise you want a full text database like OpenFTS:
http://openfts.sourceforge.net/
| How to match string with database fields in Django? | I have a database with a name column having data like
'Very big News'
'News'
'something else'
'New Nes'
'Fresh News'
'Something else'
Now given a string of words, how can I find if any of the words in the given string is contained in the name field?
For example:
I have a string 'super very news'. I need to look in my database to see if I have any record such that the name field contains either 'super' or 'very' or 'news' or 'super very' or 'very news'.
| [
"Update based on comments. See the query set docs here.\nyour_search_query = 'super very news'\n\nqset = Q()\nfor term in your_search_query.split():\n qset |= Q(name__contains=term)\n\nmatching_results = YourModel.objects.filter(qset)\n\nThis creates the equivalent of:\nmatching_result = YourModel.objects.filter... | [
7,
0
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0003259899_django_django_models_python.txt |
Q:
Django extend admin "index" view
I know how to change or extend a model's views in the Django admin ( http://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.add_view ) but I want to extend the admin index (dashboard) view.
Specifically, I want to keep it the same, but add some information to some of my models that will let me sort them into column 'A' or column 'B' depending on if the models are subclasses of model 'A' or model 'B'.
I've been able to change the index template no problem, but getting the models to sort into two columns as described seems like something I need to do in the view. I also don't want to have to rewrite the entire view, only extend it.
Thanks!
A:
Why do you want to change the templates? You can use ModelAdmin.list_display for printig these columns.
Edit: And for ordering you can use ModelAdmin.ordering.
| Django extend admin "index" view | I know how to change or extend a model's views in the Django admin ( http://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.add_view ) but I want to extend the admin index (dashboard) view.
Specifically, I want to keep it the same, but add some information to some of my models that will let me sort them into column 'A' or column 'B' depending on if the models are subclasses of model 'A' or model 'B'.
I've been able to change the index template no problem, but getting the models to sort into two columns as described seems like something I need to do in the view. I also don't want to have to rewrite the entire view, only extend it.
Thanks!
| [
"Why do you want to change the templates? You can use ModelAdmin.list_display for printig these columns.\nEdit: And for ordering you can use ModelAdmin.ordering.\n"
] | [
0
] | [] | [] | [
"admin",
"django",
"extend",
"python",
"view"
] | stackoverflow_0003268999_admin_django_extend_python_view.txt |
Q:
Django Images Display
Ok, now I know how to display images on ONE /myurl/ in Django as a list (YEAH!)
But how can I display ONE Image per url with a button to click to the next image etc.
So basically I would want to come to the first /urlstart/:
text and a next button.
brings user to e.g. /urlstart/1
There the first image of a List is displayed and below that a button.
That brings user to /urlstart/2
Here the next image of a list is displayed.
etc.
How does the url.py regex part have to look like so this is possible?
How does the view has to be tweaked to get 1 List of Images but multiple urls?
And finally if anybody has implemented this with a down loadable and installable module/library, like e.g. photologue (which unfortunately did not work for me) or any better idea than that I would be really happy to get some insights on how to make this fast and efficient.
Thanks so much to everybody who takes the time to answer!
A:
URL regex could look something like this:
url(r'^urlstart/(?P<image_id>\d*)/?$', 'urlstart', name='urlstart')
View code could look something like this:
def urlstart(request, image_id=0):
if image_id == 0:
image = None
else:
image = get_object_or_404(Image, image_id)
next_image = image_id + 1
return render_to_response('template.html', locals(), context_instance=RequestContext(request)
Template code:
{% if image %}
<img src={{ image.url }}>
<a href="/urlstart/{{ next_image }}">Next</a>
{% else %}
Put your text here. See first image by clicking <a href="/urlstart/1">here</a>
{% endif %}
Obviously this is simplified. For example, you may want to check to see if there is an image to come next.
Hope this helps.
A:
Take a look at Pagination which will provide you with Next/Previous links, etc.
Also, it would probably be a good idea to use permalinks and pass the next/previous image in from the view instead of hard-coding the URL into the template.
| Django Images Display | Ok, now I know how to display images on ONE /myurl/ in Django as a list (YEAH!)
But how can I display ONE Image per url with a button to click to the next image etc.
So basically I would want to come to the first /urlstart/:
text and a next button.
brings user to e.g. /urlstart/1
There the first image of a List is displayed and below that a button.
That brings user to /urlstart/2
Here the next image of a list is displayed.
etc.
How does the url.py regex part have to look like so this is possible?
How does the view has to be tweaked to get 1 List of Images but multiple urls?
And finally if anybody has implemented this with a down loadable and installable module/library, like e.g. photologue (which unfortunately did not work for me) or any better idea than that I would be really happy to get some insights on how to make this fast and efficient.
Thanks so much to everybody who takes the time to answer!
| [
"URL regex could look something like this:\nurl(r'^urlstart/(?P<image_id>\\d*)/?$', 'urlstart', name='urlstart')\n\nView code could look something like this:\ndef urlstart(request, image_id=0):\n if image_id == 0:\n image = None\n else:\n image = get_object_or_404(Image, image_id)\n next_image = image_id +... | [
2,
0
] | [] | [] | [
"django",
"python",
"url"
] | stackoverflow_0003266048_django_python_url.txt |
Q:
Using if/elif/else and resp=raw_input - how to respond to part of a user's input?
print "Please Type Something"
resp = raw_input()
if resp *contains* "cuttlefish"
print "Response One"
elif resp *contains* "nautilus"
print "Response Two"
else:
print "Response Three"
What I need to know is the correct syntax to use instead of the filler contains. So, for example, if the user types "two cuttlefish" then the program should respond by printing "Response One"
I did try look for this information in a few tutorials, so if you know of a good one that addresses this I wouldn't mind a pointer in that direction, either :/
A:
Python is quite an easy language, just think english and you might get it correct ;)
if 'cuttlefish' in resp:
A:
in is the operator you are looking for:
if "cuttlefish" in resp:
print "Response One"
elif "nautilus" in resp:
print "Response Two"
else:
print "Response Three"
in is basically an operator that works on sequences like str, tuple, list. x in y checks if x is part of the sequence y. See also 5.6. Sequence Types in the Python Standard Library documentation.
edit
Regarding your second question “Now, how do I change it so that "cuttlefish" is an entry on cuttlefishList, along with several other entries that should also trigger print "Response One"?”.
That's actually a big more complicated, as you cannot check if any of multiple elements are within a sequence with in. But of course there are possibilities to do this. The simples ist to simply chain all the checks together:
if "cuttlefish" in resp or "someotherfish" in resp or "yetanotherfish" in resp:
print "Response One"
If you have too many different words that would result in that response, then you can also automate that a bit like this:
if any( x in resp for x in ( "cuttlefish", "someotherfish", "yetanotherfish" ) ):
print "Response One"
That is basically a short way of writing (not literally of course, but the idea is the same):
checkList = []
for x in ( "cuttlefish", "someotherfish", "yetanotherfish" ):
checkList.append( x in resp )
if True in checkList:
print "Response One"
So what it does is that it goes through all elements of your tuple and checks for each element x if it is part of the response. It keeps a check list of the results of these checks (in the short form, a generator does this). At the end, you check if True is part of the sequence checkList. If it does, at least one of the fishes were found in the response and you can print the result.
A different way would be to use regular expressions. It might be overkill to use them for a low number of different choices, but on the other hand, you could do great fancy stuff with it.
A:
if "cuttlefish" in resp:
# found
or
if resp.find("cuttlefish") > 0:
# found
http://docs.python.org/library/stdtypes.html#str.find
A:
You can use the following syntax:
if 'string' in word:
#Code
this checks if it is in word, regardless of it is a list or another string. So it would match True if word was 'foostringbar' or ['foo', 'string', 'bar']
Also, instead of printing to tell the user to enter something, try this:
resp = raw_input("Please Type Something\n")
This will produce the same thing, but is much more pythonic.
| Using if/elif/else and resp=raw_input - how to respond to part of a user's input? | print "Please Type Something"
resp = raw_input()
if resp *contains* "cuttlefish"
print "Response One"
elif resp *contains* "nautilus"
print "Response Two"
else:
print "Response Three"
What I need to know is the correct syntax to use instead of the filler contains. So, for example, if the user types "two cuttlefish" then the program should respond by printing "Response One"
I did try look for this information in a few tutorials, so if you know of a good one that addresses this I wouldn't mind a pointer in that direction, either :/
| [
"Python is quite an easy language, just think english and you might get it correct ;)\nif 'cuttlefish' in resp:\n\n",
"in is the operator you are looking for:\nif \"cuttlefish\" in resp:\n print \"Response One\"\nelif \"nautilus\" in resp:\n print \"Response Two\"\nelse:\n print \"Response Three\"\n\nin ... | [
5,
3,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0003269376_python.txt |
Q:
"list index out of range"
Below I have the following code that is supposed to get the CPU temperature.
import wmi
w = wmi.WMI()
print w.Win32_TemperatureProbe()[0].CurrentReading
When I run it I get the following warning however:
Traceback (most recent call last):
File "<string>", line 244, in run_nodebug
File "<module1>", line 3, in <module>
IndexError: list index out of range
This is in windows 7 , btw.
A:
This just means that TemperatureProbe isn't implemented on your machine (probably your hardware vendor).
Your other option is to connect to the root\WMI namespace and query "select * from MSAcpi_ThermalZoneTemperature" which will return the probes and you can query for current temperature in tenths of kelvins. There should be a similar API in python's WMI.
UPDATE: here's some code that works:
In [18]: import wmi
In [19]: w = wmi.WMI(namespace='root\\wmi')
In [20]: ti = w.MSAcpi_ThermalZoneTemperature()[0] # first probe
In [21]: ti.CurrentTemperature
Out[21]: 3242
| "list index out of range" | Below I have the following code that is supposed to get the CPU temperature.
import wmi
w = wmi.WMI()
print w.Win32_TemperatureProbe()[0].CurrentReading
When I run it I get the following warning however:
Traceback (most recent call last):
File "<string>", line 244, in run_nodebug
File "<module1>", line 3, in <module>
IndexError: list index out of range
This is in windows 7 , btw.
| [
"This just means that TemperatureProbe isn't implemented on your machine (probably your hardware vendor). \nYour other option is to connect to the root\\WMI namespace and query \"select * from MSAcpi_ThermalZoneTemperature\" which will return the probes and you can query for current temperature in tenths of kelvin... | [
1
] | [] | [] | [
"cpu",
"python",
"windows",
"wmi"
] | stackoverflow_0003269484_cpu_python_windows_wmi.txt |
Q:
Manipulating strings in python - concentrating on part of a user's input
resp = raw_input("What is your favorite fruit?\n")
if "I like" in resp:
print "%s" - "I like" + " is a delicious fruit." % resp
else:
print "Bubbles and beans."
OK I know this code doesn't work, and I know why. You can't subtract strings from each other like numbers.
But is there a way to break apart a string and only use part of the response?
And by "is there a way" I really mean "how," because anything is possible in programming. :D
I'm trying to write my first chatterbot from scratch.
A:
One option would be to simply replace the part that you want to remove with an empty string:
resp = raw_input("What is your favorite fruit?\n")
if "I like" in resp:
print "%s is a delicious fruit." % (resp.replace("I like ", ""))
else:
print "Bubbles and beans."
If you want to look into more advanced pattern matching to grab out more specific parts of strings via flexible patterns, you might want to look into regular expressions.
A:
# python
"I like turtles".replace("I like ","")
'turtles'
A:
Here's a way to do it with regular expressions:
In [1]: import re
In [2]: pat = r'(I like )*(\w+)( is a delicious fruit)*'
In [3]: print re.match(pat, 'I like apples').groups()[1]
apples
In [4]: print re.match(pat, 'apple is a delicious fruit').groups()[1]
apple
| Manipulating strings in python - concentrating on part of a user's input | resp = raw_input("What is your favorite fruit?\n")
if "I like" in resp:
print "%s" - "I like" + " is a delicious fruit." % resp
else:
print "Bubbles and beans."
OK I know this code doesn't work, and I know why. You can't subtract strings from each other like numbers.
But is there a way to break apart a string and only use part of the response?
And by "is there a way" I really mean "how," because anything is possible in programming. :D
I'm trying to write my first chatterbot from scratch.
| [
"One option would be to simply replace the part that you want to remove with an empty string:\nresp = raw_input(\"What is your favorite fruit?\\n\")\nif \"I like\" in resp:\n print \"%s is a delicious fruit.\" % (resp.replace(\"I like \", \"\"))\nelse:\n print \"Bubbles and beans.\"\n\nIf you want to look in... | [
5,
0,
0
] | [
"Can you just strip \"I like\"? \nresp.strip(\"I like\")\n\nbe careful of case sensitivity though. \n"
] | [
-1
] | [
"python"
] | stackoverflow_0003269721_python.txt |
Q:
Python circular references
trying to have two class that reference each others, in the same file. What would be the best way to have this working:
class Foo(object):
other = Bar
class Bar(object):
other = Foo
if __name__ == '__main__':
print 'all ok'
?
The problem seems to be that since the property is on the class, since it tries to executes as soon as the class itself is parsed.
Is there a way to solve that?
edit:
those keys are used for SQLAlchemy mapping, to they realy are class variables (not instance).
A:
This would do what you want:
class Foo(object):
pass
class Bar(object):
pass
Foo.other = Bar
Bar.other = Foo
I would prefer to avoid such design completely, though.
A:
Assuming that you really want Foo.other and Bar.other to be class properties, rather than instance properties, then this works (I tested, just to be sure) :
class Foo(object):
pass
class Bar(object):
pass
Foo.other = Bar
Bar.other = Foo
If it's instance properties that you're after, then aaronasterling's answer is more appropriate.
| Python circular references | trying to have two class that reference each others, in the same file. What would be the best way to have this working:
class Foo(object):
other = Bar
class Bar(object):
other = Foo
if __name__ == '__main__':
print 'all ok'
?
The problem seems to be that since the property is on the class, since it tries to executes as soon as the class itself is parsed.
Is there a way to solve that?
edit:
those keys are used for SQLAlchemy mapping, to they realy are class variables (not instance).
| [
"This would do what you want:\nclass Foo(object):\n pass\n\nclass Bar(object):\n pass\n\nFoo.other = Bar\nBar.other = Foo\n\nI would prefer to avoid such design completely, though.\n",
"Assuming that you really want Foo.other and Bar.other to be class properties, rather than instance properties, then this w... | [
10,
1
] | [] | [] | [
"circular_dependency",
"python",
"sqlalchemy"
] | stackoverflow_0003270045_circular_dependency_python_sqlalchemy.txt |
Q:
How to select users based on their profile
I have a complicated query built up based on a users profile, I start with
qset = Profile.objects
bunch of stuff that works to return me profile objects (it uses Q objects, and optionally ignores some fields if they were left blank)
I could grab the users with selected_related() but that still leaves me with a list of profiles, rather than a list of users.
Because of the way my templates are set up for other things, I'd really like to have a list of users
{% for user in users %}
How can I convert his queryset for Profile objects into one for Users.
Currently I use:
profile_userids = list(qset.values('user_id'))
user_ids = [d['user_id'] for d in profile_userids]
users = User.objects.in_bulk(user_ids)
which results in 2 queries, and the conversion of all the user_id's into python objects.
How can I use the queryset that I have generated on the Profiles object to select users?
A:
Make your Q objects refer to profile__whatever and use them in User.objects.filter().
A:
Turns out I had to mod the templates. There is a bug in Django auth.user. When the view code looks like:
@login_required
def test(request):
a = User.objects.filter(pk=request.user.id).select_related('profile').get()
return render_to_response('test.html', {'a':a,})
and the template looks like
a.username {{ a.username }}<br />
a.get_profile.age {{ a.get_profile.age }}<br />
a.get_profile ignores the fact that the profile was loaded with select_related, and does a separate query for the profile.
However, if you code it like:
@login_required
def test(request):
a = Profile.objects.filter(user=request.user).select_related('user').get()
return render_to_response('peeks/test.html', {'a':a,})
and the template like:
a.user.username {{ a.user.username }}<br />
a.age {{ a.age }}<br />
then you get it all with one select, and when you are displaying 25 profiles on one page, that makes a fair amount of difference.
| How to select users based on their profile | I have a complicated query built up based on a users profile, I start with
qset = Profile.objects
bunch of stuff that works to return me profile objects (it uses Q objects, and optionally ignores some fields if they were left blank)
I could grab the users with selected_related() but that still leaves me with a list of profiles, rather than a list of users.
Because of the way my templates are set up for other things, I'd really like to have a list of users
{% for user in users %}
How can I convert his queryset for Profile objects into one for Users.
Currently I use:
profile_userids = list(qset.values('user_id'))
user_ids = [d['user_id'] for d in profile_userids]
users = User.objects.in_bulk(user_ids)
which results in 2 queries, and the conversion of all the user_id's into python objects.
How can I use the queryset that I have generated on the Profiles object to select users?
| [
"Make your Q objects refer to profile__whatever and use them in User.objects.filter().\n",
"Turns out I had to mod the templates. There is a bug in Django auth.user. When the view code looks like:\n@login_required\ndef test(request):\n a = User.objects.filter(pk=request.user.id).select_related('profile').get... | [
2,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0003172854_django_python.txt |
Q:
function in python
In a function, I need to perform some logic that requires me to call a function inside a function. What I did with this, like:
def dfs(problem):
stack.push(bache)
search(root)
while stack.isEmpty() != 0:
def search(vertex):
closed.add(vertex)
for index in sars:
stack.push(index)
return stack
In the function, dfs, I am using search(root), is this is the correct way to do it?
I am getting an error: local variable 'search' referenced before assignment
A:
There are many mysterious bug-looking aspects in your code. The wrong order of definition (assuming you do need the search function to be a nested one) and the syntax error from the empty while loop have already been observed, but there are more...:
def dfs(problem):
stack.push(bache)
search(root)
what's bache, what's stack, what's root? If they're all global variables, then you're overusing globals -- and apparently nowhere ever using the argument problem (?!).
while stack.isEmpty() != 0:
what's this weird-looking method isEmpty? IOW, what type is stack (clearly not a Python list, and that's weird enough, since they do make excellent LIFO stacks;-)...? And what's ever going to make it empty...?
def search(vertex):
closed.add(vertex)
...don't tell me: closed is yet another global? Presumably a set? (I remember from a few of your Qs back that you absolutely wanted to have a closed dict, not set, even though I suggested that as a possibility...
for index in sars:
...and what's sars?!
stack.push(index)
return stack
what a weird "loop" -- one that executes exactly once, altering a global variable, and then immediately returns that global variable (?) without doing any of the other steps through the loop. Even if this is exactly what you mean (push the first item of sars, period) I don't recommend hiding it in a pseudo-loop -- it seriously looks like a mystery bug just waiting to happen;-).
A:
You need to de-indent your search function. The way you have it set up right now you are defining your search function as a part of the completion of your dfs call. Also, encapsulation in a class would help.
A:
Thats the wrong order. Try this:
def dfs(problem):
def search(vertex):
closed.add(vertex)
for index in sars:
stack.push(index)
return stack
stack.push(bache)
search(root)
while stack.isEmpty() != 0:
A:
Either define search before you call it, or define it outside of dfs.
A:
you have to define the function before using it
root doesn't seem to be available in your scope - make sure it's reachable
A:
You don't have body to your for your while loop. That is probably causing problems parsing the code. I would also suggest putting the local function definition before it is used, so it is easier to follow.
| function in python | In a function, I need to perform some logic that requires me to call a function inside a function. What I did with this, like:
def dfs(problem):
stack.push(bache)
search(root)
while stack.isEmpty() != 0:
def search(vertex):
closed.add(vertex)
for index in sars:
stack.push(index)
return stack
In the function, dfs, I am using search(root), is this is the correct way to do it?
I am getting an error: local variable 'search' referenced before assignment
| [
"There are many mysterious bug-looking aspects in your code. The wrong order of definition (assuming you do need the search function to be a nested one) and the syntax error from the empty while loop have already been observed, but there are more...:\ndef dfs(problem):\n stack.push(bache)\n search(root) ... | [
2,
1,
1,
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0003269963_python.txt |
Q:
= Try Except Pattern?
I find this design pattern comes up a lot:
try: year = int(request.GET['year'])
except: year = 0
The try block can either fail because the key doesn't exist, or because it's not an int, but I don't really care. I just need a sane value in the end.
Shouldn't there be a nicer way to do this? Or at least a way to do it on one line? Something like:
year = int(request.GET['year']) except 0
Or do you guys use this pattern too?
Before you answer, I already know about request.GET.get('year',0) but you can still get a value error. Wrapping this in a try/catch block to catch the value error just means the default value appears twice in my code. Even worse IMO.
A:
You're probably better off to use get()
year = int(request.GET.get("year", 0))
This will set year to what ever request.GET['year'] is, or if the key doesn't exist, it will return 0. This gets rid of your KeyError, but you could still have a ValueError from request.GET['year'], if it is not convert'able to an int.
Regarding your question (the try/except), a common idiom in Python is EAFP.
EDIT:
If you're really concerned, why not write your own method to do this:
def myGet(obj, key, type, defaultval):
try:
return type(obj.get(key, defaultval))
except ValueError:
return defaultval
# In your code
year = myGet(request.GET, 'year', int, 0)
A:
Shouldn't there be a nicer way to do
this?
There is -- it's known as "a function"...:
def safeget(adict, key, type, default):
try: return type(adict.get(key, default))
except (ValueError, TypeError): return default
year = safeget(request.GET, 'year', int, 0)
FWIW, I don't think I've ever used this "pattern" -- the various error cases you're ignoring seem like they should be handled separately for UI reasons (a missing optional field defaulting is fine, but if somebody's mistakenly typed, say, 201o (the 0 and o keys being closed and, in some fonts, their results appearing similar), it generally doesn't seem nice to silently turn their input into 0. So, I don't think it's so frequent, nor highly advisable, to warrant anything like a special syntax form in the language, or even a built-in function.
But the nice thing about helper functions like safeget is that you and I can peacefully agree to disagree on the design issues involved (maybe we're just used to doing different kinds of software, for example!-) while letting each of us easily have exactly the helper functions each desires in their personal "utilities" modules!-)
A:
I'd use a helper function:
def get_int(request, name, default=0):
try:
val = int(request.GET[name])
except (ValueError, KeyError):
val = default
return val
then:
year = get_int(request, 'year')
It keeps the complexity of the try/catch in one place, and makes for tidy functions, where you have one line per parameter in your view functions.
A:
No way to do it in one line (that I can think of), but I'd do it like this, using get():
try:
year = int(request.GET.get("year", 0))
except ValueError:
year = 0
Also, it's generally better to catch a specific exception, not all exceptions.
| = Try Except Pattern? | I find this design pattern comes up a lot:
try: year = int(request.GET['year'])
except: year = 0
The try block can either fail because the key doesn't exist, or because it's not an int, but I don't really care. I just need a sane value in the end.
Shouldn't there be a nicer way to do this? Or at least a way to do it on one line? Something like:
year = int(request.GET['year']) except 0
Or do you guys use this pattern too?
Before you answer, I already know about request.GET.get('year',0) but you can still get a value error. Wrapping this in a try/catch block to catch the value error just means the default value appears twice in my code. Even worse IMO.
| [
"You're probably better off to use get()\nyear = int(request.GET.get(\"year\", 0))\n\nThis will set year to what ever request.GET['year'] is, or if the key doesn't exist, it will return 0. This gets rid of your KeyError, but you could still have a ValueError from request.GET['year'], if it is not convert'able to an... | [
10,
6,
5,
2
] | [] | [] | [
"design_patterns",
"python"
] | stackoverflow_0003269887_design_patterns_python.txt |
Q:
Getting isMultipartContent = false while using python poster library
I'm using the python poster library to try to upload a form containing including an image to a servlet. Locally, it runs fine, but when I deploy to app engine, it doesn't recognize it as multipart content.
ServletFileUpload.isMultipartContent(request) returns false
Here's how I'm using the poster library:
register_openers()
datagen, headers = multipart_encode({"image": open(filename)})
request = urllib2.Request(url, datagen, headers)
The servlet checks to make sure it is Multipart, but it fails that check. What can I do to further debug?
Thanks,
jean
*******update*********
printing out the stack trace...here's what i get. It complains the content type header isnull
org.apache.commons.fileupload.FileUploadBase$InvalidContentTypeException: the request doesn't contain a multipart/form-data or multipart/mixed stream, content type header is null
at org.apache.commons.fileupload.FileUploadBase$FileItemIteratorImpl.(FileUploadBase.java:885)
at org.apache.commons.fileupload.FileUploadBase.getItemIterator(FileUploadBase.java:331)
at org.apache.commons.fileupload.FileUploadBase.parseRequest(FileUploadBase.java:349)
at org.apache.commons.fileupload.servlet.ServletFileUpload.parseRequest(ServletFileUpload.java:126)
A:
If you're on Windows (or a pedant;-), open(filename) is the wrong way to open a binary file and might mess things up -- use open(filename, 'rb'). Apart from that, assuming of course that you continue with a urllib2.urlopen(request) which you've omitted, that your imports are correct, and that filename and url are properly set previously, then your code seems legit.
| Getting isMultipartContent = false while using python poster library | I'm using the python poster library to try to upload a form containing including an image to a servlet. Locally, it runs fine, but when I deploy to app engine, it doesn't recognize it as multipart content.
ServletFileUpload.isMultipartContent(request) returns false
Here's how I'm using the poster library:
register_openers()
datagen, headers = multipart_encode({"image": open(filename)})
request = urllib2.Request(url, datagen, headers)
The servlet checks to make sure it is Multipart, but it fails that check. What can I do to further debug?
Thanks,
jean
*******update*********
printing out the stack trace...here's what i get. It complains the content type header isnull
org.apache.commons.fileupload.FileUploadBase$InvalidContentTypeException: the request doesn't contain a multipart/form-data or multipart/mixed stream, content type header is null
at org.apache.commons.fileupload.FileUploadBase$FileItemIteratorImpl.(FileUploadBase.java:885)
at org.apache.commons.fileupload.FileUploadBase.getItemIterator(FileUploadBase.java:331)
at org.apache.commons.fileupload.FileUploadBase.parseRequest(FileUploadBase.java:349)
at org.apache.commons.fileupload.servlet.ServletFileUpload.parseRequest(ServletFileUpload.java:126)
| [
"If you're on Windows (or a pedant;-), open(filename) is the wrong way to open a binary file and might mess things up -- use open(filename, 'rb'). Apart from that, assuming of course that you continue with a urllib2.urlopen(request) which you've omitted, that your imports are correct, and that filename and url are... | [
0
] | [] | [] | [
"file_upload",
"google_app_engine",
"multipartform_data",
"poster",
"python"
] | stackoverflow_0003270102_file_upload_google_app_engine_multipartform_data_poster_python.txt |
Q:
Step into subroutine call, but not calls made for parameters
func(a(), b.c)
When executing the line above in the pdb debugger, using step will actually step into a, and then into the getter for b.c if its atypical (such as being a property), before actually stepping into func.
Generally I find myself using step followed by r to return from the frames I'm not interested in, and often inexplicably pass over and miss the opportunity to step directly into func.
How do I step directly into func, or what sequence of debugger commands will guarantee that I end up in func rather than passing over it?
A:
tb func ("temporary break at func") followed by c ("continue") should work.
A:
I would handle this by setting a break at the line number inside func that you're interested in, and then use continue. For example suppose your code looks like this:
110 def func(a1, a2):
111 "" docstring ""
112 first interesting line
then do this:
python -m pdb caller.py
pdb> b 112
pdb> c
| Step into subroutine call, but not calls made for parameters | func(a(), b.c)
When executing the line above in the pdb debugger, using step will actually step into a, and then into the getter for b.c if its atypical (such as being a property), before actually stepping into func.
Generally I find myself using step followed by r to return from the frames I'm not interested in, and often inexplicably pass over and miss the opportunity to step directly into func.
How do I step directly into func, or what sequence of debugger commands will guarantee that I end up in func rather than passing over it?
| [
"tb func (\"temporary break at func\") followed by c (\"continue\") should work.\n",
"I would handle this by setting a break at the line number inside func that you're interested in, and then use continue. For example suppose your code looks like this:\n110 def func(a1, a2):\n111 \"\" docstring \"\"\n112 ... | [
2,
0
] | [] | [] | [
"debugging",
"pdb",
"python"
] | stackoverflow_0003270174_debugging_pdb_python.txt |
Q:
loop until all elements have been accessed N times in python
I have a group of buckets, each with a certain number of items in them. I want to make combinations with one item from each bucket. The loop should keep making different combinations until each item has participated in at least some defined number.
I can easily see how to run the loop and stop once a single element has been accessed a certain number of times. However I can't see how to set a minimum cutoff point beyond searching through all the elements in all the buckets to check their access number after every iteration of the loop.
A:
itertools.product is one way (a very systematic one) to make the "combinations" you request (don't confuse with the .combinations function of course) -- or you could make them randomly with random.choose from each bucket; not sure which one is for you since I don't know what your real purpose is.
Anyway, I'd keep track of how many combos each item has been in with a dict (or one dict per bucket, if there can be overlap in items among buckets). Or, you could use a collections.Counter in Python 2.7, if that's your version.
At any rate, one possibility to do what you request is: the moment an item's count reaches N, remove that item from its bucket (or all buckets, if there's overlap and that's the semantics you require) -- except that if this leaves the bucket empty, restore the bucket's contents and mark that bucked as "done" (you don't need to remove items from a done bucket) e.g. by adding the bucket's index to a set.
You're done when all buckets are done (whether it be randomly or systematically).
Need some code to explain this better? Then please specify the overlap semantics (if overlap is possible) and the systematic-or-random requirements you have.
A:
try
visits = defaultdict(int)
# do at each node visiting
visits[n] += 1
if visits[n] >= MAX_VISITS:
break
print 'done'
A:
Use a dictionary with the items as keys. Every time the item is used, update its count. Then check to see whether all the values are at least above the threshold, ie:
counter = dict()
while min(counter.values) < threshold:
# make a combination
# and update the dictionary
A:
In vanilla Python, this seems to do the job:
buckets = [ [1,2,3],[4],[5,6],[7,8,9,0] ]
def combo(b, i = 0, pref = []):
if len(b) > i:
c = b[i]
for v in c:
combo(b, i + 1, pref + [v])
else:
print pref
combo(buckets)
Output:
[1, 4, 5, 7]
[1, 4, 5, 8]
[1, 4, 5, 9]
[1, 4, 5, 0]
[1, 4, 6, 7]
[1, 4, 6, 8]
[1, 4, 6, 9]
[1, 4, 6, 0]
[2, 4, 5, 7]
[2, 4, 5, 8]
[2, 4, 5, 9]
[2, 4, 5, 0]
[2, 4, 6, 7]
[2, 4, 6, 8]
[2, 4, 6, 9]
[2, 4, 6, 0]
[3, 4, 5, 7]
[3, 4, 5, 8]
[3, 4, 5, 9]
[3, 4, 5, 0]
[3, 4, 6, 7]
[3, 4, 6, 8]
[3, 4, 6, 9]
[3, 4, 6, 0]
There is no doubt a more Pythonic way of doing it.
| loop until all elements have been accessed N times in python | I have a group of buckets, each with a certain number of items in them. I want to make combinations with one item from each bucket. The loop should keep making different combinations until each item has participated in at least some defined number.
I can easily see how to run the loop and stop once a single element has been accessed a certain number of times. However I can't see how to set a minimum cutoff point beyond searching through all the elements in all the buckets to check their access number after every iteration of the loop.
| [
"itertools.product is one way (a very systematic one) to make the \"combinations\" you request (don't confuse with the .combinations function of course) -- or you could make them randomly with random.choose from each bucket; not sure which one is for you since I don't know what your real purpose is.\nAnyway, I'd ke... | [
1,
0,
0,
0
] | [] | [] | [
"list",
"loops",
"python",
"sorting",
"while_loop"
] | stackoverflow_0003270121_list_loops_python_sorting_while_loop.txt |
Q:
Chained string formatting in Python
In handling a little SQL formatting I was amazed to find I could chain string formatters:
def get_sql(table, limit=True):
sql = "select report_date from %s"
if limit:
result = "%s limit 1" % sql % table
else:
result = sql % table
return result
Is this legit? Any reason not to do this?
A:
It makes sense that it works because a statement like this:
'some value goes here %s' % value
Actually returns a string. It's probably a bit more logical to view it like this:
result = ("%s limit 1" % sql) % table
There's nothing expressly wrong with doing that, but chaining operators can lead to problems with figuring out where an error came from.
So for instance, this works fine:
>>> sql = 'a value of %s'
>>> x = 'some string %s with stuff'
>>> y = 'VALUE'
>>> x % sql % y
'some string a value of VALUE with stuff'
But if there was a formatting error in there (I realize this example is pathological, but it gets the point across):
>>> sql = 'a value of %d'
>>> x = 'some string %d with stuff'
>>> y = 123
>>> x % sql % y
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: %d format: a number is required, not str
It's really not clear which %d is causing your error. For that reason, I would split it out and just use one % formatter per line if possible because then the traceback will be able to point you to exactly which line and which formatter had the issue.
For the record, by doing it one formatter per line you'll also make life a lot easier for anyone else who has to read your code and try to figure out what's going on.
A:
It's perfectly legit.
The "single argument" form of the string formatter is really a special case - for multiple items a tuple is normally used and that would lead to a more obvious example of why it's ok
result = "%s limit 1" % (sql % (table,),)
This ^ was originally written to encourage the questioner that supporting multiple-formats was a legitimate language feature but, as Nas Banov comments, it does read like I'm trying to explain how it works (not helped by screwing up the code). It doesn't build the string right to left like this suggests it might, but HAS to build it (be associative) left to right. The operator must take a string on the left and return one, but can take a non-string (a tuple) on the right. Since you can't use % on a pair of tuples it can't possibly work in reverse
>>> "%s %f %s" % ( "%d", 0.1, "%d %d" ) % (1,2,3)
'1 0.100000 2 3'
It may, however, lead to complicated/messy code, so personally I would use it very sparingly.
You could work your example like this:
def get_sql(table, limit=True):
sql = "select report_date from"
strlimit = ""
if limit:
strlimit = "limit 1"
return "%s %s"%(sql, strlimit)
A:
Why yes, it is possible to chain %string formatting like that, even if this is the first time i see it used (and in horrible way, mind you)!
The reason is that operators of the same type group left to right (have "left associativity" - with the notable exceptions of exponentiation ** and comparisons a<b<c).
So in the same way that
>>> 1 - 2 - 3 # equals to (1-2)-3
-4
>>> 16 / 4 / 2 # equals to (16 /4) /2, NOT 16 / (4 / 2)
2
so does s1 % s2 % s3 equal to (s1 % s2) % s3
Oh and by the way, it does not matter if s1, s2 and s3 are strings or numbers - the compiler does not know that during compilation and only runtime it will be determined that whether % means "remainder from division" (if s1 is number) or string formatting (if s1 is a string).
A:
I would write it this way:
def get_sql(table,limit=True):
sql = "select report_date from %s"%table
if limit: sql += " limit 1"
return sql
PS. The code you posted works like this:
In [49]: "%s limit 1" % sql
Out[49]: 'select report_date from %s limit 1'
In [50]: "%s limit 1" % sql % 'table'
Out[50]: 'select report_date from table limit 1'
Sure you can do it, but I don't think it is particularly clear.
| Chained string formatting in Python | In handling a little SQL formatting I was amazed to find I could chain string formatters:
def get_sql(table, limit=True):
sql = "select report_date from %s"
if limit:
result = "%s limit 1" % sql % table
else:
result = sql % table
return result
Is this legit? Any reason not to do this?
| [
"It makes sense that it works because a statement like this:\n'some value goes here %s' % value\nActually returns a string. It's probably a bit more logical to view it like this:\nresult = (\"%s limit 1\" % sql) % table\nThere's nothing expressly wrong with doing that, but chaining operators can lead to problems w... | [
4,
3,
2,
0
] | [] | [] | [
"python",
"string"
] | stackoverflow_0003268825_python_string.txt |
Q:
dictionary in python
s = problem.getSuccessors(currNode)
print s
child = dict((t[0], t[1:]) for t in s)
print child
output of s = [((5, 4), 'South', 1), ((4, 5), 'West', 1)]
output of child = {(4, 5): ('West', 1), (5, 4): ('South', 1)}
Why the order has been changed?? 5,4 should be at first position and ( 4, 5) at 2nd position of child dict.
And how do I can put 1 more value for the key?
here my key is (5,4) and its values is south and 1. Now I want to have its parent node also as its value so that when I use the key[1]- it shud give me south, 1 and parent node
since "s" contains only 2 things,south and 1. so it is making only 2 values of the key. i need 1 more . what are the commands?
A:
(1) In Python dictionaries are unordered. Use an OrderedDict (available since Python 2.7 and 3.1) if you need to maintain the insertion order.
(2) I don't know what you mean by "parent node".
A:
Dictionaries do not preserve key order.
You would need to use an ordered dict substitute.
| dictionary in python | s = problem.getSuccessors(currNode)
print s
child = dict((t[0], t[1:]) for t in s)
print child
output of s = [((5, 4), 'South', 1), ((4, 5), 'West', 1)]
output of child = {(4, 5): ('West', 1), (5, 4): ('South', 1)}
Why the order has been changed?? 5,4 should be at first position and ( 4, 5) at 2nd position of child dict.
And how do I can put 1 more value for the key?
here my key is (5,4) and its values is south and 1. Now I want to have its parent node also as its value so that when I use the key[1]- it shud give me south, 1 and parent node
since "s" contains only 2 things,south and 1. so it is making only 2 values of the key. i need 1 more . what are the commands?
| [
"(1) In Python dictionaries are unordered. Use an OrderedDict (available since Python 2.7 and 3.1) if you need to maintain the insertion order.\n(2) I don't know what you mean by \"parent node\".\n",
"Dictionaries do not preserve key order.\nYou would need to use an ordered dict substitute. \n"
] | [
10,
3
] | [] | [] | [
"python"
] | stackoverflow_0003270533_python.txt |
Q:
general problem- sets,python
I got a problem:
keys here is a list.
keys = [(6,4) , (6,8)]
The entries in the keys can be 4,5...or watever
Now, I have to pick up only 1 from it.So I used:
root = keys[0]
print root
output: (6,4)
Now I have to make a set which is empty, say,...
closed = set()
for u,v of root:
if v not in closed:
closed.add(v)
for val in closed:
print val
It should add values to the set i.e 6 and 4. How should I implement it? The above method is right or wrong? I tried, but not giving me the right ans
A:
>>> keys = [(6,4) , (6,8)]
>>> root = keys[0]
>>> closed = set()
>>> closed.update(root)
>>> closed
{4, 6}
A:
You could try this to add the 6 and the 4 into your set:
closed = set()
closed.add(root[0])
closed.add(root[1])
But maybe you should explain a bit more, what you are trying to do. Then we could help you better.
The line for u,v of root: will not compile. (6,4) is a tuple, which
is an immutable sequence type. You can get its values with the []
operator (like in my code above) or you could unpack it like this:
(u,v) = root
If you want to add both values, you should include this call in your
code:
closed.add(u)
The code:
if v not in closed:
closed.add(v)
is equivalent to:
closed.add(v)
A set ensures, that each element is contained only once.
A:
If I understand you correctly you want to do:
keys = [(6,4) , (6,8)]
closed = set()
map(closed.update, keys)
By the way, this is a bit redundant:
if v not in closed:
closed.add(v)
You can just do:
closed.add(v)
If v is in closed already, nothing happens.
| general problem- sets,python | I got a problem:
keys here is a list.
keys = [(6,4) , (6,8)]
The entries in the keys can be 4,5...or watever
Now, I have to pick up only 1 from it.So I used:
root = keys[0]
print root
output: (6,4)
Now I have to make a set which is empty, say,...
closed = set()
for u,v of root:
if v not in closed:
closed.add(v)
for val in closed:
print val
It should add values to the set i.e 6 and 4. How should I implement it? The above method is right or wrong? I tried, but not giving me the right ans
| [
">>> keys = [(6,4) , (6,8)]\n>>> root = keys[0]\n>>> closed = set()\n>>> closed.update(root)\n>>> closed\n{4, 6}\n\n",
"You could try this to add the 6 and the 4 into your set:\nclosed = set()\nclosed.add(root[0])\nclosed.add(root[1])\n\nBut maybe you should explain a bit more, what you are trying to do. Then we ... | [
2,
0,
0
] | [] | [] | [
"python",
"set"
] | stackoverflow_0003263443_python_set.txt |
Q:
Strange logic with bool
I can't understand one thing with logic in python. Here is the code:
maxCounter = 1500
localCounter = 0
while True:
print str(localCounter) + ' >= ' + str(maxCounter)
print localCounter >= maxCounter
if localCounter >= maxCounter:
break
localCounter += 30
And the result output:
...
1440 >= 1500
False
1470 >= 1500
False
1500 >= 1500
False
1530 >= 1500
False
1560 >= 1500
False
...
And I have infinity cycle there. Why?
topPos = someClass.get_element_pos('element')
scrolledHeight = 0
while True:
print str(scrolledHeight) + ' >= ' + str(topPos)
print scrolledHeight >= topPos
if scrolledHeight >= topPos:
print 'break'
break
someClass.run_javascript("window.scrollBy(0, 30)")
scrolledHeight += 30
print scrolledHeight
time.sleep(0.1)
A:
To fix your code try this:
topPos = int(someClass.get_element_pos('element'))
Why?
When I copy and paste your original code I get this:
...
1440 >= 1500
False
1470 >= 1500
False
1500 >= 1500
True
One small change that I can find to make to your code that reproduces the behaviour you are seeing is to change the first line to this:
maxCounter = '1500' # string instead of integer
After making this change I can also see the output you get:
1410 >= 1500
False
1440 >= 1500
False
1470 >= 1500
False
1500 >= 1500
False
1530 >= 1500
False
etc..
A:
The problem seems to be at this line:
topPos = someClass.get_element_pos('element')
This is likely to assign a string to topPos, instead of a numeric variable. You need to convert this string to a numeric variable so you can do a numeric comparison against it.
topPos = int(someClass.get_element_pos('element'))
Otherwise, e.g. in CPython implementation of v2.7, any int is always going to compare less than any string.
Related questions
How does Python compare string and int?
| Strange logic with bool | I can't understand one thing with logic in python. Here is the code:
maxCounter = 1500
localCounter = 0
while True:
print str(localCounter) + ' >= ' + str(maxCounter)
print localCounter >= maxCounter
if localCounter >= maxCounter:
break
localCounter += 30
And the result output:
...
1440 >= 1500
False
1470 >= 1500
False
1500 >= 1500
False
1530 >= 1500
False
1560 >= 1500
False
...
And I have infinity cycle there. Why?
topPos = someClass.get_element_pos('element')
scrolledHeight = 0
while True:
print str(scrolledHeight) + ' >= ' + str(topPos)
print scrolledHeight >= topPos
if scrolledHeight >= topPos:
print 'break'
break
someClass.run_javascript("window.scrollBy(0, 30)")
scrolledHeight += 30
print scrolledHeight
time.sleep(0.1)
| [
"To fix your code try this:\ntopPos = int(someClass.get_element_pos('element'))\n\nWhy?\nWhen I copy and paste your original code I get this:\n...\n1440 >= 1500\nFalse\n1470 >= 1500\nFalse\n1500 >= 1500\nTrue\n\nOne small change that I can find to make to your code that reproduces the behaviour you are seeing is to... | [
4,
1
] | [] | [] | [
"boolean",
"python"
] | stackoverflow_0003270605_boolean_python.txt |
Q:
How does Python 2 compare string and int? Why do lists compare as greater than numbers, and tuples greater than lists?
The following snippet is annotated with the output (as seen on ideone.com):
print "100" < "2" # True
print "5" > "9" # False
print "100" < 2 # False
print 100 < "2" # True
print 5 > "9" # False
print "5" > 9 # True
print [] > float('inf') # True
print () > [] # True
Can someone explain why the output is as such?
Implementation details
Is this behavior mandated by the language spec, or is it up to implementors?
Are there differences between any of the major Python implementations?
Are there differences between versions of the Python language?
A:
From the python 2 manual:
CPython implementation detail: Objects of different types except numbers are ordered by their type names; objects of the same types that don’t support proper comparison are ordered by their address.
When you order two strings or two numeric types the ordering is done in the expected way (lexicographic ordering for string, numeric ordering for integers).
When you order a numeric and a non-numeric type, the numeric type comes first.
>>> 5 < 'foo'
True
>>> 5 < (1, 2)
True
>>> 5 < {}
True
>>> 5 < [1, 2]
True
When you order two incompatible types where neither is numeric, they are ordered by the alphabetical order of their typenames:
>>> [1, 2] > 'foo' # 'list' < 'str'
False
>>> (1, 2) > 'foo' # 'tuple' > 'str'
True
>>> class Foo(object): pass
>>> class Bar(object): pass
>>> Bar() < Foo()
True
One exception is old-style classes that always come before new-style classes.
>>> class Foo: pass # old-style
>>> class Bar(object): pass # new-style
>>> Bar() < Foo()
False
Is this behavior mandated by the language spec, or is it up to implementors?
There is no language specification. The language reference says:
Otherwise, objects of different types always compare unequal, and are ordered consistently but arbitrarily.
So it is an implementation detail.
Are there differences between any of the major Python implementations?
I can't answer this one because I have only used the official CPython implementation, but there are other implementations of Python such as PyPy.
Are there differences between versions of the Python language?
In Python 3.x the behaviour has been changed so that attempting to order an integer and a string will raise an error:
>>> '10' > 5
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
'10' > 5
TypeError: unorderable types: str() > int()
A:
Strings are compared lexicographically, and dissimilar types are compared by the name of their type ("int" < "string"). 3.x fixes the second point by making them non-comparable.
| How does Python 2 compare string and int? Why do lists compare as greater than numbers, and tuples greater than lists? | The following snippet is annotated with the output (as seen on ideone.com):
print "100" < "2" # True
print "5" > "9" # False
print "100" < 2 # False
print 100 < "2" # True
print 5 > "9" # False
print "5" > 9 # True
print [] > float('inf') # True
print () > [] # True
Can someone explain why the output is as such?
Implementation details
Is this behavior mandated by the language spec, or is it up to implementors?
Are there differences between any of the major Python implementations?
Are there differences between versions of the Python language?
| [
"From the python 2 manual:\n\nCPython implementation detail: Objects of different types except numbers are ordered by their type names; objects of the same types that don’t support proper comparison are ordered by their address.\n\nWhen you order two strings or two numeric types the ordering is done in the expected... | [
210,
24
] | [] | [] | [
"comparison",
"python",
"python_2.x",
"types"
] | stackoverflow_0003270680_comparison_python_python_2.x_types.txt |
Q:
What is the python equivalent to perl "a".."azc"
In perl, to get a list of all strings from "a" to "azc", to only thing to do is using the range operator:
perl -le 'print "a".."azc"'
What I want is a list of strings:
["a", "b", ..., "z", "aa", ..., "az" ,"ba", ..., "azc"]
I suppose I can use ord and chr, looping over and over, this is simple to get for "a" to "z", eg:
>>> [chr(c) for c in range(ord("a"), ord("z") + 1)]
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
But a bit more complex for my case, here.
Thanks for any help !
A:
Generator version:
from string import ascii_lowercase
from itertools import product
def letterrange(last):
for k in range(len(last)):
for x in product(ascii_lowercase, repeat=k+1):
result = ''.join(x)
yield result
if result == last:
return
EDIT: @ihightower asks in the comments:
I have no idea what I should do if I want to print from 'b' to 'azc'.
So you want to start with something other than 'a'. Just discard anything before the start value:
def letterrange(first, last):
for k in range(len(last)):
for x in product(ascii_lowercase, repeat=k+1):
result = ''.join(x)
if first:
if first != result:
continue
else:
first = None
yield result
if result == last:
return
A:
A suggestion purely based on iterators:
import string
import itertools
def string_range(letters=string.ascii_lowercase, start="a", end="z"):
return itertools.takewhile(end.__ne__, itertools.dropwhile(start.__ne__, (x for i in itertools.count(1) for x in itertools.imap("".join, itertools.product(letters, repeat=i)))))
print list(string_range(end="azc"))
A:
Use the product call in itertools, and ascii_letters from string.
from string import ascii_letters
from itertools import product
if __name__ == '__main__':
values = []
for i in xrange(1, 4):
values += [''.join(x) for x in product(ascii_letters[:26], repeat=i)]
print values
A:
Here's a better way to do it, though you need a conversion function:
for i in xrange(int('a', 36), int('azd', 36)):
if base36encode(i).isalpha():
print base36encode(i, lower=True)
And here's your function (thank you Wikipedia):
def base36encode(number, alphabet='0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ', lower=False):
'''
Convert positive integer to a base36 string.
'''
if lower:
alphabet = alphabet.lower()
if not isinstance(number, (int, long)):
raise TypeError('number must be an integer')
if number < 0:
raise ValueError('number must be positive')
# Special case for small numbers
if number < 36:
return alphabet[number]
base36 = ''
while number != 0:
number, i = divmod(number, 36)
base36 = alphabet[i] + base36
return base36
I tacked on the lowercase conversion option, just in case you wanted that.
A:
I generalized the accepted answer to be able to start middle and to use other than lowercase:
from string import ascii_lowercase, ascii_uppercase
from itertools import product
def letter_range(first, last, letters=ascii_lowercase):
for k in range(len(first), len(last)):
for x in product(letters, repeat=k+1):
result = ''.join(x)
if len(x) != len(first) or result >= first:
yield result
if result == last:
return
print list(letter_range('a', 'zzz'))
print list(letter_range('BA', 'DZA', ascii_uppercase))
A:
def strrange(end):
values = []
for i in range(1, len(end) + 1):
values += [''.join(x) for x in product(ascii_lowercase, repeat=i)]
return values[:values.index(end) + 1]
| What is the python equivalent to perl "a".."azc" | In perl, to get a list of all strings from "a" to "azc", to only thing to do is using the range operator:
perl -le 'print "a".."azc"'
What I want is a list of strings:
["a", "b", ..., "z", "aa", ..., "az" ,"ba", ..., "azc"]
I suppose I can use ord and chr, looping over and over, this is simple to get for "a" to "z", eg:
>>> [chr(c) for c in range(ord("a"), ord("z") + 1)]
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
But a bit more complex for my case, here.
Thanks for any help !
| [
"Generator version:\nfrom string import ascii_lowercase\nfrom itertools import product\n\ndef letterrange(last):\n for k in range(len(last)):\n for x in product(ascii_lowercase, repeat=k+1):\n result = ''.join(x)\n yield result\n if result == last:\n return\... | [
5,
4,
2,
1,
1,
0
] | [] | [] | [
"list",
"perl",
"python"
] | stackoverflow_0003264271_list_perl_python.txt |
Q:
How to use python modules that were renamed 3 in a cross compatible way?
There are several modules that were renamed in Python 3 and I'm looking for a solution that will make your code work in both python flavors.
In Python 3, __builtin__ was renamed to builtins. Example:
import __builtin__
#...
__builtin__.something # appearing multiple times ("something" may vary)
A:
Benjamin Peterson's six may be what you are looking for. Six "provides simple utilities for wrapping over differences between Python 2 and Python 3". For example:
from six.moves import builtin # works for both python 2 and 3
A:
You could solve the problem by using nested try .. except-blocks:
try:
name = __builtins__.name
except NameError:
try:
name = builtins.name
except NameError:
name = __buildins__.name
# if this will fail, the exception will be raised
This is no real code, just an example, but name will have the proper content, independent from your version. Inside of the blocks you could also import newname as oldname or copy the values from the new global builtins to the old __buildin__:
try:
__builtins__ = builtins
except NameError:
try:
__builtins__ = buildins # just for example
except NameError:
__builtins__ = __buildins__
# if this will fail, the exception will be raised
Now you can use __builtins__ just as in previous python-versions.
Hope it helps!
| How to use python modules that were renamed 3 in a cross compatible way? | There are several modules that were renamed in Python 3 and I'm looking for a solution that will make your code work in both python flavors.
In Python 3, __builtin__ was renamed to builtins. Example:
import __builtin__
#...
__builtin__.something # appearing multiple times ("something" may vary)
| [
"Benjamin Peterson's six may be what you are looking for. Six \"provides simple utilities for wrapping over differences between Python 2 and Python 3\". For example:\nfrom six.moves import builtin # works for both python 2 and 3\n\n",
"You could solve the problem by using nested try .. except-blocks:\ntry:\n ... | [
3,
1
] | [] | [] | [
"python",
"python_2.x",
"python_3.x"
] | stackoverflow_0003270891_python_python_2.x_python_3.x.txt |
Q:
issue running a test in Python, via rpy2
I have a feeling this will be a quick fix, given that I started coding two weeks ago. I am try to run a statistical test - a Mantel, looking for a correlation between two distance matrices - in Python, by using a function(?) that has already been written in R, via Rpy2. The R module is "ade4" and it contains "mantel.rtest"
from rpy2 import robjects
import rpy2.robjects as robjects
robjects.r('library(ade4)')
**EDIT** rmantel = robjects.r("mantel.rtest")
for i in windownA:
M1 = asmatrix(identityA[i]).reshape(14,14)
for j in windownB:
M2 = asmatrix(identityB[j]).reshape(14,14)
**EDIT** result = rmantel (M1, M2, nrepet = 9999)
print result
print ' '
EDIT: this now works! "This returns the error: "AttributeError: 'R' object has no attribute 'mantel'" which leads me to believe that the object being called here is truncated at the "." (i.e. "mantel" versus the full "mantel.rtest"). I tried reassigning the "mantel.rtest" as an object without a "." ex)
rmantel = "mantel.rtest"
and substituting that
result = robjects.r.rmantel (M1, M2, nrepet = 9999)
only to receive the error: "AttributeError: 'R' object has no attribute 'rmantel'" - so that did not work. Any thoughts as to how I can get around this issue?"
New Issue: The Mantel test require data in "dist" format, so when I run the edited code, I get the following error "RRuntimeError: Error in function (m1, m2, nrepet = 99) :
Object of class 'dist' expected"
So I tried to convert the file to that format and when I print the results, it's the bottom half of a matrix of the correct size, but all fields are filled with "NA"
robjects.r('library(ade4)')
rmantel = robjects.r("mantel.rtest")
distify = robjects.r("dist")
for i in windownA:
M1 = asmatrix(identityA[i]).reshape(14,14)
print distify(M1)
MOne = distify(M1, 14)
for j in windownB:
M2 = asmatrix(identityB[j]).reshape(14,14)
print distify(M2)
MTwo = distify(M2, 14)
result = rmantel(M1, M2, nrepet = 9999)
print result
print ' '
i get"
1 2 3 4 5 6 7 8 9 10 11 12 13
2 NA
3 NA NA
4 NA NA NA
5 NA NA NA NA
6 NA NA NA NA NA
7 NA NA NA NA NA NA
8 NA NA NA NA NA NA NA
9 NA NA NA NA NA NA NA NA
10 NA NA NA NA NA NA NA NA NA
11 NA NA NA NA NA NA NA NA NA NA
12 NA NA NA NA NA NA NA NA NA NA NA
13 NA NA NA NA NA NA NA NA NA NA NA NA
14 NA NA NA NA NA NA NA NA NA NA NA NA NA
A:
Try robjects.r['mantel.rtest']:
In [1]: %cpaste
Pasting code; enter '--' alone on the line to stop.
:from rpy2 import robjects
import rpy2.robjects as robjects
robjects.r('library(ade4)')
::::::--
In [3]: robjects.r['mantel.rtest']
Out[5]: <RFunction - Python:0xa2aac0c / R:0xac9ec04>
This also works:
In [8]: robjects.r('mantel.rtest')
Out[8]: <RFunction - Python:0xaf7042c / R:0xac9ec04>
Edit (for the New Issue):
Since you say mantel.rtest requires data in dist format, I suppose M1 and M2 should be in dist format. But M1 and M2 appear to be numpy arrays. On the other hand, MOne and MTwo look like they might be in dist format.
So perhaps try
result = rmantel(MOne, MTwo, nrepet = 9999)
A:
From rpy2-2.1.x, the recommended simple way to do it is:
from rpy2.robjects.packages import importr
stats = importr('stats')
ade4 = importr('ade4')
result = ade4.mantel_rtest(stats.dist(M1),
stats.dist(M2),
nrepet)
| issue running a test in Python, via rpy2 | I have a feeling this will be a quick fix, given that I started coding two weeks ago. I am try to run a statistical test - a Mantel, looking for a correlation between two distance matrices - in Python, by using a function(?) that has already been written in R, via Rpy2. The R module is "ade4" and it contains "mantel.rtest"
from rpy2 import robjects
import rpy2.robjects as robjects
robjects.r('library(ade4)')
**EDIT** rmantel = robjects.r("mantel.rtest")
for i in windownA:
M1 = asmatrix(identityA[i]).reshape(14,14)
for j in windownB:
M2 = asmatrix(identityB[j]).reshape(14,14)
**EDIT** result = rmantel (M1, M2, nrepet = 9999)
print result
print ' '
EDIT: this now works! "This returns the error: "AttributeError: 'R' object has no attribute 'mantel'" which leads me to believe that the object being called here is truncated at the "." (i.e. "mantel" versus the full "mantel.rtest"). I tried reassigning the "mantel.rtest" as an object without a "." ex)
rmantel = "mantel.rtest"
and substituting that
result = robjects.r.rmantel (M1, M2, nrepet = 9999)
only to receive the error: "AttributeError: 'R' object has no attribute 'rmantel'" - so that did not work. Any thoughts as to how I can get around this issue?"
New Issue: The Mantel test require data in "dist" format, so when I run the edited code, I get the following error "RRuntimeError: Error in function (m1, m2, nrepet = 99) :
Object of class 'dist' expected"
So I tried to convert the file to that format and when I print the results, it's the bottom half of a matrix of the correct size, but all fields are filled with "NA"
robjects.r('library(ade4)')
rmantel = robjects.r("mantel.rtest")
distify = robjects.r("dist")
for i in windownA:
M1 = asmatrix(identityA[i]).reshape(14,14)
print distify(M1)
MOne = distify(M1, 14)
for j in windownB:
M2 = asmatrix(identityB[j]).reshape(14,14)
print distify(M2)
MTwo = distify(M2, 14)
result = rmantel(M1, M2, nrepet = 9999)
print result
print ' '
i get"
1 2 3 4 5 6 7 8 9 10 11 12 13
2 NA
3 NA NA
4 NA NA NA
5 NA NA NA NA
6 NA NA NA NA NA
7 NA NA NA NA NA NA
8 NA NA NA NA NA NA NA
9 NA NA NA NA NA NA NA NA
10 NA NA NA NA NA NA NA NA NA
11 NA NA NA NA NA NA NA NA NA NA
12 NA NA NA NA NA NA NA NA NA NA NA
13 NA NA NA NA NA NA NA NA NA NA NA NA
14 NA NA NA NA NA NA NA NA NA NA NA NA NA
| [
"Try robjects.r['mantel.rtest']:\nIn [1]: %cpaste\nPasting code; enter '--' alone on the line to stop.\n:from rpy2 import robjects\nimport rpy2.robjects as robjects\nrobjects.r('library(ade4)')\n::::::--\n\nIn [3]: robjects.r['mantel.rtest']\nOut[5]: <RFunction - Python:0xa2aac0c / R:0xac9ec04>\n\nThis also works:\... | [
0,
0
] | [] | [] | [
"python",
"r",
"rpy2"
] | stackoverflow_0003266710_python_r_rpy2.txt |
Q:
Python and rpy2: How do I adjust/clear a graphic during runtime?
I'm using rpy2 to do data analysis and plotting in python. It works fine except for the fact that when I draw a plot, it's window hangs around until the program terminates. Is there a way to clear the plot during runtime? Additionally, If I ever resize the window, the plot disappears, but the window remains. When using R interactively, resizing the window simply adjusts the size of my plot. I'd like to have this functionality within python.
For example, were I to run the following code, I would be presented with a simple plot.
import rpy2.robjects as robj
xdata = [2,4,6,8,10,12]
ydata = [1,2,3,4,5,6]
Rxdata = robj.IntVector(xdata)
Rydata = robj.IntVector(ydata)
plot = robj.r.plot
plot(x=Rxdata, y=Rydata, main='title')
however, if I wanted to resize the window, the plot would dissapear, and if I want my code to keep doing other things, this window hangs around. If there is a command that works in R to clear the plot that might work, but I can't seem to find one. Any pointers would be appreciated.
A:
Yes, you can use the following commands to control the plot window interatively:
dev.new() # opens a new window, and can control the size
dev.off() # closes the window
As an example, see these questions:
Creating a Plot Window of a Particular Size
How to change current Plot Window Size (in R)
How to separate two plots in R?
A:
Check the rpy2 documentation about processing interactive events
| Python and rpy2: How do I adjust/clear a graphic during runtime? | I'm using rpy2 to do data analysis and plotting in python. It works fine except for the fact that when I draw a plot, it's window hangs around until the program terminates. Is there a way to clear the plot during runtime? Additionally, If I ever resize the window, the plot disappears, but the window remains. When using R interactively, resizing the window simply adjusts the size of my plot. I'd like to have this functionality within python.
For example, were I to run the following code, I would be presented with a simple plot.
import rpy2.robjects as robj
xdata = [2,4,6,8,10,12]
ydata = [1,2,3,4,5,6]
Rxdata = robj.IntVector(xdata)
Rydata = robj.IntVector(ydata)
plot = robj.r.plot
plot(x=Rxdata, y=Rydata, main='title')
however, if I wanted to resize the window, the plot would dissapear, and if I want my code to keep doing other things, this window hangs around. If there is a command that works in R to clear the plot that might work, but I can't seem to find one. Any pointers would be appreciated.
| [
"Yes, you can use the following commands to control the plot window interatively:\ndev.new() # opens a new window, and can control the size\ndev.off() # closes the window\n\nAs an example, see these questions:\n\nCreating a Plot Window of a Particular Size\nHow to change current Plot Window Size (in R)\nHow to sepa... | [
4,
1
] | [] | [] | [
"python",
"r",
"rpy2"
] | stackoverflow_0003087137_python_r_rpy2.txt |
Q:
A href catching
I'm using BeautifulSoup for parsing some html. Here is the content:
<tr>
<th>Your provider:</th>
<td>
<img src="/isp_logos/la-la-la.ico" alt=""/>
<a href="/isp/SomeProvider">
Provider name </a>
<a href="http://*/isp-comparer/?isp=000000">
</a>
</td>
</tr>
I have to get SomeProvider text from the link . My code is:
contentSoup = BeautifulSoup(ThatHtml)
print contentSoup.findAll('a', href=re.compile('/isp/(.*)'))
The result is empty array, why? Maybe there are another ways?
A:
With your posted code and input, I'm getting:
[<a href="/isp/SomeProvider"> Provider name </a>]
As the return of the array. Are you using the newest 3.1.x version of BeautifulSoup? I actually had the same problem, but it turns out I downloaded the 2.x version of BeautifulSoup thinking that the 2.x meant it was compatible with python 2.x.
Assuming that the first contains the SomeProvider, you could just use:
contentSoup.a
to extract that tag.
| A href catching | I'm using BeautifulSoup for parsing some html. Here is the content:
<tr>
<th>Your provider:</th>
<td>
<img src="/isp_logos/la-la-la.ico" alt=""/>
<a href="/isp/SomeProvider">
Provider name </a>
<a href="http://*/isp-comparer/?isp=000000">
</a>
</td>
</tr>
I have to get SomeProvider text from the link . My code is:
contentSoup = BeautifulSoup(ThatHtml)
print contentSoup.findAll('a', href=re.compile('/isp/(.*)'))
The result is empty array, why? Maybe there are another ways?
| [
"With your posted code and input, I'm getting:\n[<a href=\"/isp/SomeProvider\"> Provider name </a>]\n\nAs the return of the array. Are you using the newest 3.1.x version of BeautifulSoup? I actually had the same problem, but it turns out I downloaded the 2.x version of BeautifulSoup thinking that the 2.x meant it... | [
0
] | [] | [] | [
"beautifulsoup",
"html",
"python",
"regex"
] | stackoverflow_0003270907_beautifulsoup_html_python_regex.txt |
Q:
python- execution time problem
I'm able to go through the first function....but the second func is not running....getaction
def registerInitialState(self, state):
"""
This is the first time that the agent sees the layout of the game board. Here, we
choose a path to the goal. In this phase, the agent should compute the path to the
goal and store it in a local variable. All of the work is done in this method!
state: a GameState object (pacman.py)
"""
if self.searchFunction == None: raise Exception, "No search function provided for SearchAgent"
starttime = time.time()
problem = self.searchType(state) # Makes a new search problem
self.actions = self.searchFunction(problem) # Find a path
totalCost = problem.getCostOfActions(self.actions)
print('Path found with total cost of %d in %.1f seconds' % (totalCost, time.time() - starttime))
if '_expanded' in dir(problem): print('Search nodes expanded: %d' % problem._expanded)
def getAction(self, state):
"""
Returns the next action in the path chosen earlier (in registerInitialState). Return
Directions.STOP if there is no further action to take.
state: a GameState object (pacman.py)
"""
if 'actionIndex' not in dir(self): self.actionIndex = 0
i = self.actionIndex
self.actionIndex += 1
if i < len(self.actions):
return self.actions[i]
else:
return Directions.STOP
Error: File line 114, in getAction
if i < len(self.actions):
TypeError: len() of unsized object
this is my function:when i execute, it shud give me the value of node but instead of it, it is giving me error. The value of i = 0 in the get action function. I dont know, why it is not incrementing.
while stack.isEmpty()!= 0:
node = stack.pop()
print node
Error:
(5, 5)
Path found with total cost of 999999 in 0.0 seconds
Search nodes expanded: 1
None
A:
Add the print statement as per below and tell me what it says. self.actions is probably the None type or not a list-like object. You might want to check == None like the other one.
self.actionIndex += 1
print self.actions
if i < len(self.actions):
return self.actions[i]
else:
return Directions.STOP
So the problem is probably somewhere in here:
problem = self.searchType(state) # Makes a new search problem
self.actions = self.searchFunction(problem) # Find a path
making self.actions == None
You could debug further with:
problem = self.searchType(state) # Makes a new search problem
print problem
self.actions = self.searchFunction(problem) # Find a path
to check if problem is working.. if so, searchFunction is not finding the path or something is going wrong and it is returning None.
| python- execution time problem | I'm able to go through the first function....but the second func is not running....getaction
def registerInitialState(self, state):
"""
This is the first time that the agent sees the layout of the game board. Here, we
choose a path to the goal. In this phase, the agent should compute the path to the
goal and store it in a local variable. All of the work is done in this method!
state: a GameState object (pacman.py)
"""
if self.searchFunction == None: raise Exception, "No search function provided for SearchAgent"
starttime = time.time()
problem = self.searchType(state) # Makes a new search problem
self.actions = self.searchFunction(problem) # Find a path
totalCost = problem.getCostOfActions(self.actions)
print('Path found with total cost of %d in %.1f seconds' % (totalCost, time.time() - starttime))
if '_expanded' in dir(problem): print('Search nodes expanded: %d' % problem._expanded)
def getAction(self, state):
"""
Returns the next action in the path chosen earlier (in registerInitialState). Return
Directions.STOP if there is no further action to take.
state: a GameState object (pacman.py)
"""
if 'actionIndex' not in dir(self): self.actionIndex = 0
i = self.actionIndex
self.actionIndex += 1
if i < len(self.actions):
return self.actions[i]
else:
return Directions.STOP
Error: File line 114, in getAction
if i < len(self.actions):
TypeError: len() of unsized object
this is my function:when i execute, it shud give me the value of node but instead of it, it is giving me error. The value of i = 0 in the get action function. I dont know, why it is not incrementing.
while stack.isEmpty()!= 0:
node = stack.pop()
print node
Error:
(5, 5)
Path found with total cost of 999999 in 0.0 seconds
Search nodes expanded: 1
None
| [
"Add the print statement as per below and tell me what it says. self.actions is probably the None type or not a list-like object. You might want to check == None like the other one.\nself.actionIndex += 1 \nprint self.actions\nif i < len(self.actions): \n return self.actions[i] \nelse: \n return Directions.ST... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0003270987_python.txt |
Q:
SQLAlchemy and max_allowed_packet problem
Due to the nature of my application, I need to support fast inserts of large volumes of data into the database. Using executemany() increases performance, but there's a caveat. For example, MySQL has a configuration parameter called max_allowed_packet, and if the total size of my insert queries exceeds its value, MySQL throws an error.
Question #1: Is there a way to tell SQLAlchemy to split the packet into several smaller ones?
Question #2: If other RDBS have similar constraints, how should I work around them as well?
P.S. I had posted this question earlier but deleted it when I wrongly assumed that likely I will not encounter this problem after all. Sadly, that's not the case.
A:
I had a similar problem recently and used the - not very elegant - work-around:
First I parsed my.cnf for a value for max_allow_packets, if I can't find it, the maximum is set to a default value.
All data items are stored in a list.
Next, for each data item I count the approximate byte length (with strings, it's the length of the string in bytes, for other data types I take the maximum bytes used to be safe.)
I add them up, committing after I have reached approx. 75% of max_allow_packets (as SQL queries will take up space as well, just to be on the safe side).
This approach is not really beautiful, but it worked flawlessly for me.
| SQLAlchemy and max_allowed_packet problem | Due to the nature of my application, I need to support fast inserts of large volumes of data into the database. Using executemany() increases performance, but there's a caveat. For example, MySQL has a configuration parameter called max_allowed_packet, and if the total size of my insert queries exceeds its value, MySQL throws an error.
Question #1: Is there a way to tell SQLAlchemy to split the packet into several smaller ones?
Question #2: If other RDBS have similar constraints, how should I work around them as well?
P.S. I had posted this question earlier but deleted it when I wrongly assumed that likely I will not encounter this problem after all. Sadly, that's not the case.
| [
"I had a similar problem recently and used the - not very elegant - work-around:\n\nFirst I parsed my.cnf for a value for max_allow_packets, if I can't find it, the maximum is set to a default value.\nAll data items are stored in a list.\nNext, for each data item I count the approximate byte length (with strings, i... | [
2
] | [] | [] | [
"large_query",
"mysql",
"python",
"sqlalchemy"
] | stackoverflow_0003267580_large_query_mysql_python_sqlalchemy.txt |
Q:
Converting WAV audio files to MP3 on a server automatically once uploaded?
I'm working on a project, using Python/Django running on a Virtual Private Server, which allows me a blank Linux server box that I can pretty much install whatever I need. The project must allow users to upload an uncompressed WAV file for others to download. These will most probably be served up using Amazon S3. I'm not expecting a massive amount of people to use this site, but obviously scalability is to be thought of.
I'm an intermediate developer, where wrapping my head around using Amazon S3 in Django has been a little bit of a struggle. So I'm looking for a simple and reliable as possible solution to my problem...
Once a user has uploaded an uncompressed WAV file, I would like something to convert this into an MP3 to be used as a preview on the site before another user choices to download it. I'm not really sure how to go about implementing such a feature... Like I say, a simple solution to this would be best for me. Something I can wrap my head around easily! (and to especially implement)
Could anyone offer a solution to this? I would appreciate a good explanation to the process so I can take it in the right direction. Any help is greatly appreciated.
A:
Try ffmpeg e.g. something like this may work
$ ffmpeg -i audio.wav -acodec mp3 -ab 192k audio.mp3
See docs for more details
A:
gst can help you with the conversion, once the appropriate codecs are in place.
| Converting WAV audio files to MP3 on a server automatically once uploaded? | I'm working on a project, using Python/Django running on a Virtual Private Server, which allows me a blank Linux server box that I can pretty much install whatever I need. The project must allow users to upload an uncompressed WAV file for others to download. These will most probably be served up using Amazon S3. I'm not expecting a massive amount of people to use this site, but obviously scalability is to be thought of.
I'm an intermediate developer, where wrapping my head around using Amazon S3 in Django has been a little bit of a struggle. So I'm looking for a simple and reliable as possible solution to my problem...
Once a user has uploaded an uncompressed WAV file, I would like something to convert this into an MP3 to be used as a preview on the site before another user choices to download it. I'm not really sure how to go about implementing such a feature... Like I say, a simple solution to this would be best for me. Something I can wrap my head around easily! (and to especially implement)
Could anyone offer a solution to this? I would appreciate a good explanation to the process so I can take it in the right direction. Any help is greatly appreciated.
| [
"Try ffmpeg e.g. something like this may work\n$ ffmpeg -i audio.wav -acodec mp3 -ab 192k audio.mp3\n\nSee docs for more details\n",
"gst can help you with the conversion, once the appropriate codecs are in place.\n"
] | [
1,
0
] | [] | [] | [
"django",
"mp3",
"python",
"vps"
] | stackoverflow_0003271014_django_mp3_python_vps.txt |
Q:
How to: python script + imagemagic = windows application?
I have a small problem. I have a script in python, which uses imagemagic. It works fine on my Mac, or Linux. But I need to give it to the client, and he uses Windows. Actually the question: how can I build applications for it, and on what to do Gui. (Perhaps you know the finished product is open source, who knows how to resize images and cut them into pieces 'tile cutter')
A:
You can use py2exe to build application for it, may be you can bundle imagemagic with your app too.
| How to: python script + imagemagic = windows application? | I have a small problem. I have a script in python, which uses imagemagic. It works fine on my Mac, or Linux. But I need to give it to the client, and he uses Windows. Actually the question: how can I build applications for it, and on what to do Gui. (Perhaps you know the finished product is open source, who knows how to resize images and cut them into pieces 'tile cutter')
| [
"You can use py2exe to build application for it, may be you can bundle imagemagic with your app too.\n"
] | [
0
] | [] | [] | [
"python",
"tiles",
"windows"
] | stackoverflow_0003270991_python_tiles_windows.txt |
Q:
How to make non-square edges in Tkinter?
In order to make one of my programs more aesthetically pleasing I'm using images to create the boarders, however I want to create a non square boarder so the program looks kinda like this
___________
/ /
/__________/
How should I go about this?
This is on windows 7, btw.
Edit:
A tried to make a pseudo-edge using transparency however it doesn't come out transparent. For some reason it cam out as a dark grey. I want the red to be the "edge".
A:
The concept you are after is called a "shapped window". Search for "tk shaped window" with your favorite search engine. There is a tk extension that claims to support this, though I haven't personally tried it. I presume since it works with tcl/tk it can be made to work with Tkinter since Tkinter uses tcl/tk under the hood.
A:
I'm not familiar with Tkinker, but you could make an image with transparency where you don't want the border, which would make pseudo-slanted edges. There is no way for a window to be non-square however (For a good reason too).
| How to make non-square edges in Tkinter? | In order to make one of my programs more aesthetically pleasing I'm using images to create the boarders, however I want to create a non square boarder so the program looks kinda like this
___________
/ /
/__________/
How should I go about this?
This is on windows 7, btw.
Edit:
A tried to make a pseudo-edge using transparency however it doesn't come out transparent. For some reason it cam out as a dark grey. I want the red to be the "edge".
| [
"The concept you are after is called a \"shapped window\". Search for \"tk shaped window\" with your favorite search engine. There is a tk extension that claims to support this, though I haven't personally tried it. I presume since it works with tcl/tk it can be made to work with Tkinter since Tkinter uses tcl/tk u... | [
3,
0
] | [] | [] | [
"python",
"tkinter",
"windows"
] | stackoverflow_0003267797_python_tkinter_windows.txt |
Q:
Saving gtk.TextTags to file?
So I am trying to write a rich text editor in PyGTK, and originally used the older, third party script InteractivePangoBuffer from Gourmet to do this. While it worked alright, there were still plenty of bugs with it which made it frustrating to use at times, so I decided to write my own utilizing text tags. I have got them displaying and generally working alright, but now I am stuck at trying to figure out how to export them to a file when saving. I've seen that others have had the same problem I've had, though I haven't seen any solutions. I haven't come across any function (built in or otherwise) which comes close to actually getting the starting and ending position of each piece of text with a texttag applied to it so I can use it.
I have come up with one idea which should theoretically work, by walking the text by utilizing gtk.TextBuffer.get_iter_at_offset(), gtk.TextIter.get_offset(), gtk.TextIter.begins_tag(), and gtk.TextIter.ends_tag() in order to check each and every character to see if it begins or ends a tag and, if so, put the appropriate code. This would be horribly inefficient and slow, especially on larger documents, however, so I am wondering if anyone has any better solutions?
A:
You can probably use gtk.TextIter.forward_to_tag_toggle(). I.e. loop over all tags you have and for each tags scan the buffer for the position where it is toggled.
| Saving gtk.TextTags to file? | So I am trying to write a rich text editor in PyGTK, and originally used the older, third party script InteractivePangoBuffer from Gourmet to do this. While it worked alright, there were still plenty of bugs with it which made it frustrating to use at times, so I decided to write my own utilizing text tags. I have got them displaying and generally working alright, but now I am stuck at trying to figure out how to export them to a file when saving. I've seen that others have had the same problem I've had, though I haven't seen any solutions. I haven't come across any function (built in or otherwise) which comes close to actually getting the starting and ending position of each piece of text with a texttag applied to it so I can use it.
I have come up with one idea which should theoretically work, by walking the text by utilizing gtk.TextBuffer.get_iter_at_offset(), gtk.TextIter.get_offset(), gtk.TextIter.begins_tag(), and gtk.TextIter.ends_tag() in order to check each and every character to see if it begins or ends a tag and, if so, put the appropriate code. This would be horribly inefficient and slow, especially on larger documents, however, so I am wondering if anyone has any better solutions?
| [
"You can probably use gtk.TextIter.forward_to_tag_toggle(). I.e. loop over all tags you have and for each tags scan the buffer for the position where it is toggled.\n"
] | [
0
] | [] | [] | [
"pygtk",
"python"
] | stackoverflow_0003269942_pygtk_python.txt |
Q:
List of Python regular expressions for a newbie?
I recently learned a little Python and I couldnt find a good list of the RegEx's (don't know if that is the correct plural tense...) with complete explanations even a rookie will understand :)
Anybody know a such list?
A:
Vide:
A:
Well, for starters - hit up the python docs on the re module. Good list of features and methods, as well as info about special regex characters such as \w. There's also a chapter in Dive into Python about regular expressions that uses the aforementioned module.
A:
Check out the re module docs for some basic RegEx syntax.
For more, read Introduction To RegEx, or other of the many guides online. (or books!)
You could also try RegEx Buddy, which helps you learn regular expressions by telling you what they do an parsing them.
A:
The Django Book http://www.djangobook.com/en/2.0/chapter03/ chapter on urls/views has a great "newbie" friendly table explaining the gist of regexes. combine that with the info on the python.docs http://docs.python.org/library/re.html and you'll master RegEx in no time.
an excerpt:
Regular Expressions
Regular expressions (or regexes) are a compact way of specifying patterns in text. While Django URLconfs allow arbitrary regexes for powerful URL matching, you’ll probably only use a few regex symbols in practice. Here’s a selection of common symbols:
Symbol Matches
. (dot) Any single character
\d Any single digit
[A-Z] Any character between A and Z (uppercase)
[a-z] Any character between a and z (lowercase)
[A-Za-z] Any character between a and z (case-insensitive)
+ One or more of the previous expression (e.g., \d+ matches one or more digits)
? Zero or one of the previous expression (e.g., \d? matches zero or one digits)
* Zero or more of the previous expression (e.g., \d* matches zero, one or more than one >digit)
{1,3} Between one and three (inclusive) of the previous expression (e.g., \d{1,3} matches >one, two or three digits)
A:
But it's turtles all the way down!
| List of Python regular expressions for a newbie? | I recently learned a little Python and I couldnt find a good list of the RegEx's (don't know if that is the correct plural tense...) with complete explanations even a rookie will understand :)
Anybody know a such list?
| [
"Vide: \n\n\n \n",
"Well, for starters - hit up the python docs on the re module. Good list of features and methods, as well as info about special regex characters such as \\w. There's also a chapter in Dive into Python about regular expressions that uses the aforementioned module. \n",
"Check out the re mo... | [
13,
5,
1,
1,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0003266870_python_regex.txt |
Q:
Set products in Python
A product of n copies of a set S is denoted Sn. For example, {0, 1}3 is the set of all 3-bit sequences:
{0,1}3 = {(0,0,0),(0,0,1),(0,1,0),(0,1,1),(1,0,0),(1,0,1),(1,1,0),(1,1,1)}
What's the simplest way to replicate this idea in Python?
A:
In Python 2.6 or newer you can use itertools.product with the optional argument repeat:
>>> from itertools import product
>>> s1 = set((0, 1))
>>> set(product(s1, repeat = 3))
For older versions of Python you can implement product using the code found in the documentation:
def product(*args, **kwds):
# product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy
# product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111
pools = map(tuple, args) * kwds.get('repeat', 1)
result = [[]]
for pool in pools:
result = [x+[y] for x in result for y in pool]
for prod in result:
yield tuple(prod)
A:
I suppose this works?
>>> s1 = set((0,1))
>>> set(itertools.product(s1,s1,s1))
set([(0, 1, 1), (1, 1, 0), (1, 0, 0), (0, 0, 1), (1, 0, 1), (0, 0, 0), (0, 1, 0), (1, 1, 1)])
A:
Mark, good idea.
>>> def set_product(the_set, n):
return set(itertools.product(the_set, repeat=n))
>>> s2 = set((0,1,2))
>>> set_product(s2, 3)
set([(0, 1, 1), (0, 1, 2), (1, 0, 1), (0, 2, 1), (2, 2, 0), (0, 2, 0), (0, 2, 2), (1, 0, 0), (2, 0, 1), (1, 2, 0), (2, 0, 0), (1, 2, 1), (0, 0, 2), (2, 2, 2), (1, 2, 2), (2, 0, 2), (0, 0, 1), (0, 0, 0), (2, 1, 2), (1, 1, 1), (0, 1, 0), (1, 1, 0), (2, 1, 0), (2, 2, 1), (2, 1, 1), (1, 1, 2), (1, 0, 2)])
You could also extend the set type and make the __pow__ method do this.
A:
print 'You can do like this with generator:'
print set((a,b,c) for a in s1 for b in s1 for c in s1)
| Set products in Python | A product of n copies of a set S is denoted Sn. For example, {0, 1}3 is the set of all 3-bit sequences:
{0,1}3 = {(0,0,0),(0,0,1),(0,1,0),(0,1,1),(1,0,0),(1,0,1),(1,1,0),(1,1,1)}
What's the simplest way to replicate this idea in Python?
| [
"In Python 2.6 or newer you can use itertools.product with the optional argument repeat:\n>>> from itertools import product\n>>> s1 = set((0, 1))\n>>> set(product(s1, repeat = 3))\n\nFor older versions of Python you can implement product using the code found in the documentation:\ndef product(*args, **kwds):\n #... | [
16,
2,
1,
0
] | [] | [] | [
"math",
"python"
] | stackoverflow_0003271931_math_python.txt |
Q:
Finding missing values in a numpy array
Alright, extreme rookie question here. In my program, I generate a 2D numpy array, some of whom's entries are missing (not the "nan" kind of nonexistant, but the "None" kind, or NoneType). I'd like to put a mask over these entries, but I seem to be having some trouble doing so. Ordinarily, to mask over, say, all entries with value 2, I'd do
A = np.ma.masked_where(A[A==2], A)
In this case, that doesn't seem to work no matter what I try for the first parameter. Thoughts?
A:
Since you have -- entries in your array, I guess that it means that they are already masked:
>>> m = ma.masked_where([True, False]*5, arange(10))
>>> print m
[-- 1 -- 3 -- 5 -- 7 -- 9]
So, I would say that your entries are already masked and that you can directly use your array.
If you want to create an array that only contains the non-masked value, you can do
>>> m[~m.mask]
[1 3 5 7]
where m is your masked array.
If you want to have the list of masked values, you can simply select the other values:
>>> m[m.mask]
[0 2 4 6 8]
Note that the missing values are not None, but are the original values, generally. In fact, an array of integers cannot contain None.
If you want the indices of the masked values, you can do:
>>> numpy.nonzero(m.mask)
The documentation of numpy.nonzero() describes how its result must be interpreted.
A:
To find the elements in a numpy array that are None, you can use numpy.equal. Here's an example:
import numpy as np
import MA
x = np.array([1, 2, None])
print np.equal(x, None)
# array([False, False, True], dtype=bool)
# to get a masked array
print MA.array(x, mask=np.equal(x,None))
# [1 ,2 ,-- ,]
| Finding missing values in a numpy array | Alright, extreme rookie question here. In my program, I generate a 2D numpy array, some of whom's entries are missing (not the "nan" kind of nonexistant, but the "None" kind, or NoneType). I'd like to put a mask over these entries, but I seem to be having some trouble doing so. Ordinarily, to mask over, say, all entries with value 2, I'd do
A = np.ma.masked_where(A[A==2], A)
In this case, that doesn't seem to work no matter what I try for the first parameter. Thoughts?
| [
"Since you have -- entries in your array, I guess that it means that they are already masked:\n>>> m = ma.masked_where([True, False]*5, arange(10))\n>>> print m\n[-- 1 -- 3 -- 5 -- 7 -- 9]\n\nSo, I would say that your entries are already masked and that you can directly use your array.\nIf you want to create an arr... | [
5,
5
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0003262437_numpy_python.txt |
Q:
Fibonacci under 4 millions
Possible Duplicate:
Python program to find fibonacci series. More Pythonic way.
Hey, i was trying to write a script which sums all the even terms in "Fibonacci Sequence" under 4 millions.
Fibonacci1 = 1
Fibonacci2 = 2
a = 2
i = 4
for i in range(1,4000000):
Fibonacci1 = Fibonacci1 + Fibonacci2
if Fibonacci1 % 2 == 0:
a = a + Fibonacci1
Fibonacci2 = Fibonacci1 + Fibonacci2
if Fibonacci2 % 2 == 0:
a = a + Fibonacci2
print a
raw_input()
it should takes less than a minute, but it took all night and it wasn't solved !
Edit: Sorry guys, i misunderstood the problem. I though it means that i have to sum all the even terms UP TO 4 million ! But the solution was to sum all the even terms UNTIL 4 million.
Working code (finished in less than one second):
Fibonacci1 = 1
Fibonacci2 = 2
a = 2
while a < 4000000:
Fibonacci1 = Fibonacci1 + Fibonacci2
if Fibonacci1 % 2 == 0:
a = a + Fibonacci1
Fibonacci2 = Fibonacci1 + Fibonacci2
if Fibonacci2 % 2 == 0:
a = a + Fibonacci2
print a
raw_input()
A:
There are a couple of problems with your code:
You are looping four million times instead of until a condition is true.
You have repeated code in the body of your loop.
Most people when they start learning Python learn only imperative programming. This is not surprising because Python is an imperative language. But Python also supports functional programming to a certain extent and for this sort of exercise a functional programming approach is more enlightening in my opinion.
First define a generator that generates all the Fibonacci numbers:
def fib():
a = b = 1
while True:
yield a
a, b = b, a + b
To use this generator we can import a few useful functions from itertools. To print the first few numbers use islice:
from itertools import ifilter, islice, takewhile
for x in islice(fib(), 5):
print x
1
1
2
3
5
To find only the even numbers we can use ifilter to produce a new generator:
def is_even(x):
return x % 2 == 0
evenfibs = ifilter(is_even, fib())
for x in islice(evenfibs, 5):
print x
2
8
34
144
610
To fetch numbers from the generator until a number exceeds four million use takewhile:
for x in takewhile(lambda x: x < 4000000, evenfibs):
print x
To solve the problem you can use sum:
sum(list(takewhile(lambda x: x < 4000000, evenfibs)))
I hope this shows that a functional programming approach is not difficult and is a more elegant way to solve certain types of problem.
A:
Are you sure it is i that you want to be less than 4 million?
A:
You may be interested in knowing about the The On-Line Encyclopedia of Integer Sequences!
You can search information by name or by sequence.
If you search either for 0,2,8,34 or 'Even Fibonacci' you will be redirect to sequence A014445
There you you find lots of information including formulas,
from that to code a generator that will yield the even fibonacci numbers directly is easy.
def evenfib():
""" Generates the even fibonacci numbers """
a, b = 2, 0
while True:
a, b = b, a+4*b
yield a
A:
The loop condition is wrong, it should be something like this:
while True:
Fibonacci1 = Fibonacci1 + Fibonacci2
if Fibonacci1 % 2 == 0:
if a + Fibonacci1 > 4000000:
break
a = a + Fibonacci1
Fibonacci2 = Fibonacci1 + Fibonacci2
if Fibonacci2 % 2 == 0:
if a + Fibonacci2 > 4000000:
break
a = a + Fibonacci2
A:
Currently, you sum up all the first 2 million even Fibonacci numbers.
But that is not the task. You have to sum all even Fibonacci numbers that are below 4 million.
A:
NOTE: This has been heavily modified to address the actual question
Here's an alternate (and very fast, but untested, method).
It relies on a few properties:
Each Fibonacci number can be calculated directly as floor( pow( phi, n ) + 0.5 ) (See Computation by Rounding in http://en.wikipedia.org/wiki/Fibonacci_number ). Conversely the index of the biggest Fibonacci number less than i is given by floor( log(i*sqrt(5)) / log(phi) )
The sum of the first N Fibonacci numbers is the N+2th fibonacci number minus 1 (See Second Identity on the same wikipedia page)
The even Fibonacci numbers are are every third number. ( Look at the sequence mod 2 and the result is trivial )
The sum of the even Fibonacci numbers is half the sum of the odd Fibonacci numbers upto the same point in the sequence. (This follows from 3. and the property that F(3N) = F(3N-1) + F(3N-2) so F(3N-2) + F(3N-1) + F(3N) = 2 F(N) .. then summing both sides.
So convert our maximum value of 4000000 calculate the index of the highest Fibonacci number
less than it.
int n = floor(log(4000000*sqrt(5))/log(phi)) = 33.
33 is divisible by 3 so it is an even Fibonacci number, if it wasn't we'd need to adjust n like this.
n = (n/3)*3
The sum of all Fibonacci numbers up to this point if given by
sum = floor( pow( phi, n+2 )/sqrt(5) + 0.5 ) - 1 = 9227464
The sum of all even numbers is half of this:
sum_even = 4613732
Nice thing about this is that its an O(1) (or O(log(N)) if you include the cost of pow/log) algorithm, and works on doubles.. so we can calculate the sum for very large values.
A:
I don't exactly understand your algorithm, but it seems that smerriman has a point, 4000000 Fibonnacci sequence numbers would surely grow above 4M. I guess that the faster approach would be to generate sequence up to 4M, then adding up the even ones.
A:
Come on, the optimal way to compute Fibonacci sequence is using 2 tricks:
EDITED, sorry for earlier mistake
1:
N =|2 0 0|
|1 0 0|
|0 0 0|
M =|3 2 1|
|2 1 0|
|0 0 1|
Matrix N*M^(n/3) has sum of first n fibonacci numbers (filtered only to the even ones) is the upper right element.
2:
You can use http://en.wikipedia.org/wiki/Exponentiation_by_squaring, because matrix multiplication is a ring.
So you can solve our problem in O(log n)
A:
There are other tricks that make this more efficient than simply computing the complete list of Fibonacci numbers, and then summing the even numbers in the list.
I would, IF it were me trying to solve this problem, make a list of the even Fibonacci numbers. Are there any interesting characteristics of that list? Can you convince yourself that this pattern holds true in general?
Next, I might look for a way to compute the members of that list, and only those elements that are needed. I might even look to see if there are any formulas to be found that yield the sum of a sequence of Fibonacci numbers.
Of course, all of this would take up more of your own time than simply coding up the brute force solution, but Project Euler is all about finding the pretty solution rather than the brute force solution. In the end, if you have learned something about mathematics, about computation, then you have gained.
A:
## nice simple generator Mark Byers
def fib():
a = b = 1
while True:
yield a
a, b = b, a + b
## does same as takewhile 5
for fibonacci in zip(range(1,1+5),fib()):
print "fib(%i) = %i" % fibonacci
## we can slice to take every second
print "even sequence upto 100th"
total=0
for fibonacci in zip(range(1,1+100),fib())[::2]:
print "fib(%i) = %i" % fibonacci
total+=fibonacci[1] ## to double check
print "Has sum: ", sum( b for a,b in zip(range(1,1+100),fib())[::2] ),'that is ',total
print "odd sequence upto 100th"
total=0
for fibonacci in zip(range(1,1+100),fib())[1::2]:
print "fib(%i) = %i" % fibonacci
total+=fibonacci[1] ## to double check
print "Has sum: ", sum( b for a,b in zip(range(1,1+100),fib())[1::2] ),'that is ',total
| Fibonacci under 4 millions |
Possible Duplicate:
Python program to find fibonacci series. More Pythonic way.
Hey, i was trying to write a script which sums all the even terms in "Fibonacci Sequence" under 4 millions.
Fibonacci1 = 1
Fibonacci2 = 2
a = 2
i = 4
for i in range(1,4000000):
Fibonacci1 = Fibonacci1 + Fibonacci2
if Fibonacci1 % 2 == 0:
a = a + Fibonacci1
Fibonacci2 = Fibonacci1 + Fibonacci2
if Fibonacci2 % 2 == 0:
a = a + Fibonacci2
print a
raw_input()
it should takes less than a minute, but it took all night and it wasn't solved !
Edit: Sorry guys, i misunderstood the problem. I though it means that i have to sum all the even terms UP TO 4 million ! But the solution was to sum all the even terms UNTIL 4 million.
Working code (finished in less than one second):
Fibonacci1 = 1
Fibonacci2 = 2
a = 2
while a < 4000000:
Fibonacci1 = Fibonacci1 + Fibonacci2
if Fibonacci1 % 2 == 0:
a = a + Fibonacci1
Fibonacci2 = Fibonacci1 + Fibonacci2
if Fibonacci2 % 2 == 0:
a = a + Fibonacci2
print a
raw_input()
| [
"There are a couple of problems with your code:\n\nYou are looping four million times instead of until a condition is true.\nYou have repeated code in the body of your loop.\n\nMost people when they start learning Python learn only imperative programming. This is not surprising because Python is an imperative langu... | [
25,
3,
3,
2,
2,
2,
0,
0,
0,
0
] | [] | [] | [
"python",
"sequence"
] | stackoverflow_0003270863_python_sequence.txt |
Q:
In python, why is reading from an array slower than reading from list?
I'm learning python recently, and is doing many practice with the language.
One thing I found interesting is that, when I read from an array, it's almost half of the time slower than list. Does somebody know why?
here's my code:
from timeit import Timer
import array
t = 10000
l = range(t)
a = array.array('i', l)
def LIST():
for i in xrange(t):
l[i]
def ARRAY():
for i in xrange(t):
a[i]
print Timer(LIST).timeit(1000);
print Timer(ARRAY).timeit(1000);
the output is:
0.813191890717
1.16269612312
which indicates that reading array is slower than list.
I think array is a fixed size memory, while list is a dynamic structure.
So I assumed that array would be faster than list.
Does anyone has any explanation?
A:
lists are "dynamically growing vectors" (very much like C++'s std::vector, say) but that in no way slows down random access to them (they're not linked lists!-). Lists' entries are references to Python objects (the items): accessing one just requires (in CPython) an increment of the item's reference count (in other implementations, based on more advanced garbage collection, not even that;-). Array's entries are raw bits and bytes: accessing one requires a fresh new Python object to be synthesized based on that binary value. So e.g.:
$ python -mtimeit -s'import array; c=array.array("B", "bzap")' 'c[2]'
10000000 loops, best of 3: 0.0903 usec per loop
$ python -mtimeit -s'c=list("bzap")' 'c[2]'
10000000 loops, best of 3: 0.0601 usec per loop
30 nanoseconds' extra time for an access doesn't seem too bad;-).
As an aside, note that timeit is MUCH nicer to use from the command line -- automatic choice of repetition, unit of measure shown for the time, etc. That's how I always use it (importing a custom-coded module with functions to be called, if needed -- but here there is no need for that) -- it's so much handier than importing and using it from a module!
A:
It takes time to wrap a raw integer into a Python int.
A:
The Python lists really resemble some ways normal arrays, they are not Lisp lists, but they have fast random access.
| In python, why is reading from an array slower than reading from list? | I'm learning python recently, and is doing many practice with the language.
One thing I found interesting is that, when I read from an array, it's almost half of the time slower than list. Does somebody know why?
here's my code:
from timeit import Timer
import array
t = 10000
l = range(t)
a = array.array('i', l)
def LIST():
for i in xrange(t):
l[i]
def ARRAY():
for i in xrange(t):
a[i]
print Timer(LIST).timeit(1000);
print Timer(ARRAY).timeit(1000);
the output is:
0.813191890717
1.16269612312
which indicates that reading array is slower than list.
I think array is a fixed size memory, while list is a dynamic structure.
So I assumed that array would be faster than list.
Does anyone has any explanation?
| [
"lists are \"dynamically growing vectors\" (very much like C++'s std::vector, say) but that in no way slows down random access to them (they're not linked lists!-). Lists' entries are references to Python objects (the items): accessing one just requires (in CPython) an increment of the item's reference count (in o... | [
11,
7,
1
] | [] | [] | [
"python"
] | stackoverflow_0003271813_python.txt |
Q:
Python Regex (Search Multiple values in one string)
In python regex how would I match against a large string of text and flag if any one of the regex values are matched... I have tried this with "|" or statements and i have tried making a regex list.. neither worked for me.. here is an example of what I am trying to do with the or..
I think my "or" gets commented out
patterns=re.compile(r'[\btext String1\b] | [\bText String2\b]')
if(patterns.search(MyTextFile)):
print ("YAY one of your text patterns is in this file")
The above code always says it matches regardless if the string appears and if I change it around a bit I get matches on the first regex but never checks the second.... I believe this is because the "Raw" is commenting out my or statement but how would I get around this??
I also tried to get around this by taking out the "Raw" statement and putting double slashes on my \b for escaping but that didn't work either :(
patterns=re.compile(\\btext String1\\b | \\bText String2\\b)
if(patterns.search(MyTextFile)):
print ("YAY one of your text patterns is in this file")
I then tried to do 2 separate raw statements with the or and the interpreter complains about unsupported str opperands...
patterns=re.compile(r'\btext String1\b' | r'\bText String2\b')
if(patterns.search(MyTextFile)):
print ("YAY one of your text patterns is in this file")
A:
patterns=re.compile(r'(\btext String1\b)|(\bText String2\b)')
You want a group (optionally capturing), not a character class. Technically, you don't need a group here:
patterns=re.compile(r'\btext String1\b|\bText String2\b')
will also work (without any capture).
The way you had it, it checked for either one of the characters between the first square brackets, or one of those between the second pair. You may find a regex tutorial helpful.
It should be clear where the "unsupported str operands" error comes from. You can't OR strings, and you have to remember the | is processed before the argument even gets to compile.
A:
This part [\btext String1\b] means is there a "word separator" or one of the letters in "text String1" present. So that matches anything but an empty line I think.
A:
In a RE pattern, square brackets [ ] indicate a "character class" (depending on what's inside them, "any one of these character" or "any character except one of these", the latter indicate by a caret ^ as the first character after the opening [). This is what you're expressing and it has absolutely nothing to do with what you want -- just remove the brackets and you should be fine;-).
| Python Regex (Search Multiple values in one string) | In python regex how would I match against a large string of text and flag if any one of the regex values are matched... I have tried this with "|" or statements and i have tried making a regex list.. neither worked for me.. here is an example of what I am trying to do with the or..
I think my "or" gets commented out
patterns=re.compile(r'[\btext String1\b] | [\bText String2\b]')
if(patterns.search(MyTextFile)):
print ("YAY one of your text patterns is in this file")
The above code always says it matches regardless if the string appears and if I change it around a bit I get matches on the first regex but never checks the second.... I believe this is because the "Raw" is commenting out my or statement but how would I get around this??
I also tried to get around this by taking out the "Raw" statement and putting double slashes on my \b for escaping but that didn't work either :(
patterns=re.compile(\\btext String1\\b | \\bText String2\\b)
if(patterns.search(MyTextFile)):
print ("YAY one of your text patterns is in this file")
I then tried to do 2 separate raw statements with the or and the interpreter complains about unsupported str opperands...
patterns=re.compile(r'\btext String1\b' | r'\bText String2\b')
if(patterns.search(MyTextFile)):
print ("YAY one of your text patterns is in this file")
| [
"patterns=re.compile(r'(\\btext String1\\b)|(\\bText String2\\b)') \n\nYou want a group (optionally capturing), not a character class. Technically, you don't need a group here:\npatterns=re.compile(r'\\btext String1\\b|\\bText String2\\b') \n\nwill also work (without any capture).\nThe way you had it, it check... | [
7,
0,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0003272123_python_regex.txt |
Q:
how to assign new values to variables in predefined equation?
for predefined equations,assigning new values to variables do not changes value of equation.
how can i assign new values to variables so that i will get appropriate value of equation and not the previous one
a,b,c,d,e,f=sympy.symbols('abcdef')
a,b=c,d
e=a+b #equation
print e
c+d #value of eqn
a,b=d,f
print e
c+d #not d+f
A:
Perhaps use substitution instead of equality:
import sympy
a,b,c,d,e,f=sympy.symbols('abcdef')
e=a+b #equation
print e.subs([(a,c),(b,d)])
# c + d
print e.subs([(a,d),(b,f)])
# d + f
| how to assign new values to variables in predefined equation? | for predefined equations,assigning new values to variables do not changes value of equation.
how can i assign new values to variables so that i will get appropriate value of equation and not the previous one
a,b,c,d,e,f=sympy.symbols('abcdef')
a,b=c,d
e=a+b #equation
print e
c+d #value of eqn
a,b=d,f
print e
c+d #not d+f
| [
"Perhaps use substitution instead of equality:\nimport sympy\na,b,c,d,e,f=sympy.symbols('abcdef')\ne=a+b #equation \nprint e.subs([(a,c),(b,d)])\n# c + d\nprint e.subs([(a,d),(b,f)])\n# d + f\n\n"
] | [
5
] | [] | [] | [
"python",
"sympy",
"variables"
] | stackoverflow_0003272179_python_sympy_variables.txt |
Q:
Is there a wxpython list widget that displays alternating row colours even when the list is empty?
Is there a wxpython list widget that displays alternating row colours even when empty the list is empty? or Is there even one that will display a background colour(other than white) when it is empty?
A:
You could do it with a wx.Grid or you might look at the new UltimateListCtrl, which is a pure python widget. You can hack it if it doesn't do what you want it to!
A:
Indeed. Create your list as a custom class:
import wx.lib.mixins.listctrl as listmix
class CustomList(wx.ListCtrl, listmix.ListRowHighlighter):
def __init__(self, parent):
wx.ListCtrl.__init__(self, parent)
listmix.ListRowHighlighter.__init__(self, (206, 218, 255))
See: http://www.wxpython.org/docs/api/wx.lib.mixins.listctrl.ListRowHighlighter-class.html
| Is there a wxpython list widget that displays alternating row colours even when the list is empty? | Is there a wxpython list widget that displays alternating row colours even when empty the list is empty? or Is there even one that will display a background colour(other than white) when it is empty?
| [
"You could do it with a wx.Grid or you might look at the new UltimateListCtrl, which is a pure python widget. You can hack it if it doesn't do what you want it to!\n",
"Indeed. Create your list as a custom class:\nimport wx.lib.mixins.listctrl as listmix\n\nclass CustomList(wx.ListCtrl, listmix.ListRowHighlighter... | [
1,
1
] | [] | [] | [
"background_color",
"listview",
"python",
"user_interface",
"wxpython"
] | stackoverflow_0003269019_background_color_listview_python_user_interface_wxpython.txt |
Q:
Python project organization (specially for external libs)
I plan to organize my python project the following way:
<my_project>/
webapp/
mymodulea.py
mymoduleb.py
mymodulec.py
mylargemodule/
__init.py__
mysubmodule1.py
mysubmodule2.py
backend/
mybackend1.py
mybackend2.py
lib/
python_external_lib1.py
python_external_large_lib2/
__init__.py
blabla.py
python_external_lib2.py
in my development IDE (PYdev) to have all working I have setup webapp/, backend/ and lib/ as source folders and all of course works.
How can I deploy it on a remote server? Have I to set PYTHONPATH in a startupscript ?Or have I to it programmatively?
A:
If you are treating webapp, backend, and lib as source folders, then you are importing (for example) mymodulea, mybackend1, and python_external_large_lib2.
Then on the server, you must put webapp, backend, and lib into your python path. Doing it in some kind of startup script is the usual way to do it. Doing it programmatically is complicated because now your code needs to know what environment it's running in to configure the path correctly.
| Python project organization (specially for external libs) | I plan to organize my python project the following way:
<my_project>/
webapp/
mymodulea.py
mymoduleb.py
mymodulec.py
mylargemodule/
__init.py__
mysubmodule1.py
mysubmodule2.py
backend/
mybackend1.py
mybackend2.py
lib/
python_external_lib1.py
python_external_large_lib2/
__init__.py
blabla.py
python_external_lib2.py
in my development IDE (PYdev) to have all working I have setup webapp/, backend/ and lib/ as source folders and all of course works.
How can I deploy it on a remote server? Have I to set PYTHONPATH in a startupscript ?Or have I to it programmatively?
| [
"If you are treating webapp, backend, and lib as source folders, then you are importing (for example) mymodulea, mybackend1, and python_external_large_lib2. \nThen on the server, you must put webapp, backend, and lib into your python path. Doing it in some kind of startup script is the usual way to do it. Doing ... | [
1
] | [] | [] | [
"deployment",
"python"
] | stackoverflow_0003272281_deployment_python.txt |
Q:
Install Panda3d to run with python
I am running Ubuntu 10.04, I have python installed and running fine. When I installed pand3d from the deb package from the site and tried to run an sample. Like it is describe in this page:
http://www.panda3d.org/manual/index.php/Installing_Panda3D_in_Linux
I got the error:
Traceback (most recent call last):
File "Tut-Asteroids.py", line 13, in
import direct.directbase.DirectStart
ImportError: No module named direct.directbase.DirectStart
In the same page as above there is a description to how to solve this error. But I don't understand what do I need to do.
Can any one tell-me what do I need to do?
A:
Found the answer. I had two pythons installed. One in /usr/bin and the other in /usr/local/bin. Turn out I needed to use the /usr/bin version to run what I needed. Hope this helps other!
| Install Panda3d to run with python | I am running Ubuntu 10.04, I have python installed and running fine. When I installed pand3d from the deb package from the site and tried to run an sample. Like it is describe in this page:
http://www.panda3d.org/manual/index.php/Installing_Panda3D_in_Linux
I got the error:
Traceback (most recent call last):
File "Tut-Asteroids.py", line 13, in
import direct.directbase.DirectStart
ImportError: No module named direct.directbase.DirectStart
In the same page as above there is a description to how to solve this error. But I don't understand what do I need to do.
Can any one tell-me what do I need to do?
| [
"Found the answer. I had two pythons installed. One in /usr/bin and the other in /usr/local/bin. Turn out I needed to use the /usr/bin version to run what I needed. Hope this helps other!\n"
] | [
2
] | [] | [] | [
"linux",
"panda3d",
"python",
"ubuntu"
] | stackoverflow_0003271977_linux_panda3d_python_ubuntu.txt |
Q:
Printing a list of objects
I am a Python newbie. I have this small problem. I want to print a list of objects but all it prints is some weird internal representation of object. I have even defined __str__ method but still I am getting this weird output. What am I missing here?
class person(object):
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return self.name + "(" + str(self.age) + ")"
def partition(coll, pred):
left = []
right = []
for c in coll:
if pred(c):
left.append(c)
else:
right.append(c)
return left, right
people = [
person("Cheryl", 20),
person("Shemoor", 14 ),
person("Kimbala", 25),
person("Sakharam", 8)
]
young_fellas, old_fellas = partition(people, lambda p : p.age < 18)
print(young_fellas)
print(old_fellas)
Please note that I know I can use either a for loop or a map function here. I am looking for something shorter and more idiomatic. Thanks.
EDIT:
One more question: Is the above code of mine Pythonic?
A:
Unless you're explicitly converting to a str, it's the __repr__ method that's used to render your objects.
See Difference between __str__ and __repr__ in Python for more details.
A:
Your made this object:
person("Cheryl", 20)
This means repr should be same after creation:
def __repr__(self):
return 'person(%r,%r)' % (self.name,self.age)
Output becomes:
[person('Shemoor',14), person('Sakharam',8)]
[person('Cheryl',20), person('Kimbala',25)]
A:
You could do:
print(map(str,young_fellas))
A:
try overriding repr
def __repr__(self):
return self.name + "(" + str(self.age) + ")"
Edit: Better way, Thanks to Paul.
def __repr__(self):
return "%s(%d)" % (self.name, self.age)
| Printing a list of objects | I am a Python newbie. I have this small problem. I want to print a list of objects but all it prints is some weird internal representation of object. I have even defined __str__ method but still I am getting this weird output. What am I missing here?
class person(object):
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return self.name + "(" + str(self.age) + ")"
def partition(coll, pred):
left = []
right = []
for c in coll:
if pred(c):
left.append(c)
else:
right.append(c)
return left, right
people = [
person("Cheryl", 20),
person("Shemoor", 14 ),
person("Kimbala", 25),
person("Sakharam", 8)
]
young_fellas, old_fellas = partition(people, lambda p : p.age < 18)
print(young_fellas)
print(old_fellas)
Please note that I know I can use either a for loop or a map function here. I am looking for something shorter and more idiomatic. Thanks.
EDIT:
One more question: Is the above code of mine Pythonic?
| [
"Unless you're explicitly converting to a str, it's the __repr__ method that's used to render your objects.\nSee Difference between __str__ and __repr__ in Python for more details.\n",
"Your made this object:\nperson(\"Cheryl\", 20)\n\nThis means repr should be same after creation:\ndef __repr__(self):\n return '... | [
7,
2,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0003272097_python.txt |
Q:
Re-factoring To MVC pattern -Doubts on separation of view from controller
Im trying to refactor my application (with 1000+ lines of GUI code) to an MVC style pattern.
The logic code is already seperate from the GUI so that is not a problem. My concern is seperation of the view from the controller. I understand the basic principal of MVC and this tutorial in the wxpython wiki has been very helpfull but the code example is a little simplistic and leaves me with doubts when I try to apply the principal to my own project which is quite a bit more complex.
A snippet of the structure..
I have a MainWindow with a number of widgets including a noteBook (tabbed section),
the noteBook has a number of tabs one of the tabs (which I call FilterTab)holds two instances of a
class (that I call a FilterPanel)that is a panel with a listbox, three buttons, one to clear, one to remove and one to add items to/from the list. Depending on flags passed to the
class on instantiation the add buttons event can create different types of dialogs, eg a text entry dialog or directoryPicker etc..
Thats just one part of the GUI which is quite layered -with event handlers buried in the FilterPanel class.
If I were to convert that part to MVC I would have to bind the button events for each instance of the FilterPanel in my controller(instead of in the filterPanel class) -in this case there are two (filterPanel instances)
So I would have something like this for each button, (3 buttons per filterPanel * number of panel instances) plus the handlers..
self.mainWindow.filterTab.dirFilterPnl.Bind(wx.EVT_BUTTON,
self.onAdd_dirFilterPnl,
self.mainWindow.filterTab.dirFilterPnl.addBtn,
self.mainWindow.filterTab.dirFilterPnl.addBtn.GetId()
)
Which adds alot of extra code, (double the amount of event handlers if I have only two filterPanel instances)
So Id like to know am I taking the right approach?
A:
If I were to convert that part to MVC
I would have to bind the button events
for each instance of the FilterPanel
in my controller(instead of in the
filterPanel class)
Not necessarily! MVC's philosophy and practice do not imply that "views" are elementary widgets; your FilterPanel could well be thought of / implemented as a "rich/composite" widget which generate its own, higher-level "events" (directed to the controller) and update appropriately. So, that composite widget can have handlers for lower-level "events" and synthetize higher-level events from them, sending them on to the controller; the controller does not have to know or care about every button etc, just about the higher-abstraction events it receives, such as "the user wants to pick a directory for purpose X" or "the user wants to enter text for purpose Y" -- and respond to them by telling the view what to do.
The key point is that the view takes no "semantic" decisions based on the events it handles, nor does it ever send any command to the model -- the controller is the indispensable "middleman" for all such interactions.
For an analogy, consider that the lowest layer of the GUI has very low level events such as "left mouse button down" and "left mouse button up" -- a "pushbutton widget" reacts directly to them by changing the button's appearance (a "visual" decision, not a "strategic" one) and eventually, if and when appropriate, synthesizing a higher-abstraction event such as "pushbutton was clicked" (when a mouse button down is followed by a mouse button up without intermediate mouse movements invalidating the "clicking" hypothesis, for example). The latter is then directed to whatever higher layer needs to "respond" to button clicks.
Similarly, your rich/composite widgets can take such events and synthesize higher-abstraction ones for the controller to react to. (The same abstract event could be generated by a pushbutton click, a menu selection, certain keystrokes... the controller doesn't care about these lower-layer "visual" considerations, that's the view's/widget's job, and the view/widget does not hardcode "strategic" decisions and actions to such user interactions, that's the controller's job).
The separation of concerns helps with such issues as testing and application flexibility; it's not unheard of, for such advantages to be bought at the price of having some more code wrt an alternative where everything's hardcoded... but if you choose MVC you imply that the price, for you, is well worth paying.
wx may not be the ideal framework to implement this, but you can subclass wx.Event -- or you could use a separate event system like pydispatcher for the higher-abstraction events that flow between separate subsystems, in order to decouple the controller from the specific choice of GUI framework. I normally use Qt, whose signals/slots model, IMNSHO, extends/scales better than typical GUI frameworks' event systems. But, this is a different choice and a different issue.
A:
wxPython has pubsub included, which follows the Publish/Subscribe methodology. It's similar to pydispatcher, although their implementations differ. The wxPython wiki has a few examples on how to use pubsub in your program and there's also this simple tutorial on the subject:
http://www.blog.pythonlibrary.org/2010/06/27/wxpython-and-pubsub-a-simple-tutorial/
MVC in GUIs isn't quite the same as it is in Django or TurboGears. I find that I can put most of my logic in controllers and in my "view", I just bind to the controller. Something like this:
view.py
btn.Bind(wx.EVT_BUTTON, self.onButton)
def onButton(self, event):
controller.someMethod(*args, **kwargs)
Depending on what the calculation is, I may run a thread from my controller and post the result later using wx.CallAfter + pubsub.
| Re-factoring To MVC pattern -Doubts on separation of view from controller | Im trying to refactor my application (with 1000+ lines of GUI code) to an MVC style pattern.
The logic code is already seperate from the GUI so that is not a problem. My concern is seperation of the view from the controller. I understand the basic principal of MVC and this tutorial in the wxpython wiki has been very helpfull but the code example is a little simplistic and leaves me with doubts when I try to apply the principal to my own project which is quite a bit more complex.
A snippet of the structure..
I have a MainWindow with a number of widgets including a noteBook (tabbed section),
the noteBook has a number of tabs one of the tabs (which I call FilterTab)holds two instances of a
class (that I call a FilterPanel)that is a panel with a listbox, three buttons, one to clear, one to remove and one to add items to/from the list. Depending on flags passed to the
class on instantiation the add buttons event can create different types of dialogs, eg a text entry dialog or directoryPicker etc..
Thats just one part of the GUI which is quite layered -with event handlers buried in the FilterPanel class.
If I were to convert that part to MVC I would have to bind the button events for each instance of the FilterPanel in my controller(instead of in the filterPanel class) -in this case there are two (filterPanel instances)
So I would have something like this for each button, (3 buttons per filterPanel * number of panel instances) plus the handlers..
self.mainWindow.filterTab.dirFilterPnl.Bind(wx.EVT_BUTTON,
self.onAdd_dirFilterPnl,
self.mainWindow.filterTab.dirFilterPnl.addBtn,
self.mainWindow.filterTab.dirFilterPnl.addBtn.GetId()
)
Which adds alot of extra code, (double the amount of event handlers if I have only two filterPanel instances)
So Id like to know am I taking the right approach?
| [
"\nIf I were to convert that part to MVC\n I would have to bind the button events\n for each instance of the FilterPanel\n in my controller(instead of in the\n filterPanel class)\n\nNot necessarily! MVC's philosophy and practice do not imply that \"views\" are elementary widgets; your FilterPanel could well be... | [
9,
1
] | [] | [] | [
"model_view_controller",
"python",
"user_interface",
"wxpython"
] | stackoverflow_0003271553_model_view_controller_python_user_interface_wxpython.txt |
Q:
Python: Problem with if statement
I have problem with a if statement code below:
do_blast(x):
test_empty = open('/home/rv/ncbi-blast-2.2.23+/db/job_ID/%s.blast' % (z), 'r')
if test_empty.read() == '':
test_empty.close()
return 'FAIL_NO_RESULTS'
else:
do_something
def return_blast(job_ID):
if job_ID == 'FAIL_NO_RESULTS':
return '<p>Sorry no results :( boooo</p>'
else:
return open('/home/rv/ncbi-blast-2.2.23+/db/job_ID/job_ID_%s.fasta' % (job_ID), 'r').read()
For some reason the code tries to assign "job_ID" to the fasta file in return_blast even though it should have returned "sorry no results". I also understand the file names and extensions are different i have my reasons for doing this.
The code works perfectly when the test_empty file is not empty.
A:
I'm not sure if this is the problem, but your code isn't indented correctly (and that matters in Python). I believe this is what you were wanting:
do_blast(x):
test_empty = open('/home/rv/ncbi-blast-2.2.23+/db/job_ID/%s.blast' % (z), 'r')
if test_empty.read() == '':
test_empty.close()
return 'FAIL_NO_RESULTS'
else:
do_something
def return_blast(job_ID):
if job_ID == 'FAIL_NO_RESULTS':
return '<p>Sorry no results :( boooo</p>'
else:
return open('/home/rv/ncbi-blast-2.2.23+/db/job_ID/job_ID_%s.fasta' % (job_ID), 'r').read()
I don't think your code would have even run though..
A:
Maybe some simple printf style debugging will help:
def return_blast(job_ID):
print 'job_ID: ', job_ID
# ...
Then you can at least see what "job_ID" your function receives. This is crucial for trying to figure out why your if statement fails.
| Python: Problem with if statement | I have problem with a if statement code below:
do_blast(x):
test_empty = open('/home/rv/ncbi-blast-2.2.23+/db/job_ID/%s.blast' % (z), 'r')
if test_empty.read() == '':
test_empty.close()
return 'FAIL_NO_RESULTS'
else:
do_something
def return_blast(job_ID):
if job_ID == 'FAIL_NO_RESULTS':
return '<p>Sorry no results :( boooo</p>'
else:
return open('/home/rv/ncbi-blast-2.2.23+/db/job_ID/job_ID_%s.fasta' % (job_ID), 'r').read()
For some reason the code tries to assign "job_ID" to the fasta file in return_blast even though it should have returned "sorry no results". I also understand the file names and extensions are different i have my reasons for doing this.
The code works perfectly when the test_empty file is not empty.
| [
"I'm not sure if this is the problem, but your code isn't indented correctly (and that matters in Python). I believe this is what you were wanting:\ndo_blast(x):\n test_empty = open('/home/rv/ncbi-blast-2.2.23+/db/job_ID/%s.blast' % (z), 'r')\n if test_empty.read() == '':\n test_empty.close()\n ... | [
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0003270109_python.txt |
Q:
how to filter for objects with time
so lets say I have a simple class Final and I want to filter the results for the past 2 days by the created field, how do I do this? When I populate the final class it has a utc created time, but I need the difference of that time and currently this is along the line of what I want done below, but I am unsure on how to get a difference in a query for all items?
class Final(db.Model):
name = db.StringProperty()
created = db.DateTimeProperty()
now = datetime.datetime.now()
##d = now - created
##if d.days > 2:
## I could loop along something like this but that would be too slow
results = Final.all()
results.filter('created =',##what do i do here?) ##would created >, and then now - 2days work?
A:
I would try:
results.filter('created > ', now - datetime.timedelta(days=2))
| how to filter for objects with time | so lets say I have a simple class Final and I want to filter the results for the past 2 days by the created field, how do I do this? When I populate the final class it has a utc created time, but I need the difference of that time and currently this is along the line of what I want done below, but I am unsure on how to get a difference in a query for all items?
class Final(db.Model):
name = db.StringProperty()
created = db.DateTimeProperty()
now = datetime.datetime.now()
##d = now - created
##if d.days > 2:
## I could loop along something like this but that would be too slow
results = Final.all()
results.filter('created =',##what do i do here?) ##would created >, and then now - 2days work?
| [
"I would try:\nresults.filter('created > ', now - datetime.timedelta(days=2))\n\n"
] | [
3
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0003272723_google_app_engine_python.txt |
Q:
Python object instance inheriting changes to parent class by another instance
I am confused by this behaviour of Python(2.6.5), can someone shed light on why this happens?
class A():
mylist=[]
class B(A):
j=0
def addToList(self):
self.mylist.append(1)
b1 = B()
print len(b1.mylist) # prints 0 , as A.mylist is empty
b1.addToList()
print len(b1.mylist) # prints 1 , as we have added to A.mylist via addToList()
b2 = B()
print len(b2.mylist) # prints 1 !!! Why ?????
A:
You need to do:
class A:
def __init__(self):
self.mylist=[]
That way self.mylist is an instance variable. If you define it outside of a method it is a class variable and so shared between all instances.
In B if you define a constructor you'll have to explicitly call A's constructor:
class B(A):
def __init__(self):
A.__init__(self)
This is explained (not very clearly) in the Python tutorial.
A:
This code creates a shared mylist among all instances of A (or subclasses)
class A():
mylist=[]
What you want to do is:
class A():
def __init__(self):
self.mylist=[]
What you've probably seen is people who do:
class A():
somevariable = a
def doit(self):
self.somevariable = 5
This works because it creates a new "somevariable" attribute because you are doing an assignment. Before that all A instances share the same copy of somevariable. As long as you don't change the copy that is fine. When the variable is assigned to, then it gets replaced rather then modified. So that technique is only really safe when the values in question are immutable (i.e. you can't change them, you can only replace them) However, I think that's a really bad idea and you should always assign all variables in init
| Python object instance inheriting changes to parent class by another instance | I am confused by this behaviour of Python(2.6.5), can someone shed light on why this happens?
class A():
mylist=[]
class B(A):
j=0
def addToList(self):
self.mylist.append(1)
b1 = B()
print len(b1.mylist) # prints 0 , as A.mylist is empty
b1.addToList()
print len(b1.mylist) # prints 1 , as we have added to A.mylist via addToList()
b2 = B()
print len(b2.mylist) # prints 1 !!! Why ?????
| [
"You need to do:\nclass A: \n def __init__(self):\n self.mylist=[] \n\nThat way self.mylist is an instance variable. If you define it outside of a method it is a class variable and so shared between all instances.\nIn B if you define a constructor you'll have to explicitly call A's constructor:\nclass B... | [
2,
2
] | [] | [] | [
"python"
] | stackoverflow_0003272961_python.txt |
Q:
Upgraded python and can't get mysqldb to work
Running OSX 10.6.3
Just updated python to Python 2.6.5 (r265:79359
rebuilt and reinstalled mysqldb (MySQL-python-1.2.3)
rebuilt and reinstalled django (<-- should be unrelated. problem seems to be with mysqldb)
I'm getting the following error.
File "<stdin>", line 1, in <module>
File "build/bdist.macosx-10.3-fat/egg/MySQLdb/__init__.py", line 19, in <module>
File "build/bdist.macosx-10.3-fat/egg/_mysql.py", line 7, in <module>
File "build/bdist.macosx-10.3-fat/egg/_mysql.py", line 6, in __bootstrap__
ImportError: dlopen(/Users/joshuamerriam/.python-eggs/MySQL_python-1.2.3-py2.6-macosx-10.3-fat.egg-tmp/_mysql.so, 2): Symbol not found: _mysql_affected_rows
Referenced from: /Users/joshuamerriam/.python-eggs/MySQL_python-1.2.3-py2.6-macosx-10.3-fat.egg-tmp/_mysql.so
Expected in: dynamic lookup
The error is mentioned here (http://mysql-python.sourceforge.net/FAQ.html) but with no reference as to how to fix it. I'm a bit over my head. Any help?
A:
Actually, the text of the page you link to does hint at a possible solution:
This is one from Mac OS X. It seems to
have been a compiler mismatch, but
this time between two different
versions of GCC. It seems nearly every
major release of GCC changes the ABI
in some why, so linking code compiled
with GCC-3.3 and GCC-4.0, for example,
can be problematic.
It looks like the MySQL client library that mysqldb links against may have been compiled with an older or incompatible version of GCC.
Since the steps outlined in the other answers didn't work for you, here is what I would suggest you try (I've not tested this myself):
Download and build the source for the MySQL client library, installing it somewhere out of the way (e.g. /your/homedir/usr-mysql/).
Rebuild mysqldb manually, editing site.cfg to point the mysql_config variable to e.g. /your/homedir/usr-mysql/bin/mysql_config)
Try using it again.
(Note that there's no need to worry about the MySQL server -- the client libraries always use the MySQL network protocol to communicate with it, even if the connection is just going through a local socket.)
A:
Since you have already gone done the road of using MacPorts for the MySQL client library, the easiest and least trouble-prone solution long-term is to use as many other components from MacPorts as possible. That is, use python and the the MySQLdb from MacPorts as well. There's even a Django port available. One tip: on Snow Leopard, the MacPorts Python 2.6 Tkinter pulls in a lot of extra ports that you may not want to bother building. If you don't anticipate needing Tkinter, you can skip building it:
sudo port install python26 +no_tkinter py26-mysql py26-django
You may also want to install the python_select port and use it to select the default for the /opt/local/bin/python command:
sudo python_select python26
You'll need to ensure your shell PATH includes the MacPorts bin and Python framework bin directories:
export PATH="/opt/local/Library/Frameworks/Python.framework/Versions/2.6/bin:/opt/local/bin:$PATH"
| Upgraded python and can't get mysqldb to work | Running OSX 10.6.3
Just updated python to Python 2.6.5 (r265:79359
rebuilt and reinstalled mysqldb (MySQL-python-1.2.3)
rebuilt and reinstalled django (<-- should be unrelated. problem seems to be with mysqldb)
I'm getting the following error.
File "<stdin>", line 1, in <module>
File "build/bdist.macosx-10.3-fat/egg/MySQLdb/__init__.py", line 19, in <module>
File "build/bdist.macosx-10.3-fat/egg/_mysql.py", line 7, in <module>
File "build/bdist.macosx-10.3-fat/egg/_mysql.py", line 6, in __bootstrap__
ImportError: dlopen(/Users/joshuamerriam/.python-eggs/MySQL_python-1.2.3-py2.6-macosx-10.3-fat.egg-tmp/_mysql.so, 2): Symbol not found: _mysql_affected_rows
Referenced from: /Users/joshuamerriam/.python-eggs/MySQL_python-1.2.3-py2.6-macosx-10.3-fat.egg-tmp/_mysql.so
Expected in: dynamic lookup
The error is mentioned here (http://mysql-python.sourceforge.net/FAQ.html) but with no reference as to how to fix it. I'm a bit over my head. Any help?
| [
"Actually, the text of the page you link to does hint at a possible solution:\n\nThis is one from Mac OS X. It seems to\n have been a compiler mismatch, but\n this time between two different\n versions of GCC. It seems nearly every\n major release of GCC changes the ABI\n in some why, so linking code compiled\... | [
1,
1
] | [] | [] | [
"mysql",
"python"
] | stackoverflow_0003272493_mysql_python.txt |
Q:
How to use logical OR in SPARQL regex()?
I'm using this line in a SPARQL query in my python program:
FILTER regex(?name, "%s", "i" )
(where %s is the search text entered by the user)
I want this to match if either ?name or ?featurename contains %s, but I can't seem to find any documentation or tutorial for using regex(). I tried a couple things that seemed reasonable:
FILTER regex((?name | ?featurename), "%s", "i" )
FILTER regex((?name || ?featurename), "%s", "i" )
FILTER regex((?name OR ?featurename), "%s", "i" )
FILTER regex((?name, ?featurename), "%s", "i" )
and each of those without the ()
FILTER regex(?name, "%s", "i" ) || regex(?featurename, "%s", "i" )
What's the right way to do this?
Thanks
UPDATE: Using UNION works. But I figured out that it also works if you just repeat the regex() part like so:
FILTER (regex(?name, "%s", "i") || regex(?featurename, "%s", "i" ))
Both solutions seem a little messy in that you have to use a 2-element tuple with copies of the same string to fill in both %ss.
A:
What about this?
SELECT ?thing
WHERE {
{
?thing x:name ?name .
FILTER regex(?name, "%s", "i" )
} UNION {
?thing x:featurename ?name .
FILTER regex(?featurename, "%s", "i" )
}
}
| How to use logical OR in SPARQL regex()? | I'm using this line in a SPARQL query in my python program:
FILTER regex(?name, "%s", "i" )
(where %s is the search text entered by the user)
I want this to match if either ?name or ?featurename contains %s, but I can't seem to find any documentation or tutorial for using regex(). I tried a couple things that seemed reasonable:
FILTER regex((?name | ?featurename), "%s", "i" )
FILTER regex((?name || ?featurename), "%s", "i" )
FILTER regex((?name OR ?featurename), "%s", "i" )
FILTER regex((?name, ?featurename), "%s", "i" )
and each of those without the ()
FILTER regex(?name, "%s", "i" ) || regex(?featurename, "%s", "i" )
What's the right way to do this?
Thanks
UPDATE: Using UNION works. But I figured out that it also works if you just repeat the regex() part like so:
FILTER (regex(?name, "%s", "i") || regex(?featurename, "%s", "i" ))
Both solutions seem a little messy in that you have to use a 2-element tuple with copies of the same string to fill in both %ss.
| [
"What about this?\nSELECT ?thing\nWHERE {\n { \n ?thing x:name ?name .\n FILTER regex(?name, \"%s\", \"i\" )\n } UNION {\n ?thing x:featurename ?name .\n FILTER regex(?featurename, \"%s\", \"i\" )\n }\n}\n\n"
] | [
14
] | [] | [] | [
"filter",
"python",
"regex",
"sparql"
] | stackoverflow_0003272070_filter_python_regex_sparql.txt |
Q:
Understanding factorize function
Note that this question contains some spoilers.
A solution for problem #12 states that
"Number of divisors (including 1 and the number itself) can be calculated taking one element from prime (and power) divisors."
The (python) code that it has doing this is num_factors = lambda x: mul((exp+1) for (base, exp) in factorize(x)) (where mul() is reduce(operator.mul, ...).)
It doesn't state how factorize is defined, and I'm having trouble understanding how it works. How does it tell you the number of factors of the number?
A:
The basic idea is that if you have a number factorized into the following form which is the standard form actually:
let p be a prime and e be the exponent of the prime:
N = p1^e1 * p2^e2 *....* pk^ek
Now, to know how many divisors N has we have to take into consideration every combination of prime factors. So you could possibly say that the number of divisors is:
e1 * e2 * e3 *...* ek
But you have to notice that if the exponent in the standard form of one of the prime factors is zero, then the result would also be a divisor. This means, we have to add one to each exponent to make sure we included the ith p to the power of zero. Here is an example using the number 12 -- same as the question number :D
Let N = 12
Then, the prime factors are:
2^2 * 3^1
The divisors are the multiplicative combinations of these factors. Then, we have:
2^0 * 3^0 = 1
2^1 * 3^0 = 2
2^2 * 3^0 = 4
2^0 * 3^1 = 3
2^1 * 3^1 = 6
2^2 * 3^1 = 12
I hope you see now why we add one to the exponent when calculating the divisors.
A:
I'm no Python specialist, but for calculating the number of divisors, you need the prime factorization of the number.
The formula is easy: You add one to the exponent of every prime divisor, and multiply them.
Examples:
12 = 2^2 * 3^1 -> Exponents are 2 and 1, plus one is 3 and 2, 3 * 2 = 6 divisors (1,2,3,4,6,12)
30 = 2^1 * 3^1 * 5^1 -> Exponents are 1, 1 and 1, plus one is 2, 2, and 2, 2 * 2 * 2 = 8 divisors (1,2,3,5,6,10,15,30)
40 = 2^3 * 5^1 -> Exponents are 3 and 1, plus one is 4 and 2, 4 * 2 = 8 divisors (1,2,4,5,8,10,20,40)
| Understanding factorize function | Note that this question contains some spoilers.
A solution for problem #12 states that
"Number of divisors (including 1 and the number itself) can be calculated taking one element from prime (and power) divisors."
The (python) code that it has doing this is num_factors = lambda x: mul((exp+1) for (base, exp) in factorize(x)) (where mul() is reduce(operator.mul, ...).)
It doesn't state how factorize is defined, and I'm having trouble understanding how it works. How does it tell you the number of factors of the number?
| [
"The basic idea is that if you have a number factorized into the following form which is the standard form actually:\nlet p be a prime and e be the exponent of the prime:\n\nN = p1^e1 * p2^e2 *....* pk^ek\n\nNow, to know how many divisors N has we have to take into consideration every combination of prime factors. ... | [
13,
2
] | [] | [] | [
"math",
"python"
] | stackoverflow_0003273379_math_python.txt |
Q:
Python win32api registry key change
I am trying to trigger an event every time a registry value is being modified.
import win32api
import win32event
import win32con
import _winreg
key = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER,'Control Panel\Desktop',0,_winreg.KEY_READ)
sub_key = _winreg.CreateKey(key,'Wallpaper')
evt = win32event.CreateEvent(None,0,0,None)
win32api.RegNotifyChangeKeyValue(sub_key,1,win32api.REG_NOTIFY_CHANGE_ATTRIBUTES,evt,True)
ret_code=win32event.WaitForSingleObject(evt,3000)
if ret_code == win32con.WAIT_OBJECT_0:
print "CHANGED"
if ret_code == win32con.WAIT_TIMEOUT:
print "TIMED"
my problem is that this is never triggered , the event always time-out.
(the reg key I am trying to follow is the wallpaper)
[
please note I trigger the event by 1) manually changing the registry value in regedit 2) an automated script which run this :
from ctypes import windll
from win32con import *
windll.user32.SystemParametersInfoA(SPI_SETDESKWALLPAPER, 0,"C:\wall.jpg",SPIF_UPDATEINIFILE | SPIF_SENDWININICHANGE)
]
Thanks for any help in advance :)
EDIT:: sorry about formatting
A:
"WallPaper" is a value not a key/subkey. So if you bring up regedit.exe, you'll notice that you've created a new key "HKCU\Control Panel\Desktop\WallPaper" which is distinct from the "WallPaper" value under the "HKCU\Control Panel\Desktop" key.
Here's one way to modify your code to listen for changes:
key = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, 'Control Panel\Desktop', 0, _winreg.KEY_READ)
evt = win32event.CreateEvent(None, 0, 0, None)
win32api.RegNotifyChangeKeyValue(key, 1, win32api.REG_NOTIFY_CHANGE_LAST_SET, evt, True)
Note that we don't use a WallPaper subkey any more and note that the "notify fitler" has been changed to NOTIFY_CHANGE_LAST_SET; from the docs this will:
Notify the caller of changes to a value of the key. This can include adding or deleting a value, or changing an existing value.
The rest of your code will work, but you'll need to use the QueryValueEx function before and after to ensure it was the WallPaper value that changed and not some other. (I don't know of a way to listen for specific values.)
| Python win32api registry key change | I am trying to trigger an event every time a registry value is being modified.
import win32api
import win32event
import win32con
import _winreg
key = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER,'Control Panel\Desktop',0,_winreg.KEY_READ)
sub_key = _winreg.CreateKey(key,'Wallpaper')
evt = win32event.CreateEvent(None,0,0,None)
win32api.RegNotifyChangeKeyValue(sub_key,1,win32api.REG_NOTIFY_CHANGE_ATTRIBUTES,evt,True)
ret_code=win32event.WaitForSingleObject(evt,3000)
if ret_code == win32con.WAIT_OBJECT_0:
print "CHANGED"
if ret_code == win32con.WAIT_TIMEOUT:
print "TIMED"
my problem is that this is never triggered , the event always time-out.
(the reg key I am trying to follow is the wallpaper)
[
please note I trigger the event by 1) manually changing the registry value in regedit 2) an automated script which run this :
from ctypes import windll
from win32con import *
windll.user32.SystemParametersInfoA(SPI_SETDESKWALLPAPER, 0,"C:\wall.jpg",SPIF_UPDATEINIFILE | SPIF_SENDWININICHANGE)
]
Thanks for any help in advance :)
EDIT:: sorry about formatting
| [
"\"WallPaper\" is a value not a key/subkey. So if you bring up regedit.exe, you'll notice that you've created a new key \"HKCU\\Control Panel\\Desktop\\WallPaper\" which is distinct from the \"WallPaper\" value under the \"HKCU\\Control Panel\\Desktop\" key.\nHere's one way to modify your code to listen for chang... | [
3
] | [] | [] | [
"python",
"pywin32",
"registry",
"wallpaper",
"winapi"
] | stackoverflow_0003057485_python_pywin32_registry_wallpaper_winapi.txt |
Q:
QPushButton FocusIn generates which signal?
I am creating a small PyQt application and got stuck up in MouseOver effect.
I have a QMainWindow which has three buttons named createProfileButton, downloadPackagesButton and installPackagesButton. All these are of type QPushButton
Now I have created a Label which will hold the text when someone hovers the mouse over any of these button. I checked the documentation and came to know that it can be handled using over-riding
focusInEvent(self, QFocusEvent)
focusOutEvent(self, QFocusEvent)
methods of the button. Now this means that I have to extend QPushButton for each of the three buttons and each one of them have to an object for one class. I tried hunting for the signal which is emitted when mouse is hovered or taken away from the button, but in vain. All help I got on the net was to implement these two methods.
Isnt extending a class and creating one of each an overkill? A signal would be neat, unfortunately, I couldn't find any signal.
http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/html/qpushbutton.html - Has no signals
http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/html/qabstractbutton.html - Has clicked, released, pressed and toggled signals
http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/html/qwidget.html - Has only one method
So I checked the whole inheritance hierarchy and found no signal for FocusIn and FocusOut
A:
As you stated, no signals exist for this functionality. You have two basic options.
Option 1 - Subclass:
class FocusEmittingButton(QPushButton):
#...
def focusInEvent(self, event):
# emit your signal
You can then connect to that signal in your client code. Also, if necessary, you can use designer's Promote To feature to promote each button to the FocusEmittingButton type. You'll only need to subclass once, and then make sure the different buttons are all of the same type.
Option 2 - Use QApplication.focusChanged
You can also leverage QApplication.focusChanged(oldQWidget, newQWidget). By doing so, you won't need to subclass and override the focus events. Instead, you connect to the QApplication.focusChanged signal and then respond in a handler.
A:
There is another way to receive focus signals in a parent widget. You can add an event filter:
class MyParent(QWidget):
def __init__(self):
#...
self.mybutton.installEventFilter()
def eventFilter(self, obj, event):
if obj is self.mybutton and event.type() == QEvent.FocusOut:
#...
return QWidget.eventFilter(self, obj, event)
| QPushButton FocusIn generates which signal? | I am creating a small PyQt application and got stuck up in MouseOver effect.
I have a QMainWindow which has three buttons named createProfileButton, downloadPackagesButton and installPackagesButton. All these are of type QPushButton
Now I have created a Label which will hold the text when someone hovers the mouse over any of these button. I checked the documentation and came to know that it can be handled using over-riding
focusInEvent(self, QFocusEvent)
focusOutEvent(self, QFocusEvent)
methods of the button. Now this means that I have to extend QPushButton for each of the three buttons and each one of them have to an object for one class. I tried hunting for the signal which is emitted when mouse is hovered or taken away from the button, but in vain. All help I got on the net was to implement these two methods.
Isnt extending a class and creating one of each an overkill? A signal would be neat, unfortunately, I couldn't find any signal.
http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/html/qpushbutton.html - Has no signals
http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/html/qabstractbutton.html - Has clicked, released, pressed and toggled signals
http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/html/qwidget.html - Has only one method
So I checked the whole inheritance hierarchy and found no signal for FocusIn and FocusOut
| [
"As you stated, no signals exist for this functionality. You have two basic options.\nOption 1 - Subclass:\nclass FocusEmittingButton(QPushButton):\n #...\n def focusInEvent(self, event):\n # emit your signal\n\nYou can then connect to that signal in your client code. Also, if necessary, you can use ... | [
4,
1
] | [] | [] | [
"focus",
"pyqt",
"python",
"qt",
"signals_slots"
] | stackoverflow_0002194158_focus_pyqt_python_qt_signals_slots.txt |
Q:
dictionary and stack in python problem
I have made a dictionary and I put the keys of the dict in a list. My list contains elements like this:
s = [((5, 4), 'South', 1), ((4, 5), 'West', 1)]
I made a dict from this:
child = dict((t[0], t[1]) for t in s)
keys = child.keys()
print keys
The output is : [(4, 5), (5, 4)]
Now I need to put (4,5) and (5,4) into stack. What should I do?
I tried, but when I do pop from the stack it is giving me the 2 elements together.
like stack.pop() - output is : [(4, 5), (5, 4)]. I want to pop one by one... (4,5) and then (5,4)
A:
You can use a list as a stack:
stack = list(child.keys())
print stack.pop()
print stack.pop()
Result:
(5, 4)
(4, 5)
Important note: the keys of a dictionary are not ordered so if you want the items in a specific order you need to handle that yourself. For example if you want them in normal sorted order you could use sorted. If you want them to pop off in reverse order from the order they were in s you could skip the conversion to a dictionary and just go straight from s to your stack:
stack = [x[0] for x in s]
print stack.pop()
print stack.pop()
Result:
(4, 5)
(5, 4)
A:
use
element = stack[0]
if len(stack) > 0:
stack = stack[1:]
print element
but it is not that kind of a stack :/
A:
I think user wants this:
# python
> stack = [(4, 5), (5, 4)]
> stack.pop(0)
(4,5)
> stack.pop(0)
(5,4)
Just a reminder, though, this is not a proper stack. This is a proper stack:
# python
> stack=[]
> stack.append( (4,5) )
> stack.append( (5,4) )
> stack.pop()
(5,4)
> stack.pop()
(4,5)
| dictionary and stack in python problem | I have made a dictionary and I put the keys of the dict in a list. My list contains elements like this:
s = [((5, 4), 'South', 1), ((4, 5), 'West', 1)]
I made a dict from this:
child = dict((t[0], t[1]) for t in s)
keys = child.keys()
print keys
The output is : [(4, 5), (5, 4)]
Now I need to put (4,5) and (5,4) into stack. What should I do?
I tried, but when I do pop from the stack it is giving me the 2 elements together.
like stack.pop() - output is : [(4, 5), (5, 4)]. I want to pop one by one... (4,5) and then (5,4)
| [
"You can use a list as a stack:\nstack = list(child.keys())\nprint stack.pop()\nprint stack.pop()\n\nResult:\n\n(5, 4)\n(4, 5)\n\nImportant note: the keys of a dictionary are not ordered so if you want the items in a specific order you need to handle that yourself. For example if you want them in normal sorted orde... | [
2,
0,
0
] | [] | [] | [
"python",
"stack"
] | stackoverflow_0003273533_python_stack.txt |
Q:
Tool to easily create a wxPython preference dialog from a template?
I need a wxPython preference dialog box from a Python application. I could hand-code it (and use wxGlade to do part of the job), but I was wondering if there is no tool that makes creation of simple preference dialog boxes easier.
The 'easier' part would be in that you can specify that you need e.g. a text box, and both the GUI elements as well as the config file handling code (read/write) would be created.
I found something that is pretty close here, but it seems a bit limited (I need some more controls, and tab pages).
Before I try to extend it, anybody knows about any other such tools?
(Ideally, the perfect tool would just take the XML file I am currently using, and would generate the Python code for the preference dialog box and writing/saving of the preferences)
A:
I wrote an article on something similar, but I used a Configuration file generated with the ConfigObj module. Here's the link:
http://www.blog.pythonlibrary.org/2010/01/20/generating-a-dialog-from-a-file/
You can probably take the concepts there and use them for this project.
| Tool to easily create a wxPython preference dialog from a template? | I need a wxPython preference dialog box from a Python application. I could hand-code it (and use wxGlade to do part of the job), but I was wondering if there is no tool that makes creation of simple preference dialog boxes easier.
The 'easier' part would be in that you can specify that you need e.g. a text box, and both the GUI elements as well as the config file handling code (read/write) would be created.
I found something that is pretty close here, but it seems a bit limited (I need some more controls, and tab pages).
Before I try to extend it, anybody knows about any other such tools?
(Ideally, the perfect tool would just take the XML file I am currently using, and would generate the Python code for the preference dialog box and writing/saving of the preferences)
| [
"I wrote an article on something similar, but I used a Configuration file generated with the ConfigObj module. Here's the link:\nhttp://www.blog.pythonlibrary.org/2010/01/20/generating-a-dialog-from-a-file/\nYou can probably take the concepts there and use them for this project.\n"
] | [
2
] | [] | [] | [
"preferences",
"python",
"templates",
"wxpython"
] | stackoverflow_0003272884_preferences_python_templates_wxpython.txt |
Q:
python 2.5.1 and supported version of xpath
trying to figure out how to determine what version of XPath is supported by python 2.4.3/2.5.1 using libxml2dom.
in looking through various docs, i must be missing something!
basically, i'm considering how/if i can have an XPath function, and use regex within the XPath... i understand the XPath v2.0 supports using regex, so i'm hopeful that i can simply do an import libxml2dom, and have the ability to then incorporate regex in the XPath functions..
thanks
A:
I believe that Python is loading whichever version of libxml2 is on your machine. I think that all versions of libxml2 implement XPath 1.0. I don't know of any Python ready implementation of XPath 2.0.
| python 2.5.1 and supported version of xpath | trying to figure out how to determine what version of XPath is supported by python 2.4.3/2.5.1 using libxml2dom.
in looking through various docs, i must be missing something!
basically, i'm considering how/if i can have an XPath function, and use regex within the XPath... i understand the XPath v2.0 supports using regex, so i'm hopeful that i can simply do an import libxml2dom, and have the ability to then incorporate regex in the XPath functions..
thanks
| [
"I believe that Python is loading whichever version of libxml2 is on your machine. I think that all versions of libxml2 implement XPath 1.0. I don't know of any Python ready implementation of XPath 2.0.\n"
] | [
1
] | [] | [] | [
"python",
"xpath"
] | stackoverflow_0003273774_python_xpath.txt |
Q:
how to Reference some model in a db.ListProperty on google-app-engine
this is my model:
class Geo(db.Model):
entry = db.ListProperty(db.Key)
geo=Geo()
geo.entry.append(otherModel.key())
and the html is :
{% for i in geo.entry %}
<p><a href="{{ i.link }}">{{ i.title }}</a></p>
{% endfor%}
but it show nothing,
i think maybe should :
class Geo(db.Model):
entry = db.ListProperty(db.Model)
geo=Geo()
geo.entry.append(otherModel)
but it show :
ValueError: Item type Model is not acceptable
so , how to make the html shows the right thing.
thanks
A:
You can't use that template (or the like) to show the model directly, but you can easily prepare a context with a list of models by simply calling db.get on the list of keys -- e.g., have {'entries': db.get(listofkeys), ... at the start of your context dictionary, and for i in entries in the template.
| how to Reference some model in a db.ListProperty on google-app-engine | this is my model:
class Geo(db.Model):
entry = db.ListProperty(db.Key)
geo=Geo()
geo.entry.append(otherModel.key())
and the html is :
{% for i in geo.entry %}
<p><a href="{{ i.link }}">{{ i.title }}</a></p>
{% endfor%}
but it show nothing,
i think maybe should :
class Geo(db.Model):
entry = db.ListProperty(db.Model)
geo=Geo()
geo.entry.append(otherModel)
but it show :
ValueError: Item type Model is not acceptable
so , how to make the html shows the right thing.
thanks
| [
"You can't use that template (or the like) to show the model directly, but you can easily prepare a context with a list of models by simply calling db.get on the list of keys -- e.g., have {'entries': db.get(listofkeys), ... at the start of your context dictionary, and for i in entries in the template.\n"
] | [
1
] | [] | [] | [
"google_app_engine",
"listproperty",
"python"
] | stackoverflow_0003272985_google_app_engine_listproperty_python.txt |
Q:
append tuples to a list
How can I append the content of each of the following tuples (ie, elements within the list) to another list which already has 'something' in it?
So, I want to append the following to a list (eg: result[]) which isn't empty:
l = [('AAAA', 1.11), ('BBB', 2.22), ('CCCC', 3.33)]
Obviously, the following doesn't do the thing:
for item in l:
result.append(item)
print result
I want to printout:
[something, 'AAAA', 1.11]
[something, 'BBB', 2.22]
[something, 'CCCC', 3.33]
A:
result.extend(item)
A:
You can convert a tuple to a list easily:
>>> t = ('AAA', 1.11)
>>> list(t)
['AAAA', 1.11]
And then you can concatenate lists with extend:
>>> t = ('AAA', 1.11)
>>> result = ['something']
>>> result.extend(list(t))
['something', 'AAA', 1.11])
A:
You can use the inbuilt list() function to convert a tuple to a list. So an easier version is:
l = [('AAAA', 1.11), ('BBB', 2.22), ('CCCC', 3.33)]
result = [list(t) for t in l]
print result
Output:
[['AAAA', 1.1100000000000001],
['BBB', 2.2200000000000002],
['CCCC', 3.3300000000000001]]
A:
You will need to unpack the tuple to append its individual elements. Like this:
l = [('AAAA', 1.11), ('BBB', 2.22), ('CCCC', 3.33)]
for each_tuple in l:
result = ['something']
for each_item in each_tuple:
result.append(each_item)
print result
You will get this:
['something', 'AAAA', 1.1100000000000001]
['something', 'BBB', 2.2200000000000002]
['something', 'CCCC', 3.3300000000000001]
You will need to do some processing on the numerical values so that they display correctly, but that would be another question.
| append tuples to a list | How can I append the content of each of the following tuples (ie, elements within the list) to another list which already has 'something' in it?
So, I want to append the following to a list (eg: result[]) which isn't empty:
l = [('AAAA', 1.11), ('BBB', 2.22), ('CCCC', 3.33)]
Obviously, the following doesn't do the thing:
for item in l:
result.append(item)
print result
I want to printout:
[something, 'AAAA', 1.11]
[something, 'BBB', 2.22]
[something, 'CCCC', 3.33]
| [
"result.extend(item)\n\n",
"You can convert a tuple to a list easily:\n>>> t = ('AAA', 1.11)\n>>> list(t)\n['AAAA', 1.11]\n\nAnd then you can concatenate lists with extend:\n>>> t = ('AAA', 1.11)\n>>> result = ['something']\n>>> result.extend(list(t))\n['something', 'AAA', 1.11])\n\n",
"You can use the inbuilt ... | [
44,
5,
3,
1
] | [] | [] | [
"python"
] | stackoverflow_0003274095_python.txt |
Q:
Good compilers for compiling perl/python/php scripts into linux executables?
I am working on a project that requires reading text files, extracting data from them, and then generating reports (text files). Since there are a lot of string parsing, I decided to do it in Perl or Python or PHP (preference in that order). But I don't want to expose the source code to my client. Is there any good compiler for compiling perl/python/php scripts into linux executables?
I am not looking for a 100% perfect one, but I am looking for an at least 90% perfect one. By perfect, I mean the compiler doesn't require to write scripts with a limited subset of language features.
A:
I'm sorry, it's simply not worth spending your time on. For any language you choose (from among the ones you listed), for any compiler/obfuscator someone chooses to come up with, I promise you I can get readable source code out of it (within an hour if it's Perl; longer if it's Python or PHP simply because I'm less acquainted with the implementations of those languages, not because it's intrinsically harder with those languages).
I think you should take a better look at what your goals are and why you want to work for a client that you're assuming a priori wants to rip you off. And if you still want to go ahead with such a scheme, write in C or Fortran -- certainly not anything starting with "P".
A:
There does exist a Compiler for perl, called perlcc. I'm not familar with perl, but it looks like what you're looking for.
A:
There are 3 options of encrypting Perl code:
Use PAR to create executable file with PAR::Filter::Obfuscate or PAR::Filter::Crypto
Use Filter::Crypto::CryptFile (will require some modules installed on target OS)
Turn into module and encrypt into Module::Crypt.
Also you can try B::C - it was removed from core Perl distribution and is now available on CPAN.
A:
So far we've heard about perlcc and PAR with some obfuscation filters. These may work.
I have had very good luck with ActiveState's PerlApp which is part of their Perl Dev Kit.
It works well to bundle your code and hide it. You can try it for free, and it comes with some nice extras. Whether it is expensive or cheap depends on your perspective. For me, it was cheap. The cost in time of getting code hiding working and reliable with PAR or messing with perlcc was easily less than the price of the package. YMMV.
A:
For Python You can call your code and give the *.pyc file to the client.
A:
For linux an executable is something which has +x set, so there's no need to compile scripts. To hide your sourcecode you could use an obfuscator. This makes your sourcecode unreadable.
A:
I've never used this, so I don't know how easy it is to setup, but you could use HipHop PHP to turn your PHP scripts into C++ code and compile them. (Assuming you choose to write them in PHP)
http://developers.facebook.com/blog/post/358
http://github.com/facebook/hiphop-php
A:
For Python you can use cx.freeze. I have not used this but I believe that it basically bundles the .pyc into a zip file and adds an executable front-end.
Alternatively you could try compiling you Python code with Cython. this translates a modified version of the Python language into C code, which can then be compiled. This is normally used to write high performance extensions or interface with existing C libraries, but the latest version can also be used to make a complete executable.
| Good compilers for compiling perl/python/php scripts into linux executables? | I am working on a project that requires reading text files, extracting data from them, and then generating reports (text files). Since there are a lot of string parsing, I decided to do it in Perl or Python or PHP (preference in that order). But I don't want to expose the source code to my client. Is there any good compiler for compiling perl/python/php scripts into linux executables?
I am not looking for a 100% perfect one, but I am looking for an at least 90% perfect one. By perfect, I mean the compiler doesn't require to write scripts with a limited subset of language features.
| [
"I'm sorry, it's simply not worth spending your time on. For any language you choose (from among the ones you listed), for any compiler/obfuscator someone chooses to come up with, I promise you I can get readable source code out of it (within an hour if it's Perl; longer if it's Python or PHP simply because I'm les... | [
3,
2,
2,
1,
0,
0,
0,
0
] | [] | [] | [
"compiler_construction",
"perl",
"php",
"python",
"scripting_language"
] | stackoverflow_0003270464_compiler_construction_perl_php_python_scripting_language.txt |
Q:
python dictionary problem
output of n is in the form:- ((6,5),'north',1)
I am making a dict child for it...in which (6,5) is the key and north and 1 are the values. I need to keep the (6,5) as the key and north as a direction....and I want to keep adding all the values till the while loop continues
A:
If you want to keep all the key / value pairs in one dict (and all keys are distinct, of course):
totaldict = {}
for ...whatever your loop is...:
...
totaldict.update(( t[0], t[1:]) for t in n )
If you want a list of dicts, @San's answer is good. If you want a single dict with not necessarily all distinct keys, and each key's corresponding value a list of tuples:
import collections
totaldict = collections.defaultdict(list)
for ...whatever your loop is...:
...
for t in n:
totaldict[t[0]].append(t[1:])
There may be other senses yet which you might mean "keep all the values of this dictioanary" to signify, but it is, as usual, impossible to guess precisely in what of the many possible meanings you intend it.
Edit: from the OP's edit (much-clarifying his question, though many murky aspects remain which I already asked about on some of his previous questions), he doesn't necessarily need one dict -- he needs to be able to trace any path backwards when he finally gets to a node that's deemed by the problem object to be "a solution" (or "goal").
The OP's edit to the Q now seems to mysteriously have disappeared, but if (as I dimly recall) he's skipping any node that's previously been pushed onto the stack, then one dict will do, because each node will be visited at most once (hence, no duplicate keys) -- however, that dict's entry, with the node as a key, should not point to the node's successors (signally useless in tracing the path backwards from the goal!), but to the predecessor which led to visiting this node (and the direction that was taken from that immediate predecessor to come to this node). The root's node entry should be empty (since it has no predecessor).
A:
It sounds like you want a list of dictionaries, but it's difficult to tell with so little context.
my_list = []
while some_loop_condition:
child = dict(( t[0], t[1:]) for t in n )
my_list.append(child)
A:
It looks like you want to define 'child' outside if the loop, and reference it within:
e.g.:
child = {}
while blah:
...
child.update(dict(( t[0], t[1:]) for t in n )
...
| python dictionary problem | output of n is in the form:- ((6,5),'north',1)
I am making a dict child for it...in which (6,5) is the key and north and 1 are the values. I need to keep the (6,5) as the key and north as a direction....and I want to keep adding all the values till the while loop continues
| [
"If you want to keep all the key / value pairs in one dict (and all keys are distinct, of course):\ntotaldict = {}\n\nfor ...whatever your loop is...:\n ...\n totaldict.update(( t[0], t[1:]) for t in n )\n\nIf you want a list of dicts, @San's answer is good. If you want a single dict with not necessarily all d... | [
3,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0003274114_python.txt |
Q:
How do I force matplotlib to write out the full form of the x-axis label, avoiding scientific notation?
I've created a simple hexbin plot with matplotlib.pyplot. I haven't changed any default settings. My x-axis information ranges from 2003 to 2009, while the y values range from 15 to 35. Rather than writing out 2003, 2004, etc., matplotlib collapses it into 0, 1, 2, ... + 2.003e+03. Is there a simple way to force matplotlib to write out the full numbers?
Thanks,
Mark C.
A:
I think you can use the xticks function to set string labels:
nums = arange(2003, 2010)
xticks(nums, (str(n) for n in nums))
EDIT: This is a better way:
gca().xaxis.set_major_formatter(FormatStrFormatter('%d'))
or something like that, anyway. (In older versions of Matplotlib the method was called setMajorFormatter.)
| How do I force matplotlib to write out the full form of the x-axis label, avoiding scientific notation? | I've created a simple hexbin plot with matplotlib.pyplot. I haven't changed any default settings. My x-axis information ranges from 2003 to 2009, while the y values range from 15 to 35. Rather than writing out 2003, 2004, etc., matplotlib collapses it into 0, 1, 2, ... + 2.003e+03. Is there a simple way to force matplotlib to write out the full numbers?
Thanks,
Mark C.
| [
"I think you can use the xticks function to set string labels:\nnums = arange(2003, 2010)\nxticks(nums, (str(n) for n in nums))\n\nEDIT: This is a better way:\ngca().xaxis.set_major_formatter(FormatStrFormatter('%d'))\n\nor something like that, anyway. (In older versions of Matplotlib the method was called setMajor... | [
8
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0003274200_matplotlib_python.txt |
Q:
twisted callback function confusion
I'm working on a twisted tutorial just to learn more python and it seems I've ran into a road block here. The doRead() function below is the "callback" of a reactor. What I can't understand is how the except part works.
The way I read the code is that if bytes += self.sock.recv(1024) would've caused a block then it will reach the following part of the code:
if e.args[0] == errno.EWOULDBLOCK:
break
Then it would've continued to the following:
if not bytes:
print 'Task %d finished' % self.task_num
return main.CONNECTION_DONE
else:
msg = 'Task %d: got %d bytes of poetry from %s'
print msg % (self.task_num, len(bytes), self.format_addr())
The tricky part for me is that if it blocked, then bytes variable would've contained nothing and would've printed "finish" but it doesn't. Or at least it would've printed something like "got 0 bytes" but it also doesn't. It almost seems to me like when the code encounters a block from the recv call, it skips the above part completely. Can someone explain why this is happening?
Output is something like this:
Task 1: got 30 bytes of poetry from 127.0.0.1:10000
Task 3: got 10 bytes of poetry from 127.0.0.1:10002
Task 1: got 30 bytes of poetry from 127.0.0.1:10000
Task 3: got 10 bytes of poetry from 127.0.0.1:10002
Task 1: got 30 bytes of poetry from 127.0.0.1:10000
Task 3: got 3 bytes of poetry from 127.0.0.1:10002
Task 1: got 30 bytes of poetry from 127.0.0.1:10000
This is the whole function:
def doRead(self):
bytes = ''
while True:
try:
bytes += self.sock.recv(1024)
if not bytes:
break
except socket.error, e: # I don't understand this part
if e.args[0] == errno.EWOULDBLOCK:
break
return main.CONNECTION_LOST
if not bytes:
print 'Task %d finished' % self.task_num
return main.CONNECTION_DONE
else:
msg = 'Task %d: got %d bytes of poetry from %s'
print msg % (self.task_num, len(bytes), self.format_addr())
self.poem += bytes
The whole module is pasted here: http://pastebin.com/bUnXgbCA
A:
The point is that method doRead gets called only when the socket is "ready for reading": either it has some data on it, or else it's all done (and then, reading will return 0). So the solution to your problem cannot be in the doRead function -- it's all in the code calling it only when appropriate.
That code is all in the Twisted "reactor", to which the instance of PoetrySocket adds itself in __init__ (via the reactor's addReader method). If you want to understand twisted's mechanisms in real unalloyed depth, you seem to be at the right place, by the way (net of studying twisted's sources themselves, of course;-).
| twisted callback function confusion | I'm working on a twisted tutorial just to learn more python and it seems I've ran into a road block here. The doRead() function below is the "callback" of a reactor. What I can't understand is how the except part works.
The way I read the code is that if bytes += self.sock.recv(1024) would've caused a block then it will reach the following part of the code:
if e.args[0] == errno.EWOULDBLOCK:
break
Then it would've continued to the following:
if not bytes:
print 'Task %d finished' % self.task_num
return main.CONNECTION_DONE
else:
msg = 'Task %d: got %d bytes of poetry from %s'
print msg % (self.task_num, len(bytes), self.format_addr())
The tricky part for me is that if it blocked, then bytes variable would've contained nothing and would've printed "finish" but it doesn't. Or at least it would've printed something like "got 0 bytes" but it also doesn't. It almost seems to me like when the code encounters a block from the recv call, it skips the above part completely. Can someone explain why this is happening?
Output is something like this:
Task 1: got 30 bytes of poetry from 127.0.0.1:10000
Task 3: got 10 bytes of poetry from 127.0.0.1:10002
Task 1: got 30 bytes of poetry from 127.0.0.1:10000
Task 3: got 10 bytes of poetry from 127.0.0.1:10002
Task 1: got 30 bytes of poetry from 127.0.0.1:10000
Task 3: got 3 bytes of poetry from 127.0.0.1:10002
Task 1: got 30 bytes of poetry from 127.0.0.1:10000
This is the whole function:
def doRead(self):
bytes = ''
while True:
try:
bytes += self.sock.recv(1024)
if not bytes:
break
except socket.error, e: # I don't understand this part
if e.args[0] == errno.EWOULDBLOCK:
break
return main.CONNECTION_LOST
if not bytes:
print 'Task %d finished' % self.task_num
return main.CONNECTION_DONE
else:
msg = 'Task %d: got %d bytes of poetry from %s'
print msg % (self.task_num, len(bytes), self.format_addr())
self.poem += bytes
The whole module is pasted here: http://pastebin.com/bUnXgbCA
| [
"The point is that method doRead gets called only when the socket is \"ready for reading\": either it has some data on it, or else it's all done (and then, reading will return 0). So the solution to your problem cannot be in the doRead function -- it's all in the code calling it only when appropriate.\nThat code i... | [
2
] | [] | [] | [
"python",
"twisted"
] | stackoverflow_0003274214_python_twisted.txt |
Q:
how to create one-to-many relevance on google-app-engine
like one forum has many topic ,
ths specific is : forum and topic has the same model :
class Geo(db.Model):
#self = db.SelfReferenceProperty()
title = db.StringProperty()
link = db.StringProperty()
updated = db.DateTimeProperty(auto_now =True)
author = db.ReferenceProperty(MyUser)
id = db.StringProperty()
entry_keys = db.ListProperty(db.Key)
summary = db.StringProperty(multiline=True)
point = db.StringProperty()
@property
def entry(self):
return [db.get(key) for key in self.entry_keys]
all they are a geo-rss format , i use ListProperty this place ,but ListProperty has max size ,
so i have to find other method,
so what i should do ,
thanks
A:
If you want a many-to-many relationship, @thethimble's suggestion is good. If you do want a many-to-one relationship, though, you could use a SelfReferenceProperty from forum to topic -- like any other ReferenceProperty, that, too, makes an implicit collection property on the referenced entity (the one, while the referencers are the many).
A:
This is actually a many-to-many relationship. A forum can have multiple topics. One topic can be associated with multiple forums.
Check out the many-to-many section in the Google App Engine documentation.
| how to create one-to-many relevance on google-app-engine | like one forum has many topic ,
ths specific is : forum and topic has the same model :
class Geo(db.Model):
#self = db.SelfReferenceProperty()
title = db.StringProperty()
link = db.StringProperty()
updated = db.DateTimeProperty(auto_now =True)
author = db.ReferenceProperty(MyUser)
id = db.StringProperty()
entry_keys = db.ListProperty(db.Key)
summary = db.StringProperty(multiline=True)
point = db.StringProperty()
@property
def entry(self):
return [db.get(key) for key in self.entry_keys]
all they are a geo-rss format , i use ListProperty this place ,but ListProperty has max size ,
so i have to find other method,
so what i should do ,
thanks
| [
"If you want a many-to-many relationship, @thethimble's suggestion is good. If you do want a many-to-one relationship, though, you could use a SelfReferenceProperty from forum to topic -- like any other ReferenceProperty, that, too, makes an implicit collection property on the referenced entity (the one, while the... | [
1,
0
] | [] | [] | [
"google_app_engine",
"listproperty",
"one_to_many",
"python"
] | stackoverflow_0003273973_google_app_engine_listproperty_one_to_many_python.txt |
Q:
binary16 in Python
The struct module is useful when you're trying to convert data to and from binary formats. However, recently I came across a file format specification that uses the binary16 floating point format. I looked through the Python documentation, but can't find anything that can convert to and from it. What would be the best way to convert this data to/from Python floats?
A:
You can do it roughly like you'd do it in C -- i.e., I think, roughly like this...:
def tofloat(b16):
sign = -1 if b16 & 0x8000 else +1
expo = ( b16 & 0x7C00 ) >> 10
prec = b16 & 0x03FF
if expo == 0:
return sign * (2.0 ** -24) * prec
elif expo == 0x1F:
return sign * float('inf')
prec |= 0x0400
return sign * (2.0 ** (expo - 25)) * prec
A:
This guy's blog post gives an implementation in both and python. He uses the struct module, then decodes it manually. It is not all that complicated a conversion.
A:
A quick Google search turned up http://packages.python.org/bigfloat/ which says it has a context for manipulation of binary16 floating-point numbers. I'm not familiar with the package myself, though, so I couldn't tell you anything about how to use it (at least, nothing more than you can read yourself in the documentation).
| binary16 in Python | The struct module is useful when you're trying to convert data to and from binary formats. However, recently I came across a file format specification that uses the binary16 floating point format. I looked through the Python documentation, but can't find anything that can convert to and from it. What would be the best way to convert this data to/from Python floats?
| [
"You can do it roughly like you'd do it in C -- i.e., I think, roughly like this...:\ndef tofloat(b16):\n sign = -1 if b16 & 0x8000 else +1\n expo = ( b16 & 0x7C00 ) >> 10\n prec = b16 & 0x03FF\n if expo == 0:\n return sign * (2.0 ** -24) * prec\n elif expo == 0x1F:\n return sign * float('inf')\n prec |... | [
4,
2,
1
] | [] | [] | [
"floating_point",
"format",
"packing",
"python",
"struct"
] | stackoverflow_0003274278_floating_point_format_packing_python_struct.txt |
Q:
How to make a class field [list] read-only in python?
i have self.some_field = [] in my class
Im enquiring is there a way to make this list read-only like a property?
A:
You need to make it, indeed, a property...: e.g., in __init__
self._some_field = []
and then later in the class's body:
@property
def some_field(self):
return self._some_field
Note that this does not make the list itself immutable: what will fail is an assignment like, say,
self.some_field = 'bah'
not the call of a mutator, like, say,
self.some_field.append('blah')
If you want to make the field immutable, it cannot be a list, by definition (since a list is a mutable sequence) -- it must be some other type of sequence (an immutable one) which you need to define for the purpose.
A:
If you mean the attribute, then make it a read-only property. If you mean the list itself, then use a tuple instead since they're immutable.
| How to make a class field [list] read-only in python? | i have self.some_field = [] in my class
Im enquiring is there a way to make this list read-only like a property?
| [
"You need to make it, indeed, a property...: e.g., in __init__\nself._some_field = []\n\nand then later in the class's body:\n@property\ndef some_field(self):\n return self._some_field\n\nNote that this does not make the list itself immutable: what will fail is an assignment like, say,\nself.some_field = 'bah'\n... | [
7,
1
] | [] | [] | [
"oop",
"python"
] | stackoverflow_0003274350_oop_python.txt |
Q:
design workflow/flowchart representation in python?
In my web application I have wizards with many next previous buttons and choices ( kind of flow chart with events and options ). Wizard do not run in one go, but may wait for external event, user come later or next day to carry on with that wizard. Currently I am manually writing code ( hard coded ) for each states of a wizard ( or a flow chart ) and running through it.
Now, as number of wizards grows, I would like to make it more object oriented, to make it
more easy to write new states and wizards.
How should I design my classes for different states and wizards ?
I am using python programming language. So, If there is reference implementation in python, It will be cool to look at.
A:
Looks like you want a Finite State Machine (AKA "FSM") -- if so, see here.
| design workflow/flowchart representation in python? | In my web application I have wizards with many next previous buttons and choices ( kind of flow chart with events and options ). Wizard do not run in one go, but may wait for external event, user come later or next day to carry on with that wizard. Currently I am manually writing code ( hard coded ) for each states of a wizard ( or a flow chart ) and running through it.
Now, as number of wizards grows, I would like to make it more object oriented, to make it
more easy to write new states and wizards.
How should I design my classes for different states and wizards ?
I am using python programming language. So, If there is reference implementation in python, It will be cool to look at.
| [
"Looks like you want a Finite State Machine (AKA \"FSM\") -- if so, see here.\n"
] | [
1
] | [] | [] | [
"class_design",
"flowchart",
"oop",
"python",
"workflow"
] | stackoverflow_0003274403_class_design_flowchart_oop_python_workflow.txt |
Q:
How do I do this with Django objects.filter?
MYTable.objects.filter( where id = 42, 55, 65, and 55)
and it returns a query set ?
A:
MYTable.objects.filter( id__in = [42,55,65,55] )
| How do I do this with Django objects.filter? | MYTable.objects.filter( where id = 42, 55, 65, and 55)
and it returns a query set ?
| [
"MYTable.objects.filter( id__in = [42,55,65,55] )\n\n"
] | [
12
] | [] | [] | [
"database",
"django",
"mysql",
"python"
] | stackoverflow_0003274492_database_django_mysql_python.txt |
Q:
Python: defining a union of regular expressions
I have a list of patterns like
list_patterns = [': error:', ': warning:', 'cc1plus:', 'undefine reference to']
what I want to do is to produce a union of all of them yielding a regular expression that matches every element in list_patterns [but presumably does not match any re not in list_patterns -- msw]
re.compile(list_patterns)
Is this possible?
A:
There are a couple of ways of doing this. The simplest is:
list_patterns = [': error:', ': warning:', 'cc1plus:', 'undefine reference to']
string = 'there is an : error: and a cc1plus: in this string'
print re.findall('|'.join(list_patterns), string)
Output:
[': error:', 'cc1plus:']
which is fine as long as concatenating your search patterns doesn't break the regex (eg if one of them contains a regex special character like an opening parenthesis). You can handle that this way:
list_patterns = [': error:', ': warning:', 'cc1plus:', 'undefine reference to']
string = 'there is an : error: and a cc1plus: in this string'
pattern = "|".join(re.escape(p) for p in list_patterns)
print re.findall(pattern, string)
Output is the same. But what this does is pass each pattern through re.escape() to escape any regex special characters.
Now which one you use depends on your list of patterns. Are they regular expressions and can thus be assumed to be valid? If so, the first would probably be appropriate. If they are strings, use the second method.
For the first, it gets more complicated however because by concatenating several regular expressions you may change the grouping and have other unintended side effects.
A:
list_regexs = [re.compile(x) for x in list_patterns]
A:
How about
ptrn = re.compile('|'.join(re.escape(e) for e in list_patterns))
Note the use of re.escape() to avoid unintended consequences by presence of characters like ()[]|.+* etc in some of the strings. Assuming you want that, otherwise skip the escape().
It also depends how do you intend to 'consume' that expression - is it only for search of a match or would you like to collect the matching groups back?
A:
You want a pattern that matches any item in the list? Wouldn't that just be:
': error:|: warning:|cc1plus:|undefine reference to'?
Or, in Python code:
re.compile("|".join(list_patterns))
A:
Cletus gave a very good answer. If however one of the strings to match could be a substring of another, then you would to reverse sort the strings first so that shortest matches do not obscure longer ones.
If, as Alex has noted, the original poster wanted what he actually asked for, then a more tractable solution than using permutations might be to:
Remove any duplicates in list_patterns. (It could be better off starting with a set then turning it into a reverse-sorted list without duplicates).
re.escape() the items of the list.
Surround each item in individually a group (... ).
'|'.join() all the groups.
Find the set of the indices of all groups that matched, and compare its length with len(list_patterns).
If there is at least one match for every entry in your original list of strings, then the length of the set should match.
The code would be something like:
import re
def usedgroupindex(indexabledata):
for i,datum in enumerate(indexabledata):
if datum: return i
# return None
def findallstrings(list_patterns, string):
lp = sorted(set(list_patterns), reverse=True)
pattern = "|".join("(%s)" % re.escape(p) for p in lp)
# for m in re.findall(pattern, string): print (m, usedgroupindex(m))
return ( len(set(usedgroupindex(m) for m in re.findall(pattern, string)))
== len(lp) )
list_patterns = [': error:', ': warning:', 'cc1plus:', 'undefine reference to']
string = ' XZX '.join(list_patterns)
print ( findallstrings(list_patterns, string) )
A:
a regular expression that matches
every element in the list
I see you've already got several answers based on the assumption that by "matches every element in the list" you actually meant "matches any element in the list" (the answers in questions are based on the | "or" operator of regular expressions).
If you actually do want a RE to match every element of the list (as opposed to any single such element), then you might want to match them either in the same order as the list gives them (easy), or, in any order whatever (hard).
For in-order matching, '.*?'.join(list_patterns) should serve you well (if the items are indeed to be taken as RE patterns - if they're to be taken as literal strings instead, '.*?'.join(re.escape(p) for p list_patterns)).
For any-order matching, regular expressions, per se, offer no direct support. You could take all permutations of the list (e.g. with itertools.permutations), join up each of them with '.*?', and join the whole with | -- but that can produce a terribly long RE pattern as a result, because the number of permutations of N items is N! ("N factorial" -- for example, for N equal 4, the permutations are 4 * 3 * 2 * 1 == 24). Performance may therefore easily suffer unless the number of items in the list is known to be very, very small.
For a more general solution to the "match every item in arbitrary order" problem (if that's what you need), one with a performance and memory footprint that's still acceptable for decently large lengths of list, you need to give up on the target of making it all work with a single RE object, and inject some logic in the mix -- for example, make a list of RE objects with relist=[re.compile(p) for p in list_patterns], and check "they all match string s, in any order" with all(r.search(s) for r in relist) or the like.
Of course, if you need to make this latest approach work in a "duck-typing compatible way" with actual RE objects, that's not hard, e.g., if all you need is a search method which returns a boolean result (since returning a "match object" would make no sense)...:
class relike(object):
def __init__(self, list_patterns):
self.relist = [re.compile(p) for p in list_patterns]
def search(self, s):
return all(r.search(s) for r in relist)
| Python: defining a union of regular expressions | I have a list of patterns like
list_patterns = [': error:', ': warning:', 'cc1plus:', 'undefine reference to']
what I want to do is to produce a union of all of them yielding a regular expression that matches every element in list_patterns [but presumably does not match any re not in list_patterns -- msw]
re.compile(list_patterns)
Is this possible?
| [
"There are a couple of ways of doing this. The simplest is:\nlist_patterns = [': error:', ': warning:', 'cc1plus:', 'undefine reference to']\nstring = 'there is an : error: and a cc1plus: in this string'\nprint re.findall('|'.join(list_patterns), string)\n\nOutput:\n[': error:', 'cc1plus:']\n\nwhich is fine as long... | [
12,
3,
2,
1,
1,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0003274027_python_regex.txt |
Q:
how to combine exponents? (x**a)**b => x**(a*b)?
how to simplify exponents in equations in sympy
from sympy import symbols
a,b,c,d,e,f=symbols('abcdef')
j=(a**b**5)**(b**10)
print j
(a**(b**5))**(b**10) #ans even after using expand simplify
# desired output
a**(b**15)
and if it is not possible with sympy which module should i import in python?
edit
even if i define 'b' as real,and also all other symbols
b=symbols('b',real=True)
not getting simplified exponents
it simplifies only if exponents are constants
a=symbols('a',real=True)
b=symbols('b',real=True)
(a**5)**10
a**50 #simplifies only if exp are numbers
(a**b**5)**b**10
(a**(b**5))**b**10 #no simplification
A:
(xm)n = xmn is true only if m, n are real.
>>> import math
>>> x = math.e
>>> m = 2j*math.pi
>>> (x**m)**m # (e^(2πi))^(2πi) = 1^(2πi) = 1
(1.0000000000000016+0j)
>>> x**(m*m) # e^(2πi×2πi) = e^(-4π²) ≠ 1
(7.157165835186074e-18-0j)
AFAIK, sympy supports complex numbers, so I believe this simplification should not be done unless you can prove b is real.
Edit: It is also false if x is not positive.
>>> x = -2
>>> m = 2
>>> n = 0.5
>>> (x**m)**n
2.0
>>> x**(m*n)
-2.0
Edit(by gnibbler): Here is the original example with Kenny's restrictions applied
>>> from sympy import symbols
>>> a,b=symbols('ab', real=True, positive=True)
>>> j=(a**b**5)**(b**10)
>>> print j
a**(b**15)
A:
a,b,c=symbols('abc',real=True,positive=True)
(a**b**5)**b**10
a**(b**15)#ans
A:
This may be related to this bug.
| how to combine exponents? (x**a)**b => x**(a*b)? | how to simplify exponents in equations in sympy
from sympy import symbols
a,b,c,d,e,f=symbols('abcdef')
j=(a**b**5)**(b**10)
print j
(a**(b**5))**(b**10) #ans even after using expand simplify
# desired output
a**(b**15)
and if it is not possible with sympy which module should i import in python?
edit
even if i define 'b' as real,and also all other symbols
b=symbols('b',real=True)
not getting simplified exponents
it simplifies only if exponents are constants
a=symbols('a',real=True)
b=symbols('b',real=True)
(a**5)**10
a**50 #simplifies only if exp are numbers
(a**b**5)**b**10
(a**(b**5))**b**10 #no simplification
| [
"(xm)n = xmn is true only if m, n are real.\n>>> import math\n>>> x = math.e\n>>> m = 2j*math.pi\n>>> (x**m)**m # (e^(2πi))^(2πi) = 1^(2πi) = 1\n(1.0000000000000016+0j)\n>>> x**(m*m) # e^(2πi×2πi) = e^(-4π²) ≠ 1\n(7.157165835186074e-18-0j)\n\nAFAIK, sympy supports complex numbers, so I believe this simpl... | [
7,
2,
0
] | [] | [] | [
"exponent",
"python",
"simplify",
"sympy"
] | stackoverflow_0003274487_exponent_python_simplify_sympy.txt |
Q:
problem in dictionary python
I made a dictionary, then split up the values and keys into lists and now its looks like this:
keys = [(4,5),(5,6),(4,8)......so on].
values = [('west',1),('south',1).......]
Then I made a new dictionary like in this way,
final = dict((k,v[0]) for k,v in zip(keys, values))
When I execute -print final - output is in this form... {(4,5):west,(5,6):south,......so on}
Now i need to have the value of key (4,5)...it can be any key..
q:2
win = gap.pop() - here gap is a stack
print win - the output is (1,1)
return final.get(win) -
but when I do this return, it gives me an error and final is the directory that I have made with lists of keys and values
The error is: 'W'
A:
Works for me:
>>> keys=[(4,5),(5,6)]
>>> values = ["west","south"]
>>> f=dict(zip(keys,values))
>>> f
{(4, 5): 'west', (5, 6): 'south'}
>>> f[(4,5)]
'west'
A:
Works for me:
>>> final = {(4,5):"West", (5,6): "East"}
>>> print final
{(4, 5): 'West', (5, 6): 'East'}
>>> final[(4,5)]
'West'
You might want to try final.get((4,5)).
Or post more code, maybe you do something fancy with final. If you don't get a value back, you should at least get a KeyError:
>>> final[(7,8)]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: (7, 8)
In this case you either have to handle the exception:
try:
final[(7,8)]
except KeyError:
print "Key not in dict."
or use final.get((7,8), <default value>) which will return <default value> if the key is not found (or None if you don't specify a default value).
Read about dictionaries in the Python documentation.
| problem in dictionary python | I made a dictionary, then split up the values and keys into lists and now its looks like this:
keys = [(4,5),(5,6),(4,8)......so on].
values = [('west',1),('south',1).......]
Then I made a new dictionary like in this way,
final = dict((k,v[0]) for k,v in zip(keys, values))
When I execute -print final - output is in this form... {(4,5):west,(5,6):south,......so on}
Now i need to have the value of key (4,5)...it can be any key..
q:2
win = gap.pop() - here gap is a stack
print win - the output is (1,1)
return final.get(win) -
but when I do this return, it gives me an error and final is the directory that I have made with lists of keys and values
The error is: 'W'
| [
"Works for me:\n>>> keys=[(4,5),(5,6)]\n>>> values = [\"west\",\"south\"]\n>>> f=dict(zip(keys,values))\n>>> f\n{(4, 5): 'west', (5, 6): 'south'}\n>>> f[(4,5)]\n'west'\n\n",
"Works for me:\n>>> final = {(4,5):\"West\", (5,6): \"East\"}\n>>> print final\n{(4, 5): 'West', (5, 6): 'East'}\n>>> final[(4,5)]\n'West'\n... | [
2,
2
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0003274762_dictionary_python.txt |
Q:
Error in executing python code- dictionary problem
while stack.isEmpty() != 1:
fin = stack.pop()
print fin - output is (1,1)
k = final.get(fin)
return k
def directionToVector(direction, speed = 1.0):
dx, dy = Actions._directions[direction]
return (dx * speed, dy * speed)
directionToVector = staticmethod(directionToVector)
but when I do this return, it gives me an error and final is the directory that I have made with lists of keys and values
The error is:
File "line 212, in directionToVector
dx, dy = Actions._directions[direction]
KeyError: 'W'
A:
Actions._directions is presumably a dictionary, so the line:
dx, dy = Actions._directions[direction]
at runtime (based on the error message) is:
dx, dy = Actions._directions["W"]
and it's complaining that there's no key "W" in that dictionary. So you should check to see that you've actually added that key with some value in there. Alternatively, you can do something like:
dx, dy = Actions._directions.get(direction, (0, 0))
where (0, 0) can be any default value you choose when there's no such key. Another possibility is to handle the error explicitly:
try:
dx, dy = Actions._directions[direction]
except KeyError:
# handle the error for missing key
A:
This error
KeyError: 'W'
means that the key you requested ('W') is not one of the keys that are stored in the dictionary. This is because your dictionary key is 'west' not 'W' (see your previous question). Try this instead:
key = { 'N' : 'north', 'S' : 'south', 'E' : 'east', 'W' : 'west' }[direction]
dx, dy = Actions._directions[key]
Alternatively, make sure you pass the string 'west' to directionToVector and not the string 'W'.
| Error in executing python code- dictionary problem | while stack.isEmpty() != 1:
fin = stack.pop()
print fin - output is (1,1)
k = final.get(fin)
return k
def directionToVector(direction, speed = 1.0):
dx, dy = Actions._directions[direction]
return (dx * speed, dy * speed)
directionToVector = staticmethod(directionToVector)
but when I do this return, it gives me an error and final is the directory that I have made with lists of keys and values
The error is:
File "line 212, in directionToVector
dx, dy = Actions._directions[direction]
KeyError: 'W'
| [
"Actions._directions is presumably a dictionary, so the line:\ndx, dy = Actions._directions[direction]\n\nat runtime (based on the error message) is:\ndx, dy = Actions._directions[\"W\"]\n\nand it's complaining that there's no key \"W\" in that dictionary. So you should check to see that you've actually added th... | [
1,
0
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0003274889_dictionary_python.txt |
Q:
How can I define a string in a python function?
I'm playing with Python and Google App Engine for the first time but am unable to define a string within my function (mytest2), I get an indentation error on the line after the declaration. I can define one in the parameters that works (test) but can't see why I wouldn't be able to do it in the function aswell.
I've read a few tutorials without gaining enlightenment. Can anyone let me know what I've got wrong here?
I'm also wondering how I could do this by having something like mytest1 defined in the class and then accessible within the function?
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
class MainPage(webapp.RequestHandler):
#mytest1 = "test1"
#Runtime failure on this line talking about an indent issue
def get(self, test = 'testing!'):
mytest2= "test2" #Runtime failure on this line talking about an indent issue
self.response.headers['Content-Type'] = 'text/plain'
self.response.out.write('Hello, webapp World!\n')
self.response.out.write(self)
#self.response.out.write('\n' + mytest1)
self.response.out.write('\n' + mytest2)
application = webapp.WSGIApplication(
[('/', MainPage)],
debug=True)
def main():
run_wsgi_app(application)
if __name__ == "__main__":
main()
A:
Never mix tabs and spaces in python!
Generally accepted practice is to use 4 spaces for indentation. This is written in PEP 8 , the python style guide. I strongly recommmend reading it.
I usually set my editor to replace tabs with 4 spaces, every decent text editor supports this.
The reason why tabs are a problem in your example is that they are replaced by up to 8 spaces and your indentation is mostly 4 spaces (Python documentation)
| How can I define a string in a python function? | I'm playing with Python and Google App Engine for the first time but am unable to define a string within my function (mytest2), I get an indentation error on the line after the declaration. I can define one in the parameters that works (test) but can't see why I wouldn't be able to do it in the function aswell.
I've read a few tutorials without gaining enlightenment. Can anyone let me know what I've got wrong here?
I'm also wondering how I could do this by having something like mytest1 defined in the class and then accessible within the function?
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
class MainPage(webapp.RequestHandler):
#mytest1 = "test1"
#Runtime failure on this line talking about an indent issue
def get(self, test = 'testing!'):
mytest2= "test2" #Runtime failure on this line talking about an indent issue
self.response.headers['Content-Type'] = 'text/plain'
self.response.out.write('Hello, webapp World!\n')
self.response.out.write(self)
#self.response.out.write('\n' + mytest1)
self.response.out.write('\n' + mytest2)
application = webapp.WSGIApplication(
[('/', MainPage)],
debug=True)
def main():
run_wsgi_app(application)
if __name__ == "__main__":
main()
| [
"Never mix tabs and spaces in python!\nGenerally accepted practice is to use 4 spaces for indentation. This is written in PEP 8 , the python style guide. I strongly recommmend reading it.\nI usually set my editor to replace tabs with 4 spaces, every decent text editor supports this.\nThe reason why tabs are a probl... | [
2
] | [] | [] | [
"google_app_engine",
"indentation",
"python",
"syntax_error"
] | stackoverflow_0003274873_google_app_engine_indentation_python_syntax_error.txt |
Q:
SimpleXmlRpcServer _sock.rcv freezes after thousands of requests
I'm serving requests from several XMLRPC clients over WAN. The thing works great for, let's say, a period of one day (sometimes two), then freezes in socket.py:
data = self._sock.recv(self._rbufsize)
_sock.timeout is -1, _sock.gettimeout is None
There is nothing special I do in the main thread (just receiving XMLRPC calls), there are another two threads talking to DB. Both these threads work fine and survive this block (did a check with WinPdb). Clients are sending requests not being longer than 1KB, and there isn't any special content: just nice and clean strings in dictionary. Between two blockings I serve tens of thousands requests without problems.
Firewall is off, no strange software on the same machine, etc...
I use Windows XP and Python 2.6.4. I've checked differences between 2.6.4. and 2.6.5, and didn't find anything important (or am I mistaking?). 2.7 version is not an option as I would miss binaries for MySqlDB.
The only thing that happens from time to time caused by the clients that have poor internet connection is that sockets break. This is happening, every 5-10 minutes (there are just five clients accessing server every 2 seconds).
I've spent great deal of time on this issue, now I'm beginning to lose any ideas what to do. Any hint or thought would be highly appreciated.
A:
What exactly is happening in your OS's TCP/IP stack (possibly in the python layers on top, but that's less likely) to cause this is a mystery. As a practical workaround, I'd set a timeout longer than the delays you expect between requests (10 seconds should be plenty if you expect a request every 2 seconds) and if one occurs, close and reopen. (Calibrate the delay needed to work around freezes without interrupting normal traffic by trial and error). Unpleasant to hack a fix w/o understanding the problem, I know, but being pragmatical about such things is a necessary survival trait in the world of writing, deploying and operating actual server systems. Be sure to comment the workaround accurately for future maintainers!
A:
thanks so much for the fast response. Right after I've receive it I augmented the timeout to 10 seconds. Now it is all running without problems, but of course I would need to wait another day or two to have sort of confirmation, but only after 5 days I'll be sure and will come back with the results. I see now that 140K request went well already, having so hard experience on this one I would wait at least another 200K.
What you were proposing about auto adaptation of timeouts (without putting the system down) sounds also reasonable. Would the right way to go be in creating a small class (e.g. AutoTimeoutCalibrator) and embedding it directly into serial.py?
Yes - being pragmatical is the only way without loosing another 10 days trying to figure out the real reason behind.
Thanks again, I'll be back with the results.
(sorry, but for some reason I was not able to post it as a reply to your post)
| SimpleXmlRpcServer _sock.rcv freezes after thousands of requests | I'm serving requests from several XMLRPC clients over WAN. The thing works great for, let's say, a period of one day (sometimes two), then freezes in socket.py:
data = self._sock.recv(self._rbufsize)
_sock.timeout is -1, _sock.gettimeout is None
There is nothing special I do in the main thread (just receiving XMLRPC calls), there are another two threads talking to DB. Both these threads work fine and survive this block (did a check with WinPdb). Clients are sending requests not being longer than 1KB, and there isn't any special content: just nice and clean strings in dictionary. Between two blockings I serve tens of thousands requests without problems.
Firewall is off, no strange software on the same machine, etc...
I use Windows XP and Python 2.6.4. I've checked differences between 2.6.4. and 2.6.5, and didn't find anything important (or am I mistaking?). 2.7 version is not an option as I would miss binaries for MySqlDB.
The only thing that happens from time to time caused by the clients that have poor internet connection is that sockets break. This is happening, every 5-10 minutes (there are just five clients accessing server every 2 seconds).
I've spent great deal of time on this issue, now I'm beginning to lose any ideas what to do. Any hint or thought would be highly appreciated.
| [
"What exactly is happening in your OS's TCP/IP stack (possibly in the python layers on top, but that's less likely) to cause this is a mystery. As a practical workaround, I'd set a timeout longer than the delays you expect between requests (10 seconds should be plenty if you expect a request every 2 seconds) and i... | [
1,
0
] | [] | [] | [
"python",
"recv",
"simplexmlrpcserver"
] | stackoverflow_0003271966_python_recv_simplexmlrpcserver.txt |
Q:
Is there an equivalent to python's urllib in c/c++?
any c/c++ library out there that provides functions like getUrl, urlopen, post etc. ?
A:
There are some libraries, libcurl and libwww amongst others.
libcurl website even lists some other alternatives.
A:
Not a batteries-included, officially endorsed library, but there are numerous libraries out there. The most popular, AFAIK, is libCURL, which I've used to good effect in the past. It has an "easy" interface, which really is easy to use (though definitely not as easy as Python's urllib).
| Is there an equivalent to python's urllib in c/c++? | any c/c++ library out there that provides functions like getUrl, urlopen, post etc. ?
| [
"There are some libraries, libcurl and libwww amongst others.\nlibcurl website even lists some other alternatives.\n",
"Not a batteries-included, officially endorsed library, but there are numerous libraries out there. The most popular, AFAIK, is libCURL, which I've used to good effect in the past. It has an \"ea... | [
7,
1
] | [] | [] | [
"c++",
"python",
"url"
] | stackoverflow_0003275252_c++_python_url.txt |
Q:
What is happening in this Python program?
I'd like to know what is getting assigned to what in line 8.
# Iterators
class Fibs:
def __init__(self):
self.a = 0
self.b = 1
def next(self):
self.a, self.b = self.b, self.a+self.b # <--- here
return self.a
def __iter__(self):
return self
fibs = Fibs()
for f in fibs:
if f > 1000:
print f
break
The rest of the program I really don't need much explanation. I'm not sure what's getting assigned to what.
A:
It's a multiple assignment roughly equivalent to this:
tmp = self.a
self.a = self.b
self.b = tmp + self.b
Or this pseudo-code:
a' = b
b' = a + b
As you can see the multiple assignment is much more concise than separate assignments and more closely resembles the pseudo-code example.
Almost that example is given in the Python documentation as an example of calculating Fibonacci numbers. One of the advantages of the multiple assignment is that the variables on the right hand side are evaluated before any of the assignments take place, saving the need for the temporary variable in this case.
A:
It's a pair assignment, a shorthand of
t = self.a
self.a = self.b
self.b = t+self.b
just to use an one-liner instead that two assignments.. to be precise i think that the left operand of the assignment is considered a tuple of two elements, so you are like assigning to tuple (self.a, self,b) the value (self.b, self.a+self.b) which does the same thing as the three separate assignments written before without the need of a temporary variable. This because, while without using tuple the assignments are executed sequentially, in your example they are resolved at the same time, preserving the value of self.a in second assignment.
As stated in documentation:
Assignment of an object to a target list is recursively defined as follows.
If the target list is a single target: The object is assigned to that target.
If the target list is a comma-separated list of targets (your case): The object must be an iterable with the same number of items as there are targets in the target list, and the items are assigned, from left to right, to the corresponding targets. (This rule is relaxed as of Python 1.5; in earlier versions, the object had to be a tuple. Since strings are sequences, an assignment like a, b = "xy" is now legal as long as the string has the right length.)
A:
Without looking at the surrounding code, I'd say it's the heart of an algorithm for computing Fibonacci numbers.
It translates to the equivalent of:
a = b
b = a + b
...thereby computing the next number(s) in the sequence.
If you look at a sequence of numbers like
1 1 2 3 5 8 13 21 ...
and you let a and b be the last two numbers, then afterwards you'll have the next number in b and the former last number (b) in a.
The reason to use that strange notation is so as to accomplish both assignments at the same time. If they were done sequentially as in the 2 lines above, the value of a would be clobbered in the first line and you'd just be doubling b in the 2nd line.
A:
Be aware that a paired assignment is not a "special feature" of Python. If you know a bit about Python, it's something you already know about but you may not know you know. When you put the following into the python console:
>>> 'a', 'b'
What you get in return is:
('a', 'b')
In other words, a tuple. In your example,
self.a, self.b = self.b, self.a+self.b
what you're really doing is:
(self.a, self.b) = (self.b, self.a+self.b)
Create a tuple that contains the value of self.b and the value of self.a+self.b. (The tuple on the right.)
Create a tuple that contains self.a and self.b. (The left-hand tuple.)
In order to create that left-hand tuple, create a new instance of self.a and self.b for that new tuple. Their old values don't matter anymore: they're in the temporary right-hand tuple.
Assign value 0 of the left tuple variable to value 0 of the right tuple.
Assign value 1 of the left tuple variable to value 1 of the right tuple.
Now that both variables of the left tuple are assigned, delete both tuples. The new variables remain with their new values.
So, for example, you can do:
>>> a, b = 1, 2
>>> a, b
(1, 2)
>>> a, b = b, a
>>> a, b
(2, 1)
There are still temporary variables involved under the hood, but you, the programmer, don't have to deal with them.
| What is happening in this Python program? | I'd like to know what is getting assigned to what in line 8.
# Iterators
class Fibs:
def __init__(self):
self.a = 0
self.b = 1
def next(self):
self.a, self.b = self.b, self.a+self.b # <--- here
return self.a
def __iter__(self):
return self
fibs = Fibs()
for f in fibs:
if f > 1000:
print f
break
The rest of the program I really don't need much explanation. I'm not sure what's getting assigned to what.
| [
"It's a multiple assignment roughly equivalent to this:\ntmp = self.a\nself.a = self.b\nself.b = tmp + self.b\n\nOr this pseudo-code:\n\na' = b\nb' = a + b\n\nAs you can see the multiple assignment is much more concise than separate assignments and more closely resembles the pseudo-code example.\nAlmost that exampl... | [
8,
7,
3,
0
] | [] | [] | [
"iterator",
"python",
"variable_assignment"
] | stackoverflow_0003273092_iterator_python_variable_assignment.txt |
Q:
Compiling .go in Windows ... & Can python connect to Go?
i know that go language does not support windows yet, now, how can i compile .go file is windows ?
and can python connect to go ?
like connecting c++ or java to python ... lol
A:
While the Go language implementation for Windows is still experimental, it's steadily improving. An updated binary version is published regularly: Win32 build of Go.
| Compiling .go in Windows ... & Can python connect to Go? | i know that go language does not support windows yet, now, how can i compile .go file is windows ?
and can python connect to go ?
like connecting c++ or java to python ... lol
| [
"While the Go language implementation for Windows is still experimental, it's steadily improving. An updated binary version is published regularly: Win32 build of Go.\n"
] | [
4
] | [] | [] | [
"go",
"python",
"windows"
] | stackoverflow_0003275255_go_python_windows.txt |
Q:
How to write a twisted server that is also a client?
How do I create a twisted server that's also a client?
I want the reactor to listen while at the same time it can also be use to connect to the same server instance which can also connect and listen.
A:
Call reactor.listenTCP and reactor.connectTCP. You can have as many different kinds of connections - servers or clients - as you want.
For example:
from twisted.internet import protocol, reactor
from twisted.protocols import basic
class SomeServerProtocol(basic.LineReceiver):
def lineReceived(self, line):
host, port = line.split()
port = int(port)
factory = protocol.ClientFactory()
factory.protocol = SomeClientProtocol
reactor.connectTCP(host, port, factory)
class SomeClientProtocol(basic.LineReceiver):
def connectionMade(self):
self.sendLine("Hello!")
self.transport.loseConnection()
def main():
import sys
from twisted.python import log
log.startLogging(sys.stdout)
factory = protocol.ServerFactory()
factory.protocol = SomeServerProtocol
reactor.listenTCP(12345, factory)
reactor.run()
if __name__ == '__main__':
main()
| How to write a twisted server that is also a client? | How do I create a twisted server that's also a client?
I want the reactor to listen while at the same time it can also be use to connect to the same server instance which can also connect and listen.
| [
"Call reactor.listenTCP and reactor.connectTCP. You can have as many different kinds of connections - servers or clients - as you want.\nFor example:\nfrom twisted.internet import protocol, reactor\nfrom twisted.protocols import basic\n\nclass SomeServerProtocol(basic.LineReceiver):\n def lineReceived(self, lin... | [
15
] | [] | [] | [
"python",
"twisted"
] | stackoverflow_0003275004_python_twisted.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.