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:
Can't import scriptext module in PyS60 2.0 on N95
When I try and import scriptext on PyS60 version 2.0 on my N95 phone, I get an import error saying that there is no module named scriptext.
How can I work out what the problem is?
A:
From:
http://pys60.garage.maemo.org/doc/s60/scriptext.html
Note: The service is available from
'S60 third edition FP2 and later'.
N95 is a 3rd edition FP1 device.
You can adapt your app at runtime according to the availability of this module by putting the import in a try..except block:
try:
import scriptext
except ImportError:
# Module could not be imported, tell the user to update to a newer device
# or continue without it if having scriptext is not crucial to your app.
| Can't import scriptext module in PyS60 2.0 on N95 | When I try and import scriptext on PyS60 version 2.0 on my N95 phone, I get an import error saying that there is no module named scriptext.
How can I work out what the problem is?
| [
"From:\nhttp://pys60.garage.maemo.org/doc/s60/scriptext.html\n\nNote: The service is available from\n 'S60 third edition FP2 and later'.\n\nN95 is a 3rd edition FP1 device.\nYou can adapt your app at runtime according to the availability of this module by putting the import in a try..except block:\ntry:\n impor... | [
1
] | [] | [] | [
"importerror",
"module",
"n95",
"pys60",
"python"
] | stackoverflow_0003092707_importerror_module_n95_pys60_python.txt |
Q:
Sort list of names in Python, ignoring numbers?
['7', 'Google', '100T', 'Chrome', '10', 'Python']
I'd like the result to be all numbers at the end and the rest sorted. The numbers need not be sorted.
Chrome
Google
Python
100T
7
10
It's slightly more complicated though, because I sort a dictionary by value.
def sortname(k): return get[k]['NAME']
sortedbyname = sorted(get,key=sortname)
I only added 100T after both answers were posted already, but the accepted answer still works with a slight modification I posted in a comment. To clarify, a name matching ^[^0-9] should be sorted.
A:
I've been struggling to get a dictionary version working, so here's the array version for you to extrapolate from:
def sortkey(x):
try:
return (1, int(x))
except:
return (0, x)
sorted(get, key=sortkey)
The basic principle is to create a tuple who's first element has the effect of grouping all strings together then all ints. Unfortunately, there's no elegant way to confirm whether a string happens to be an int without using exceptions, which doesn't go so well inside a lambda. My original solution used a regex, but since moving from a lambda to a stand-alone function, I figured I might as well go for the simple option.
A:
>>> l = ['7', 'Google', 'Chrome', '10', 'Python']
>>> sorted(l, key=lambda s: (s.isdigit(), s))
['Chrome', 'Google', 'Python', '10', '7']
Python's sort is stable, so you could also use multiple successive sorts:
>>> m = sorted(l)
>>> m.sort(key=str.isdigit)
>>> m
['Chrome', 'Google', 'Python', '10', '7']
| Sort list of names in Python, ignoring numbers? | ['7', 'Google', '100T', 'Chrome', '10', 'Python']
I'd like the result to be all numbers at the end and the rest sorted. The numbers need not be sorted.
Chrome
Google
Python
100T
7
10
It's slightly more complicated though, because I sort a dictionary by value.
def sortname(k): return get[k]['NAME']
sortedbyname = sorted(get,key=sortname)
I only added 100T after both answers were posted already, but the accepted answer still works with a slight modification I posted in a comment. To clarify, a name matching ^[^0-9] should be sorted.
| [
"I've been struggling to get a dictionary version working, so here's the array version for you to extrapolate from:\ndef sortkey(x):\n try:\n return (1, int(x))\n except:\n return (0, x)\n\nsorted(get, key=sortkey)\n\nThe basic principle is to create a tuple who's first element has the effect of... | [
3,
1
] | [] | [] | [
"dictionary",
"list",
"python",
"sorting"
] | stackoverflow_0004058455_dictionary_list_python_sorting.txt |
Q:
how to make a chat room on google app engine , has some demo ? and example?
has any app engine already do this ?
thanks
A:
Partychat an example of an XMPP-based chatroom running on App Engine. And it's open-source.
A:
AppEngine only supports HTTP and limits the response time (which makes Comet a no-go).
The only (supported) way is XMPP, but it only supports BOSH protocol, which does not facilitate push from server to clients.
It seems that your only way would be polling.
| how to make a chat room on google app engine , has some demo ? and example? | has any app engine already do this ?
thanks
| [
"Partychat an example of an XMPP-based chatroom running on App Engine. And it's open-source.\n",
"AppEngine only supports HTTP and limits the response time (which makes Comet a no-go).\nThe only (supported) way is XMPP, but it only supports BOSH protocol, which does not facilitate push from server to clients.\nI... | [
3,
1
] | [] | [] | [
"chatroom",
"google_app_engine",
"javascript",
"python"
] | stackoverflow_0004057942_chatroom_google_app_engine_javascript_python.txt |
Q:
Using colons in ConfigParser Python
According to the documentation:
The configuration file consists of
sections, led by a [section] header
and followed by name: value entries,
with continuations in the style of RFC
822 (see section 3.1.1, “LONG HEADER
FIELDS”); name=value is also accepted.
Python Docs
However, writing a config file always use the equal sign (=). Is there any option to use the colon sign (:)?
Thanks in advance.
H
A:
If you look at the code defining the RawConfigParser.write method inside ConfigParser.py you'll see that the equal signs are hard-coded. So to change the behavior you could subclass the ConfigParser you wish to use:
import ConfigParser
class MyConfigParser(ConfigParser.ConfigParser):
def write(self, fp):
"""Write an .ini-format representation of the configuration state."""
if self._defaults:
fp.write("[%s]\n" % DEFAULTSECT)
for (key, value) in self._defaults.items():
fp.write("%s : %s\n" % (key, str(value).replace('\n', '\n\t')))
fp.write("\n")
for section in self._sections:
fp.write("[%s]\n" % section)
for (key, value) in self._sections[section].items():
if key != "__name__":
fp.write("%s : %s\n" %
(key, str(value).replace('\n', '\n\t')))
fp.write("\n")
filename='/tmp/testconfig'
with open(filename,'w') as f:
parser=MyConfigParser()
parser.add_section('test')
parser.set('test','option','Spam spam spam!')
parser.set('test','more options',"Really? I can't believe it's not butter!")
parser.write(f)
yields:
[test]
more options : Really? I can't believe it's not butter!
option : Spam spam spam!
| Using colons in ConfigParser Python | According to the documentation:
The configuration file consists of
sections, led by a [section] header
and followed by name: value entries,
with continuations in the style of RFC
822 (see section 3.1.1, “LONG HEADER
FIELDS”); name=value is also accepted.
Python Docs
However, writing a config file always use the equal sign (=). Is there any option to use the colon sign (:)?
Thanks in advance.
H
| [
"If you look at the code defining the RawConfigParser.write method inside ConfigParser.py you'll see that the equal signs are hard-coded. So to change the behavior you could subclass the ConfigParser you wish to use:\nimport ConfigParser\nclass MyConfigParser(ConfigParser.ConfigParser):\n def write(self, fp):\n ... | [
7
] | [] | [] | [
"configuration",
"file",
"python"
] | stackoverflow_0004058400_configuration_file_python.txt |
Q:
opening a parent folder and highlighting particular child in default file browser using python
I am using following code to open a folder in default file browser.
if os.name == 'mac':
subprocess.call(('open', folderPath))
elif os.name == 'nt':
subprocess.call(('start', folderPath))
elif os.name == 'posix':
subprocess.call(('xdg-open', folderPath))
Now the problem is I want to highlight the child folder/file which was selected earlier. Is there any way to do it? If not for all, at least for nautilus?
A:
xdg-open doesn't support this, so it has to be done on a per-app basis. After poking around the Nautilus code, I don't think it has this feature either. So, yeah, you're pretty much out of luck.
For Windows Explorer, you can use
subprocess.call(("explorer", "/select,", file_path))
| opening a parent folder and highlighting particular child in default file browser using python | I am using following code to open a folder in default file browser.
if os.name == 'mac':
subprocess.call(('open', folderPath))
elif os.name == 'nt':
subprocess.call(('start', folderPath))
elif os.name == 'posix':
subprocess.call(('xdg-open', folderPath))
Now the problem is I want to highlight the child folder/file which was selected earlier. Is there any way to do it? If not for all, at least for nautilus?
| [
"xdg-open doesn't support this, so it has to be done on a per-app basis. After poking around the Nautilus code, I don't think it has this feature either. So, yeah, you're pretty much out of luck.\nFor Windows Explorer, you can use\nsubprocess.call((\"explorer\", \"/select,\", file_path))\n\n"
] | [
2
] | [] | [] | [
"directory",
"nautilus",
"python"
] | stackoverflow_0004030044_directory_nautilus_python.txt |
Q:
SQL Query that relies on COUNT from another table? - SQLAlchemy
I need a query that can return the records from table A that have greater than COUNT records in table B. The query needs to be able to go in line with other filters that might be applied on table A.
Example case study:
I have a person and appointments table. I am looking for all people who have been in for 5 or more appointments. It must also support extra filter statements on the person table, such as age > 18.
EDIT -- SOLUTION
subquery = db.session.query(Appointment.id_person,
func.count('*').label('person_count')) \
.group_by(Appointment.id_person).subquery()
qry = db.session.query(Person) \
.outerjoin((subquery, Person.id == subquery.c.id_person)) \
.order_by(Person.id).filter(subquery.c.person_count >= 5).filter(Person.dob <= '1992-10-29')
A:
Use a subquery:
SELECT * from person
WHERE PersonID IN
(SELECT PersonId FROM appointments
GROUP BY PersonId
HAVING COUNT(*) >= 5)
AND dob > 25
A:
SELECT Person.PersonID, Person.Name
FROM Person INNER JOIN Appointment
ON Person.PersonID = Appointment.PersonID
GROUP BY Person.PersonID, Person.Name
HAVING COUNT(Person.PersonID) >= 5
| SQL Query that relies on COUNT from another table? - SQLAlchemy | I need a query that can return the records from table A that have greater than COUNT records in table B. The query needs to be able to go in line with other filters that might be applied on table A.
Example case study:
I have a person and appointments table. I am looking for all people who have been in for 5 or more appointments. It must also support extra filter statements on the person table, such as age > 18.
EDIT -- SOLUTION
subquery = db.session.query(Appointment.id_person,
func.count('*').label('person_count')) \
.group_by(Appointment.id_person).subquery()
qry = db.session.query(Person) \
.outerjoin((subquery, Person.id == subquery.c.id_person)) \
.order_by(Person.id).filter(subquery.c.person_count >= 5).filter(Person.dob <= '1992-10-29')
| [
"Use a subquery:\nSELECT * from person\nWHERE PersonID IN \n (SELECT PersonId FROM appointments\n GROUP BY PersonId\n HAVING COUNT(*) >= 5)\nAND dob > 25\n\n",
"SELECT Person.PersonID, Person.Name\nFROM Person INNER JOIN Appointment\nON Person.PersonID = Appointment.PersonID\nGROUP BY Person.PersonID, Person... | [
1,
0
] | [] | [] | [
"python",
"sql",
"sqlalchemy"
] | stackoverflow_0004057223_python_sql_sqlalchemy.txt |
Q:
In Django's template engine, how do I display a datetime object in a meaningful way?
{{ p.date }}
is displayed as:
Date: 2010-10-29 21:56:39.226000
How do I make changes to how that's displayed?
A:
Using date filter, for eg : {{ study.created_date|date:"d/m/Y"}}
A:
With the date filter.
| In Django's template engine, how do I display a datetime object in a meaningful way? | {{ p.date }}
is displayed as:
Date: 2010-10-29 21:56:39.226000
How do I make changes to how that's displayed?
| [
"Using date filter, for eg : {{ study.created_date|date:\"d/m/Y\"}}\n",
"With the date filter.\n"
] | [
5,
1
] | [] | [] | [
"datetime",
"django",
"python",
"templates"
] | stackoverflow_0004056220_datetime_django_python_templates.txt |
Q:
best way for a c# developer to break into Tkinter?
I'm a full time c# developer, but I want to get more into Python. At the same time, I have a friend who will learn it with me, he however has no programming knowledge.
I was thinking about starting with some visual programming. I.E: having buttons, labels and text boxes on a form.
Does some kind of IDE exist which allows you to very quickly build a Tkinter app in Python, and compile run it for Windows?
In a nutshell I'm trying to find something with similar functionality to MS Visual Studio.
If not, would Iron Python running in VS be what I need to start with?
A:
Does some kind of IDE exist which allows you to very quickly build a Tkinter app in Python, and compile run it for Windows?
There's nothing similar to VisualStudio for building tkinter interfaces, although some visual designers do exist take a look at this question.
Keep in mind that a lot of professional python developers use nothing but a text editor even on huge codebases.
You don't have to compile your python programs in order to run them. The interpreter automagically compiles them to bytecode when you run them.
Now. I suggest you don't start with GUI programming in python just yet. But if you insist PyQT is much better than tkinter.
I'd probably start with a small RSS agregator, a small web page crawler that downloads all the images from a website with a CLI. Then move on to web and GUI apps.
| best way for a c# developer to break into Tkinter? | I'm a full time c# developer, but I want to get more into Python. At the same time, I have a friend who will learn it with me, he however has no programming knowledge.
I was thinking about starting with some visual programming. I.E: having buttons, labels and text boxes on a form.
Does some kind of IDE exist which allows you to very quickly build a Tkinter app in Python, and compile run it for Windows?
In a nutshell I'm trying to find something with similar functionality to MS Visual Studio.
If not, would Iron Python running in VS be what I need to start with?
| [
"\nDoes some kind of IDE exist which allows you to very quickly build a Tkinter app in Python, and compile run it for Windows?\n\nThere's nothing similar to VisualStudio for building tkinter interfaces, although some visual designers do exist take a look at this question.\nKeep in mind that a lot of professional py... | [
1
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0004058443_python_tkinter.txt |
Q:
Delayed loading of modules in python
I'm writing a python applet for data acquisition from scientific instruments and I'm trying to figure out the best way to manage my device "drivers".
Each driver is represented by a separate python module in the package that is my program. They each implement some standard interface, but mostly it's a gigantic list of commands (and function mappings) that are specific to each device and bus involved. In the long run, (I'm writing this for my lab group and am planning on supporting a few dozen or so devices) I want to avoid loading all of them in at once. Instead, at run-time, I want to read in a list of modules into a dictionary/list and then load them only when they are actually needed.
When the user wants to use a new device, he selects the driver to use, and passes the name along to the driver subsystem which then checks to see if that driver is in the list of loaded modules, and if it's not, it calls the __import__ function and loads the driver in then instantiates a device object using the driver and hands it back to the user to use.
My question is: What is the best way to get a list of all modules in a relative way? What I mean is, if I know that the drivers are located in ..drivers is there a way to get a tidy list of modules in that subpacakage? To illustrate: usually I just call from ..drivers import driver_name to import the module, but since I'm not guaranteed to be in the package directory, can't just us os to get a list of module names.
In any case, any ideas (even maybe a better way to accomplish what I want - loadable "drivers") would be appreciated.
A:
There is pkgutil which has iter_modules. (Note: The Python 2 documentation doesn't mention that function, but it works just fine for me on Python 2.6.)
You can also do it manually using __file__, os.path and os.listdir.
A:
If the location of the driver packages is known, then you could use the absolute path to the driver folder(s).
I think that a more robust approach would be to have a list of all known drivers for your program, perhaps along with a bit of metadata so that users can choose them more easily. You could have the drivers register themselves, or register them yourself if you know of likely locations. One advantage of having the drivers register themselves is that you might have python files other than drivers in the driver package directories.
Edit
For a driver to "register itself," you might do something like this:
if __name__ == "__main__":
import mamapackage
mamapackage.register("thisdriver",
os.path.abspath(__file__),
"A description of this driver")
Then in your own package, provide a "register" function that updates a list of drivers, with their locations and descriptions (a simple text file should do for starters).
A:
Why not make a package of all the drivers? Then you could
import drivers
drivers.load("device1")
where the load function maintains a mapping of device name to module in package? Then you could dynamically import each of the required modules when necessary...
| Delayed loading of modules in python | I'm writing a python applet for data acquisition from scientific instruments and I'm trying to figure out the best way to manage my device "drivers".
Each driver is represented by a separate python module in the package that is my program. They each implement some standard interface, but mostly it's a gigantic list of commands (and function mappings) that are specific to each device and bus involved. In the long run, (I'm writing this for my lab group and am planning on supporting a few dozen or so devices) I want to avoid loading all of them in at once. Instead, at run-time, I want to read in a list of modules into a dictionary/list and then load them only when they are actually needed.
When the user wants to use a new device, he selects the driver to use, and passes the name along to the driver subsystem which then checks to see if that driver is in the list of loaded modules, and if it's not, it calls the __import__ function and loads the driver in then instantiates a device object using the driver and hands it back to the user to use.
My question is: What is the best way to get a list of all modules in a relative way? What I mean is, if I know that the drivers are located in ..drivers is there a way to get a tidy list of modules in that subpacakage? To illustrate: usually I just call from ..drivers import driver_name to import the module, but since I'm not guaranteed to be in the package directory, can't just us os to get a list of module names.
In any case, any ideas (even maybe a better way to accomplish what I want - loadable "drivers") would be appreciated.
| [
"There is pkgutil which has iter_modules. (Note: The Python 2 documentation doesn't mention that function, but it works just fine for me on Python 2.6.)\nYou can also do it manually using __file__, os.path and os.listdir.\n",
"If the location of the driver packages is known, then you could use the absolute path t... | [
3,
3,
0
] | [] | [] | [
"module",
"package",
"python"
] | stackoverflow_0004058115_module_package_python.txt |
Q:
Split list of names into alphabetic dictionary, in Python
List.
['Chrome', 'Chromium', 'Google', 'Python']
Result.
{'C': ['Chrome', 'Chromium'], 'G': ['Google'], 'P': ['Python']}
I can make it work like this.
alphabet = dict()
for name in ['Chrome', 'Chromium', 'Google', 'Python']:
character = name[:1].upper()
if not character in alphabet:
alphabet[character] = list()
alphabet[character].append(name)
It is probably a bit faster to pre-populate the dictionary with A-Z, to save the key check on every name, and then afterwards delete keys with empty lists. I'm not sure either is the best solution though.
Is there a pythonic way to do this?
A:
Anything wrong with this? I agree with Antoine, the oneliner solution is rather cryptic.
import collections
alphabet = collections.defaultdict(list)
for word in words:
alphabet[word[0].upper()].append(word)
A:
I don't know if it's Pythonic, but it's more succinct:
import itertools
def keyfunc(x):
return x[:1].upper()
l = ['Chrome', 'Chromium', 'Google', 'Python']
l.sort(key=keyfunc)
dict((key, list(value)) for (key,value) in itertools.groupby(l, keyfunc))
EDIT 2 made it less succinct than previous version, more readable and more correct (groupby works as intended only on sorted lists)
| Split list of names into alphabetic dictionary, in Python | List.
['Chrome', 'Chromium', 'Google', 'Python']
Result.
{'C': ['Chrome', 'Chromium'], 'G': ['Google'], 'P': ['Python']}
I can make it work like this.
alphabet = dict()
for name in ['Chrome', 'Chromium', 'Google', 'Python']:
character = name[:1].upper()
if not character in alphabet:
alphabet[character] = list()
alphabet[character].append(name)
It is probably a bit faster to pre-populate the dictionary with A-Z, to save the key check on every name, and then afterwards delete keys with empty lists. I'm not sure either is the best solution though.
Is there a pythonic way to do this?
| [
"Anything wrong with this? I agree with Antoine, the oneliner solution is rather cryptic.\nimport collections\n\nalphabet = collections.defaultdict(list)\nfor word in words:\n alphabet[word[0].upper()].append(word)\n\n",
"I don't know if it's Pythonic, but it's more succinct:\nimport itertools\ndef keyfunc(x):... | [
10,
5
] | [] | [] | [
"dictionary",
"list",
"python"
] | stackoverflow_0004058967_dictionary_list_python.txt |
Q:
Menubuttons located in the middle of menubar
how do I put my menu bar buttons on menu bar's left ? Right now I pack() them with side=LEFT but still they're in the middle. Here's the code for my menu bar: http://pastebin.com/bgncELcb
A:
What does menubar.pack(side=LEFT) give you?
Can you also try with menubar.pack()?
A:
I recommend against creating menubars a) with frames and menubuttons, and b) with menus in non-standard places. You should use the menu option of your toplevel window if you're at all interested in usability. However, since you specifically asked about menubuttons in the middle of a frame...
If you want something precisely in the middle, one thing you can do is break your menu into three sections, a left, middle and right. Place those three subframes inside your "menubar" frame. Use grid to give the left and right sections the most weight (and equal to each other, so the middle stays in the middle). You can then pack a button or buttons in the middle frame and they will remain in the middle.
Another choice is to use place, and set the relative X position to .5 and the anchor to "n". That is probably the easiest, though you can have problems with overlapping buttons if they don't all fit because the user resized the window.
The option you chose -- pack -- is the most difficult route to take. pack by it's very nature is designed to pack things along edges. Again, you can use three subframes, but pack isn't the natural choice here.
My advice: rethink why you want a non-standard menubar. Use a real menubar with menu buttons along the left like 99.9% of all other apps in the world. Your users will thank you.
| Menubuttons located in the middle of menubar | how do I put my menu bar buttons on menu bar's left ? Right now I pack() them with side=LEFT but still they're in the middle. Here's the code for my menu bar: http://pastebin.com/bgncELcb
| [
"What does menubar.pack(side=LEFT) give you?\nCan you also try with menubar.pack()?\n",
"I recommend against creating menubars a) with frames and menubuttons, and b) with menus in non-standard places. You should use the menu option of your toplevel window if you're at all interested in usability. However, since y... | [
0,
0
] | [] | [] | [
"python",
"tkinter",
"user_interface"
] | stackoverflow_0004058272_python_tkinter_user_interface.txt |
Q:
Column filtering on trace file
I am doing visualization analysis on a trace file I generate from ns-2 that traces out the packets sent/received/dropped at various times of the simulation
here is a sample trace output - http://pastebin.com/aPm3EFax
I want to filter out the column1 after grouping it into S/D/R separately, so that I can sum it over to separately to find packet delivery fraction.
I am clueless on how to get this done? (maybe some awk/python help?)
UPDATE: okay, I did this -
cut -d' ' -f1 wireless-out.tr | grep <x> | wc -l
where <x> is either s or r or D
A:
Give this a try:
awk '{data[$1]+=$2} END{for (d in data) print d,data[d]}' inputfile
Output:
D 80.1951
r 80.059
s 160.158
A:
import collections
result=collections.defaultdict(list)
with open('data','r') as f:
for line in f:
line=line.split()
key=line[0]
value=float(line[1])
result[key].append(value)
for key,values in result.iteritems():
print(key,sum(values))
yields:
('s', 160.15817391900003)
('r', 80.058963809000005)
('D', 80.195127232999994)
Is this close to the form you want?
A:
import csv
import itertools
data = csv.reader(open('aPm3EFax.txt', 'rb'), delimiter=' ')
result = [(i, sum(float(k[1]) for k in g))
for i, g in itertools.groupby(sorted(list(data)), key=lambda x: x[0])]
| Column filtering on trace file | I am doing visualization analysis on a trace file I generate from ns-2 that traces out the packets sent/received/dropped at various times of the simulation
here is a sample trace output - http://pastebin.com/aPm3EFax
I want to filter out the column1 after grouping it into S/D/R separately, so that I can sum it over to separately to find packet delivery fraction.
I am clueless on how to get this done? (maybe some awk/python help?)
UPDATE: okay, I did this -
cut -d' ' -f1 wireless-out.tr | grep <x> | wc -l
where <x> is either s or r or D
| [
"Give this a try:\nawk '{data[$1]+=$2} END{for (d in data) print d,data[d]}' inputfile\n\nOutput:\nD 80.1951\nr 80.059\ns 160.158\n\n",
"import collections\nresult=collections.defaultdict(list)\nwith open('data','r') as f:\n for line in f:\n line=line.split()\n key=line[0]\n value=float(li... | [
1,
0,
0
] | [] | [] | [
"awk",
"python"
] | stackoverflow_0004058588_awk_python.txt |
Q:
how to change data Automatically not using open the webpage for Per hour
i seem like this :
class myData(db.Model):
today= db.DateTimeProperty()
how to set 'today' to now time for Per hour ,not using open the webpage ?
thanks
A:
You need to use a Task Queue.
| how to change data Automatically not using open the webpage for Per hour | i seem like this :
class myData(db.Model):
today= db.DateTimeProperty()
how to set 'today' to now time for Per hour ,not using open the webpage ?
thanks
| [
"You need to use a Task Queue.\n"
] | [
1
] | [] | [] | [
"google_app_engine",
"javascript",
"python"
] | stackoverflow_0004058087_google_app_engine_javascript_python.txt |
Q:
Full internal resize of control in wx.Panel
Hi at all friends :)
I have a problem with a control inside a wx.Panel.
With my code the wx.GenericDirCtrl inside a wx.Panel don't fit in all directions in the Panel (or fit only in a direction if I use wx.BoxSizer).
I use an istance of MyPanel in a wx.Frame.
How I can solve it? Thanks
The code is:
class MyPanel(wx.Panel):
def __init__(self, parent):
wx.Panel.__init__(self, parent, wx.ID_ANY)
resizeBox = wx.BoxSizer(wx.VERTICAL)
self.dir1 = wx.GenericDirCtrl(self, wx.ID_ANY)
resizeBox.Add(self.dir1, wx.EXPAND | wx.ALL)
self.SetSizerAndFit(resizeBox)
and the code where I instancing Panel in wx.Framec is:
# controls
self.splitterMain = wx.SplitterWindow(self, wx.ID_ANY) # create a vertical splitter
self.panel1 = MyPanel(self.splitterMain)
self.panel1.SetBackgroundColour(wx.BLACK)
self.panel2 = wx.Panel(self.splitterMain, wx.ID_ANY)
self.panel2.SetBackgroundColour(wx.WHITE)
self.splitterMain.SplitVertically(self.panel1, self.panel2)
A:
You're using the Add method wrong. Its signature is
Add(self, item, proportion=0, flag=0, border=0, userData=None)
You've passed the "flag" parameter as the proportion parameter.
| Full internal resize of control in wx.Panel | Hi at all friends :)
I have a problem with a control inside a wx.Panel.
With my code the wx.GenericDirCtrl inside a wx.Panel don't fit in all directions in the Panel (or fit only in a direction if I use wx.BoxSizer).
I use an istance of MyPanel in a wx.Frame.
How I can solve it? Thanks
The code is:
class MyPanel(wx.Panel):
def __init__(self, parent):
wx.Panel.__init__(self, parent, wx.ID_ANY)
resizeBox = wx.BoxSizer(wx.VERTICAL)
self.dir1 = wx.GenericDirCtrl(self, wx.ID_ANY)
resizeBox.Add(self.dir1, wx.EXPAND | wx.ALL)
self.SetSizerAndFit(resizeBox)
and the code where I instancing Panel in wx.Framec is:
# controls
self.splitterMain = wx.SplitterWindow(self, wx.ID_ANY) # create a vertical splitter
self.panel1 = MyPanel(self.splitterMain)
self.panel1.SetBackgroundColour(wx.BLACK)
self.panel2 = wx.Panel(self.splitterMain, wx.ID_ANY)
self.panel2.SetBackgroundColour(wx.WHITE)
self.splitterMain.SplitVertically(self.panel1, self.panel2)
| [
"You're using the Add method wrong. Its signature is \nAdd(self, item, proportion=0, flag=0, border=0, userData=None)\n\nYou've passed the \"flag\" parameter as the proportion parameter.\n"
] | [
1
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0004058263_python_wxpython.txt |
Q:
Twisted and connection to SQL Server
I have a Twisted application that runs in an x86 64bit machine with Win 2008 server.
It needs to be connected to a SQL Server database that runs in another machine (in a cloud actually but I have IP, port, db name, credentials).
Do I need to install anything more that Twisted to my machine?
And which API should be used?
A:
twisted.enterprise.adbapi will help you use any DB-API 2.0 module without blocking. It gives you a non-blocking, Deferred-based API by running database operations in a thread pool. python-mssql appears to be a DB-API 2.0 compliant module for MSSQL (I've never used it myself though).
A:
If you want to have portable mssql server library, you can try the module from www.pytds.com.
It works with 2.5+ and 3.1, have a good stored procedure support. It's api is more "functional", and has some good features you won't find anywhere else.
| Twisted and connection to SQL Server | I have a Twisted application that runs in an x86 64bit machine with Win 2008 server.
It needs to be connected to a SQL Server database that runs in another machine (in a cloud actually but I have IP, port, db name, credentials).
Do I need to install anything more that Twisted to my machine?
And which API should be used?
| [
"twisted.enterprise.adbapi will help you use any DB-API 2.0 module without blocking. It gives you a non-blocking, Deferred-based API by running database operations in a thread pool. python-mssql appears to be a DB-API 2.0 compliant module for MSSQL (I've never used it myself though).\n",
"If you want to have po... | [
2,
1
] | [] | [] | [
"python",
"sql_server",
"twisted"
] | stackoverflow_0003657271_python_sql_server_twisted.txt |
Q:
Is IronPython a 100% pure Python variant?
I just downloaded the original Python interpreter from Python's site. I just want to learn this language but to start with, I want to write Windows-based standalone applications that are powered by any RDBMS. I want to bundle it like any typical Windows setup.
I searched old posts on SO and found guys suggesting wxPython and py2exe. Apart from that few suggested IronPython since it is powered by .NET.
I want to know whether IronPython is a pure variant of Python or a modified variant. Secondly, what is the actual use of Python? Is it for PHP like thing or like C# (you can either program Windows-based app. or Web.).
A:
IronPython isn't a variant of Python, it is Python. It's an implementation of the Python language based on the .NET framework. So, yes, it is pure Python.
IronPython is caught up to CPython (the implementation you're probably used to) 2.6, so some of the features/changes seen in Python 2.7 or 3.x will not be present in IronPython. Also, the standard library is a bit different (but what you lose is replaced by all that .NET has to offer).
The primary application of IronPython is to script .NET applications written in C# etc., but it can also be used as a standalone. IronPython can also be used to write web applications using the SilverLight framework.
If you need access to .NET features, use IronPython. If you're just trying to make a Windows executable, use py2exe.
Update
For writing basic RDBMS apps, just use CPython (original Python), it's more extensible and faster. Then, you can use a number of tools to make it stand alone on a Windows PC. For now, though, just worry about learning Python (those skills will mostly carry over to IronPython if you choose to switch) and writing your application.
A:
IronPython is an independent Python implementation written in C# as opposed to the original implementation, often referred to as CPython due to it being written in (no surprise) C.
Python is multi-purpose - you can use it to write web apps (often using a framework such as Django or Pylons), GUI apps (as you've mentioned), command-line tools and as a scripting language embedded inside an app written in another language (for instance, the 3D modelling tool Blender can be scripted using Python).
A:
what does "Pure Python" mean? If you're talking about implemented in Python in the same sense that a module may be pure python, then no, and no Python implementation is. If you mean "Compatible with cPython" then yes, code written to cPython will work in IronPython, with a few caveats. The one that's likely to matter most is that the libraries are different, for instance code depending on ctypes or Tkinter won't work. Another difference is that IronPython lags behind cPython by a bit. the very latest version of this writing is 2.6.1, with an Alpha version supporting a few of the 2.7 language features available too.
What do you really need? If you want to learn to program with python, and also want to produce code for windows, you can use IronPython for that, but you can also use cPython and py2exe; both will work equally well for this with only differences in the libraries.
A:
IronPython is an implementation of Python using C#. It's just like the implementation of Python using Java by Jython. You might want to note that IronPython and Jython will always lag behind a little bit in development. However, you do get the benefit of having some libraries that's not available in the standard Python libraries. In IronPython, you will be able to get access to some of the .NET stuff, like System.Drawings and such, though by using these non-standard libraries, it will be harder to port your code to other platforms. For example, you will have to install mono to run apps written in IronPython on Linux (On windows you will need the .NET Framework)
| Is IronPython a 100% pure Python variant? | I just downloaded the original Python interpreter from Python's site. I just want to learn this language but to start with, I want to write Windows-based standalone applications that are powered by any RDBMS. I want to bundle it like any typical Windows setup.
I searched old posts on SO and found guys suggesting wxPython and py2exe. Apart from that few suggested IronPython since it is powered by .NET.
I want to know whether IronPython is a pure variant of Python or a modified variant. Secondly, what is the actual use of Python? Is it for PHP like thing or like C# (you can either program Windows-based app. or Web.).
| [
"IronPython isn't a variant of Python, it is Python. It's an implementation of the Python language based on the .NET framework. So, yes, it is pure Python.\nIronPython is caught up to CPython (the implementation you're probably used to) 2.6, so some of the features/changes seen in Python 2.7 or 3.x will not be pres... | [
6,
1,
1,
1
] | [] | [] | [
"ironpython",
"python",
"wxpython"
] | stackoverflow_0004059201_ironpython_python_wxpython.txt |
Q:
Any recommendations to improve this function?
I am very new to working with SQL queries. Any suggestions to improve this bit of code:
(by the way, I really don't care about sql security here; this is a bit of code that will be in a pyexe file connecting to a local sqlite file - so it doesnt make sense to worry about security of the query here).
def InitBars(QA = "GDP1POP1_20091224_gdp", QB = "1 pork", reset = False):
global heights, values
D, heights, values, max, = [], {}, {}, 0.0001
if reset: GHolder.remove()
Q = "SELECT wbcode, Year, "+QA+" FROM DB WHERE commodity='"+QB+"' and "+QA+" IS NOT 'NULL'"
for i in cursor.execute(Q):
D.append((str(i[0]) + str(i[1]), float(i[2])))
if float(i[2]) > max: max = float(i[2])
for (i, n) in D: heights[i] = 5.0 / max * n; values[i] = n
Gui["YRBox_Slider"].set(0.0)
Gui["YRBox_Speed"].set(0.0)
after following the advices, this is what I got:
def InitBars(QA = "GDP1POP1_20091224_gdp", QB = "1 pork", reset = False):
global heights, values; D, heights, values, max, = [], {}, {}, 0.0001
if reset: GHolder.remove()
Q = "SELECT wbcode||Year, %s FROM DB WHERE commodity='%s' and %s IS NOT 'NULL'" % (QA, QB, QA)
for a, b in cursor.execute(Q):
if float(b) > max: max = float(b)
values[a] = float(b)
for i in values: heights[i] = 5.0 / max * values[i]
Gui["YRBox_Slider"].set(0.0); Gui["YRBox_Speed"].set(0.0)
A:
If this is a one-off script where you totally trust all of the input data and you just need to get a job done, then fine.
If this is part of a system, and this is indicative of the kind of code in it, there are several problems:
Don't construct SQL queries by appending strings. You said that you don't care about security, but this is such a big problem and so easily solved, then really -- you should do it right all of the time
This function seems to use and manipulate global state. Again, if this is a small one-time use script, then go for it -- in systems that span just a few files, this becomes impossible to maintain.
Naming conventions --- not following any consistency in capitalization
Names of things are not helpful at all. QA, D, QB, -- QA and QB don't even seem to be the same kind of thing -- one is a field, and the other is a value.
All kinds of questionable things are uncommented -- why is max .0001? What the heck is GHolder? What could that loop be doing at the end? Really, the code should be clearer, but if not, throw the maintainer a bone.
A:
Use more descriptive variable names than QA and QB.
Comment the code.
Don't put multiple statements in the same line
Try not to use globals. Use member variables instead.
if QA and QB may come from user input, don't use them to build SQL queries
A:
You should check for SQL injection. Make sure that there's no SQL statement in QA. Also you should probably add slashes if it applies.
A:
Use
Q = "SELECT wbcode, Year, %s FROM DB WHERE commodity='%s' and %s IS NOT 'NULL'" % (QA, QB, QA)
instead:
Q = "SELECT wbcode, Year, "+QA+" FROM DB WHERE commodity='"+QB+"' and "+QA+" IS NOT 'NULL'"
Care about security (sql injection).
Look at any ORM (SqlAlchemy, for example). It makes things easy :)
| Any recommendations to improve this function? | I am very new to working with SQL queries. Any suggestions to improve this bit of code:
(by the way, I really don't care about sql security here; this is a bit of code that will be in a pyexe file connecting to a local sqlite file - so it doesnt make sense to worry about security of the query here).
def InitBars(QA = "GDP1POP1_20091224_gdp", QB = "1 pork", reset = False):
global heights, values
D, heights, values, max, = [], {}, {}, 0.0001
if reset: GHolder.remove()
Q = "SELECT wbcode, Year, "+QA+" FROM DB WHERE commodity='"+QB+"' and "+QA+" IS NOT 'NULL'"
for i in cursor.execute(Q):
D.append((str(i[0]) + str(i[1]), float(i[2])))
if float(i[2]) > max: max = float(i[2])
for (i, n) in D: heights[i] = 5.0 / max * n; values[i] = n
Gui["YRBox_Slider"].set(0.0)
Gui["YRBox_Speed"].set(0.0)
after following the advices, this is what I got:
def InitBars(QA = "GDP1POP1_20091224_gdp", QB = "1 pork", reset = False):
global heights, values; D, heights, values, max, = [], {}, {}, 0.0001
if reset: GHolder.remove()
Q = "SELECT wbcode||Year, %s FROM DB WHERE commodity='%s' and %s IS NOT 'NULL'" % (QA, QB, QA)
for a, b in cursor.execute(Q):
if float(b) > max: max = float(b)
values[a] = float(b)
for i in values: heights[i] = 5.0 / max * values[i]
Gui["YRBox_Slider"].set(0.0); Gui["YRBox_Speed"].set(0.0)
| [
"If this is a one-off script where you totally trust all of the input data and you just need to get a job done, then fine.\nIf this is part of a system, and this is indicative of the kind of code in it, there are several problems:\n\nDon't construct SQL queries by appending strings. You said that you don't care ab... | [
2,
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0004059499_python.txt |
Q:
Doing something with each line that belongs to a process's output
When using the subprocess module, how can I do something with each line of a process's output? I don't want to wait for all the output, like when using communicate, but rather do something with it as soon as it's produced. Can this be done?
A:
Unfortunately the proposal to add this to subprocess is not yet accepted: http://www.python.org/dev/peps/pep-3145/
Here is a recipe for doing it with the existing subprocess: http://code.activestate.com/recipes/440554/
A commenter also notes this simple solution (with some downsides):
flags = fcntl.fcntl(subprocess.stdout, fcntl.F_GETFL)
fcntl.fcntl(subprocess.stdout, fcntl.F_SETFL, flags | os.O_NONBLOCK)
| Doing something with each line that belongs to a process's output | When using the subprocess module, how can I do something with each line of a process's output? I don't want to wait for all the output, like when using communicate, but rather do something with it as soon as it's produced. Can this be done?
| [
"Unfortunately the proposal to add this to subprocess is not yet accepted: http://www.python.org/dev/peps/pep-3145/\nHere is a recipe for doing it with the existing subprocess: http://code.activestate.com/recipes/440554/\nA commenter also notes this simple solution (with some downsides):\nflags = fcntl.fcntl(subpro... | [
1
] | [] | [] | [
"python",
"subprocess"
] | stackoverflow_0004059684_python_subprocess.txt |
Q:
How to insert a large number of list entries into sqlite statements
Ok, I am using apsw with sqlite, and have a large list of entries.Each entry contains a new row to be inserted. The number of entries is sometimes 20, sometimes 21. Since apsw supports multiple sql statements in curser.execute(), I was wondering if there would be a less confusing way of inserting all my list entries into the database than just doing something like
for entry in foo:
cursor.execute(INSERT OR UPDATE INTO database.main ("{0}".format(entry))
I want to do it in all one thread because sqlite auto-commits to the database each time the execute finishes. Is there an easier, more efficient, and less confusing way?
A:
apsw cursors have an executemany method:
cursor.executemany('INSERT OR UPDATE INTO database.main values (?)',foo)
| How to insert a large number of list entries into sqlite statements | Ok, I am using apsw with sqlite, and have a large list of entries.Each entry contains a new row to be inserted. The number of entries is sometimes 20, sometimes 21. Since apsw supports multiple sql statements in curser.execute(), I was wondering if there would be a less confusing way of inserting all my list entries into the database than just doing something like
for entry in foo:
cursor.execute(INSERT OR UPDATE INTO database.main ("{0}".format(entry))
I want to do it in all one thread because sqlite auto-commits to the database each time the execute finishes. Is there an easier, more efficient, and less confusing way?
| [
"apsw cursors have an executemany method:\ncursor.executemany('INSERT OR UPDATE INTO database.main values (?)',foo)\n\n"
] | [
1
] | [] | [] | [
"list",
"python",
"sqlite"
] | stackoverflow_0004059776_list_python_sqlite.txt |
Q:
CherryPy Logging: How do I configure and use the global and application level loggers?
I'm having trouble with logging. I'm running CherryPy 3.2 and I've been reading through the docs here, but haven't found any examples of how to configure a local log file for output and how to write to it.
Raspberry.py:
import socket
import sys
import cherrypy
app_roots = {
# Sean's laptop dev environment.
"mylaptop": "/home/src/local-mydomain.com/py",
# Hosted dev environment.
"mydomain.com" : "/home/dev/src/py"
}
hostname = socket.gethostname()
CherryPyLog = cherrypy.tree.mount().log
if hostname not in app_roots:
CherryPyLog("The following hostname does not have an app_root entry in raspberry.py. Exiting early.")
sys.exit()
sys.stdout = sys.stderr
sys.path.append(app_roots[hostname])
import os
os.chdir(app_root)
# Setup for raspberry application logging.
import datetime
today = datetime.datetime.today()
log.access_file = "{0}/{1}.raspberry.access.log".format(app_roots[hostname],today.strftime("%Y%m%d-%H%M"))
log.error_file = "{0}/{1}.raspberry.error.log".format(app_roots[hostname],today.strftime("%Y%m%d-%H%M"))
#Testing logger
log("{0} -- Logger configured".format(today.strftime("%Y%m%d-%H%M%S")))
import atexit
cherrypy.config.update({'environment': 'embedded'})
if cherrypy.__version__.startswith('3.0') and cherrypy.engine.state == 0:
cherrypy.engine.start(blocking = False)
atexit.register(cherrypy.engine.stop)
from web.controllers.root import RaspberryRequestHandler
application = cherrypy.Application(RaspberryRequestHandler(), script_name = None, config = None)
UPDATE: Here's the code block that I ended up going with.
app_roots = {
# Sean's laptop dev environment.
"mylaptop": "/home/src/local-plottools.com/py",
# Hosted dev environment.
"myDomain" : "/home/dev/src/py"
}
import socket
hostname = socket.gethostname()
import cherrypy
import sys
if hostname not in app_roots:
cherrypy.log("The hostname {0} does not have an app_root entry in {1}. Exiting early.".format(hostname,__file__))
sys.exit()
sys.stdout = sys.stderr
sys.path.append(app_roots[hostname])
import os
os.chdir(app_roots[hostname])
from web.controllers.root import RaspberryRequestHandler
cherrypy.config.update({
'log.access_file': "{0}/cherrypy-access.log".format(app_roots[hostname]),
'log.error_file': "{0}/cherrypy.log".format(app_roots[hostname]),
"server.thread_pool" : 10
})
# special case, handling debug sessions when quickstart is needed.
if __name__ == "__main__":
cherrypy.config.update({
'log.screen': True,
"server.socket_port": 8000
})
cherrypy.quickstart(RaspberryRequestHandler())
sys.exit()
# This configuration is needed for running under mod_wsgi. See here: http://tools.cherrypy.org/wiki/ModWSGI
cherrypy.config.update({'environment': 'embedded'})
applicationLogName = "{0}/raspberry.log".format(app_roots[hostname])
from logging import handlers
applicationLogFileHandler = handlers.RotatingFileHandler(applicationLogName, 'a', 10000000, 1000)
import logging
applicationLogFileHandler.setLevel(logging.DEBUG)
from cherrypy import _cplogging
applicationLogFileHandler.setFormatter(_cplogging.logfmt)
cherrypy.log.error_log.addHandler(applicationLogFileHandler)
application = cherrypy.Application(RaspberryRequestHandler(), None)
A:
Simplifying a bit:
import os
import socket
import sys
import cherrypy
app_roots = {
# Sean's laptop dev environment.
"mylaptop": "/home/src/local-mydomain.com/py",
# Hosted dev environment.
"mydomain.com" : "/home/dev/src/py"
}
hostname = socket.gethostname()
if hostname not in app_roots:
cherrypy.log("The hostname %r does not have an app_root entry in "
"raspberry.py. Exiting early." % hostname)
sys.exit()
sys.path.append(app_roots[hostname])
os.chdir(app_root)
cherrypy.config.update({
'environment': 'embedded',
'log.access_file': "{0}/raspberry.access.log".format(app_roots[hostname]),
'log.error_file': "{0}/raspberry.error.log".format(app_roots[hostname]),
})
from web.controllers.root import RaspberryRequestHandler
application = cherrypy.tree.mount(RaspberryRequestHandler(), '/')
# Insert log changes here
cherrypy.engine.start()
If you want different logs per day, use a RotatingFileHandler as described at http://www.cherrypy.org/wiki/Logging#CustomHandlers The important point I think you're missing is that you should muck about with app.log only after you've instantiated your app (e.g. via tree.mount(), as above), but before engine.start. That is, for the error log:
application = cherrypy.tree.mount(RaspberryRequestHandler(), '/')
log = application.log
log.error_file = ""
# Make a new RotatingFileHandler for the error log.
fname = "{0}/raspberry.error.log".format(app_roots[hostname])
h = handlers.RotatingFileHandler(fname, 'a', 10000000, 1000)
h.setLevel(DEBUG)
h.setFormatter(_cplogging.logfmt)
log.error_log.addHandler(h)
cherrypy.engine.start()
Hope that helps...
| CherryPy Logging: How do I configure and use the global and application level loggers? | I'm having trouble with logging. I'm running CherryPy 3.2 and I've been reading through the docs here, but haven't found any examples of how to configure a local log file for output and how to write to it.
Raspberry.py:
import socket
import sys
import cherrypy
app_roots = {
# Sean's laptop dev environment.
"mylaptop": "/home/src/local-mydomain.com/py",
# Hosted dev environment.
"mydomain.com" : "/home/dev/src/py"
}
hostname = socket.gethostname()
CherryPyLog = cherrypy.tree.mount().log
if hostname not in app_roots:
CherryPyLog("The following hostname does not have an app_root entry in raspberry.py. Exiting early.")
sys.exit()
sys.stdout = sys.stderr
sys.path.append(app_roots[hostname])
import os
os.chdir(app_root)
# Setup for raspberry application logging.
import datetime
today = datetime.datetime.today()
log.access_file = "{0}/{1}.raspberry.access.log".format(app_roots[hostname],today.strftime("%Y%m%d-%H%M"))
log.error_file = "{0}/{1}.raspberry.error.log".format(app_roots[hostname],today.strftime("%Y%m%d-%H%M"))
#Testing logger
log("{0} -- Logger configured".format(today.strftime("%Y%m%d-%H%M%S")))
import atexit
cherrypy.config.update({'environment': 'embedded'})
if cherrypy.__version__.startswith('3.0') and cherrypy.engine.state == 0:
cherrypy.engine.start(blocking = False)
atexit.register(cherrypy.engine.stop)
from web.controllers.root import RaspberryRequestHandler
application = cherrypy.Application(RaspberryRequestHandler(), script_name = None, config = None)
UPDATE: Here's the code block that I ended up going with.
app_roots = {
# Sean's laptop dev environment.
"mylaptop": "/home/src/local-plottools.com/py",
# Hosted dev environment.
"myDomain" : "/home/dev/src/py"
}
import socket
hostname = socket.gethostname()
import cherrypy
import sys
if hostname not in app_roots:
cherrypy.log("The hostname {0} does not have an app_root entry in {1}. Exiting early.".format(hostname,__file__))
sys.exit()
sys.stdout = sys.stderr
sys.path.append(app_roots[hostname])
import os
os.chdir(app_roots[hostname])
from web.controllers.root import RaspberryRequestHandler
cherrypy.config.update({
'log.access_file': "{0}/cherrypy-access.log".format(app_roots[hostname]),
'log.error_file': "{0}/cherrypy.log".format(app_roots[hostname]),
"server.thread_pool" : 10
})
# special case, handling debug sessions when quickstart is needed.
if __name__ == "__main__":
cherrypy.config.update({
'log.screen': True,
"server.socket_port": 8000
})
cherrypy.quickstart(RaspberryRequestHandler())
sys.exit()
# This configuration is needed for running under mod_wsgi. See here: http://tools.cherrypy.org/wiki/ModWSGI
cherrypy.config.update({'environment': 'embedded'})
applicationLogName = "{0}/raspberry.log".format(app_roots[hostname])
from logging import handlers
applicationLogFileHandler = handlers.RotatingFileHandler(applicationLogName, 'a', 10000000, 1000)
import logging
applicationLogFileHandler.setLevel(logging.DEBUG)
from cherrypy import _cplogging
applicationLogFileHandler.setFormatter(_cplogging.logfmt)
cherrypy.log.error_log.addHandler(applicationLogFileHandler)
application = cherrypy.Application(RaspberryRequestHandler(), None)
| [
"Simplifying a bit:\nimport os\nimport socket\nimport sys\n\nimport cherrypy\n\napp_roots = {\n # Sean's laptop dev environment.\n \"mylaptop\": \"/home/src/local-mydomain.com/py\",\n\n # Hosted dev environment. \n \"mydomain.com\" : \"/home/dev/src/py\"\... | [
10
] | [] | [] | [
"cherrypy",
"logging",
"python"
] | stackoverflow_0004056958_cherrypy_logging_python.txt |
Q:
Generate all possible strings from a list of token
I have a list of tokens, like:
hel
lo
bye
and i want to generate all the possible combinations of such strings, like:
hello
lohel
helbye
byehel
lobye
byelo
Language is not important, any advice?
I found Generating permutations using bash, but this makes permutation on a single line.
A:
Your example can be written in Python as
from itertools import combinations
print list(combinations(["hel", "lo", "bye"], 2))
To combine the output to strings again:
print ["".join(a) for a in combinations(["hel", "lo", "bye"], 2)]
If you interested in the actual implementation of this function, have a look at the documentation.
A:
itertools.permutations can do that for you.
>>> l = ['hel', 'lo', 'bye']
>>> list(itertools.permutations(l, 2))
[('hel', 'lo'), ('hel', 'bye'), ('lo', 'hel'), ('lo', 'bye'), ('bye', 'hel'), ('bye', 'lo')]
Or if you want combinations, you can use itertools.combinations.
>>> l = ['hel', 'lo', 'bye']
>>> list(itertools.combinations(l, 2))
[('hel', 'lo'), ('hel', 'bye'), ('lo', 'bye')]
A:
Given that other languages are acceptable:
#!/usr/bin/perl
use strict; use warnings;
use Algorithm::Combinatorics qw(permutations);
my $data = [ qw( hel lo bye ) ];
my $it = permutations($data);
while ( my $p = $it->next ) {
print @$p, "\n";
}
hellobye
helbyelo
lohelbye
lobyehel
byehello
byelohel
A:
a = ['hel', 'lo', 'bye']
print '\n'.join(''.join(x) for x in itertools.permutations(a, 2))
A:
Easy in python with itertools.
Here is the token permutation example:
import itertools
tokens = ["hel", "lo", "bye"]
for i in range(1, len(tokens) + 1):
for p in itertools.permutations(tokens, i):
print "".join(p)
Alternatively, this treats each character as a token:
import itertools
tokens = ["hel", "lo", "bye"]
chars = "".join(tokens)
for i in range(1, len(chars) + 1):
for p in itertools.permutations(chars, i):
print "".join(p)
A:
Looks like you want permutations:
from itertools import permutations
# easy way to make a list for words
words = 'hel lo bye'.split()
# fetch two-word permutations, joined into a string
for word in [''.join(s) for s in permutations(words,2)]:
print word
Output:
hello
helbye
lohel
lobye
byehel
byelo
A:
Python has a permutations too. :)
A:
Update: I see I wasn't explicit enough.
Haskell has a permutations function that would help:
import Data.List
permutations ["hel","lo","bye"] ==
[["hel","lo","bye"],["lo","hel","bye"],["bye","lo","hel"],
["lo","bye","hel"],["bye","hel","lo"],["hel","bye","lo"]]
If you want each permutation concatenated, use
map concat (permutations ["hel","lo","bye"]) ==
["hellobye","lohelbye","byelohel","lobyehel","byehello","helbyelo"]
If you actually want combinations of two substrings (like your example output) instead of all permutations of substrings, as @Sven noticed, use the Math.Combinatorics.Graph module and:
map concat (combinationsOf 2 ["hel","lo","bye"])
That matches your example data in some respects but not others. I could go on to speculate that you want "all possible strings" as the title says, or all permutations of two-token subsets, or what have you, but it's kind of pointless to speculate since you've already accepted an answer.
| Generate all possible strings from a list of token | I have a list of tokens, like:
hel
lo
bye
and i want to generate all the possible combinations of such strings, like:
hello
lohel
helbye
byehel
lobye
byelo
Language is not important, any advice?
I found Generating permutations using bash, but this makes permutation on a single line.
| [
"Your example can be written in Python as\nfrom itertools import combinations\nprint list(combinations([\"hel\", \"lo\", \"bye\"], 2))\n\nTo combine the output to strings again:\nprint [\"\".join(a) for a in combinations([\"hel\", \"lo\", \"bye\"], 2)]\n\nIf you interested in the actual implementation of this funct... | [
24,
8,
3,
2,
2,
2,
1,
0
] | [] | [] | [
"bash",
"language_agnostic",
"python"
] | stackoverflow_0004059550_bash_language_agnostic_python.txt |
Q:
Strange python's comparison behaviour
I have a sample code looking like this, values (position = 2, object.position = 3) :
new_position = position
old_position = object.position
logging.debug("1. new_position: %s, old_position: %s" % (new_position, old_position))
if old_position != new_position:
logging.debug("old position other than new position")
if new_position > old_position:
logging.debug("Why am I here ?")
and now the debug:
DEBUG 1. new_position: 2, old_position: 3
DEBUG 2. old position other than new position
DEBUG Why am I here?
A:
It's probably because you are comparing different incompatible types (e.g. strings and integers). If so, then the order depends on the alphabetical order of the type names.
>>> '2' > 3
True
This applies to Python 2.x. In Python 3.x this will raise a TypeError instead.
A:
Are you sure old_position and new_position are integers? Any object can be made to print '2' and '3' when using %s... even when they implement comparisons in totally different way.
Try %r instead.
| Strange python's comparison behaviour | I have a sample code looking like this, values (position = 2, object.position = 3) :
new_position = position
old_position = object.position
logging.debug("1. new_position: %s, old_position: %s" % (new_position, old_position))
if old_position != new_position:
logging.debug("old position other than new position")
if new_position > old_position:
logging.debug("Why am I here ?")
and now the debug:
DEBUG 1. new_position: 2, old_position: 3
DEBUG 2. old position other than new position
DEBUG Why am I here?
| [
"It's probably because you are comparing different incompatible types (e.g. strings and integers). If so, then the order depends on the alphabetical order of the type names.\n>>> '2' > 3\nTrue\n\nThis applies to Python 2.x. In Python 3.x this will raise a TypeError instead.\n",
"Are you sure old_position and new_... | [
4,
2
] | [
"assuming a sane comparison operator, old_position != new_position is equivalent to old_position < new_position or old_position > new_position\n"
] | [
-2
] | [
"compare",
"python"
] | stackoverflow_0004060066_compare_python.txt |
Q:
I need to return a link generated after the completion of ModelForm
part of forms.py
class FormPublicar(forms.ModelForm):
class Meta:
model = Publicacao
exclude = ('usuario', 'aprovado', 'cadastrado_em', 'slug')
def enviar(self):
titulo = 'mensagem enviada pelo site'
destino = self.cleaned_data['emailp']
mensagem = u"""
Message that will be sent after completing the form.
Here I must pass a link to the full URL into the body of the email, something like:
[ 1 ]http://www.domain.com/item/playstation3/
/view/slug/
""" % self.cleaned_data
send_mail(
subject = titulo,
message = mensagem,
from_email = 'inform@domain.com',
recipient_list =[destino],
)
[ 1 ] I read about the "reverse", tried to mount url + view + parameter.
But I could not generate the link correctly, did a number of ways but could not.
I need to pass the domain name+view+parameter slug that is generated after completing the form.
For the recipient of e-mail see the correct link.
Can anyone help me?
Thanks in advance.
A:
Using reverse() is normally the proper way to generate the portion of the URL without the domain. For example, if your URL config contains something like the following:
(r'^item/(?P<item>[-%\w]+)/view/(?P<slug>[-\w]+)$', 'my_view_function')
Then the following call
reverse('my_view_function', kwargs={'item': 'playstation3', 'slug': 'my-slug'})
should return /item/playstation3/view/my-slug.
Preferably, your model Publicacao should define a get_absolute_url method that returns the actual URL for the model instance. See http://docs.djangoproject.com/en/1.2/ref/models/instances/#get-absolute-url.
The domain name part could be retrieved using the Sites framework:
>>> from django.contrib.sites.models import Site
>>> s = Site.objects.get_current()
>>> s.domain
u'localhost:8000'
Of course, you will have to configure the domain of your site properly. See also http://docs.djangoproject.com/en/1.2/ref/contrib/sites/#getting-the-current-domain-for-full-urls.
A:
Bernd, thanks.
About the "reverse" I already knew.
A short example.
here is only a matter of identation. http://pastebin.ca/1977489
Thanks and I apologize, I'm still studying Django.
| I need to return a link generated after the completion of ModelForm | part of forms.py
class FormPublicar(forms.ModelForm):
class Meta:
model = Publicacao
exclude = ('usuario', 'aprovado', 'cadastrado_em', 'slug')
def enviar(self):
titulo = 'mensagem enviada pelo site'
destino = self.cleaned_data['emailp']
mensagem = u"""
Message that will be sent after completing the form.
Here I must pass a link to the full URL into the body of the email, something like:
[ 1 ]http://www.domain.com/item/playstation3/
/view/slug/
""" % self.cleaned_data
send_mail(
subject = titulo,
message = mensagem,
from_email = 'inform@domain.com',
recipient_list =[destino],
)
[ 1 ] I read about the "reverse", tried to mount url + view + parameter.
But I could not generate the link correctly, did a number of ways but could not.
I need to pass the domain name+view+parameter slug that is generated after completing the form.
For the recipient of e-mail see the correct link.
Can anyone help me?
Thanks in advance.
| [
"Using reverse() is normally the proper way to generate the portion of the URL without the domain. For example, if your URL config contains something like the following:\n(r'^item/(?P<item>[-%\\w]+)/view/(?P<slug>[-\\w]+)$', 'my_view_function')\n\nThen the following call\nreverse('my_view_function', kwargs={'item':... | [
0,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0004052599_django_python.txt |
Q:
Python/Django: Have DB TimeZoneField for user, how do I use that with datetime and time to get strftime() like '%Y-%m-%dT%H:%M:%S.000Z'?
I have a DB "TimeZoneField" type for users, how do I use that with the "datetime.datetime()" object to get a strftime() string like '%Y-%m-%dT%H:%M:%S.000Z'?
A:
This was for Google Calendar's Python data API feed and it was a lot of work because Python's datetime library doesn't support ISO 8601:
http://wiki.python.org/moin/WorkingWithTime
In addition if you transmit dates with .000Z timezone to Google calendar it will ignore DST (Daylight Savings Time) for events that occur in EDT and others (so things will be off by an hour for parts of the year.)
Here is my fix: Assuming start_time and end_time are timezone aware datetime.datetime objects:
timezone_string = start_datetime.strftime('%z')[0:3] + ":" + start_datetime.strftime('%z')[3:6]
start_time = start_datetime.strftime('%Y-%m-%dT%H:%M:%S' + timezone_string)
end_time = end_datetime.strftime('%Y-%m-%dT%H:%M:%S' + timezone_string)
Note that stftime("%z") doesn't include that ":" character to separate the hours/minutes in the offset that Google's calendar API requires.
| Python/Django: Have DB TimeZoneField for user, how do I use that with datetime and time to get strftime() like '%Y-%m-%dT%H:%M:%S.000Z'? | I have a DB "TimeZoneField" type for users, how do I use that with the "datetime.datetime()" object to get a strftime() string like '%Y-%m-%dT%H:%M:%S.000Z'?
| [
"This was for Google Calendar's Python data API feed and it was a lot of work because Python's datetime library doesn't support ISO 8601:\nhttp://wiki.python.org/moin/WorkingWithTime\nIn addition if you transmit dates with .000Z timezone to Google calendar it will ignore DST (Daylight Savings Time) for events that ... | [
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0004060354_django_python.txt |
Q:
any way to invoke fragment identifiers '#' in python
Is there any way to invoke fragment identifiers from python? I'm currently using python mechanize.
A:
I think this earlier question holds your answer:
In the HTTP protocol, the fragment
(from # onwards) is not sent to the
server across the network: it's
locally retained by the browser and
used, once the server's response is
fully received, to somehow "visually
locate" the exact spot in the page to
be shown as "current" (for example, if
the returned page is in HTML, this
will be done by parsing the HTML and
looking for the first suitable
flag).
And Alex Martelli's recommendation for action also holds:
So, the procedure is: remove the
fragment e.g. via urlparse.urlparse;
use the rest to fetch the resource;
parse it appropriately based on the
server response's content-type header;
then take whatever visual action your
program does regarding the "current
spot" on the resource, based on
locating within the parsed resource
the fragment you retained in the first
step.
| any way to invoke fragment identifiers '#' in python | Is there any way to invoke fragment identifiers from python? I'm currently using python mechanize.
| [
"I think this earlier question holds your answer:\n\nIn the HTTP protocol, the fragment\n (from # onwards) is not sent to the\n server across the network: it's\n locally retained by the browser and\n used, once the server's response is\n fully received, to somehow \"visually\n locate\" the exact spot in the p... | [
4
] | [] | [] | [
"fragment_identifier",
"mechanize",
"python",
"url"
] | stackoverflow_0004060110_fragment_identifier_mechanize_python_url.txt |
Q:
Pygtk: Name is not defined
I'm trying out a few pygtk tutorials and have run across a seemingly obvious newbie mistake, but for the life of me can't figure out what's going on here.
The error:
Traceback (most recent call last):
File "main.py", line 8, in
class Base:
File "main.py", line 61, in Base
cv.set_line_width(9)
NameError: name 'cv' is not defined
The code:
def expose(self, widget, data=None):
cv = widget.window.cairo_create()
cv.set_line_width(9)
cv.set_source_rgb(0.7, 0.2, 0.0)
w = self.window.allocation.width
h = self.window.allocation.height
cv.translate(w/2, h/2)
cv.arc(0, 0, 50, 0, 2*math.pi)
cv.stroke_preserve()
cv.set_source_rgb(0.3, 0.4, 0.6)
cv.fill()
Here is the full source: http://gist.github.com/655728
A:
Your code in github reads:
def expose(self, widget, data=None):
selcv = widget.window.cairo_create()
cv.set_line_width(9)
cv.set_source_rgb(0.7, 0.2, 0.0)
...which would surely explain why cv is not defined when you try to access it.
A:
This was solved by switching to 4-space indents instead of tabs and re-indenting the entire file.
Something weird was going on, gedit was showing everything nicely indented while Netbeans showed the indent culprit
A:
You have a mixture of tabs and spaces in your file.
| Pygtk: Name is not defined | I'm trying out a few pygtk tutorials and have run across a seemingly obvious newbie mistake, but for the life of me can't figure out what's going on here.
The error:
Traceback (most recent call last):
File "main.py", line 8, in
class Base:
File "main.py", line 61, in Base
cv.set_line_width(9)
NameError: name 'cv' is not defined
The code:
def expose(self, widget, data=None):
cv = widget.window.cairo_create()
cv.set_line_width(9)
cv.set_source_rgb(0.7, 0.2, 0.0)
w = self.window.allocation.width
h = self.window.allocation.height
cv.translate(w/2, h/2)
cv.arc(0, 0, 50, 0, 2*math.pi)
cv.stroke_preserve()
cv.set_source_rgb(0.3, 0.4, 0.6)
cv.fill()
Here is the full source: http://gist.github.com/655728
| [
"Your code in github reads:\ndef expose(self, widget, data=None): \n selcv = widget.window.cairo_create()\n\n cv.set_line_width(9)\n cv.set_source_rgb(0.7, 0.2, 0.0)\n\n...which would surely explain why cv is not defined when you try to access it.\n",
"This was solved by switching to 4-space inden... | [
1,
0,
0
] | [] | [] | [
"pygtk",
"python"
] | stackoverflow_0004060681_pygtk_python.txt |
Q:
python/cgi - serves distorted images
I have been struggling for a couple hours now with serving jpg's with a python cgi site. For some reason the images always come out distorted.
Here is my code:
print('Content-type: image/jpg\n')
path = 'C:\\Users\\Admin\\Documents\\image.jpg'
print file(path, 'rb').read()
This post describes a nearly identical problem, however I am not using WSGI. I am using windows and apache and have played around with \r\n\r\n as well as print 'Content-type: image/jpg\r\n\r\n',. Similarly I have tried print file(path, 'rb').read(), thinking that a new line might be distorting the image somehow.
Any more troubleshooting ideas?
Thanks,
Josh
ps. The site must remain a cgi site.
[edit] changed to print('Content-type: image/jpeg\n')
[edit] example image:
A:
This article shows sending a file to CGI using C++. The program takes some care to convert stdout to binary:
int main()
{
#if _WIN32
// Standard I/O is in text mode by default; since we intend
// to send binary image data to standard output, we have to
// set it to binary mode.
// Error handling is tricky to say the least, so we have none.
_fmode = _O_BINARY;
if (_setmode(_fileno(stdin), _fmode) == -1) {}
if (_setmode(_fileno(stdout), _fmode) == -1) {}
#endif
You could do this in python. Here is a Windows-specific solution:
import sys
if sys.platform == "win32":
import os, msvcrt
msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
Here is code specific to python 3.x:
The standard streams are in text mode
by default. To write or read binary
data to these, use the underlying
binary buffer. For example, to write
bytes to stdout, use
sys.stdout.buffer.write(b'abc'). Using
io.TextIOBase.detach() streams can be
made binary by default. This function
sets stdin and stdout to binary:
def make_streams_binary():
sys.stdin = sys.stdin.detach()
sys.stdout = sys.stdout.detach()
Later: I also think that you should be able to UU64-encode your jpeg and send it over the wire as text with an appropriate content-length and content-type, but I've never done HTTP at this level. You'd have to look it up.
| python/cgi - serves distorted images | I have been struggling for a couple hours now with serving jpg's with a python cgi site. For some reason the images always come out distorted.
Here is my code:
print('Content-type: image/jpg\n')
path = 'C:\\Users\\Admin\\Documents\\image.jpg'
print file(path, 'rb').read()
This post describes a nearly identical problem, however I am not using WSGI. I am using windows and apache and have played around with \r\n\r\n as well as print 'Content-type: image/jpg\r\n\r\n',. Similarly I have tried print file(path, 'rb').read(), thinking that a new line might be distorting the image somehow.
Any more troubleshooting ideas?
Thanks,
Josh
ps. The site must remain a cgi site.
[edit] changed to print('Content-type: image/jpeg\n')
[edit] example image:
| [
"This article shows sending a file to CGI using C++. The program takes some care to convert stdout to binary:\nint main()\n{\n#if _WIN32\n // Standard I/O is in text mode by default; since we intend\n // to send binary image data to standard output, we have to\n // set it to binary mode.\n // Error hand... | [
2
] | [] | [] | [
"apache",
"header",
"http",
"python"
] | stackoverflow_0004060339_apache_header_http_python.txt |
Q:
is it possible to read the text written in a sticky note using a script in linux?
I am using sticky notes in ubuntu . And was wondering if it would be possible to read the text written in sticky notes using any scripting language .
A:
If you meant the "Sticky Notes" applet you can add to your panel then yes you can read that notes too.
The XML file containing all notes typically is located at ~/.gnome2/stickynotes_applet.
You just have to parse the information you need out of it. The structure should look like this.
<?xml version="1.0"?>
<stickynotes version="2.30.0">
<note title="10/31/2010" x="658" y="176" w="477" h="418">Some text</note>
</stickynotes>
Where xstands for the notes position on the x-axis, yfor its position on the y-axis, w stands for the width and h stands for the height.
It should be pretty simple to build a parser for it using Perl for example.
A:
I am not sure whether you can do it using the sticky notes, but assuming if you use Tomboy, you can do it.
You need tomboycli, a Python script which provides access to Tomboy through d-bus.
The project is hosted on Google Code here. Maybe you can study this to make your own implementation if you are interested.
A:
The tomboy notes are saved as xml files so you could write a xml parser.
| is it possible to read the text written in a sticky note using a script in linux? | I am using sticky notes in ubuntu . And was wondering if it would be possible to read the text written in sticky notes using any scripting language .
| [
"If you meant the \"Sticky Notes\" applet you can add to your panel then yes you can read that notes too.\nThe XML file containing all notes typically is located at ~/.gnome2/stickynotes_applet.\nYou just have to parse the information you need out of it. The structure should look like this.\n<?xml version=\"1.0\"?>... | [
2,
0,
0
] | [] | [] | [
"perl",
"python",
"ruby"
] | stackoverflow_0004059851_perl_python_ruby.txt |
Q:
Are there any other good alternatives to zc.buildout and/or virtualenv for installing non-python dependencies?
I am a member of a team that is about to launch a beta of a python (Django specifically) based web site and accompanying suite of backend tools. The team itself has doubled in size from 2 to 4 over the past few weeks and we expect continued growth for the next couple of months at least. One issue that has started to plague us is getting everyone up to speed in terms of getting their development environment configured and having all the right eggs installed, etc.
I'm looking for ways to simplify this process and make it less error prone. Both zc.buildout and virtualenv look like they would be good tools for addressing this problem but both seem to concentrate primarily on the python-specific issues. We have a couple of small subprojects in other languages (Java and Ruby specifically) as well as numerous python extensions that have to be compiled natively (lxml, MySQL drivers, etc). In fact, one of the biggest thorns in our side has been getting some of these extensions compiled against appropriate versions of the shared libraries so as to avoid segfaults, malloc errors and all sorts of similar issues. It doesn't help that out of 4 people we have 4 different development environments -- 1 leopard on ppc, 1 leopard on intel, 1 ubuntu and 1 windows.
Ultimately what would be ideal would be something that works roughly like this, from the dos/unix prompt:
$ git clone [repository url]
...
$ python setup-env.py
...
that then does what zc.buildout/virtualenv does (copy/symlink the python interpreter, provide a clean space to install eggs) then installs all required eggs, including installing any native shared library dependencies, installs the ruby project, the java project, etc.
Obviously this would be useful for both getting development environments up as well as deploying on staging/production servers.
Ideally I would like for the tool that accomplishes this to be written in/extensible via python, since that is (and always will be) the lingua franca of our team, but I am open to solutions in other languages.
So, my question then is: does anyone have any suggestions for better alternatives or any experiences they can share using one of these solutions to handle larger/broader install bases?
A:
Setuptools may be capable of more of what you're looking for than you realize -- if you need a custom version of lxml to work correctly on MacOS X, for instance, you can put a URL to an appropriate egg inside your setup.py and have setuptools download and install that inside your developers' environments as necessary; it also can be told to download and install a specific version of a dependency from revision control.
That said, I'd lean towards using a scriptably generated virtual environment. It's pretty straightforward to build a kickstart file which installs whichever packages you depend on and then boot virtual machines (or production hardware!) against it, with puppet or similar software doing other administration (adding users, setting up services [where's your database come from?], etc). This comes in particularly handy when your production environment includes multiple machines -- just script the generation of multiple VMs within their handy little sandboxed subnet (I use libvirt+kvm for this; while kvm isn't available on all the platforms you have developers working on, qemu certainly is, or you can do as I do and have a small number of beefy VM hosts shared by multiple developers).
This gets you out of the headaches of supporting N platforms -- you only have a single virtual platform to support -- and means that your deployment process, as defined by the kickstart file and puppet code used for setup, is source-controlled and run through your QA and review processes just like everything else.
A:
I always create a develop.py file at the top level of the project, and have also a packages directory with all of the .tar.gz files from PyPI that I want to install, and also included an unpacked copy of virtualenv that is ready to run right from that file. All of this goes into version control. Every developer can simply check out the trunk, run develop.py, and a few moments later will have a virtual environment ready to use that includes all of our dependencies at exactly the versions the other developers are using. And it works even if PyPI is down, which is very helpful at this point in that service's history.
A:
Basically, you're looking for a cross-platform software/package installer (on the lines of apt-get/yum/etc.) I'm not sure something like that exists?
An alternative might be specifying the list of packages that need to be installed via the OS-specific package management system such as Fink or DarwinPorts for Mac OS X and having a script that sets up the build environment for the in-house code?
A:
I have continued to research this issue since I posted the question. It looks like there are some attempts to address some of the needs I outlined, e.g. Minitage and Puppet which take different approaches but both may accomplish what I want -- although Minitage does not explicitly state that it supports Windows. Lacking any better options I will try to make either one of these or just extensive customized use of zc.buildout work for our needs, but I still feel like there must be better options out there.
A:
You might consider creating virtual machine appliances with whatever production OS you are running, and all of the software dependencies pre-built. Code can be edited either remotely, or with a shared folder. It worked pretty well for me in a past life that had a fairly complicated development environment.
A:
Puppet doesn't (easily) support the Win32 world either. If you're looking for a deployment mechanism and not just a "dev setup" tool, you might consider looking into ControlTier (http://open.controltier.com/) which has a open-source cross-platform solution.
Beyond that you're looking at "enterprise" software such as BladeLogic or OpsWare and typically an outrageous pricetag for the functionality offered (my opinion, obviously).
A lot of folks have been aggressively using a combination of Puppet and Capistrano (even non-rails developers) for deployment automation tools to pretty good effect. Downside, again, is that it's expecting a somewhat homogeneous environment.
| Are there any other good alternatives to zc.buildout and/or virtualenv for installing non-python dependencies? | I am a member of a team that is about to launch a beta of a python (Django specifically) based web site and accompanying suite of backend tools. The team itself has doubled in size from 2 to 4 over the past few weeks and we expect continued growth for the next couple of months at least. One issue that has started to plague us is getting everyone up to speed in terms of getting their development environment configured and having all the right eggs installed, etc.
I'm looking for ways to simplify this process and make it less error prone. Both zc.buildout and virtualenv look like they would be good tools for addressing this problem but both seem to concentrate primarily on the python-specific issues. We have a couple of small subprojects in other languages (Java and Ruby specifically) as well as numerous python extensions that have to be compiled natively (lxml, MySQL drivers, etc). In fact, one of the biggest thorns in our side has been getting some of these extensions compiled against appropriate versions of the shared libraries so as to avoid segfaults, malloc errors and all sorts of similar issues. It doesn't help that out of 4 people we have 4 different development environments -- 1 leopard on ppc, 1 leopard on intel, 1 ubuntu and 1 windows.
Ultimately what would be ideal would be something that works roughly like this, from the dos/unix prompt:
$ git clone [repository url]
...
$ python setup-env.py
...
that then does what zc.buildout/virtualenv does (copy/symlink the python interpreter, provide a clean space to install eggs) then installs all required eggs, including installing any native shared library dependencies, installs the ruby project, the java project, etc.
Obviously this would be useful for both getting development environments up as well as deploying on staging/production servers.
Ideally I would like for the tool that accomplishes this to be written in/extensible via python, since that is (and always will be) the lingua franca of our team, but I am open to solutions in other languages.
So, my question then is: does anyone have any suggestions for better alternatives or any experiences they can share using one of these solutions to handle larger/broader install bases?
| [
"Setuptools may be capable of more of what you're looking for than you realize -- if you need a custom version of lxml to work correctly on MacOS X, for instance, you can put a URL to an appropriate egg inside your setup.py and have setuptools download and install that inside your developers' environments as necess... | [
4,
3,
0,
0,
0,
0
] | [] | [] | [
"build_process",
"deployment",
"python"
] | stackoverflow_0000160834_build_process_deployment_python.txt |
Q:
How do I use simplejson to decode JSON responses to python objects?
JSON serialization Python using simpleJSON
How do I create an object so that we can optimize the serialization of the object
I'm using simpleJSON
1,2 are fixed variables
3 is a fixed dict of category and score
4 is an array of dicts that are fixed in length (4), the array is a length specificed at run-time.
The process needs to be as fast as possible, so I'm not sure about the best solution.
{
"always-include": true,
"geo": null,
"category-score" : [
{
"Arts-Entertainment": 0.72,
"Business": 0.03,
"Computers-Internet": 0.08,
"Gaming": 0.02,
"Health": 0.02,
}
],
"discovered-entities" : [
{
'relevance': '0.410652',
'count': '2',
'type': 'TelevisionStation',
'text': 'Fox News'
},
{
'relevance': '0.396494',
'count': '2',
'type': 'Organization',
'text': 'NBA'
}
]
],
}
A:
Um...
import simplejson as json
result_object = json.loads(input_json_string)
?
| How do I use simplejson to decode JSON responses to python objects? | JSON serialization Python using simpleJSON
How do I create an object so that we can optimize the serialization of the object
I'm using simpleJSON
1,2 are fixed variables
3 is a fixed dict of category and score
4 is an array of dicts that are fixed in length (4), the array is a length specificed at run-time.
The process needs to be as fast as possible, so I'm not sure about the best solution.
{
"always-include": true,
"geo": null,
"category-score" : [
{
"Arts-Entertainment": 0.72,
"Business": 0.03,
"Computers-Internet": 0.08,
"Gaming": 0.02,
"Health": 0.02,
}
],
"discovered-entities" : [
{
'relevance': '0.410652',
'count': '2',
'type': 'TelevisionStation',
'text': 'Fox News'
},
{
'relevance': '0.396494',
'count': '2',
'type': 'Organization',
'text': 'NBA'
}
]
],
}
| [
"Um...\nimport simplejson as json\nresult_object = json.loads(input_json_string)\n\n?\n"
] | [
5
] | [] | [] | [
"python",
"simplejson"
] | stackoverflow_0004060959_python_simplejson.txt |
Q:
Google App Engine: Get entity key to use in a template
Assuming I have the following:
class Person(db.Model):
name = db.StringProperty()
I would like to print all the names in an html file using a template.
template_values = {'list': Person.all()}
And the template will look like this:
{% for person in list %}
<form>
<p>{{ person.name}} </p>
<button type="button" name="**{{ person.id }}**">Delete!</button>
</form>
{% endfor %}
Ideally I would like to use person.key or person.id to then be able to delete the record using the key but that doesn't seem to work. Any Ideas how can I accomplish this?
A:
Use {{person.key.id}}, not just {{id}}. This will call each object's .key().id() method(s).
However, you should also be aware that passing Person.all() as a template value isn't necessarily a great idea; .all() returns a db.Query object, which can be treated as an iterable like you're doing but which will do multiple RPCs as you iterate through the query; instead you should use something like Person.all().fetch(SOME_NUMBER), where SOME_NUMBER is a reasonable amount to display to the user (or an arbitrarily large number if you insist on trying to display everything in one view.)
A:
Found the solution in one of the code samples:
template_values = {'list': **list**(Person.all())}
And in the template:
{% for person in list %}
<form>
<p>{{ person.name}}</p>
<button type="button" name="**{{ person.key }}**">Delete!</button>
</form>
{% endfor %}
As Wooble recommended, you may want to try Person.all().fetch(SOME_NUMBER) instead.
| Google App Engine: Get entity key to use in a template | Assuming I have the following:
class Person(db.Model):
name = db.StringProperty()
I would like to print all the names in an html file using a template.
template_values = {'list': Person.all()}
And the template will look like this:
{% for person in list %}
<form>
<p>{{ person.name}} </p>
<button type="button" name="**{{ person.id }}**">Delete!</button>
</form>
{% endfor %}
Ideally I would like to use person.key or person.id to then be able to delete the record using the key but that doesn't seem to work. Any Ideas how can I accomplish this?
| [
"Use {{person.key.id}}, not just {{id}}. This will call each object's .key().id() method(s).\nHowever, you should also be aware that passing Person.all() as a template value isn't necessarily a great idea; .all() returns a db.Query object, which can be treated as an iterable like you're doing but which will do mul... | [
6,
0
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0004059965_google_app_engine_python.txt |
Q:
Durand-kerner implementation doesn't work
What's wrong with this implementation of the Durand-Kerner algorithm (here) ?
def durand_kerner(poly, start=complex(.4, .9), epsilon=10**-16):#float('-inf')):
roots = []
for e in xrange(poly.degree):
roots.append(start ** e)
while True:
new = []
for i, r in enumerate(roots):
new_r = r - (poly(r))/(reduce(operator.mul, [(r - r_1) for j, r_1 in enumerate(roots) if i != j]))
new.append(new_r)
if all(n == roots[i] or abs(n - roots[i]) < epsilon for i, n in enumerate(new)):
return new
roots = new
When I try it, I have to stop it with KeyboardInterrupt because it doesn't stop!
poly is a Polynomial instance of the pypol library.
Thank you in advance,
rubik
EDIT: Using a numpy polynomial it takes 9 iterations:
In [1]: import numpy as np
In [2]: roots.d1(np.poly1d([1, -3, 3, -5]))
3
[(1.3607734793516519+2.0222302921553128j), (-1.3982133295376746-0.69356635962504309j), (3.0374398501860234-1.3286639325302696j)]
[(0.98096328371966801+1.3474626910848715j), (-0.3352519326012724-0.64406860772816388j), (2.3542886488816044-0.70339408335670761j)]
[(0.31718054925650596+0.93649454851955749j), (0.49001572078718736-0.9661410790307261j), (2.1928037299563066+0.029646530511168612j)]
[(0.20901563897345796+1.5727420147652911j), (0.041206038662691125-1.5275192097633465j), (2.7497783223638508-0.045222805001944255j)]
[(0.21297050700971876+1.3948274731404162j), (0.18467846583682396-1.3845653821841168j), (2.6023510271534573-0.010262090956299326j)]
[(0.20653075193800668+1.374878742771485j), (0.20600107336130213-1.3746529207714699j), (2.5874681747006911-0.00022582200001499547j)]
[(0.20629950692533283+1.3747296033941407j), (0.20629947661265013-1.374729584400741j), (2.5874010164620169-1.899339978055233e-08j)]
[(0.20629947401589896+1.3747296369986031j), (0.20629947401590082-1.3747296369986042j), (2.5874010519682002+9.1830687539942581e-16j)]
[(0.20629947401590029+1.3747296369986026j), (0.20629947401590026-1.3747296369986026j), (2.5874010519681994+1.1832913578315177e-30j)]
Out[2]:
[(0.20629947401590029+1.3747296369986026j),
(0.20629947401590029-1.3747296369986026j),
(2.5874010519681994+0j)]
Using a pypol polynomial it never finishes (it is probably a bug in pypol):
In [3]: roots.d2(poly1d([1, -3, 3, -5]))
^C---------------------------------------------------------------------------
KeyboardInterrupt
but I can't find the bug!!
EDIT2: Comparing the __call__ method with Martin's Poly:
>>> p = Poly(-5, 3, -3, 1)
>>> from pypol import poly1d
>>> p2 = poly1d([1, -3, 3, -5])
>>> for i in xrange(-100000, 100000):
assert p(i) == p2(i)
>>>
>>> for i in xrange(-10000, 10000):
assert p(complex(1, i)) == p2(complex(1, i))
>>> for i in xrange(-10000, 10000):
assert p(complex(i, i)) == p2(complex(i, i))
>>>
EDIT3: pypol works fine if the roots aren't complex numbers:
In [1]: p = pypol.funcs.from_roots([4, -2, 443, -11212])
In [2]: durand_kerner(p)
Out[2]: [(4+0j), (443+0j), (-2+0j), (-11212+0j)]
So it doesn't works only when the roots are complex numbers!
EDIT4: I wrote a slightly different implementation for numpy polynomials and saw that after one iteration the roots (of the Wikipedia polynomial) are different:
In [4]: d1(numpyp.poly1d([1, -3, 3, -5]))
Out[4]:
[(0.98096328371966801+1.3474626910848715j),
(-0.3352519326012724-0.64406860772816388j),
(2.3542886488816044-0.70339408335670761j)]
In [5]: d2(pypol.poly1d([1, -3, 3, -5]))
Out[5]:
[(0.9809632837196679+1.3474626910848717j),
(-0.33525193260127306-0.64406860772816377j),
(2.3542886488816048-0.70339408335670772j)] ## here
EDIT5: Hey! If I change the line: if all(n == roots[i] ... ) into if all(str(n) == str(roots[i]) ... ) it finishes and returns the right roots!!!
In [9]: p = pypol.poly1d([1, -3, 3, -5])
In [10]: roots.durand_kerner(p)
Out[10]:
[(0.20629947401590029+1.3747296369986026j),
(0.20629947401590013-1.3747296369986026j),
(2.5874010519681994+0j)]
But the question is: why does it work with a different complex numbers comparation??
UPDATE
Now it works, and I've done some tests:
In [1]: p = pypol.poly1d([1, -3, 3, -1])
In [2]: p
Out[2]: + x^3 - 3x^2 + 3x - 1
In [3]: pypol.roots.cubic(p)
Out[3]: (1.0, 1.0, 1.0)
In [4]: durand_kerner(p)
Out[4]:
((1+0j),
(1.0000002484566535-2.708692281244913e-17j),
(0.99999975147728026+2.9792265510301965e-17j))
In [5]: q = x ** 3 - 1
In [6]: q
Out[6]: + x^3 - 1
In [7]: pypol.roots.cubic(q)
Out[7]: (1.0, (-0.5+0.8660254037844386j), (-0.5-0.8660254037844386j))
In [8]: durand_kerner(q)
Out[8]: ((1+0j), (-0.5-0.8660254037844386j), (-0.5+0.8660254037844386j))
A:
Your algorithm looks fine, and it works for me for the example in the wikipedia
import operator
class Poly:
def __init__(self, *koeff):
self.koeff = koeff
self.degree = len(koeff)-1
def __call__(self, val):
res = 0
x = 1
for k in self.koeff:
res += x*k
x *= val
return res
def durand_kerner(poly, start=complex(.4, .9), epsilon=10**-16):#float('-inf')):
roots = []
for e in xrange(poly.degree):
roots.append(start ** e)
while True:
new = []
for i, r in enumerate(roots):
new_r = r - (poly(r))/(reduce(operator.mul, [(r - r_1)
for j, r_1 in enumerate(roots) if i != j]))
new.append(new_r)
if all((n == roots[i] or abs(n - roots[i]) < epsilon) for i, n in enumerate(new)):
return new
roots = new
print durand_kerner(Poly(-5,3,-3,1))
gives
[(0.20629947401590026+1.3747296369986026j),
(0.20629947401590026-1.3747296369986026j),
(2.5874010519681994+8.6361685550944446e-78j)]
A:
About your "EDIT 5": this happens because str() doesn't format numbers to the full precision.
>>> print str((2.5874010519681994+8.636168555094445e-78j))
(2.58740105197+8.63616855509e-78j)
>>> print repr((2.5874010519681994+8.636168555094445e-78j))
(2.5874010519681994+8.636168555094445e-78j)
>>>
So don't do that.
In any case, the equality test in your code:
if all(n == roots[i] or abs(n - roots[i]) < epsilon for i, n in enumerate(new)):
is redundant; if n == roots[i], then abs(n - roots[i]) will be zero, so you could do just
if all(abs(n - roots[i]) < epsilon for i, n in enumerate(new)):
and put a bit of effort into working out what the default for epsilon should be; as I pointed out in a comment, solving X**3 == 1 converges but your default epsilon is too small to stop it looping forever. 1.12e-16 looks like a better bet for the default epsilon.
For amusement, try the unsuited Poly([-1, 3, -3, 1]) ... three roots all equal to (1+0j) ... it takes over 600 iterations, and the errors in the last 10 or so iterations jump about astonishingly until it just arrives at a reasonable solution from far out in left field.
| Durand-kerner implementation doesn't work | What's wrong with this implementation of the Durand-Kerner algorithm (here) ?
def durand_kerner(poly, start=complex(.4, .9), epsilon=10**-16):#float('-inf')):
roots = []
for e in xrange(poly.degree):
roots.append(start ** e)
while True:
new = []
for i, r in enumerate(roots):
new_r = r - (poly(r))/(reduce(operator.mul, [(r - r_1) for j, r_1 in enumerate(roots) if i != j]))
new.append(new_r)
if all(n == roots[i] or abs(n - roots[i]) < epsilon for i, n in enumerate(new)):
return new
roots = new
When I try it, I have to stop it with KeyboardInterrupt because it doesn't stop!
poly is a Polynomial instance of the pypol library.
Thank you in advance,
rubik
EDIT: Using a numpy polynomial it takes 9 iterations:
In [1]: import numpy as np
In [2]: roots.d1(np.poly1d([1, -3, 3, -5]))
3
[(1.3607734793516519+2.0222302921553128j), (-1.3982133295376746-0.69356635962504309j), (3.0374398501860234-1.3286639325302696j)]
[(0.98096328371966801+1.3474626910848715j), (-0.3352519326012724-0.64406860772816388j), (2.3542886488816044-0.70339408335670761j)]
[(0.31718054925650596+0.93649454851955749j), (0.49001572078718736-0.9661410790307261j), (2.1928037299563066+0.029646530511168612j)]
[(0.20901563897345796+1.5727420147652911j), (0.041206038662691125-1.5275192097633465j), (2.7497783223638508-0.045222805001944255j)]
[(0.21297050700971876+1.3948274731404162j), (0.18467846583682396-1.3845653821841168j), (2.6023510271534573-0.010262090956299326j)]
[(0.20653075193800668+1.374878742771485j), (0.20600107336130213-1.3746529207714699j), (2.5874681747006911-0.00022582200001499547j)]
[(0.20629950692533283+1.3747296033941407j), (0.20629947661265013-1.374729584400741j), (2.5874010164620169-1.899339978055233e-08j)]
[(0.20629947401589896+1.3747296369986031j), (0.20629947401590082-1.3747296369986042j), (2.5874010519682002+9.1830687539942581e-16j)]
[(0.20629947401590029+1.3747296369986026j), (0.20629947401590026-1.3747296369986026j), (2.5874010519681994+1.1832913578315177e-30j)]
Out[2]:
[(0.20629947401590029+1.3747296369986026j),
(0.20629947401590029-1.3747296369986026j),
(2.5874010519681994+0j)]
Using a pypol polynomial it never finishes (it is probably a bug in pypol):
In [3]: roots.d2(poly1d([1, -3, 3, -5]))
^C---------------------------------------------------------------------------
KeyboardInterrupt
but I can't find the bug!!
EDIT2: Comparing the __call__ method with Martin's Poly:
>>> p = Poly(-5, 3, -3, 1)
>>> from pypol import poly1d
>>> p2 = poly1d([1, -3, 3, -5])
>>> for i in xrange(-100000, 100000):
assert p(i) == p2(i)
>>>
>>> for i in xrange(-10000, 10000):
assert p(complex(1, i)) == p2(complex(1, i))
>>> for i in xrange(-10000, 10000):
assert p(complex(i, i)) == p2(complex(i, i))
>>>
EDIT3: pypol works fine if the roots aren't complex numbers:
In [1]: p = pypol.funcs.from_roots([4, -2, 443, -11212])
In [2]: durand_kerner(p)
Out[2]: [(4+0j), (443+0j), (-2+0j), (-11212+0j)]
So it doesn't works only when the roots are complex numbers!
EDIT4: I wrote a slightly different implementation for numpy polynomials and saw that after one iteration the roots (of the Wikipedia polynomial) are different:
In [4]: d1(numpyp.poly1d([1, -3, 3, -5]))
Out[4]:
[(0.98096328371966801+1.3474626910848715j),
(-0.3352519326012724-0.64406860772816388j),
(2.3542886488816044-0.70339408335670761j)]
In [5]: d2(pypol.poly1d([1, -3, 3, -5]))
Out[5]:
[(0.9809632837196679+1.3474626910848717j),
(-0.33525193260127306-0.64406860772816377j),
(2.3542886488816048-0.70339408335670772j)] ## here
EDIT5: Hey! If I change the line: if all(n == roots[i] ... ) into if all(str(n) == str(roots[i]) ... ) it finishes and returns the right roots!!!
In [9]: p = pypol.poly1d([1, -3, 3, -5])
In [10]: roots.durand_kerner(p)
Out[10]:
[(0.20629947401590029+1.3747296369986026j),
(0.20629947401590013-1.3747296369986026j),
(2.5874010519681994+0j)]
But the question is: why does it work with a different complex numbers comparation??
UPDATE
Now it works, and I've done some tests:
In [1]: p = pypol.poly1d([1, -3, 3, -1])
In [2]: p
Out[2]: + x^3 - 3x^2 + 3x - 1
In [3]: pypol.roots.cubic(p)
Out[3]: (1.0, 1.0, 1.0)
In [4]: durand_kerner(p)
Out[4]:
((1+0j),
(1.0000002484566535-2.708692281244913e-17j),
(0.99999975147728026+2.9792265510301965e-17j))
In [5]: q = x ** 3 - 1
In [6]: q
Out[6]: + x^3 - 1
In [7]: pypol.roots.cubic(q)
Out[7]: (1.0, (-0.5+0.8660254037844386j), (-0.5-0.8660254037844386j))
In [8]: durand_kerner(q)
Out[8]: ((1+0j), (-0.5-0.8660254037844386j), (-0.5+0.8660254037844386j))
| [
"Your algorithm looks fine, and it works for me for the example in the wikipedia\nimport operator\nclass Poly:\n def __init__(self, *koeff):\n self.koeff = koeff\n self.degree = len(koeff)-1\n\n def __call__(self, val):\n res = 0\n x = 1\n for k in self.koeff:\n r... | [
1,
1
] | [] | [] | [
"algorithm",
"infinite_loop",
"polynomial_math",
"python"
] | stackoverflow_0004057684_algorithm_infinite_loop_polynomial_math_python.txt |
Q:
python: how to validate userdefined condition?
what I am struggling with is testing predefined conditions which takes user provided parameters like in example below:
cond = "if ( 1 is yes and 2 is no ) or ( 1 is yes and 2 is no )"
cond2 = "if (3 is no or 1 is no )"
vars = []
lst = cond.split()
lst += cond2.split()
for l in lst:
if l.isdigit():
if l not in vars:
vars.append(l)
# ... sort
# ... read user answers => x = no, y = no, y = yes
# ... replace numbers with input (yes or no)
# ... finally I have
cond = "if ( no is yes and no is no ) or ( no is yes and no is no )"
cond2 = "if (yes is no or no is no )"
First of all, is this the right approach?
Secondly, how do I validate above conditions if True or False ?
Thank You in advance.
A:
Use Python's language services to parse and compile the string, then execute the resulting AST.
A:
so, after some reading based on Ignacio's tip, I think I have it after some string modifications. However, still not quite sure if this is the right approach.
So, my condition variable is defined as below
cond = """if ( 'no' is 'yes' and 'no' is 'no' ):
result.append[1]
else:
result.append[0]
"""
Additionally I create variable to store condition result to evaluate it later
result = []
I run exec on my string
exec(cond)
Finally, I can evaluate result.
if result[0] == 1
print "Condition was met"
else:
print "Condition wasn't met"
Any thoughts or comments highly appreciated.
A:
All a user's answers taken together can be used to form a unique binary number (one composed of only zeros and ones). You could make a table (list) for each condition indexed by the each of the possible combinations of answer in each position store the value a given condition -- expressed as a lambda function -- would have for that set.
Once these tables are set up, you could determine whether any condition is true by looking up the value in the corresponding table indexed by a given combination of answers. Below is an example of how this might be set up.
NUM_ANSWERS = 4
NUM_COMBOS = 2**NUM_ANSWERS
NO,YES = 'no','yes'
def index(answers):
""" Convert a list of yes/no answers into binary number. """
binstr = ''.join([('1' if a is 'yes' else '0') for a in answers])
return int(binstr, 2)
def answers(index):
""" Convert binary value of number into list of yes/no answers. """
masks = [2**p for p in range(NUM_ANSWERS-1, -1, -1)]
bits = [((index & m) / m) for m in masks]
return [[NO,YES][b] for b in bits]
# condition expressions
cond_expr1 = lambda a1,a2,a3,a4: a1 is YES and a2 is NO # a3,a4 ignored
cond_expr2 = lambda a1,a2,a3,a4: (
( a1 is YES and a2 is NO ) or ( a3 is YES and a4 is NO )
)
# build tables for each condition
cond1 = []
cond2 = []
for i in range(NUM_COMBOS):
ans_combo = answers(i)
cond1.append( cond_expr1(*ans_combo) )
cond2.append( cond_expr2(*ans_combo) )
# once tables are built, you can lookup the corresponding conditional
print cond1[ index(['yes', 'no', 'no', 'yes']) ] # True
print cond2[ index(['yes', 'no', 'yes', 'no']) ] # True
| python: how to validate userdefined condition? | what I am struggling with is testing predefined conditions which takes user provided parameters like in example below:
cond = "if ( 1 is yes and 2 is no ) or ( 1 is yes and 2 is no )"
cond2 = "if (3 is no or 1 is no )"
vars = []
lst = cond.split()
lst += cond2.split()
for l in lst:
if l.isdigit():
if l not in vars:
vars.append(l)
# ... sort
# ... read user answers => x = no, y = no, y = yes
# ... replace numbers with input (yes or no)
# ... finally I have
cond = "if ( no is yes and no is no ) or ( no is yes and no is no )"
cond2 = "if (yes is no or no is no )"
First of all, is this the right approach?
Secondly, how do I validate above conditions if True or False ?
Thank You in advance.
| [
"Use Python's language services to parse and compile the string, then execute the resulting AST.\n",
"so, after some reading based on Ignacio's tip, I think I have it after some string modifications. However, still not quite sure if this is the right approach.\nSo, my condition variable is defined as below \n\n... | [
1,
0,
0
] | [] | [] | [
"conditional_statements",
"python",
"validation"
] | stackoverflow_0004059691_conditional_statements_python_validation.txt |
Q:
How can I build a regular expression to match a single word?
Say I had the following strings:
Dublin, Ireland.
DublinIreland
Ireland, Dublin
What regular Expression could I use to find the word Dublin in the above strings, but, it cannot count DublinIreland. As in, DublinIreland doesn't say Dublin, it is a whole word that says DublinIreland.
A:
Edit : this answer referred to OP's first question, and it actually still answers is second :-p
Use boundaries, such as \b. \bwent\b would match went.
A:
This would match all capitalised words:
/\b([A-Z][a-z]+)\b/
Or just the word 'Dublin':
/\bDublin\b/
A:
In some languages you can use () to specify a selection and then reference the first selection with $1 or 1.
A:
This should match ever instance of Dublin in your sample, but you will have to look at the match groups because it would also capture the I in DublinIreland.
/(\bDublin)(\b|[A-Z])/g
| How can I build a regular expression to match a single word? | Say I had the following strings:
Dublin, Ireland.
DublinIreland
Ireland, Dublin
What regular Expression could I use to find the word Dublin in the above strings, but, it cannot count DublinIreland. As in, DublinIreland doesn't say Dublin, it is a whole word that says DublinIreland.
| [
"Edit : this answer referred to OP's first question, and it actually still answers is second :-p\nUse boundaries, such as \\b. \\bwent\\b would match went.\n",
"This would match all capitalised words:\n/\\b([A-Z][a-z]+)\\b/\n\nOr just the word 'Dublin':\n/\\bDublin\\b/\n\n",
"In some languages you can use () to... | [
7,
0,
0,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0004061083_python_regex.txt |
Q:
Does linux disk buffer cache make python cPickle more efficient than shelve?
Is IO more efficient, due to the linux disk buffer cache, when storing frequently accessed python objects as separate cPickle files instead of storing all objects in one large shelf?
Does the disk buffer cache operate differently in these two scenarios with respect to efficiency?
There may be thousands of large files (generally around 100Mb, but sometimes 1Gb), but much RAM (eg 64 Gb).
A:
I don't know of any theoretical way to decide which method is faster, and even if I did, I'm not sure I would trust it. So let's write some code and test it.
If we package our pickle/shelve managers in classes with a common interface, then it will be easy to swap them in and out of your code. So if at some future point you discover one is better than the other (or discover some even better way) all you have to do is write a class with the same interface and you'll be able to plug the new class into your code with very little modification to anything else.
test.py:
import cPickle
import shelve
import os
class PickleManager(object):
def store(self,name,value):
with open(name,'w') as f:
cPickle.dump(value,f)
def load(self,name):
with open(name,'r') as f:
return cPickle.load(f)
class ShelveManager(object):
def __enter__(self):
if os.path.exists(self.fname):
self.shelf=shelve.open(self.fname)
else:
self.shelf=shelve.open(self.fname,'n')
return self
def __exit__(self,ext_type,exc_value,traceback):
self.shelf.close()
def __init__(self,fname):
self.fname=fname
def store(self,name,value):
self.shelf[name]=value
def load(self,name):
return self.shelf[name]
def write(manager):
for i in range(100):
fname='/tmp/{i}.dat'.format(i=i)
data='The sky is so blue'*100
manager.store(fname,data)
def read(manager):
for i in range(100):
fname='/tmp/{i}.dat'.format(i=i)
manager.load(fname)
Normally, you'd use PickleManager like this:
manager=PickleManager()
manager.load(...)
manager.store(...)
while you'd use the ShelveManager like this:
with ShelveManager('/tmp/shelve.dat') as manager:
manager.load(...)
manager.store(...)
But to test performance, you could do something like this:
python -mtimeit -s'import test' 'with test.ShelveManager("/tmp/shelve.dat") as s: test.read(s)'
python -mtimeit -s'import test' 'test.read(test.PickleManager())'
python -mtimeit -s'import test' 'with test.ShelveManager("/tmp/shelve.dat") as s: test.write(s)'
python -mtimeit -s'import test' 'test.write(test.PickleManager())'
At least on my machine, the results came out like this:
read (ms) write (ms)
PickleManager 9.26 7.92
ShelveManager 5.32 30.9
So it looks like ShelveManager may be faster at reading, but PickleManager may be faster at writing.
Be sure to run these tests yourself. Timeit results can vary due to version of Python, OS, filesystem type, hardware, etc.
Also, note my write and read functions generate very small files. You'll want to test this on data more similar to your use case.
| Does linux disk buffer cache make python cPickle more efficient than shelve? | Is IO more efficient, due to the linux disk buffer cache, when storing frequently accessed python objects as separate cPickle files instead of storing all objects in one large shelf?
Does the disk buffer cache operate differently in these two scenarios with respect to efficiency?
There may be thousands of large files (generally around 100Mb, but sometimes 1Gb), but much RAM (eg 64 Gb).
| [
"I don't know of any theoretical way to decide which method is faster, and even if I did, I'm not sure I would trust it. So let's write some code and test it.\nIf we package our pickle/shelve managers in classes with a common interface, then it will be easy to swap them in and out of your code. So if at some future... | [
3
] | [] | [] | [
"caching",
"linux",
"pickle",
"python",
"shelve"
] | stackoverflow_0004060937_caching_linux_pickle_python_shelve.txt |
Q:
Getting started with json
I have never worked with json before. I am trying: http://api.worldbank.org//topics?format=JSON and make things with it, but I don't even know how to get started.
Following some manuals, I did this:
import urllib
import urllib2
import simplejson
urlb = 'http://api.worldbank.org/topics'
datab = urllib2.urlopen(urlb+'?'+ param)
resultb = simplejson.load(datab)
but I have no clue of how to parse and work on it now, how do I list the individual items? count them? filter them?. Is there any simple tutorial that you guys can point me to or advice? I checked diveintopython, json's website and most of the obvious ones, but I am still struggling with it. Is there any simple step-by-step guide that somebody could point me to?
Thanks
A:
Trying printing resultb. Its just a python list with dictionaries inside it. Treat it like you would any list.
| Getting started with json | I have never worked with json before. I am trying: http://api.worldbank.org//topics?format=JSON and make things with it, but I don't even know how to get started.
Following some manuals, I did this:
import urllib
import urllib2
import simplejson
urlb = 'http://api.worldbank.org/topics'
datab = urllib2.urlopen(urlb+'?'+ param)
resultb = simplejson.load(datab)
but I have no clue of how to parse and work on it now, how do I list the individual items? count them? filter them?. Is there any simple tutorial that you guys can point me to or advice? I checked diveintopython, json's website and most of the obvious ones, but I am still struggling with it. Is there any simple step-by-step guide that somebody could point me to?
Thanks
| [
"Trying printing resultb. Its just a python list with dictionaries inside it. Treat it like you would any list.\n"
] | [
4
] | [] | [] | [
"json",
"python"
] | stackoverflow_0004061274_json_python.txt |
Q:
Using Python lxml.html how can I find images within link tags?
I am using lxml.html to parse some hmtl to get links, however when it hits a link which contains an image it just returns blank, what it'd really like is to be able to detect if it's an image, and then try and return the image alt text.
So it looks like this...
from lxml.html import parse, fromstring
doc = fromstring('<a href="Link One">Anchor Link One</a><br /><a href="Link Two"<img src="Image Link Two" alt="Alt Image" /></a><br /><a href="Link Three">Anchor Link Three</a><br />')
for link in doc.cssselect('a'):
print '%s: %s' % (link.text_content(), link.get('href'))
result
Anchor Link One: Link One
: Link Two
Anchor Link Three: Link Three
So I tried using .html_content() to try and get the raw html and then check if that was an image.
Hmm.. How to detect if wrapped in image, and/or pull out the html there....
A:
Just modify your css selector:
for img in doc.cssselect('a img'):
You can also use an XPATH expression:
for img in doc.xpath('a//img'):
A:
for link in doc.xpath('a'):
img = link.find('img')
if img is not None:
print '%s: %s' % (img.get('alt'), link.get('href'))
else:
print '%s: %s' % (link.text_content(), link.get('href'))
| Using Python lxml.html how can I find images within link tags? | I am using lxml.html to parse some hmtl to get links, however when it hits a link which contains an image it just returns blank, what it'd really like is to be able to detect if it's an image, and then try and return the image alt text.
So it looks like this...
from lxml.html import parse, fromstring
doc = fromstring('<a href="Link One">Anchor Link One</a><br /><a href="Link Two"<img src="Image Link Two" alt="Alt Image" /></a><br /><a href="Link Three">Anchor Link Three</a><br />')
for link in doc.cssselect('a'):
print '%s: %s' % (link.text_content(), link.get('href'))
result
Anchor Link One: Link One
: Link Two
Anchor Link Three: Link Three
So I tried using .html_content() to try and get the raw html and then check if that was an image.
Hmm.. How to detect if wrapped in image, and/or pull out the html there....
| [
"Just modify your css selector:\nfor img in doc.cssselect('a img'):\n\nYou can also use an XPATH expression:\nfor img in doc.xpath('a//img'):\n\n",
"for link in doc.xpath('a'):\n img = link.find('img')\n if img is not None:\n print '%s: %s' % (img.get('alt'), link.get('href'))\n else:\n pri... | [
3,
2
] | [] | [] | [
"html_parsing",
"lxml",
"python"
] | stackoverflow_0004061354_html_parsing_lxml_python.txt |
Q:
multiple return statements in python "def" causes syntax error
I'm trying to test my function "def" in a python shell, but when i paste it in there are errors. It seems not to like it when i have multiple return statements inside one "def".
For example:
def foo():
valid = True
if valid:
return True
return False
Does anyone know why?
thanks!
A:
Your indentation is wrong. Should be this:
def foo():
valid = True
if valid:
return True
return False
| multiple return statements in python "def" causes syntax error | I'm trying to test my function "def" in a python shell, but when i paste it in there are errors. It seems not to like it when i have multiple return statements inside one "def".
For example:
def foo():
valid = True
if valid:
return True
return False
Does anyone know why?
thanks!
| [
"Your indentation is wrong. Should be this:\ndef foo():\n valid = True\n if valid:\n return True\n return False\n\n"
] | [
10
] | [] | [] | [
"python"
] | stackoverflow_0004061475_python.txt |
Q:
Tail Call Optimization in Mono/Ironpython
given that CLR supports tail call optimization I was wondering if Mono, and consequently Ironpython running on Mono has support for TCO ?
A:
I can't give a definitive answer, but there is ample evidence in forums (e.g., here) that because Mono doesn't use a callee-pops-arguments calling convention, it can't (easily) support tail calls. There is a couple of unresolved bugs, here and here, indicating that F# is still waiting for this.
| Tail Call Optimization in Mono/Ironpython | given that CLR supports tail call optimization I was wondering if Mono, and consequently Ironpython running on Mono has support for TCO ?
| [
"I can't give a definitive answer, but there is ample evidence in forums (e.g., here) that because Mono doesn't use a callee-pops-arguments calling convention, it can't (easily) support tail calls. There is a couple of unresolved bugs, here and here, indicating that F# is still waiting for this.\n"
] | [
4
] | [] | [] | [
".net",
"ironpython",
"mono",
"python"
] | stackoverflow_0004061671_.net_ironpython_mono_python.txt |
Q:
fit mysql db in memory
I am using Redis database where we store the navigational information. These data must be persistent and should be fetched faster. I don't have more than 200 MB data in this data set.
I face problem when writing admin modules for redis db and I really missing the sql schema and power of django style admin modules.
Now I am thinking of using MySQL. The requirement is, I want the persistent database but the data can be loaded into the memory like redis so that I can do the SQL queries REALLY faster.
Is it possible to use MySQL in persistent mode and instruct MySQL to use the memory for querying purpose? What is the best suitable MySQL DB where I do not worry much on consistencies where our writes are very few.
A:
I would create a read only slave to your mysql database and force its database engines to memory. You'd have to handle failures by re-initializing the read only database, but that can be scripted rather easily.
This way you still have your persistence in the regular mysql database and your read speed in the read only memory tables.
A:
I would think you could have a persistent table, copy all of the data into a MEMORY engine table whenever the server starts, and have triggers on the memory db for INSERT UPDATE and DELETE write to the persistent table so it is hidden for the user. Correct me if I'm wrong though, it's just the approach I would first try.
A:
i did that with HSQLDB (link: http://hsqldb.org/)
has a few basic SQL features missing, like the IN clause. but it mostly does the job.
| fit mysql db in memory | I am using Redis database where we store the navigational information. These data must be persistent and should be fetched faster. I don't have more than 200 MB data in this data set.
I face problem when writing admin modules for redis db and I really missing the sql schema and power of django style admin modules.
Now I am thinking of using MySQL. The requirement is, I want the persistent database but the data can be loaded into the memory like redis so that I can do the SQL queries REALLY faster.
Is it possible to use MySQL in persistent mode and instruct MySQL to use the memory for querying purpose? What is the best suitable MySQL DB where I do not worry much on consistencies where our writes are very few.
| [
"I would create a read only slave to your mysql database and force its database engines to memory. You'd have to handle failures by re-initializing the read only database, but that can be scripted rather easily.\nThis way you still have your persistence in the regular mysql database and your read speed in the read... | [
1,
0,
0
] | [] | [] | [
"mysql",
"performance",
"python",
"sqlalchemy"
] | stackoverflow_0004061828_mysql_performance_python_sqlalchemy.txt |
Q:
Saving map data in a 2d ORPG
I'm trying to figure out how I can best save the map data for a 2d ORPG engine I am developing, the file would contain tile data (Is it blocked, what actual graphics would it use, and various other properties).
I am currently using a binary format but I think this might be a bit too limited and hard to debug, what alternatives are there, I was thinking about perhaps JSON or XML but I don't know if there are any other better options.
It has to work with C++ and C# and preferably also with Python.
A:
XML is well supported across basically every language. It may become verbose for large maps, however, depending on how you encode the map data in XML.
JSON might not be a good choice, simply because I don't think it supports multiline strings, which would be helpful (although not really necessary)
YAML is another alternative, though it's not as well-known.
You could just stick to binary - most maps would be a pain to edit by hand, no matter what format you pick (though I've heard of Starcraft maps being edited with hex editors...) Just use whatever seems easiest for you.
Additionally, check out the Tiled map editor (http://www.mapeditor.org/), which lets you edit maps (with custom tile properties, I think) and save it in an XML based format, including optional GZip for compression.
A:
Personally, I would stick with a binary format. Whatever method you choose, it's going to be a pain in the ass to edit by hand anyway, so you may as well stick to binary which gives you a size and speed advantage.
You're also going to want a map editor anyway so that you do not have to edit it by hand.
A:
Lua is also a possibility which can be used as a config file with tables. It's been a while since I worked with Python but doesn't it also support a AJAX style data structure? You could simply use Python files if you are already using it.
| Saving map data in a 2d ORPG | I'm trying to figure out how I can best save the map data for a 2d ORPG engine I am developing, the file would contain tile data (Is it blocked, what actual graphics would it use, and various other properties).
I am currently using a binary format but I think this might be a bit too limited and hard to debug, what alternatives are there, I was thinking about perhaps JSON or XML but I don't know if there are any other better options.
It has to work with C++ and C# and preferably also with Python.
| [
"XML is well supported across basically every language. It may become verbose for large maps, however, depending on how you encode the map data in XML.\nJSON might not be a good choice, simply because I don't think it supports multiline strings, which would be helpful (although not really necessary)\nYAML is anoth... | [
1,
1,
0
] | [] | [] | [
"c#",
"c++",
"python"
] | stackoverflow_0004052990_c#_c++_python.txt |
Q:
How to access a MS SQL Server using Python 3?
I'm using a linux machine to make a little python program that needs to input its result in a SQL Server 2000 DB.
I'm new to python so I'm struggling quite a bit to find what's the best solution to connect to the DB using python 3, since most of the libs I looked only work in python 2.
As an added bonus question, the finished version of this will be compiled to a windows program using py2exe. Is there anything I should be aware of, any changes to make?
Thanks
A:
One option would be trying the pyodbc branch for python 3 support. I think some people have reported success, but you might want to inquire at the pyodbc discussion group.
If you stick to platform independent parts of the python library (most of it), you shouldn't have any issues on windows with py2exe.
A:
I can't answer your question directly, but given that many popular Python packages and frameworks are not yet fully supported on Python 3, you might consider just using Python 2.x. Unless there are features you absolutely cannot live without in Python 3, of course.
And it isn't clear from your post if you plan to deploy to Windows only, or Windows and Linux. If it's only Windows, then you should probably just develop on Windows to start with: the native MSSQL drivers are included in most recent versions so you don't have anything extra to install, and it gives you more options, such as adodbapi.
A:
If you want to have portable mssql server library, you can try the module from www.pytds.com. It works with 2.5+ AND 3.1, have a good stored procedure support. It's api is more "functional", and has some good features you won't find anywhere else.
| How to access a MS SQL Server using Python 3? | I'm using a linux machine to make a little python program that needs to input its result in a SQL Server 2000 DB.
I'm new to python so I'm struggling quite a bit to find what's the best solution to connect to the DB using python 3, since most of the libs I looked only work in python 2.
As an added bonus question, the finished version of this will be compiled to a windows program using py2exe. Is there anything I should be aware of, any changes to make?
Thanks
| [
"One option would be trying the pyodbc branch for python 3 support. I think some people have reported success, but you might want to inquire at the pyodbc discussion group.\nIf you stick to platform independent parts of the python library (most of it), you shouldn't have any issues on windows with py2exe.\n",
"I... | [
1,
0,
0
] | [] | [] | [
"py2exe",
"python",
"python_3.x",
"sql_server"
] | stackoverflow_0003571819_py2exe_python_python_3.x_sql_server.txt |
Q:
enumerate in python
Say,
term='asdf'; InvertedIndex = {}; InvertedIndex[term] = [1,2,2,2,4,5,6,6,6,6,7].
Now we have this function which counts no. of occurances of any item. This is the function I've having a problem with.
def TF(term, doc):
idx = InvertedIndex[term].index(doc)
return next(i for i, item in enumerate(InvertedIndex[term][idx:])
if item != doc)
It is giving 1 for TF(term, 1), 3 for TF(term, 2),1 for TF(term, 4). Fine so far.
But it is giving StopIteration error for TF(term, 7). It is also giving same error if I had InvertedIndex[term] = [7] and called TF(term, 7). How to fix it?
Edit:
Clarification about aim of the function. that function is supposed to count no. of occurances of an item. Considering the used example TF(term, 2) must return 3 because it occured 3 times in InvertedIndex[term]
Solution:
def TF(term, doc):
return InvertedIndex[term].count(doc)
A:
I feel like I wrote that loop on another answer but the correct answer for what you want to do is InvertedIndex[term].count(doc)
This will count the number of times that doc occurs in the list.
A:
At the language-level, your problem is that you're calling 'next' on a sequence, and when the sequence is empty it raises StopIteration.
Otherwise, it's not clear how to help you, since it's not obvious what the function you've written is supposed to do. You may want something like this:
def uniq_docs(inverted_index):
last = None
for i, doc in enumerate(inverted_index):
if doc != last:
yield i, doc
last = doc
and where you're currently calling TF, use something like:
for index, doc in uniq_docs(InvertedIndex[term]):
...
| enumerate in python | Say,
term='asdf'; InvertedIndex = {}; InvertedIndex[term] = [1,2,2,2,4,5,6,6,6,6,7].
Now we have this function which counts no. of occurances of any item. This is the function I've having a problem with.
def TF(term, doc):
idx = InvertedIndex[term].index(doc)
return next(i for i, item in enumerate(InvertedIndex[term][idx:])
if item != doc)
It is giving 1 for TF(term, 1), 3 for TF(term, 2),1 for TF(term, 4). Fine so far.
But it is giving StopIteration error for TF(term, 7). It is also giving same error if I had InvertedIndex[term] = [7] and called TF(term, 7). How to fix it?
Edit:
Clarification about aim of the function. that function is supposed to count no. of occurances of an item. Considering the used example TF(term, 2) must return 3 because it occured 3 times in InvertedIndex[term]
Solution:
def TF(term, doc):
return InvertedIndex[term].count(doc)
| [
"I feel like I wrote that loop on another answer but the correct answer for what you want to do is InvertedIndex[term].count(doc)\nThis will count the number of times that doc occurs in the list.\n",
"At the language-level, your problem is that you're calling 'next' on a sequence, and when the sequence is empty i... | [
3,
2
] | [] | [] | [
"python"
] | stackoverflow_0004062448_python.txt |
Q:
Order of numpy orperations is not equal to logic (and also octave)?
Maybe this question should be strictly in the scipy-users, but I'll try here too.
So here is something which I discovered lately and is making me wonder.
I want to define a scalar which I call Net Absolute Mass Balance Error or in short NAMBE.
This NAMBE is the absolute difference between a base vector and another vector, divided by the base vector and multiplied by a hundred, in pseudo-code notation:
NAMBE=sum(abs(a-b)/a)*100
When I do it in python, I decided to break the line into two lines so the code is more
readable:
>>> a=np.array([0.1,0.1,0.1,0.1,0.1])
>>> b=np.array([0.1,0.1,0.1,0.1,0.1])*2
>>> b
array([ 0.2, 0.2, 0.2, 0.2, 0.2])
>>> a-b
array([-0.1, -0.1, -0.1, -0.1, -0.1])
>>> s=np.sum(abs(a-b))
>>> s
0.5
>>> s/np.sum(a)
1.0
I thought the numpy does everything element wise so if I do it one line, I noticed the the result is different:
>>> s=np.sum(abs(a-b)/a)
>>> s
5.0
Now If I check myself on the data I have with a octave, I get different results:
octave:1> a=[0.1,0.1,0.1,0.1,0.1]
a =
0.10000 0.10000 0.10000 0.10000 0.10000
octave:2> b=a*2
b =
0.20000 0.20000 0.20000 0.20000 0.20000
octave:3> sum(a)
ans = 0.50000
octave:4> sum(b)
ans = 1
octave:5> sum(a-b)
ans = -0.50000
octave:6> sum(abs(a-b))
ans = 0.50000
octave:7> s=sum(abs(a-b))
s = 0.50000
octave:8> s/sum(a)
ans = 1
octave:9> s=sum(abs(a-b)/a)
s = 1.0000
octave:10> s=sum(abs(a-b)/sum(a))
s = 1
Note that the is no difference in the output of 9 and 10 in Octave, although there is in Python ...
So, my question is:
Why is python is behaving like that ? Which one is right ? Octave or Python ?
A:
sum(a-b)/sum(a) is not the same as sum((a-b)/a).
Consider e.g. a=[1,0] and b=[-1,1]. Then sum(a/b) == sum([-1,0]) == -1, but sum(a)/(sum(b) == 1/0 which doesn't make sense.
| Order of numpy orperations is not equal to logic (and also octave)? | Maybe this question should be strictly in the scipy-users, but I'll try here too.
So here is something which I discovered lately and is making me wonder.
I want to define a scalar which I call Net Absolute Mass Balance Error or in short NAMBE.
This NAMBE is the absolute difference between a base vector and another vector, divided by the base vector and multiplied by a hundred, in pseudo-code notation:
NAMBE=sum(abs(a-b)/a)*100
When I do it in python, I decided to break the line into two lines so the code is more
readable:
>>> a=np.array([0.1,0.1,0.1,0.1,0.1])
>>> b=np.array([0.1,0.1,0.1,0.1,0.1])*2
>>> b
array([ 0.2, 0.2, 0.2, 0.2, 0.2])
>>> a-b
array([-0.1, -0.1, -0.1, -0.1, -0.1])
>>> s=np.sum(abs(a-b))
>>> s
0.5
>>> s/np.sum(a)
1.0
I thought the numpy does everything element wise so if I do it one line, I noticed the the result is different:
>>> s=np.sum(abs(a-b)/a)
>>> s
5.0
Now If I check myself on the data I have with a octave, I get different results:
octave:1> a=[0.1,0.1,0.1,0.1,0.1]
a =
0.10000 0.10000 0.10000 0.10000 0.10000
octave:2> b=a*2
b =
0.20000 0.20000 0.20000 0.20000 0.20000
octave:3> sum(a)
ans = 0.50000
octave:4> sum(b)
ans = 1
octave:5> sum(a-b)
ans = -0.50000
octave:6> sum(abs(a-b))
ans = 0.50000
octave:7> s=sum(abs(a-b))
s = 0.50000
octave:8> s/sum(a)
ans = 1
octave:9> s=sum(abs(a-b)/a)
s = 1.0000
octave:10> s=sum(abs(a-b)/sum(a))
s = 1
Note that the is no difference in the output of 9 and 10 in Octave, although there is in Python ...
So, my question is:
Why is python is behaving like that ? Which one is right ? Octave or Python ?
| [
"sum(a-b)/sum(a) is not the same as sum((a-b)/a).\nConsider e.g. a=[1,0] and b=[-1,1]. Then sum(a/b) == sum([-1,0]) == -1, but sum(a)/(sum(b) == 1/0 which doesn't make sense.\n"
] | [
7
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0004062360_numpy_python.txt |
Q:
Language specific redirect
I want to create simple application that detects language(using Google API) of phrase and send it to corresponded search engine. For example, if search query is in Russian then I need to redirect it to Yandex.ru in all other cases to Google.
That's how I do this:
def get(self):
decoded = unicode(unquote(self.request.query), "windows-1251")
text = decoded.encode("utf-8")
url = "http://ajax.googleapis.com/ajax/services/language/detect?v=1.0&q="+ quote(text)
try:
data = json.loads(urllib2.urlopen(url).read())
redirectUrl = "http://www.google.com/search?q=" + text
if data["responseData"]["language"] == 'ru':
redirectUrl = "http://yandex.ru/yandsearch?text=" + text
self.redirect(redirectUrl)
except urllib2.HTTPError, e:
self.response.out.write( "HTTP error: %d" % e.code )
except urllib2.URLError, e:
self.response.out.write( "Network error: %s" % e.reason.args[1])
When I request this url "http://findinrightplace.appspot.com/q?test query" it redirects to google but redirection to yandex doesn't work (http://findinrightplace.appspot.com/q?тестовый запрос).
What I'm doing wrong?
A:
You need to remove quote() from url = "http://ajax.googleapis.com/ajax/services/language/detect?v=1.0&q="+ quote(text), its returning a bad result for your Russian query.
I tested your code in my local python shell and it worked without quote(), but did not work with quote().
A:
I suggest using the Google Prediction API [http://code.google.com/apis/predict/]. You'll notice that the example on the main page is exactly what you are trying to do.
A:
You're not quoting text when building redirectUrl. Try:
...
redirectUrl = "http://www.google.com/search?q=" + quote(text)
if data["responseData"]["language"] == 'ru':
redirectUrl = "http://yandex.ru/yandsearch?text=" + quote(text)
...
A:
You are incorrect in assuming that the query string will be windows-1251 encoded. In the link you give, it's up to the web browser on how to encode it (since HTTP is also silent as to what the encoding of URLs should be). However, today, most browsers will assume that the URL must be encoded in UTF-8. As then language/detect also assumes that the query string is UTF-8 encoded (and URL escaped), you neither need to unquote nor decode the string at all. Also, yandex supports UTF-8 encoded query strings just fine. So putting this all together: try
def get(self):
text = self.request.query
url = "http://ajax.googleapis.com/ajax/services/language/detect?v=1.0&q=" + text
try:
data = json.loads(urllib2.urlopen(url).read())
redirectUrl = "http://www.google.com/search?q=" + text
if data["responseData"]["language"] == 'ru':
redirectUrl = "http://yandex.ru/yandsearch?text=" + text
self.redirect(redirectUrl)
except urllib2.HTTPError, e:
self.response.out.write( "HTTP error: %d" % e.code )
except urllib2.URLError, e:
self.response.out.write( "Network error: %s" % e.reason.args[1])
| Language specific redirect | I want to create simple application that detects language(using Google API) of phrase and send it to corresponded search engine. For example, if search query is in Russian then I need to redirect it to Yandex.ru in all other cases to Google.
That's how I do this:
def get(self):
decoded = unicode(unquote(self.request.query), "windows-1251")
text = decoded.encode("utf-8")
url = "http://ajax.googleapis.com/ajax/services/language/detect?v=1.0&q="+ quote(text)
try:
data = json.loads(urllib2.urlopen(url).read())
redirectUrl = "http://www.google.com/search?q=" + text
if data["responseData"]["language"] == 'ru':
redirectUrl = "http://yandex.ru/yandsearch?text=" + text
self.redirect(redirectUrl)
except urllib2.HTTPError, e:
self.response.out.write( "HTTP error: %d" % e.code )
except urllib2.URLError, e:
self.response.out.write( "Network error: %s" % e.reason.args[1])
When I request this url "http://findinrightplace.appspot.com/q?test query" it redirects to google but redirection to yandex doesn't work (http://findinrightplace.appspot.com/q?тестовый запрос).
What I'm doing wrong?
| [
"You need to remove quote() from url = \"http://ajax.googleapis.com/ajax/services/language/detect?v=1.0&q=\"+ quote(text), its returning a bad result for your Russian query.\nI tested your code in my local python shell and it worked without quote(), but did not work with quote().\n",
"I suggest using the Google P... | [
1,
0,
0,
0
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0004022332_google_app_engine_python.txt |
Q:
Fail safe code for cgi python scripts
Coming from mostly C++ I'm relatively new to python and probably far from thinking in pythonic ways. Recently my web hoster activated python as cgi for my web space. I got an email asking me to test any python scripts on a local server (xampp, ...) since my web space is hosted on a productivity server.
Now my question is: What would be a good and maybe even pythonic way to keep scripts from infinite looping and such things? Obviously writing correct code is the solution, but I can't guarantee that. So is there a nice way to supervise my scripts from the outside or to prevent any processor max out or infinite loops?
A:
Writing tests is always a good thing to do. Use this alongside coverage.py, and you should get some pretty safe code.
| Fail safe code for cgi python scripts | Coming from mostly C++ I'm relatively new to python and probably far from thinking in pythonic ways. Recently my web hoster activated python as cgi for my web space. I got an email asking me to test any python scripts on a local server (xampp, ...) since my web space is hosted on a productivity server.
Now my question is: What would be a good and maybe even pythonic way to keep scripts from infinite looping and such things? Obviously writing correct code is the solution, but I can't guarantee that. So is there a nice way to supervise my scripts from the outside or to prevent any processor max out or infinite loops?
| [
"Writing tests is always a good thing to do. Use this alongside coverage.py, and you should get some pretty safe code.\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0004062750_python.txt |
Q:
In what structure is a Python object stored in memory?
Say I have a class A:
class A(object):
def __init__(self, x):
self.x = x
def __str__(self):
return self.x
And I use sys.getsizeof to see how many bytes instance of A takes:
>>> sys.getsizeof(A(1))
64
>>> sys.getsizeof(A('a'))
64
>>> sys.getsizeof(A('aaa'))
64
As illustrated in the experiment above, the size of an A object is the same no matter what self.x is.
So I wonder how python store an object internally?
A:
It depends on what kind of object, and also which Python implementation :-)
In CPython, which is what most people use when they use python, all Python objects are represented by a C struct, PyObject. Everything that 'stores an object' really stores a PyObject *. The PyObject struct holds the bare minimum information: the object's type (a pointer to another PyObject) and its reference count (an ssize_t-sized integer.) Types defined in C extend this struct with extra information they need to store in the object itself, and sometimes allocate extra data separately.
For example, tuples (implemented as a PyTupleObject "extending" a PyObject struct) store their length and the PyObject pointers they contain inside the struct itself (the struct contains a 1-length array in the definition, but the implementation allocates a block of memory of the right size to hold the PyTupleObject struct plus exactly as many items as the tuple should hold.) The same way, strings (PyStringObject) store their length, their cached hashvalue, some string-caching ("interning") bookkeeping, and the actual char* of their data. Tuples and strings are thus single blocks of memory.
On the other hand, lists (PyListObject) store their length, a PyObject ** for their data and another ssize_t to keep track of how much room they allocated for the data. Because Python stores PyObject pointers everywhere, you can't grow a PyObject struct once it's allocated -- doing so may require the struct to move, which would mean finding all pointers and updating them. Because a list may need to grow, it has to allocate the data separately from the PyObject struct. Tuples and strings cannot grow, and so they don't need this. Dicts (PyDictObject) work the same way, although they store the key, the value and the cached hashvalue of the key, instead of just the items. Dict also have some extra overhead to accommodate small dicts and specialized lookup functions.
But these are all types in C, and you can usually see how much memory they would use just by looking at the C source. Instances of classes defined in Python rather than C are not so easy. The simplest case, instances of classic classes, is not so difficult: it's a PyObject that stores a PyObject * to its class (which is not the same thing as the type stored in the PyObject struct already), a PyObject * to its __dict__ attribute (which holds all other instance attributes) and a PyObject * to its weakreflist (which is used by the weakref module, and only initialized if necessary.) The instance's __dict__ is usually unique to the instance, so when calculating the "memory size" of such an instance you usually want to count the size of the attribute dict as well. But it doesn't have to be specific to the instance! __dict__ can be assigned to just fine.
New-style classes complicate manners. Unlike with classic classes, instances of new-style classes are not separate C types, so they do not need to store the object's class separately. They do have room for the __dict__ and weakreflist reference, but unlike classic instances they don't require the __dict__ attribute for arbitrary attributes. if the class (and all its baseclasses) use __slots__ to define a strict set of attributes, and none of those attributes is named __dict__, the instance does not allow arbitrary attributes and no dict is allocated. On the other hand, attributes defined by __slots__ have to be stored somewhere. This is done by storing the PyObject pointers for the values of those attributes directly in the PyObject struct, much like is done with types written in C. Each entry in __slots__ will thus take up a PyObject *, regardless of whether the attribute is set or not.
All that said, the problem remains that since everything in Python is an object and everything that holds an object just holds a reference, it's sometimes very difficult to draw the line between objects. Two objects can refer to the same bit of data. They may hold the only two references to that data. Getting rid of both objects also gets rid of the data. Do they both own the data? Does only one of them, but if so, which one? Or would you say they own half the data, even though getting rid of one object doesn't release half the data? Weakrefs can make this even more complicated: two objects can refer to the same data, but deleting one of the objects may cause the other object to also get rid of its reference to that data, causing the data to be cleaned up after all.
Fortunately the common case is fairly easy to figure out. There are memory debuggers for Python that do a reasonable job at keeping track of these things, like heapy. And as long as your class (and its baseclasses) is reasonably simple, you can make an educated guess at how much memory it would take up -- especially in large numbers. If you really want to know the exact sizes of your datastructures, consult the CPython source; most builtin types are simple structs described in Include/<type>object.h and implemented in Objects/<type>object.c. The PyObject struct itself is described in Include/object.h. Just keep in mind: it's pointers all the way down; those take up room too.
A:
in the case of a new class instance getsizeof() return the size of a reference to PyObject which is returned by the C function PyInstance_New()
if you want a list of all the object size check this.
| In what structure is a Python object stored in memory? | Say I have a class A:
class A(object):
def __init__(self, x):
self.x = x
def __str__(self):
return self.x
And I use sys.getsizeof to see how many bytes instance of A takes:
>>> sys.getsizeof(A(1))
64
>>> sys.getsizeof(A('a'))
64
>>> sys.getsizeof(A('aaa'))
64
As illustrated in the experiment above, the size of an A object is the same no matter what self.x is.
So I wonder how python store an object internally?
| [
"It depends on what kind of object, and also which Python implementation :-)\nIn CPython, which is what most people use when they use python, all Python objects are represented by a C struct, PyObject. Everything that 'stores an object' really stores a PyObject *. The PyObject struct holds the bare minimum informat... | [
27,
0
] | [] | [] | [
"object",
"python",
"python_internals"
] | stackoverflow_0004062752_object_python_python_internals.txt |
Q:
Python regular expressions
Is there any regular expression to match this:
a continuous string of characters or/and digits XOR
a string of any characters between a pairquotation marks (" XOR ')including nested quotations
?
Examples:
dgsdggsgggdggsggsd
'dsfsasf .asgafaasfafw rq'
"sadas fa fasfa "
A:
Perhaps relevant: do you know about the shlex module?
A:
Maybe you can try this:
>>> message = "blabla df qdsf dqsf \"fqdfdqsfsdf fdqs fqdsf\""
>>> pattern = "(\w+|'.*[^']'|\".*[^\"]\")"
>>> re.findall(pattern, message)
['blabla', 'df', 'qdsf', 'dqsf', '"fqdfdqsfsdf fdqs fqdsf"']
| Python regular expressions | Is there any regular expression to match this:
a continuous string of characters or/and digits XOR
a string of any characters between a pairquotation marks (" XOR ')including nested quotations
?
Examples:
dgsdggsgggdggsggsd
'dsfsasf .asgafaasfafw rq'
"sadas fa fasfa "
| [
"Perhaps relevant: do you know about the shlex module?\n",
"Maybe you can try this:\n>>> message = \"blabla df qdsf dqsf \\\"fqdfdqsfsdf fdqs fqdsf\\\"\"\n>>> pattern = \"(\\w+|'.*[^']'|\\\".*[^\\\"]\\\")\"\n>>> re.findall(pattern, message)\n['blabla', 'df', 'qdsf', 'dqsf', '\"fqdfdqsfsdf fdqs fqdsf\"']\n\n"
] | [
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0004058943_python.txt |
Q:
string conversion
I’ve got a long string object which has been formatted like this
myString = “[name = john, family = candy, age = 72],[ name = jeff, family = Thomson, age = 24]”
of course the string is longer than this.
Also i have 3 lists with related names:
Names = []
Families = []
Ages = []
I want to read that string character by character and take the data and append it into appropriate lists. Can anyone help me on this about how to separate the string into variables?
The thing I need is something like this:
Names = [“john”, “jeff”, ...]
Families = [“candy”, “Thomson”, ...]
Ages = [72, 24, ...]
A:
This can be most easily done using a regex. Basically, construct a regex that extracts the name,family and age from the string and extract the relevant data from the tuples returned to build your lists.
import re
if __name__=='__main__':
myString = "[name = john adams, family = candy, age = 72],[ name = jeff, family = Thomson, age = 24]"
answers=re.findall("\\[\\s*name = ([^,]+), family = (\\w+), age = (\\d+)\\]",myString)
names=[x[0] for x in answers]
families=[x[1] for x in answers]
ages=map(int,(x[2] for x in answers))
print "names: ",names
print "families: ", families
print "ages: ", ages
A:
import re
Names = []
Families = []
Ages = []
myString = "[name = john, family = candy, age = 72],[ name = jeff, family = Thomson, age = 24"
myregex = re.compile("name = (?P<name>.*?), family = (?P<family>.*?), age = (?P<age>.*)")
for list_ in myString.split(']'):
found = re.search(myregex, list_).groupdict()
Names.append(found['name'])
Families.append(found['family'])
Ages.append(int(found['age']))
A:
Break the problem down:
Parse the string into lists
Load the lists into your other lists.
You'll have a problem, because the entities between commas aren't nice dictionaries.
A:
You should parse that to a list of dictionaries, not three differente lists, co-related only by data order.
Like in data = [ {"name": "John", "family": "Candy", "age": 72 }, ...]
One possibility, if you can't change the data source, is to do some naive parsing with string methods like split:
myString = "[name = john, family = candy, age = 72],[ name = jeff, family = Thomson, age = 24]"
data = []
for block in myString.split("]"):
if not block: break
block = block.split("[")[1]
entry_dict = {}
for part in block.split(","):
key, value = part.split("=")
key = key.strip()
value = value.strip()
if key == "age": value = int(value)
entry_dict[key] = value
data.append (entry_dict)
Or, if you are on python 2.7 (or 3.1) and want a shorter code, you can use a dict generator
(you can use generators in other versions as well, just creating alist of tuples and adding a "dict" call) :
myString = "[name = john, family = candy, age = 72],[ name = jeff, family = Thomson, age = 24]"
data = []
for block in myString.split("]"):
if not block: break
block = block.split("[")[1]
entry_dict = {}
data.append ({(part.split("=")[0].strip(), part.split("=")[1].strip()) for part in block.split(",") })
(in this version did not convert "age" to numbers, though)
| string conversion | I’ve got a long string object which has been formatted like this
myString = “[name = john, family = candy, age = 72],[ name = jeff, family = Thomson, age = 24]”
of course the string is longer than this.
Also i have 3 lists with related names:
Names = []
Families = []
Ages = []
I want to read that string character by character and take the data and append it into appropriate lists. Can anyone help me on this about how to separate the string into variables?
The thing I need is something like this:
Names = [“john”, “jeff”, ...]
Families = [“candy”, “Thomson”, ...]
Ages = [72, 24, ...]
| [
"This can be most easily done using a regex. Basically, construct a regex that extracts the name,family and age from the string and extract the relevant data from the tuples returned to build your lists.\nimport re\n\nif __name__=='__main__':\n myString = \"[name = john adams, family = candy, age = 72],[ name = ... | [
5,
3,
1,
1
] | [] | [] | [
"python",
"string"
] | stackoverflow_0004063019_python_string.txt |
Q:
override multiprocessing in python
how can i get variable in class which is override multiprocessing in python:
#!/usr/bin/env python
import multiprocessing
import os
class TestMultiprocess(multiprocessing.Process):
def __init__(self):
multiprocessing.Process.__init__(self)
self.myvar = ''
def myfunc(self):
return os.getpid()
def run(self):
self.myvar = self.myfunc()
mlist = []
for i in range(10):
t = TestMultiprocess()
mlist.append(t)
t.start()
for j in mlist:
t.join()
print t.myvar
i can not get value "myvar" from class TestMultiprocess, i just get blank. But i already override the run() function from Process.
sorry if my spell very bad ...
A:
The run() will executed in a separate process; processes don't share memory, normally. multiprocessing does support shared variables, though, through the explicit Value class:
#!/usr/bin/env python
import multiprocessing
import os
class TestMultiprocess(multiprocessing.Process):
def __init__(self):
multiprocessing.Process.__init__(self)
self.myvar = multiprocessing.Value('i',0)
def myfunc(self):
return os.getpid()
def run(self):
self.myvar.value = self.myfunc()
mlist = []
for i in range(10):
t = TestMultiprocess()
mlist.append(t)
t.start()
for j in mlist:
j.join()
print j.myvar.value
A:
replace t with j in the last loop
for j in mlist:
j.join() # t with j
print j.myvar # t with j
EDIT: and this will not solve your problem
by the way if you want to get the process pid you don't have to override the run() method just for that you can just do:
for j in mlist:
j.pid
| override multiprocessing in python | how can i get variable in class which is override multiprocessing in python:
#!/usr/bin/env python
import multiprocessing
import os
class TestMultiprocess(multiprocessing.Process):
def __init__(self):
multiprocessing.Process.__init__(self)
self.myvar = ''
def myfunc(self):
return os.getpid()
def run(self):
self.myvar = self.myfunc()
mlist = []
for i in range(10):
t = TestMultiprocess()
mlist.append(t)
t.start()
for j in mlist:
t.join()
print t.myvar
i can not get value "myvar" from class TestMultiprocess, i just get blank. But i already override the run() function from Process.
sorry if my spell very bad ...
| [
"The run() will executed in a separate process; processes don't share memory, normally. multiprocessing does support shared variables, though, through the explicit Value class:\n#!/usr/bin/env python\n\nimport multiprocessing\nimport os\n\nclass TestMultiprocess(multiprocessing.Process):\n def __init__(self):\n ... | [
3,
0
] | [] | [] | [
"multiprocessing",
"python"
] | stackoverflow_0004063220_multiprocessing_python.txt |
Q:
convert python request to PHP-cURL equivalent
I am sending a POST request to a URL. It works correctly in python but in php-curl, I always get a bad request error (i.e. my POST data is not as expected by the server)
Python code: (works correctly. 200 OK)
import httplib, urllib, json
def SendRequest(param1):
url = "api.xyz.com"
body = {"version": "1.0", "data":[{"param1":param1, "age":35}]}
jsonBody = json.dumps(body)
headers = {"Content-type": "application/json",
"Accept": "application/json; charset=utf8"}
conn = httplib.HTTPConnection(url)
conn.request("POST", "/api/?client_id=xx-xx-xx", jsonBody, headers)
response = conn.getresponse()
php-cURL code (does not work. 406 Bad request error)
function sendCurlRequest($param1)
{
$payload = preparePayload($param1);
$url = "http://api.xyz.com/api/?client_id=xx-xx-xx";
$jsonResponse = executePOSTRequest($url, $payload);
$response = json_decode($jsonResponse);
}
function preparePayload($param1)
{
$payload = array("version" = "1.0",
"data" => array(array("param1" => $param1,
"age" => 35
)
),
);
$jsonPayload = json_encode($payload);
return $jsonPayload;
}
function executePOSTRequest($url, $payload)
{
$newlines = array("\r", "\n", " ");
$url = str_replace($newlines, '', $url);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_HTTPHEADERS,array('Content-Type:application/json; Accept: application/json; charset=utf8'));
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
}
I know there is some mistake in my use of cURL. Please suggest.
Update: Use of double array in php is because server expects the JSON string (POST payload) in this format
{
"version": "1.0",
"data":
[{"param1":name, "age":35},{"param1":name,"age":60}]
}
In python, I am using list of dict; in php I think it is array of arrays only.
A:
In a case like this, I find that it's always better to look at what goes over the wire instead of trying to puzzle out what might be wrong with the code.
My advice:
Create a little test server using the python BaseHTTPServer and
derive a class from
BaseHTTPRequestHandler that doesn't
do anything but provide an override
of the do_POST method
Your do_POST should just dump the
headers and POST body it receives to
file
Point your code samples at this
little test server and then diff the
files that it creates. I'm guessing
that if the answer isn't immediately
obvious, you'll at the very least get
one or more useful clues to stomp
this problem out.
A:
I'm not sure if it causes your problem, but I do see a difference between the two:
In the python code you send two header lines: Content-Type and Accept. While in the PHP code, they are a single line.
A:
You are missing the parameter index - cURL POST fields need to be sent as a query string or as an array.
Either:
curl_setopt($ch, CURLOPT_POSTFIELDS, 'payload=' . urlencode($payload));
Or
curl_setopt($ch, CURLOPT_POSTFIELDS, array('payload' => $payload));
Replace payload with the name of the parameter expected by the API to hold the JSON string.
If the endpoint API is not expecting a parameter, then it should work - it just won't appear in the POST array in your test script. You can fetch the body of the POST contents using
$data = file_get_contents("php://input");
var_dump($data);
| convert python request to PHP-cURL equivalent | I am sending a POST request to a URL. It works correctly in python but in php-curl, I always get a bad request error (i.e. my POST data is not as expected by the server)
Python code: (works correctly. 200 OK)
import httplib, urllib, json
def SendRequest(param1):
url = "api.xyz.com"
body = {"version": "1.0", "data":[{"param1":param1, "age":35}]}
jsonBody = json.dumps(body)
headers = {"Content-type": "application/json",
"Accept": "application/json; charset=utf8"}
conn = httplib.HTTPConnection(url)
conn.request("POST", "/api/?client_id=xx-xx-xx", jsonBody, headers)
response = conn.getresponse()
php-cURL code (does not work. 406 Bad request error)
function sendCurlRequest($param1)
{
$payload = preparePayload($param1);
$url = "http://api.xyz.com/api/?client_id=xx-xx-xx";
$jsonResponse = executePOSTRequest($url, $payload);
$response = json_decode($jsonResponse);
}
function preparePayload($param1)
{
$payload = array("version" = "1.0",
"data" => array(array("param1" => $param1,
"age" => 35
)
),
);
$jsonPayload = json_encode($payload);
return $jsonPayload;
}
function executePOSTRequest($url, $payload)
{
$newlines = array("\r", "\n", " ");
$url = str_replace($newlines, '', $url);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_HTTPHEADERS,array('Content-Type:application/json; Accept: application/json; charset=utf8'));
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
}
I know there is some mistake in my use of cURL. Please suggest.
Update: Use of double array in php is because server expects the JSON string (POST payload) in this format
{
"version": "1.0",
"data":
[{"param1":name, "age":35},{"param1":name,"age":60}]
}
In python, I am using list of dict; in php I think it is array of arrays only.
| [
"In a case like this, I find that it's always better to look at what goes over the wire instead of trying to puzzle out what might be wrong with the code. \nMy advice:\n\nCreate a little test server using the python BaseHTTPServer and\nderive a class from\nBaseHTTPRequestHandler that doesn't\ndo anything but provi... | [
1,
1,
1
] | [] | [] | [
"curl",
"php",
"python"
] | stackoverflow_0004058405_curl_php_python.txt |
Q:
How to perform Job scheduling algorithms using python?
Well , i want to test out which scheduling algorithm is suitable for my application , but unable to figure out on how to go about testing. i have a set of jobs to be executed , for SMP (Symmetric Multi Process ) execution i used Parallel Python , but not able to apply Job Scheduling algorithm .
For ex: if i want to implement SJF (Shortest Job First) how will know that the job i am submitting is the shortest compared to others , it may also happen that eventually a larger job submitted may become smaller than a relative smaller job submitted at that time.
A:
You can only tell if the job you're submitting is the shortest if you know the runtime of all your jobs in advance. This is not an easy thing to know without first running the jobs. SJF is rarely used for this reason. Scheduling in a FIFO is much easier; you stick the jobs in a list as they come in (with lst.append()) and lst.pop(0) one off whenever you need a new job to run.
| How to perform Job scheduling algorithms using python? | Well , i want to test out which scheduling algorithm is suitable for my application , but unable to figure out on how to go about testing. i have a set of jobs to be executed , for SMP (Symmetric Multi Process ) execution i used Parallel Python , but not able to apply Job Scheduling algorithm .
For ex: if i want to implement SJF (Shortest Job First) how will know that the job i am submitting is the shortest compared to others , it may also happen that eventually a larger job submitted may become smaller than a relative smaller job submitted at that time.
| [
"You can only tell if the job you're submitting is the shortest if you know the runtime of all your jobs in advance. This is not an easy thing to know without first running the jobs. SJF is rarely used for this reason. Scheduling in a FIFO is much easier; you stick the jobs in a list as they come in (with lst.appen... | [
3
] | [] | [] | [
"python"
] | stackoverflow_0004063534_python.txt |
Q:
Problem with reading file in Python
I have a file: Alus.txt
File content: (each name in new line)
Margus
Mihkel
Daniel
Mark
Juri
Victor
Marek
Nikolai
Pavel
Kalle
Problem: While programm reads this file, there are \n after each name (['Margus\n', 'Mihkel\n', 'Daniel\n', 'Mark\n', 'Juri\n', 'Victor\n', 'Marek\n', 'Nikolai\n', 'Pavel\n', 'Kalle']). How can I remove \n and have a list with names? What I am doing wrong? Thank you.
alus = []
file = open('alus.txt', 'r')
while True:
rida = file.readline()
if (rida == ''):
break
else:
alus.append(rida)
A:
You can remove the linebreaks with rstrip:
alus = []
with open('alus.txt', 'r') as f:
for rida in f:
rida=rida.rstrip()
if rida: alus.append(rida)
else: break
By the way, the usual way to test if a string is empty is
if not rida:
rather than
if (rida == ''):
And if you have an if...else block, you should consider the non-negated form:
if rida:
since it is usually easier to read and understand.
Edit: My previous comment about removing break was wrong. (I was mistaking break with continue.) Since break stops the loop, it needs to be kept to preserve the behavior of your original code.
Edit 2: A.L. Flanagan rightly points out that rstrip removes all trailing whitespace, not just the ending newline character(s). If you'd like to remove the newline characters only, you could use A.L. Flanagan's method, or list the characters you wish to remove as an argument to rstrip:
rida = rida.rstrip(r'\r\n')
A:
alnus = [l.rstrip() for l in open('alus.txt', 'r')]
A:
open('alus.txt').read().splitlines()
A:
One possible problem with rstrip() is that it will remove any whitespace. If you want to preserve whitespace, you can use slices:
if line.endswith('\n'):
line = line[:-1]
If you could be sure all the lines end with '\n', you could speed it up by removing the if. However, in general, you can't be sure the last line in a text file has a newline.
| Problem with reading file in Python | I have a file: Alus.txt
File content: (each name in new line)
Margus
Mihkel
Daniel
Mark
Juri
Victor
Marek
Nikolai
Pavel
Kalle
Problem: While programm reads this file, there are \n after each name (['Margus\n', 'Mihkel\n', 'Daniel\n', 'Mark\n', 'Juri\n', 'Victor\n', 'Marek\n', 'Nikolai\n', 'Pavel\n', 'Kalle']). How can I remove \n and have a list with names? What I am doing wrong? Thank you.
alus = []
file = open('alus.txt', 'r')
while True:
rida = file.readline()
if (rida == ''):
break
else:
alus.append(rida)
| [
"You can remove the linebreaks with rstrip:\nalus = []\nwith open('alus.txt', 'r') as f:\n for rida in f:\n rida=rida.rstrip()\n if rida: alus.append(rida)\n else: break\n\nBy the way, the usual way to test if a string is empty is\nif not rida:\n\nrather than\nif (rida == ''):\n\nAnd if you ... | [
4,
4,
3,
1
] | [] | [] | [
"file",
"list",
"python"
] | stackoverflow_0004062858_file_list_python.txt |
Q:
What is proper Tokenization algorithm? & Error: TypeError: coercing to Unicode: need string or buffer, list found
I'm doing an Information Retrieval Task. As part of pre-processing I want to doing.
Stopword removal
Tokenization
Stemming (Porter Stemmer)
Initially, I skipped tokenization. As a result I got terms like this:
broker
broker'
broker,
broker.
broker/deal
broker/dealer'
broker/dealer,
broker/dealer.
broker/dealer;
broker/dealers),
broker/dealers,
broker/dealers.
brokerag
brokerage,
broker-deal
broker-dealer,
broker-dealers,
broker-dealers.
brokered.
brokers,
brokers.
So, Now I realized importance of tokenization. Is there any standard algorithm for tokenization for English language? Based on string.whitespace and commonly used puncuation marks. I wrote
def Tokenize(text):
words = text.split(['.',',', '?', '!', ':', ';', '-','_', '(', ')', '[', ']', '\'', '`', '"', '/',' ','\t','\n','\x0b','\x0c','\r'])
return [word.strip() for word in words if word.strip() != '']
I'm getting TypeError: coercing to Unicode: need string or buffer, list found error!
How can this Tokenization routine be improved?
A:
There is no single perfect algorithm for tokenization, though your algorithm may suffice for information retrieval purposes. It will be easier to implement using a regular expression:
def Tokenize(text):
words = re.split(r'[-\.,?!:;_()\[\]\'`"/\t\n\r \x0b\x0c]+', text)
return [word.strip() for word in words if word.strip() != '']
It can be improved in various ways, such as handling abbreviations properly:
>>> Tokenize('U.S.')
['U', 'S']
And watch out what you do with the dash (-). Consider:
>>> Tokenize('A-level')
['A', 'level']
If 'A' or 'a' occurs in your stop list, this will be reduced to just level.
I suggest you check out Natural Language Processing with Python, chapter 3, and the NLTK toolkit.
A:
As larsman mentions, ntlk has a variety of different tokenizers that accept various options. Using the default:
>>> import nltk
>>> words = nltk.wordpunct_tokenize('''
... broker
... broker'
... broker,
... broker.
... broker/deal
... broker/dealer'
... broker/dealer,
... broker/dealer.
... broker/dealer;
... broker/dealers),
... broker/dealers,
... broker/dealers.
... brokerag
... brokerage,
... broker-deal
... broker-dealer,
... broker-dealers,
... broker-dealers.
... brokered.
... brokers,
... brokers.
... ''')
['broker', 'broker', "'", 'broker', ',', 'broker', '.', 'broker', '/', 'deal', 'broker', '/', 'dealer', "'", 'broker', '/', 'dealer', ',', 'broker', '/', 'dealer', '.', 'broker', '/', 'dealer', ';', 'broker', '/', 'dealers', '),', 'broker', '/', 'dealers', ',', 'broker', '/', 'dealers', '.', 'brokerag', 'brokerage', ',', 'broker', '-', 'deal', 'broker', '-', 'dealer', ',', 'broker', '-', 'dealers', ',', 'broker', '-', 'dealers', '.', 'brokered', '.', 'brokers', ',', 'brokers', '.']
If you want to filter out list items that are punctuation only, you could do something like this:
>>> filter_chars = "',.;()-/"
>>> def is_only_punctuation(s):
'''
returns bool(set(s) is not a subset of set(filter_chars))
'''
return not set(list(i)) < set(list(filter_chars))
>>> filter(is_only_punctuation, words)
returns
>>> ['broker', 'broker', 'broker', 'broker', 'broker', 'deal', 'broker', 'dealer', 'broker', 'dealer', 'broker', 'dealer', 'broker', 'dealer', 'broker', 'dealers', 'broker', 'dealers', 'broker', 'dealers', 'brokerag', 'brokerage', 'broker', 'deal', 'broker', 'dealer', 'broker', 'dealers', 'broker', 'dealers', 'brokered', 'brokers', 'brokers']
| What is proper Tokenization algorithm? & Error: TypeError: coercing to Unicode: need string or buffer, list found | I'm doing an Information Retrieval Task. As part of pre-processing I want to doing.
Stopword removal
Tokenization
Stemming (Porter Stemmer)
Initially, I skipped tokenization. As a result I got terms like this:
broker
broker'
broker,
broker.
broker/deal
broker/dealer'
broker/dealer,
broker/dealer.
broker/dealer;
broker/dealers),
broker/dealers,
broker/dealers.
brokerag
brokerage,
broker-deal
broker-dealer,
broker-dealers,
broker-dealers.
brokered.
brokers,
brokers.
So, Now I realized importance of tokenization. Is there any standard algorithm for tokenization for English language? Based on string.whitespace and commonly used puncuation marks. I wrote
def Tokenize(text):
words = text.split(['.',',', '?', '!', ':', ';', '-','_', '(', ')', '[', ']', '\'', '`', '"', '/',' ','\t','\n','\x0b','\x0c','\r'])
return [word.strip() for word in words if word.strip() != '']
I'm getting TypeError: coercing to Unicode: need string or buffer, list found error!
How can this Tokenization routine be improved?
| [
"There is no single perfect algorithm for tokenization, though your algorithm may suffice for information retrieval purposes. It will be easier to implement using a regular expression:\ndef Tokenize(text):\n words = re.split(r'[-\\.,?!:;_()\\[\\]\\'`\"/\\t\\n\\r \\x0b\\x0c]+', text)\n return [word.strip() for... | [
1,
0
] | [] | [] | [
"information_retrieval",
"nlp",
"python",
"tokenize"
] | stackoverflow_0004063423_information_retrieval_nlp_python_tokenize.txt |
Q:
invisible watermarks in images
How do you insert invisible watermarks in images for copyright purposes? I'm looking for a python library.
What algorithm do you use? What about performance and efficiency?
A:
You might want to look into Steganography; that is hiding data inside of images. There are forms that won't get lost if you convert to a lossier format or even crop parts of the image out.
A:
I'm looking for "unbreakable" watermarks, so data stored in exif or image metadata are out.
I have found some interesting stuff on the web while waiting for replies here:
http://www.cosy.sbg.ac.at/~pmeerw/Watermarking/
There is a master thesis that's fairly exhaustive about algorithms and their caracteristics (what they do and how unbreakable they are). I haven't got any time to read it in depth, but this stuff looks serious. There are algorithms that support JPEG compression, cropping, gamma correction or down scaling in some way. It's C, but I can port it to Python or use C libraries from Python.
However, it's from 2001 and I guess 7 years are a long time in this field :( Does anybody have some similar and more recent stuff?
A:
I use the following code. It requires PIL:
def reduceOpacity(im, opacity):
"""Returns an image with reduced opacity."""
assert opacity >= 0 and opacity <= 1
if im.mode != 'RGBA':
im = im.convert('RGBA')
else:
im = im.copy()
alpha = im.split()[3]
alpha = ImageEnhance.Brightness(alpha).enhance(opacity)
im.putalpha(alpha)
return im
def watermark(im, mark, position, opacity=1):
"""Adds a watermark to an image."""
if opacity < 1:
mark = reduceOpacity(mark, opacity)
if im.mode != 'RGBA':
im = im.convert('RGBA')
# create a transparent layer the size of the image and draw the
# watermark in that layer.
layer = Image.new('RGBA', im.size, (0,0,0,0))
if position == 'tile':
for y in range(0, im.size[1], mark.size[1]):
for x in range(0, im.size[0], mark.size[0]):
layer.paste(mark, (x, y))
elif position == 'scale':
# scale, but preserve the aspect ratio
ratio = min(float(im.size[0]) / mark.size[0], float(im.size[1]) / mark.size[1])
w = int(mark.size[0] * ratio)
h = int(mark.size[1] * ratio)
mark = mark.resize((w, h))
layer.paste(mark, ((im.size[0] - w) / 2, (im.size[1] - h) / 2))
else:
layer.paste(mark, position)
# composite the watermark with the layer
return Image.composite(layer, im, layer)
img = Image.open('/path/to/image/to/be/watermarked.jpg')
mark1 = Image.open('/path/to/watermark1.png')
mark2 = Image.open('/path/to/watermark2.png')
img = watermark(img, mark1, (img.size[0]-mark1.size[0]-5, img.size[1]-mark1.size[1]-5), 0.5)
img = watermark(img, mark2, 'scale', 0.01)
The watermark is too faint to see. Only a solid color image would really show it. I can use it to create an image that doesn't show a watermark, but if I do a bit-by-bit subtraction using the original image, I can demonstrate that my watermark is there.
If you want to see how it works, go to TylerGriffinPhotography.com. Each image on the site is watermarked twice: once with the watermark in the lower right corner at 50% opacity (5px from the edge), and once over the whole image at 1% opacity (using "scale", which scales the watermark to the whole image). Can you figure out what the second, low opacity watermark shape is?
A:
If you're talking about steganography, here's an old not too-fancy module I did for a friend once (Python 2.x code):
the code
from __future__ import division
import math, os, array, random
import itertools as it
import Image as I
import sys
def encode(txtfn, imgfn):
with open(txtfn, "rb") as ifp:
txtdata= ifp.read()
txtdata= txtdata.encode('zip')
img= I.open(imgfn).convert("RGB")
pixelcount= img.size[0]*img.size[1]
## sys.stderr.write("image %dx%d\n" % img.size)
factor= len(txtdata) / pixelcount
width= int(math.ceil(img.size[0]*factor**.5))
height= int(math.ceil(img.size[1]*factor**.5))
pixelcount= width * height
if pixelcount < len(txtdata): # just a sanity check
sys.stderr.write("phase 2, %d bytes in %d pixels?\n" % (len(txtdata), pixelcount))
sys.exit(1)
## sys.stderr.write("%d bytes in %d pixels (%dx%d)\n" % (len(txtdata), pixelcount, width, height))
img= img.resize( (width, height), I.ANTIALIAS)
txtarr= array.array('B')
txtarr.fromstring(txtdata)
txtarr.extend(random.randrange(256) for x in xrange(len(txtdata) - pixelcount))
newimg= img.copy()
newimg.putdata([
(
r & 0xf8 |(c & 0xe0)>>5,
g & 0xfc |(c & 0x18)>>3,
b & 0xf8 |(c & 0x07),
)
for (r, g, b), c in it.izip(img.getdata(), txtarr)])
newimg.save(os.path.splitext(imgfn)[0]+'.png', optimize=1, compression=9)
def decode(imgfn, txtfn):
img= I.open(imgfn)
with open(txtfn, 'wb') as ofp:
arrdata= array.array('B',
((r & 0x7) << 5 | (g & 0x3) << 3 | (b & 0x7)
for r, g, b in img.getdata())).tostring()
findata= arrdata.decode('zip')
ofp.write(findata)
if __name__ == "__main__":
if sys.argv[1] == 'e':
encode(sys.argv[2], sys.argv[3])
elif sys.argv[1] == 'd':
decode(sys.argv[2], sys.argv[3])
the algorithm
It stores a byte of data per image pixel using: the 3 least-significant bits of the blue band, the 2 LSB of the green one and the 3 LSB of the red one.
encode function: An input text file is compressed by zlib, and the input image is resized (keeping proportions) to ensure that there are at least as many pixels as compressed bytes. A PNG image with the same name as the input image (so don't use a ".png" filename as input if you leave the code as-is :) is saved containing the steganographic data.
decode function: The previously stored zlib-compressed data are extracted from the input image, and saved uncompressed under the provided filename.
I verified the old code still runs, so here's an example image containing steganographic data:
You'll notice that the noise added is barely visible.
A:
Well, invisible watermarking is not that easy. Check digimarc, what money did they earn on it. There is no free C/Python code that a lonely genius has written a leave it for free usage. I've implemented my own algorithm and the name of the tool is SignMyImage. Google it if interested ... F>
A:
What about Exif? It's probably not as secure as what you're thinking, but most users don't even know it exists and if you make it that easy to read the watermark information those who care will still be able to do it anyway.
A:
I don't think there is a library that does this out of the box. If you want to implement your own, I would definitely go with the Python Imaging Library (PIL).
This is a Python Cookbook recipe that uses PIL to add a visible watermark to an image. If it's enough for your needs, you could use this to add a watermark with enough transparency that it is only visible if you know what you are looking for.
A:
There is a newer (2005) digital watermarking FAQ at watermarkingworld.org
A:
I was going to post an answer similar to Ugh. I would suggest putting a small TXT file describing the image source (and perhaps a small copyright statement, if one applies) into the image in a manner that is difficult to detect and break.
A:
I'm not sure how important it is to be unbreakable, but a simple solution might just be to append a text file to the end of the image. Something like "This image belongs to ...".
If you open the image in a viewer/browser, it looks like a normal jpeg, but if you open it in a text editor, the last line would be readable.
The same method allows you include an actual file into an image. (hide a file inside of an image) I've found that it's a bit hit-or-miss, but 7-zip files seem to work. You could hide all sorts of copywrite goodies inside the image.
Again, it's not unbreakable by any stretch of the imagination, but it's completely invisible to the naked eye.
A:
Some image formats have headers where you can store arbitrary information as well.
For example, the PNG specification has a chunk where you can store text data. This is similar to the answers above, but without adding random data to the image data itself.
| invisible watermarks in images | How do you insert invisible watermarks in images for copyright purposes? I'm looking for a python library.
What algorithm do you use? What about performance and efficiency?
| [
"You might want to look into Steganography; that is hiding data inside of images. There are forms that won't get lost if you convert to a lossier format or even crop parts of the image out.\n",
"I'm looking for \"unbreakable\" watermarks, so data stored in exif or image metadata are out.\nI have found some intere... | [
6,
5,
4,
3,
2,
1,
1,
1,
0,
0,
0
] | [] | [] | [
"image",
"python",
"watermark"
] | stackoverflow_0000044101_image_python_watermark.txt |
Q:
how to reliably decode various encodings to system default encoding
I am trying to work with several documents that all have various encodings - some utf-8, some ISO-8859-2, some ascii etc. Is there a reliable way of decoding to a standard encoding for processing?
I have tried the following:
import chardet
encoding = chardet.detect(text)
text = unicode(text,encoding['encoding']).decode(sys.getdefaultencoding(),'ignore')
With the above code I still get UnicodeEncodeError errors
A:
Use decode to convert bytes to unicode, and encode to convert unicode to bytes:
text.decode(encoding['encoding'], 'ignore').encode(sys.getdefaultencoding(), 'ignore')
Although I would recommend doing your processing on the unicode objects themselves, or UTF-8 encoded strings if you absolutely need to work with bytes. sys.getdefaultencoding() is 'ascii', which provides a very limited character set. See also: http://wiki.python.org/moin/DefaultEncoding
A:
You probably mean encode:
u = unicode(text, encoding['encoding'], 'ignore')
text = u.encode(sys.getdefaultencoding(), 'ignore')
or equivalently and more commonly,
u = text.decode(encoding['encoding'], 'ignore')
text = u.encode(sys.getdefaultencoding(), 'ignore')
You may want ignore on both, as above: the incoming text may have invalid characters in it, causing it to fail to decode to Unicode, and it may have characters which can't be represented in the default encoding, causing it to fail to encode. (You may not actually want to ignore errors, though, since it looks like you were just trying to work around using the wrong function.)
| how to reliably decode various encodings to system default encoding | I am trying to work with several documents that all have various encodings - some utf-8, some ISO-8859-2, some ascii etc. Is there a reliable way of decoding to a standard encoding for processing?
I have tried the following:
import chardet
encoding = chardet.detect(text)
text = unicode(text,encoding['encoding']).decode(sys.getdefaultencoding(),'ignore')
With the above code I still get UnicodeEncodeError errors
| [
"Use decode to convert bytes to unicode, and encode to convert unicode to bytes:\ntext.decode(encoding['encoding'], 'ignore').encode(sys.getdefaultencoding(), 'ignore')\n\nAlthough I would recommend doing your processing on the unicode objects themselves, or UTF-8 encoded strings if you absolutely need to work with... | [
3,
0
] | [] | [] | [
"character_encoding",
"python"
] | stackoverflow_0004063860_character_encoding_python.txt |
Q:
Read other items in a python list while iterating through it
Possible Duplicate:
Python: Looping through all but the last item of a list
Is there a better way of iterating through a list when you also need the next item (or any other arbitrary item) in the list? I use this, but maybe someone can do better...
values = [1, 3, 6, 7 ,9]
diffs = []
for i in range(len(values)):
try: diffs.append(values[i+1] - values[i])
except: pass
print diffs
gives:
[2, 3, 1, 2]
A:
>>> values = range(10)
>>> values
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> zip(values[0:],values[1:])
[(0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (6, 7), (7, 8), (8, 9)]
A:
what about with the aid of pairwise recipe from itertools document
from itertools import tee, izip
def pairwise(iterable):
"s -> (s0,s1), (s1,s2), (s2, s3), ..."
a, b = tee(iterable)
next(b, None)
return izip(a, b)
def main():
values = [1, 3, 6, 7 ,9]
diffs = [post - prior for prior, post in pairwise(values)]
print diffs
if __name__ == "__main__":
main()
output
[2, 3, 1, 2]
A:
You could use
for pos, item in enumerate(values):
try:
diffs.append(values[pos+1] - item)
except IndexError:
pass
although in your case (since you're just looking for the next value), you could also simply use
for item,nextitem in zip(values, values[1:]):
diffs.append(nextitem-item)
which can also be expressed as a list comprehension:
diffs = [nextitem-item for item,nextitem in zip(values, values[1:])]
A:
for i, j in zip(values, values[1:]):
j - i
A:
diff = [values[i+1] - values[i] for i in range(len(values)-1)]
A:
[y - x for x,y in zip(L,L[1:])]
| Read other items in a python list while iterating through it |
Possible Duplicate:
Python: Looping through all but the last item of a list
Is there a better way of iterating through a list when you also need the next item (or any other arbitrary item) in the list? I use this, but maybe someone can do better...
values = [1, 3, 6, 7 ,9]
diffs = []
for i in range(len(values)):
try: diffs.append(values[i+1] - values[i])
except: pass
print diffs
gives:
[2, 3, 1, 2]
| [
">>> values = range(10)\n>>> values\n[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n>>> zip(values[0:],values[1:])\n[(0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (6, 7), (7, 8), (8, 9)]\n\n",
"what about with the aid of pairwise recipe from itertools document\nfrom itertools import tee, izip\n\ndef pairwise(iterable):\n \... | [
4,
2,
1,
1,
1,
0
] | [] | [] | [
"iterator",
"list",
"python"
] | stackoverflow_0004062583_iterator_list_python.txt |
Q:
Maximum match length of a regular expression
What is the easiest way to determine the maximum match length of a regular expression?
Specifically, I am using Python's re module.
E.g. for foo((bar){2,3}|potato) it would be 12.
Obviously, regexes using operators like * and + have theoretically unbounded match lengths; in those cases returning an error or something is fine. Giving an error for regexes using the (?...) extensions is also fine.
I would also be ok with getting an approximate upper bound, as long as it is always greater than the actual maximum length, but not too much greater.
A:
Using pyparsing's invRegex module:
import invRegex
data='foo(bar{2,3}|potato)'
print(list(invRegex.invert(data)))
# ['foobarr', 'foobarrr', 'foopotato']
print(max(map(len,invRegex.invert(data))))
# 9
Another alternative is to use ipermute from this module.
import inverse_regex
data='foo(bar{2,3}|potato)'
print(list(inverse_regex.ipermute(data)))
# ['foobarr', 'foobarrr', 'foopotato']
print(max(map(len,inverse_regex.ipermute(data))))
# 9
A:
Solved, I think. Thanks to unutbu for pointing me to sre_parse!
import sre_parse
def get_regex_max_match_len(regex):
minlen, maxlen = sre_parse.parse(regex).getwidth()
if maxlen >= sre_parse.MAXREPEAT: raise ValueError('unbounded regex')
return maxlen
Results in:
>>> get_regex_max_match_len('foo((bar){2,3}|potato)')
12
>>> get_regex_max_match_len('.*')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in get_regex_max_match_len
ValueError: unbounded regex
| Maximum match length of a regular expression | What is the easiest way to determine the maximum match length of a regular expression?
Specifically, I am using Python's re module.
E.g. for foo((bar){2,3}|potato) it would be 12.
Obviously, regexes using operators like * and + have theoretically unbounded match lengths; in those cases returning an error or something is fine. Giving an error for regexes using the (?...) extensions is also fine.
I would also be ok with getting an approximate upper bound, as long as it is always greater than the actual maximum length, but not too much greater.
| [
"Using pyparsing's invRegex module:\nimport invRegex\ndata='foo(bar{2,3}|potato)' \nprint(list(invRegex.invert(data)))\n# ['foobarr', 'foobarrr', 'foopotato'] \nprint(max(map(len,invRegex.invert(data))))\n# 9\n\nAnother alternative is to use ipermute from this module.\nimport inverse_regex\ndata='foo(bar{2,3}... | [
6,
3
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0004063392_python_regex.txt |
Q:
django template question (accessing a list)
I am writing a template for my first django website.
I am passing a list of dictionaries to the template in a variable. I also need to pass a few other lists which hold boolean flags. (Note: all lists have the same length)
The template looks something like this:
<html>
<head><title>First page</title></head><body>
{% for item in data_tables %}
<table>
<tbody>
<tr><td colspan="15">
{% if level_one_flags[forloop.counter-1] %}
<tr><td>Premier League
{% endif %}
<tr><td>Junior league
<tr><td>Member count
{% if level_two_flags[forloop.counter-1] %}
<tr><td>Ashtano League
{% endif %}
</tbody>
</table>
{% endfor %}
</body>
</html>
I am getting the following error:
Template error
In template /mytemplate.html, error at
line 7 Could not parse the remainder:
'[forloop.counter-1]' from
'level_one_flags[forloop.counter-1]'
I am, not suprised I am getting this error, since I was just trying to see if would work. So far, from the documentation, I have not found out how to obtain the items in a list by index (i.e. other than by enumeration).
Does anyone know how I may access a list by index in a template?
A:
In short, Django doesn't do what you want.
The for loop has a number of useful properties within a loop.
forloop.counter The current iteration of the loop (1-indexed)
forloop.counter0 The current iteration of the loop (0-indexed)
forloop.revcounter The number of iterations from the end of the loop (1-indexed)
forloop.revcounter0 The number of iterations from the end of the loop (0-indexed)
forloop.first True if this is the first time through the loop
forloop.last True if this is the last time through the loop
forloop.parentloop For nested loops, this is the loop "above" the current one
You could probably use forloop.counter0 to get the zero-based indexes you want; unfortunately, the Django template language doesn't support variable array indexes (You can do {{ foo.5 }}, but you can't do {{ foo.{{bar}} }}).
What I usually do is to try and arrange the data in the view to make it easier to present in the template. As an example, for you could create an array in your view composed of dictionaries so that all you have to do is loop through the array and pull exactly what you need out of the individual dictionaries. For really complicated things, I've gone so far as to create a DataRow object that would correctly format the data for a particular row in a table.
A:
You use the dot-operator to index the array, or, really, to do anything.
Technically, when the template system
encounters a dot, it tries the
following lookups, in this order:
* Dictionary lookup
* Attribute lookup
* Method call
* List-index lookup
I don't believe you can do math on the index. You'll have to pass in your array constructed in some other way so that you don't have to do this subtraction.
A:
Try using "slice" to access a list by index
http://docs.djangoproject.com/en/dev/ref/templates/builtins/#slice
A:
Perhaps a better way is to use forloop.last. Of course, this will require that you send to the template the specific level_one_flag and level_two_flag out of the level_one_flags and level_two_flags arrays, but I think this solution keeps a better logical separation between view and template:
<html>
<head><title>First page</title></head><body>
{% for item in data_tables %}
<table>
<tbody>
<tr><td colspan="15">
{% if forloop.last and level_one_flag %}
<tr><td>Premier League
{% endif %}
<tr><td>Junior league
<tr><td>Member count
{% if forloop.last and level_two_flag %}
<tr><td>Ashtano League
{% endif %}
</tbody>
</table>
{% endfor %}
</body>
</html>
| django template question (accessing a list) | I am writing a template for my first django website.
I am passing a list of dictionaries to the template in a variable. I also need to pass a few other lists which hold boolean flags. (Note: all lists have the same length)
The template looks something like this:
<html>
<head><title>First page</title></head><body>
{% for item in data_tables %}
<table>
<tbody>
<tr><td colspan="15">
{% if level_one_flags[forloop.counter-1] %}
<tr><td>Premier League
{% endif %}
<tr><td>Junior league
<tr><td>Member count
{% if level_two_flags[forloop.counter-1] %}
<tr><td>Ashtano League
{% endif %}
</tbody>
</table>
{% endfor %}
</body>
</html>
I am getting the following error:
Template error
In template /mytemplate.html, error at
line 7 Could not parse the remainder:
'[forloop.counter-1]' from
'level_one_flags[forloop.counter-1]'
I am, not suprised I am getting this error, since I was just trying to see if would work. So far, from the documentation, I have not found out how to obtain the items in a list by index (i.e. other than by enumeration).
Does anyone know how I may access a list by index in a template?
| [
"In short, Django doesn't do what you want.\nThe for loop has a number of useful properties within a loop.\n\nforloop.counter The current iteration of the loop (1-indexed)\nforloop.counter0 The current iteration of the loop (0-indexed)\nforloop.revcounter The number of iterations from the end of the loop (1... | [
7,
2,
1,
0
] | [] | [] | [
"django",
"django_templates",
"python"
] | stackoverflow_0004063515_django_django_templates_python.txt |
Q:
Jinja2 - Given 2 templates (as strings) how to render one that extends the other?
I'm making a simple script that works on Jinja2 templates. Right now it's just reading files in from disk manually, i.e. no Jinja Loaders. I have 2 strings (A and B), representing 2 templates. I want to make one template (B) inherit from the other (A), i.e. I have {% block body %}{% endblock %} in A, and I want to make the body block be the contents of B. How can I get the rendered output of this?
Normally I'd use {% extends 'filename' %} in B and it'd use the right one, however I don't have the filename (per se) for A.
A:
Your best bet probably to use a different template loader. Take a look at DictLoader and FunctionLoader, or try your hand a writing your own template loader.
| Jinja2 - Given 2 templates (as strings) how to render one that extends the other? | I'm making a simple script that works on Jinja2 templates. Right now it's just reading files in from disk manually, i.e. no Jinja Loaders. I have 2 strings (A and B), representing 2 templates. I want to make one template (B) inherit from the other (A), i.e. I have {% block body %}{% endblock %} in A, and I want to make the body block be the contents of B. How can I get the rendered output of this?
Normally I'd use {% extends 'filename' %} in B and it'd use the right one, however I don't have the filename (per se) for A.
| [
"Your best bet probably to use a different template loader. Take a look at DictLoader and FunctionLoader, or try your hand a writing your own template loader.\n"
] | [
3
] | [] | [] | [
"jinja2",
"python",
"templates"
] | stackoverflow_0004064362_jinja2_python_templates.txt |
Q:
python class attributes not setting?
I am having a weird problem with a chatbot I am writing that supports plugin extensions. The base extension class have attributes and methods predefined that will be inherited and can be overloaded and set. Here is the base class:
class Ext:
# Info about the extension
Name = 'Unnamed'
Author = 'Nobody'
Version = 0
Desc = 'This extension has no description'
Webpage = ''
# Determines whether the extension will automatically be on when added or not
OnByDefault = False
def __init__(self):
# Overwrite me! You can use me to load files and set attributes at startup
raise Exception('AbstractClassError: This class must be overloaded')
def SetName(self, name):
name = name.split(' ')
name = ''.join(name)
self.Name = name
def Load(self, file):
# Loads a file
return Misc.read_obj(file)
def Save(self, file, obj):
# Saves a file
return Misc.write_obj(file, obj)
def Activate(self, Komodo):
# When the extension is turned on, this is called
pass
def add_cmd(self, Komodo, name, callback, default=False, link=''):
# Add a command to the bot
if name in Komodo.Ext.commands:
Komodo.logger(msg = ">> Command '{0}' was already defined, so {1}'s version of the command couldn't be added".format(
name, self.meta.name))
else:
Komodo.Ext.commands[name] = callback
if default:
Komodo.Ext.default_commands.append(name)
if len(link) > 0:
Komodo.Ext.links[name] = link
def add_event(self, Komodo, type, callback):
# Add an event to the bot
if type not in Komodo.Ext.trigs:
Komodo.logger(msg =
">> Could not add '{0}' to event type '{1}' from extension '{2}' because that type does not exist".format(
str(callback), type, self.name))
else:
Komodo.Ext.trigs[type].append(callback)
This is what an extension normally looks like:
class Extension(Ext):
def __init__(self, K):
self.file = 'Storage/Extensions/AI.txt'
self.SetName('AI')
self.Version = 1.1
self.Author = 'blazer-flamewing'
self.Desc = 'An extension that lets you talk to an Artificial Intelligence program online called Kato.'
self.Webpage = 'http://botdom.com/wiki/Komodo/Extensions/AI'
try: self.AI = self.Load(file)
except: self.AI = {}
def Activate(self, K):
print(self.Version)
self.add_cmd(K, 'ai', self.cmd_AI, False, 'http://botdom.com/wiki/Komodo/Extensions/AI')
self.add_event(K, 'msg', self.msg_AI)
...more methods down here that aren't part of the base class
Every extension written like this works... except for one, the one mentioned above. It only succeeds when setting it's Name attribute, and when the other attributes are read they are still what the base class was set. At startup, I looped through every extension to print the dict entry, the actual name, the version, the author, and whether the extension was on or not and got this result:
Responses Responses 1.2 blazer-flamewing OFF
Ai AI 0 Nobody ON
Notes Notes 1.2 blazer-flamewing OFF
Misc Misc 1.5 blazer-flamewing OFF
System System 2.2 blazer-flamewing ON
Helloworld HelloWorld 1.3 blazer-flamewing OFF
Goodbyes Goodbyes 0 blazer-flamewing OFF
Spamfilter Spamfilter 1.2 blazer-flamewing OFF
Damn dAmn 2.2 blazer-flamewing ON
Bds BDS 0.2 blazer-flamewing OFF
Fun Fun 1.6 blazer-flamewing OFF
Welcomes Welcomes 1.5 blazer-flamewing OFF
Cursefilter Cursefilter 1.7 blazer-flamewing OFF
Similarly, Extension.Activate() isn't working for AI when it is turned on. I assume that has to do with the same sort of problem (not being set properly)
Any ideas as to why the class's attributes aren't setting? I've been stuck on this for hours and the extension is set up the exact same way other extensions are
EDIT: Here is another extension for comparison. This one actually works, Activate() actually calls. everything is pretty much exactly the same other than content
from komodo.extension import Ext
import time
class Extension(Ext):
def __init__(self, K):
self.SetName('dAmn')
self.Version = 2.2
self.Author = 'blazer-flamewing'
self.Desc = 'Module for all standard dAmn commands such as join, part, and say.'
self.Webpage = 'http://botdom.com/wiki/Komodo/Extensions/dAmn'
self.OnByDefault = True
def Activate(self, K):
self.add_cmd(K, 'action', self.cmd_action, False, "http://botdom.com/wiki/Komodo/Extensions/dAmn#Me_or_Action")
self.add_cmd(K, 'ban', self.cmd_ban, False, "http://botdom.com/wiki/Komodo/Extensions/dAmn#Ban_and_Unban")
self.add_cmd(K, 'chat', self.cmd_chat, True, "http://botdom.com/wiki/Komodo/Extensions/dAmn#Chat")
self.add_cmd(K, 'demote', self.cmd_demote, False, "http://botdom.com/wiki/Komodo/Extensions/dAmn#Demote_and_Promote")
self.add_cmd(K, 'join', self.cmd_join, False, "http://botdom.com/wiki/Komodo/Extensions/dAmn#Join_and_Part")
...etc
A:
You forgot a 'self' in class Extension:
try: self.AI = self.Load(self.file)
also, maybe your printing test is inaccurate. Have you tried unit tests?
A:
Is it possible that the block below the SetName call is actually indented differently (say, with tabs instead of spaces) and the following lines are not actually part of __init__?
A:
I don't think this is your problem, as you get what you want with the other classes - but I hope you can see you are not setting any "class" attributes on the inherited classes - you are setting just instance attributes for them. (therefore, if you try to get Extension.Version - it will pick the attribute from the base class "Ext" -- only when you have an Extension Object it's Version attribute is overriden with the instance attribute "Version".
That does not cover why "Activate" would not be working though.
A:
I solved my own question. Turns out I had an extension overwriting AI, so it wasn't the AI extension itself. thanks alot for trying to help though, guys. one up for all of you
| python class attributes not setting? | I am having a weird problem with a chatbot I am writing that supports plugin extensions. The base extension class have attributes and methods predefined that will be inherited and can be overloaded and set. Here is the base class:
class Ext:
# Info about the extension
Name = 'Unnamed'
Author = 'Nobody'
Version = 0
Desc = 'This extension has no description'
Webpage = ''
# Determines whether the extension will automatically be on when added or not
OnByDefault = False
def __init__(self):
# Overwrite me! You can use me to load files and set attributes at startup
raise Exception('AbstractClassError: This class must be overloaded')
def SetName(self, name):
name = name.split(' ')
name = ''.join(name)
self.Name = name
def Load(self, file):
# Loads a file
return Misc.read_obj(file)
def Save(self, file, obj):
# Saves a file
return Misc.write_obj(file, obj)
def Activate(self, Komodo):
# When the extension is turned on, this is called
pass
def add_cmd(self, Komodo, name, callback, default=False, link=''):
# Add a command to the bot
if name in Komodo.Ext.commands:
Komodo.logger(msg = ">> Command '{0}' was already defined, so {1}'s version of the command couldn't be added".format(
name, self.meta.name))
else:
Komodo.Ext.commands[name] = callback
if default:
Komodo.Ext.default_commands.append(name)
if len(link) > 0:
Komodo.Ext.links[name] = link
def add_event(self, Komodo, type, callback):
# Add an event to the bot
if type not in Komodo.Ext.trigs:
Komodo.logger(msg =
">> Could not add '{0}' to event type '{1}' from extension '{2}' because that type does not exist".format(
str(callback), type, self.name))
else:
Komodo.Ext.trigs[type].append(callback)
This is what an extension normally looks like:
class Extension(Ext):
def __init__(self, K):
self.file = 'Storage/Extensions/AI.txt'
self.SetName('AI')
self.Version = 1.1
self.Author = 'blazer-flamewing'
self.Desc = 'An extension that lets you talk to an Artificial Intelligence program online called Kato.'
self.Webpage = 'http://botdom.com/wiki/Komodo/Extensions/AI'
try: self.AI = self.Load(file)
except: self.AI = {}
def Activate(self, K):
print(self.Version)
self.add_cmd(K, 'ai', self.cmd_AI, False, 'http://botdom.com/wiki/Komodo/Extensions/AI')
self.add_event(K, 'msg', self.msg_AI)
...more methods down here that aren't part of the base class
Every extension written like this works... except for one, the one mentioned above. It only succeeds when setting it's Name attribute, and when the other attributes are read they are still what the base class was set. At startup, I looped through every extension to print the dict entry, the actual name, the version, the author, and whether the extension was on or not and got this result:
Responses Responses 1.2 blazer-flamewing OFF
Ai AI 0 Nobody ON
Notes Notes 1.2 blazer-flamewing OFF
Misc Misc 1.5 blazer-flamewing OFF
System System 2.2 blazer-flamewing ON
Helloworld HelloWorld 1.3 blazer-flamewing OFF
Goodbyes Goodbyes 0 blazer-flamewing OFF
Spamfilter Spamfilter 1.2 blazer-flamewing OFF
Damn dAmn 2.2 blazer-flamewing ON
Bds BDS 0.2 blazer-flamewing OFF
Fun Fun 1.6 blazer-flamewing OFF
Welcomes Welcomes 1.5 blazer-flamewing OFF
Cursefilter Cursefilter 1.7 blazer-flamewing OFF
Similarly, Extension.Activate() isn't working for AI when it is turned on. I assume that has to do with the same sort of problem (not being set properly)
Any ideas as to why the class's attributes aren't setting? I've been stuck on this for hours and the extension is set up the exact same way other extensions are
EDIT: Here is another extension for comparison. This one actually works, Activate() actually calls. everything is pretty much exactly the same other than content
from komodo.extension import Ext
import time
class Extension(Ext):
def __init__(self, K):
self.SetName('dAmn')
self.Version = 2.2
self.Author = 'blazer-flamewing'
self.Desc = 'Module for all standard dAmn commands such as join, part, and say.'
self.Webpage = 'http://botdom.com/wiki/Komodo/Extensions/dAmn'
self.OnByDefault = True
def Activate(self, K):
self.add_cmd(K, 'action', self.cmd_action, False, "http://botdom.com/wiki/Komodo/Extensions/dAmn#Me_or_Action")
self.add_cmd(K, 'ban', self.cmd_ban, False, "http://botdom.com/wiki/Komodo/Extensions/dAmn#Ban_and_Unban")
self.add_cmd(K, 'chat', self.cmd_chat, True, "http://botdom.com/wiki/Komodo/Extensions/dAmn#Chat")
self.add_cmd(K, 'demote', self.cmd_demote, False, "http://botdom.com/wiki/Komodo/Extensions/dAmn#Demote_and_Promote")
self.add_cmd(K, 'join', self.cmd_join, False, "http://botdom.com/wiki/Komodo/Extensions/dAmn#Join_and_Part")
...etc
| [
"You forgot a 'self' in class Extension:\ntry: self.AI = self.Load(self.file)\n\nalso, maybe your printing test is inaccurate. Have you tried unit tests?\n",
"Is it possible that the block below the SetName call is actually indented differently (say, with tabs instead of spaces) and the following lines are not... | [
2,
1,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0004061740_python.txt |
Q:
scramble function won't output
this function will not give me an output when tested in python's IDLE:
import random
def scramble(string):
rlist = []
while len(rlist) < len(string):
n = random.randint(0, len(string) - 1)
if rlist.count(string[n]) < string.count(string[n]):
rlist += string[n]
rstring = str(rlist)
return rstring
scramble('sdfa')
I've spent a long time trying to figure out the problem, but the code seems good to me.
A:
Correctly formatting this seems to solve the problem.
import random
def scramble(string):
rlist = []
while len(rlist) < len(string):
n = random.randint(0, len(string) - 1)
if rlist.count(string[n]) < string.count(string[n]):
rlist += string[n]
rstring = str(rlist)
return rstring
print(scramble('sdfa'))
In Python, indentation is just as important as good syntax :)
By the way, as @Vincent Savard said, you did not print the result. In your scramble() you returned a string, but you did not do anything with said string.
A:
A couple of notes:
Do not use string as the argument name, it could clash with the standard module string.
You probably do not want to return an str() of the list, which results in something like
>>> rlist = ['s', 'a', 'f', 'd']
>>> str(rlist)
>>> "['s', 'a', 'f', 'd']"
Instead, to get a scrambled string result, use str.join():
>>> rlist = ['s', 'a', 'f', 'd']
>>> ''.join(rlist)
'safd'
>>>
The last 2 lines of scramble can be joined in a single return:
return str(rlist)
or
return ''.join(rlist)
| scramble function won't output | this function will not give me an output when tested in python's IDLE:
import random
def scramble(string):
rlist = []
while len(rlist) < len(string):
n = random.randint(0, len(string) - 1)
if rlist.count(string[n]) < string.count(string[n]):
rlist += string[n]
rstring = str(rlist)
return rstring
scramble('sdfa')
I've spent a long time trying to figure out the problem, but the code seems good to me.
| [
"Correctly formatting this seems to solve the problem.\nimport random\n\ndef scramble(string):\n rlist = []\n while len(rlist) < len(string):\n n = random.randint(0, len(string) - 1)\n if rlist.count(string[n]) < string.count(string[n]):\n rlist += string[n]\n rstring = str(rlist) \n ... | [
0,
0
] | [] | [] | [
"function",
"python",
"scramble"
] | stackoverflow_0004064619_function_python_scramble.txt |
Q:
Python statement uses excessive amounts of RAM
This simple statement:
zip(xrange(0, 11614321), xrange(0, 11627964))
...is eating most of my RAM. (>150 MiB!) Why?
Edit: Ah, re-reading the docs, I see zip returns a list, not an iterable. Anything like zip that returns an iterable?
The larger picture: I'm iterating over two large arrays of file data, and I'm doing things like iterating (0-end, 0-end), (0-end, 1-end), etc. I'd like to not slice the array, as it would cause excessive allocations of memory. I figured I'd just iterate over the indexes instead, but that doesn't seem to work, as per above. The whole code:
def subsequence_length(data_a, data_b, loc_a, loc_b):
length = 0
for i_a, i_b in zip(xrange(loc_a, len(data_a)), xrange(loc_b, len(data_b))):
if data_a[i_a] == data_b[i_b]:
length += 1
else:
break
return length
A:
Use izip from itertools
A:
If for some reason you didn't want to use the itertools module, it would be trivial to write your own iterator that did the same thing, at least if you know you're dealing with exactly two input iterators.
def xzip2(i1, i2):
i1, i2 = iter(i1), iter(i2)
while True:
yield next(i1), next(i2)
Actually, upon further reflection, it is not that hard to make it work with any number of iterators. I am fairly sure itertools.izip must be implemented something like this.
def xzip(*iters):
iters = [iter(i) for i in iters]
while True:
yield tuple([next(i) for i in iters])
(And looking at the documentation, I see it is, except they're using map rather than list comprehensions.)
| Python statement uses excessive amounts of RAM | This simple statement:
zip(xrange(0, 11614321), xrange(0, 11627964))
...is eating most of my RAM. (>150 MiB!) Why?
Edit: Ah, re-reading the docs, I see zip returns a list, not an iterable. Anything like zip that returns an iterable?
The larger picture: I'm iterating over two large arrays of file data, and I'm doing things like iterating (0-end, 0-end), (0-end, 1-end), etc. I'd like to not slice the array, as it would cause excessive allocations of memory. I figured I'd just iterate over the indexes instead, but that doesn't seem to work, as per above. The whole code:
def subsequence_length(data_a, data_b, loc_a, loc_b):
length = 0
for i_a, i_b in zip(xrange(loc_a, len(data_a)), xrange(loc_b, len(data_b))):
if data_a[i_a] == data_b[i_b]:
length += 1
else:
break
return length
| [
"Use izip from itertools\n",
"If for some reason you didn't want to use the itertools module, it would be trivial to write your own iterator that did the same thing, at least if you know you're dealing with exactly two input iterators.\ndef xzip2(i1, i2):\n i1, i2 = iter(i1), iter(i2)\n while True:\n ... | [
12,
3
] | [] | [] | [
"memory_management",
"python"
] | stackoverflow_0004064818_memory_management_python.txt |
Q:
Python: Cannot pop from empty list? When list is clearly not empty?
I'm obviously missing something here. Same project I've been working on for a number of days. Stepping through it bit by bit, seemed to be working fine. I added in a portion of the main() function to actually create the comparison lists, and suddenly starts throwing out cannot pop from empty list error at me, even through a print function I've placed ahead of the pop() call clearly shows that the list is not empty? Any ideas what I'm doing wrong? and is this monstrosity gonna actually work the way I intend? First time working with threads and all. Here is the code in its entirety:
import urllib
import urllib2
import sys
from lxml.html import parse, tostring, fromstring
from urlparse import urlparse
import threading
class Crawler(threading.Thread):
def __init__(self):
self.links = []
self.queue = []
self.mal_list = []
self.count = 0
self.mal_set = set(self.mal_list)
self.crawled = []
self.crawled_set = set(self.crawled)
self.links_set = set(self.links)
self.queue.append(sys.argv[1])
self.queue_set = set(self.queue)
def run(self, max_depth):
print(self.queue)
while self.count < max_depth:
tgt = self.queue.pop(0)
if tgt not in self.mal_set:
self.crawl(tgt)
else:
print("Malicious Link Found: {0}".format(tgt)
continue
sys.exit("Finished!")
def crawl(self, tgt):
url = urlparse(tgt)
self.crawled.append(tgt)
try:
print("Crawling {0}".format(tgt))
request = urllib2.Request(tgt)
request.add_header("User-Agent", "Mozilla/5,0")
opener = urllib2.build_opener()
data = opener.open(request)
self.count += 1
except:
return
doc = parse(data).getroot()
for tag in doc.xpath("//a[@href]"):
old = tag.get('href')
fixed = urllib.unquote(old)
self.links.append(fixed)
self.queue_links(self.links_set, url)
def queue_links(self, links, url):
for link in links:
if link.startswith('/'):
link = "http://" + url.netloc + "/" + link
elif link.startswith('#'):
continue
elif link.startswith('http'):
link = 'http://' + url.netloc + '/' + link
if link.decode('utf-8') not in self.crawled_set:
self.queue.append(link)
def make_mal_list(self):
"""
Open various malware and phishing related blacklists and create a list
of URLS from which to compare to the crawled links
"""
hosts1 = "hosts.txt"
hosts2 = "MH-sitelist.txt"
hosts3 = "urls.txt"
with open(hosts1) as first:
for line1 in first.readlines():
link = "http://" + line1.strip()
self.mal_list.append(link)
with open(hosts2) as second:
for line2 in second.readlines():
link = "http://" + line2.strip()
self.mal_list.append(link)
with open(hosts3) as third:
for line3 in third.readlines():
link = "http://" + line3.strip()
self.mal_list.append(link)
def main():
crawler = Crawler()
crawler.make_mal_list()
crawler.run(25)
if __name__ == "__main__":
main()
A:
First of all , i did get lost while reading your code so maybe i can give you some remark if i may before:
to many instance variable you don't have to create a new instance var just to put on it a set() of another vars like this code : self.mal_set = set(self.mal_list)and you are repeating the same thing many times
if you want to use threading so use it, because in your code you are just creating one thread, for that you should create like (10) thread or so each thread will deal with a bunch of URL that he should fetch, and don't forget to put the threads in a Queue.Queue to synchronize between them.
EDIT : Ahh i forgot : indent your code :)
now about your problem :
where do you assign self.queue because i don't see it ? you are just calling the make_mal_list() method that will initialize only self.mal_listand after when you run you own thread i think it's obvious that self.queue is empty so you can't pop() right ?
EDIT 2:
i think your example is more complicate (using black list and all this stuff, ...) but you can start with something like this:
import threading
import Queue
import sys
import urllib2
import url
from urlparse import urlparse
THREAD_NUMBER = 10
class Crawler(threading.Thread):
def __init__(self, queue, mal_urls):
self.queue = queue
self.mal_list = mal_urls
threading.Thread.__init__(self) # i forgot , thanks seriyPS :)
def run(self):
while True:
# Grabs url to fetch from queue.
url = self.queue.get()
if url not in self.mal_list:
self.crawl(url)
else:
print "Malicious Link Found: {0}".format(url)
# Signals to queue job is done
self.queue.task_done()
def crawl(self, tgt):
try:
url = urlparse(tgt)
print("Crawling {0}".format(tgt))
request = urllib2.Request(tgt)
request.add_header("User-Agent", "Mozilla/5,0")
opener = urllib2.build_opener()
data = opener.open(request)
except: # TODO: write explicit exceptions the URLError, ValueERROR ...
return
doc = parse(data).getroot()
for tag in doc.xpath("//a[@href]"):
old = tag.get('href')
fixed = urllib.unquote(old)
# I don't think you need this, but maybe i'm mistaken.
# self.links.append(fixed)
# Add more URL to the queue.
self.queue_links(fixed, url)
def queue_links(self, link, url):
"""I guess this method allow recursive download of urls that will
be fetched from the web pages ????
"""
#for link in links: # i changed the argument so now links it just one url.
if link.startswith('/'):
link = "http://" + url.netloc + "/" + link
elif link.startswith('#'):
continue
elif link.startswith('http'):
link = 'http://' + url.netloc + '/' + link
# Add urls extracted from the HTML text to the queue to fetche them
if link.decode('utf-8') not in self.crawled_set:
self.queue.put(link)
def get_make_mal_list():
"""Open various malware and phishing related blacklists and create a list
of URLS from which to compare to the crawled links
"""
hosts1 = "hosts.txt"
hosts2 = "MH-sitelist.txt"
hosts3 = "urls.txt"
mal_list = []
with open(hosts1) as first:
for line1 in first:
link = "http://" + line1.strip()
mal_list.append(link)
with open(hosts2) as second:
for line2 in second:
link = "http://" + line2.strip()
mal_list.append(link)
with open(hosts3) as third:
for line3 in third:
link = "http://" + line3.strip()
mal_list.append(link)
return mal_list
def main():
queue = Queue.Queue()
# Get malicious URLs.
mal_urls = set(get_make_mal_list())
# Create a THREAD_NUMBER thread and start them.
for i in xrange(THREAD_NUMBER):
cr = Crawler(queue, mal_urls)
cr.start()
# Get all url that you want to fetch and put them in the queue.
for url in sys.argv[1:]:
queue.put(url)
# Wait on the queue until everything has been processed.
queue.join()
if __name__ == '__main__':
main()
A:
Small offtopic:
class Crawler(threading.Thread):
def __init__(self):
#you code
threading.Thread.__init__(self)#!!!
don't forget run Thread.__init__(self) directly if you override __init__ function
And, ofcourse, you must use http://docs.python.org/library/queue.html class for implement you job's queue in thread-safe mode
A:
My primary language is C#, but issue you are experiencing is because of threading. In thread #1 you check that list is not empty, while thread #2 clears that list and thus you receive exception.
A:
list is not thread-safe. If you need a thread-safe data structure, use Queue.Queue (Python 2.x) or queue.Queue (Python 3.x).
A:
Also, look on this fragment:
print(self.queue)
while self.count < max_depth:
tgt = self.queue.pop(0)
you do print(self.queue) only before in first while iteration, so, self.queue.pop() can make many iterations (and fetch many links) and raise "cannot pop from empty list" only when queue is really empty!
try this:
while self.count < max_depth:
print(self.queue)
tgt = self.queue.pop(0)
for detect moment when you take exception.
| Python: Cannot pop from empty list? When list is clearly not empty? | I'm obviously missing something here. Same project I've been working on for a number of days. Stepping through it bit by bit, seemed to be working fine. I added in a portion of the main() function to actually create the comparison lists, and suddenly starts throwing out cannot pop from empty list error at me, even through a print function I've placed ahead of the pop() call clearly shows that the list is not empty? Any ideas what I'm doing wrong? and is this monstrosity gonna actually work the way I intend? First time working with threads and all. Here is the code in its entirety:
import urllib
import urllib2
import sys
from lxml.html import parse, tostring, fromstring
from urlparse import urlparse
import threading
class Crawler(threading.Thread):
def __init__(self):
self.links = []
self.queue = []
self.mal_list = []
self.count = 0
self.mal_set = set(self.mal_list)
self.crawled = []
self.crawled_set = set(self.crawled)
self.links_set = set(self.links)
self.queue.append(sys.argv[1])
self.queue_set = set(self.queue)
def run(self, max_depth):
print(self.queue)
while self.count < max_depth:
tgt = self.queue.pop(0)
if tgt not in self.mal_set:
self.crawl(tgt)
else:
print("Malicious Link Found: {0}".format(tgt)
continue
sys.exit("Finished!")
def crawl(self, tgt):
url = urlparse(tgt)
self.crawled.append(tgt)
try:
print("Crawling {0}".format(tgt))
request = urllib2.Request(tgt)
request.add_header("User-Agent", "Mozilla/5,0")
opener = urllib2.build_opener()
data = opener.open(request)
self.count += 1
except:
return
doc = parse(data).getroot()
for tag in doc.xpath("//a[@href]"):
old = tag.get('href')
fixed = urllib.unquote(old)
self.links.append(fixed)
self.queue_links(self.links_set, url)
def queue_links(self, links, url):
for link in links:
if link.startswith('/'):
link = "http://" + url.netloc + "/" + link
elif link.startswith('#'):
continue
elif link.startswith('http'):
link = 'http://' + url.netloc + '/' + link
if link.decode('utf-8') not in self.crawled_set:
self.queue.append(link)
def make_mal_list(self):
"""
Open various malware and phishing related blacklists and create a list
of URLS from which to compare to the crawled links
"""
hosts1 = "hosts.txt"
hosts2 = "MH-sitelist.txt"
hosts3 = "urls.txt"
with open(hosts1) as first:
for line1 in first.readlines():
link = "http://" + line1.strip()
self.mal_list.append(link)
with open(hosts2) as second:
for line2 in second.readlines():
link = "http://" + line2.strip()
self.mal_list.append(link)
with open(hosts3) as third:
for line3 in third.readlines():
link = "http://" + line3.strip()
self.mal_list.append(link)
def main():
crawler = Crawler()
crawler.make_mal_list()
crawler.run(25)
if __name__ == "__main__":
main()
| [
"First of all , i did get lost while reading your code so maybe i can give you some remark if i may before:\n\nto many instance variable you don't have to create a new instance var just to put on it a set() of another vars like this code : self.mal_set = set(self.mal_list)and you are repeating the same thing many t... | [
4,
2,
1,
0,
0
] | [] | [] | [
"list",
"multithreading",
"python"
] | stackoverflow_0004064424_list_multithreading_python.txt |
Q:
Message queue proxy in Python + Twisted
I want to implement a lightweight Message Queue proxy. It's job is to receive messages from a web application (PHP) and send them to the Message Queue server asynchronously. The reason for this proxy is that the MQ isn't always avaliable and is sometimes lagging, or even down, but I want to make sure the messages are delivered, and the web application returns immediately.
So, PHP would send the message to the MQ proxy running on the same host. That proxy would save the messages to SQLite for persistence, in case of crashes. At the same time it would send the messages from SQLite to the MQ in batches when the connection is available, and delete them from SQLite.
Now, the way I understand, there are these components in this service:
message listener (listens to the messages from PHP and writes them to a Incoming Queue)
DB flusher (reads messages from the Incoming Queue and saves them to a database; due to SQLite single-threadedness)
MQ connection handler (keeps the connection to the MQ server online by reconnecting)
message sender (collects messages from SQlite db and sends them to the MQ server, then removes them from db)
I was thinking of using Twisted for #1 (TCPServer), but I'm having problem with integrating it with other points, which aren't event-driven. Intuition tells me that each of these points should be running in a separate thread, because all are IO-bound and independent of each other, but I could easily put them in a single thread. Even though, I couldn't find any good and clear (to me) examples on how to implement this worker thread aside of Twisted's main loop.
The example I've started with is the chatserver.py, which uses service.Application and internet.TCPServer objects. If I start my own thread prior to creating TCPServer service, it runs a few times, but the it stops and never runs again. I'm not sure, why this is happening, but it's probably because I don't use threads with Twisted correctly.
Any suggestions on how to implement a separate worker thread and keep Twisted? Do you have any alternative architectures in mind?
A:
You're basically considering writing an ad-hoc extension to your messaging server, the job of which it is to provide whatever reliability guarantees you've asked of it.
Instead, perhaps you should take the hardware where you were planning to run this new proxy and run another MQ node on it. The new node should take care of persisting and relaying messages that you deliver to it while the other nodes are overloaded or offline.
A:
Maybe it's not the best bang for your buck to use a separate thread in Twisted to get around a blocking call, but sometimes the least evil solution is the best. Here's a link that shows you how to integrate threading into Twisted:
http://twistedmatrix.com/documents/10.1.0/core/howto/threading.html
Sometimes in a pinch easy-to-implement is faster than hours/days of research which may all turn out to be for nought.
A:
A neat solution to this problem would be to use the Key Value store Redis. Its a high speed persistent data store, with plenty of clients - it has a php and a python client (if you want to use a timed/batch process to process messages - it saves you creating a database, and also deals with your persistence stories. It runs fine on Cywin/Windows + posix environments.
PHP Redis client is here.
Python client is here.
Both have a very clean and simple API. Redis also offers a publish/subscribe mechanism, should you need it, although it sounds like it would be of limited value if you're publishing to an inconsistent queue.
| Message queue proxy in Python + Twisted | I want to implement a lightweight Message Queue proxy. It's job is to receive messages from a web application (PHP) and send them to the Message Queue server asynchronously. The reason for this proxy is that the MQ isn't always avaliable and is sometimes lagging, or even down, but I want to make sure the messages are delivered, and the web application returns immediately.
So, PHP would send the message to the MQ proxy running on the same host. That proxy would save the messages to SQLite for persistence, in case of crashes. At the same time it would send the messages from SQLite to the MQ in batches when the connection is available, and delete them from SQLite.
Now, the way I understand, there are these components in this service:
message listener (listens to the messages from PHP and writes them to a Incoming Queue)
DB flusher (reads messages from the Incoming Queue and saves them to a database; due to SQLite single-threadedness)
MQ connection handler (keeps the connection to the MQ server online by reconnecting)
message sender (collects messages from SQlite db and sends them to the MQ server, then removes them from db)
I was thinking of using Twisted for #1 (TCPServer), but I'm having problem with integrating it with other points, which aren't event-driven. Intuition tells me that each of these points should be running in a separate thread, because all are IO-bound and independent of each other, but I could easily put them in a single thread. Even though, I couldn't find any good and clear (to me) examples on how to implement this worker thread aside of Twisted's main loop.
The example I've started with is the chatserver.py, which uses service.Application and internet.TCPServer objects. If I start my own thread prior to creating TCPServer service, it runs a few times, but the it stops and never runs again. I'm not sure, why this is happening, but it's probably because I don't use threads with Twisted correctly.
Any suggestions on how to implement a separate worker thread and keep Twisted? Do you have any alternative architectures in mind?
| [
"You're basically considering writing an ad-hoc extension to your messaging server, the job of which it is to provide whatever reliability guarantees you've asked of it.\nInstead, perhaps you should take the hardware where you were planning to run this new proxy and run another MQ node on it. The new node should t... | [
4,
1,
0
] | [] | [] | [
"message_queue",
"multithreading",
"proxy_classes",
"python",
"twisted"
] | stackoverflow_0002950777_message_queue_multithreading_proxy_classes_python_twisted.txt |
Q:
Python Read and Output from Stdin Unbuffered
In C++ or any other languages, you can write programs that continuously take input lines from stdin and output the result after each line. Something like:
while (true) {
readline
break if eof
print process(line)
}
I can't seem to get this kind of behavior in Python because it buffers the output (i.e. no printing will happen until the loop exits (?)). Thus, everything is printed when the program finishes. How do I get the same behavior as with C programs (where endl flushes).
A:
Do you have an example which shows the problem?
For example (Python 3):
def process(line):
return len(line)
try:
while True:
line = input()
print(process(line))
except EOFError:
pass
Prints the length of each line after each line.
A:
use sys.stdout.flush() to flush out the print buffer.
import sys
while True:
input = raw_input("Provide input to process")
# process input
print process(input)
sys.stdout.flush()
Docs : http://docs.python.org/library/sys.html
A:
Python should not buffer text past newlines, but you could try sys.stdout.flush() if that's what is happening.
A:
$ cat test.py
import sys
while True:
print sys.stdin.read(1)
then i run it in terminal and hit Enter after '123' and '456'
$ python test.py
123
1
2
3
456
4
5
6
| Python Read and Output from Stdin Unbuffered | In C++ or any other languages, you can write programs that continuously take input lines from stdin and output the result after each line. Something like:
while (true) {
readline
break if eof
print process(line)
}
I can't seem to get this kind of behavior in Python because it buffers the output (i.e. no printing will happen until the loop exits (?)). Thus, everything is printed when the program finishes. How do I get the same behavior as with C programs (where endl flushes).
| [
"Do you have an example which shows the problem?\nFor example (Python 3):\ndef process(line):\n return len(line)\ntry:\n while True:\n line = input()\n print(process(line))\nexcept EOFError:\n pass\n\nPrints the length of each line after each line.\n",
"use sys.stdout.flush() to flush out t... | [
3,
2,
1,
0
] | [] | [] | [
"loops",
"python",
"stdin"
] | stackoverflow_0004064401_loops_python_stdin.txt |
Q:
uTidylib segmentation fault
uTidylib is crashing and giving me a segmentation fault every time I try to use it.
Here's some info about the crash:
Process: Python [432]
Path: /System/Library/Frameworks/Python.framework/Versions/2.6/Resources/Python.app/Contents/MacOS/Python
Identifier: Python
Version: ??? (???)
Code Type: X86-64 (Native)
Parent Process: bash [429]
PlugIn Path: /usr/local/lib/libtidy.so
PlugIn Identifier: libtidy.so
PlugIn Version: ??? (???)
Date/Time: 2010-10-31 14:45:22.069 -0600
OS Version: Mac OS X 10.6.4 (10F569)
Report Version: 6
Interval Since Last Report: 78084 sec
Crashes Since Last Report: 6
Per-App Crashes Since Last Report: 5
Exception Type: EXC_BAD_ACCESS (SIGSEGV)
Exception Codes: KERN_INVALID_ADDRESS at 0x00000000008a8aa0
Any ideas?
Is there any other python tidy wrapper?
A:
pyTidyLib , the utidylib is too old (last time updated 2004 )
| uTidylib segmentation fault | uTidylib is crashing and giving me a segmentation fault every time I try to use it.
Here's some info about the crash:
Process: Python [432]
Path: /System/Library/Frameworks/Python.framework/Versions/2.6/Resources/Python.app/Contents/MacOS/Python
Identifier: Python
Version: ??? (???)
Code Type: X86-64 (Native)
Parent Process: bash [429]
PlugIn Path: /usr/local/lib/libtidy.so
PlugIn Identifier: libtidy.so
PlugIn Version: ??? (???)
Date/Time: 2010-10-31 14:45:22.069 -0600
OS Version: Mac OS X 10.6.4 (10F569)
Report Version: 6
Interval Since Last Report: 78084 sec
Crashes Since Last Report: 6
Per-App Crashes Since Last Report: 5
Exception Type: EXC_BAD_ACCESS (SIGSEGV)
Exception Codes: KERN_INVALID_ADDRESS at 0x00000000008a8aa0
Any ideas?
Is there any other python tidy wrapper?
| [
"pyTidyLib , the utidylib is too old (last time updated 2004 ) \n"
] | [
2
] | [] | [] | [
"macos",
"python",
"segmentation_fault",
"tidy"
] | stackoverflow_0004065061_macos_python_segmentation_fault_tidy.txt |
Q:
Extraction from a string in R or Python
I have a csv file with addresses that include ',', empty space, numbers. I have two other files with city and zip codes. I want to read the address file and extract the city name and zip codes. As you will see below the addresses have no easy pattern and is randomly sprinkled with ',' spaces etc.Here is an example.
Address file
123 Riverside Drive Riverside CA 12034
Santa clara CA 93453
231 Monroe drive, OR
43 Mystic cove, O'Fallon 63045
City file
riverside
O'fallon
santa clara
Morgantown
Zip code file
02343
23454
12034
93453
Expected output file (corresponding to the input address file) in two columns
City Zipcode
Riverside 12034
Santa clara 93453
Missing Missing
O'Fallon Missing
Note that the matching shouldn't be case sensitive. I am more familiar with R but will be happy with any help in python too.
Thank you in advance.
A:
Use Google Refine. It's an open source project that is perfect for data cleansing and export into a format that actually makes sense. Everything is GUI based and it stores a complete history. You wont need to mess around with tedious regular expressions.
A:
You might consider using something like this, though be careful -- there are plenty of things that can go wrong. For example,
'12034 Riverside Road' would be misinterpreted to be Riverside city, with zipcode 12034.
One way to avoid such a mistake would be to enumerate all the forms an address can take, and then use pyparsing or regex to try to match those forms.
Another problem with the code below is that it forms two possibly gigantic regexps (if the zipcode and/or city files are very large). I'm not sure how the code would perform under such a condition. We can think about how to rework the code if this proves to be a problem.
import re
import itertools as it
with open('zipcode','r') as z:
zipcode_pat=re.compile('({0})'.format('|'.join(line.rstrip() for line in z)),
re.IGNORECASE)
with open('city','r') as c:
city_pat=re.compile('({0})'.format('|'.join(line.rstrip() for line in c)),
re.IGNORECASE)
def gitone(seq):
for match in seq:
if match:
yield match.group(1)
else:
yield 'Missing'
with open('address','r') as f:
f1,f2=it.tee(f,2)
zipcodes=gitone(zipcode_pat.search(line) for line in f1)
cities=gitone(city_pat.search(line) for line in f2)
for city,zipcode in it.izip(cities,zipcodes):
print('{c} {z}'.format(c=city,z=zipcode))
# Riverside 12034
# Santa clara 93453
# Missing Missing
# O'Fallon Missing
A:
I'm sure a gsubfn wizard could do this better but here are some initial steps:
Addresses <- "123 Riverside Drive Riverside CA 12034
Santa clara CA 93453
231 Monroe drive, OR
43 Mystic cove, O'Fallon 63045"
cities <- tolower(c("riverside", "O'fallon", "santa clara", "Morgantown"))
addrs <- readLines(textConnection(Addresses) )
To get the lines which have ST nnnnn, which appears to be the rule you want, try:
gsub(".*[A-Z]{2},? (\\d{5})", "\\1", addr.df)
## [1] "12034" "93453"
## [3] "231 Monroe drive, OR" "43 Mystic cove, O'Fallon 63045"
And mark those lines with nchar(lines) == 5 .
gsub(".*[A-Z]{2},? (\\d{5})", "\\1", addrs)[
+ grep("^\\d{5}$", gsub(".*[A-Z]{2},? (\\d{5})", "\\1", addr.df) )]
## [1] "12034" "93453"
To get the line indices with valid city names:
unlist( sapply(cities, function(xpatt) grep(xpatt, tolower(addrs)) ) )
## riverside o'fallon santa clara
## 1 4 2
| Extraction from a string in R or Python | I have a csv file with addresses that include ',', empty space, numbers. I have two other files with city and zip codes. I want to read the address file and extract the city name and zip codes. As you will see below the addresses have no easy pattern and is randomly sprinkled with ',' spaces etc.Here is an example.
Address file
123 Riverside Drive Riverside CA 12034
Santa clara CA 93453
231 Monroe drive, OR
43 Mystic cove, O'Fallon 63045
City file
riverside
O'fallon
santa clara
Morgantown
Zip code file
02343
23454
12034
93453
Expected output file (corresponding to the input address file) in two columns
City Zipcode
Riverside 12034
Santa clara 93453
Missing Missing
O'Fallon Missing
Note that the matching shouldn't be case sensitive. I am more familiar with R but will be happy with any help in python too.
Thank you in advance.
| [
"Use Google Refine. It's an open source project that is perfect for data cleansing and export into a format that actually makes sense. Everything is GUI based and it stores a complete history. You wont need to mess around with tedious regular expressions.\n",
"You might consider using something like this, though ... | [
3,
1,
0
] | [] | [] | [
"python",
"r"
] | stackoverflow_0004064464_python_r.txt |
Q:
Python problem with circular reference:
I get:
ImportError: cannot import name Image (from image_blob.py)
please help me thanks :s
my code:
image.py:
from google.appengine.ext import db
from app.models.item import Item
class Image(Item):
# imports
from app.models.image_blob import ImageBlob
#from app.models.user import User
#from list_user import ListUser # is needed in order to have the references
# references
#uploaded_by_user = db.ReferenceProperty(User, required = True)
large_image = db.ReferenceProperty(ImageBlob, required = True)
small_image = db.ReferenceProperty(ImageBlob, required = True)
# image info
title = db.StringProperty(required = True)
description = db.StringProperty(required = False)
# metadata
# relations
image_blob:
from google.appengine.ext import db
class ImageBlob(db.Model):
from app.models.image import Image
data = db.BlobProperty(required = True)
image = db.ReferenceProperty(Image, required = True)
A:
You're trying to import from image_blob.py before the entirety of image.py is processed. At the time which the from app.models.item import Item occurs, class Image hasn't yet been defined, and thus can't yet be imported (the entire class definition must have been processed before the symbol is actually defined).
There's a simple solution to this: Don't define the image property on ImageBlob. AppEngine's models automatically define a backwards reference for you, so when you add the ImageBlob to the Image, it'll automatically define a property on the ImageBlob which references back to the set of Images which reference it (which, in your current use case, should be of size 1).
| Python problem with circular reference: | I get:
ImportError: cannot import name Image (from image_blob.py)
please help me thanks :s
my code:
image.py:
from google.appengine.ext import db
from app.models.item import Item
class Image(Item):
# imports
from app.models.image_blob import ImageBlob
#from app.models.user import User
#from list_user import ListUser # is needed in order to have the references
# references
#uploaded_by_user = db.ReferenceProperty(User, required = True)
large_image = db.ReferenceProperty(ImageBlob, required = True)
small_image = db.ReferenceProperty(ImageBlob, required = True)
# image info
title = db.StringProperty(required = True)
description = db.StringProperty(required = False)
# metadata
# relations
image_blob:
from google.appengine.ext import db
class ImageBlob(db.Model):
from app.models.image import Image
data = db.BlobProperty(required = True)
image = db.ReferenceProperty(Image, required = True)
| [
"You're trying to import from image_blob.py before the entirety of image.py is processed. At the time which the from app.models.item import Item occurs, class Image hasn't yet been defined, and thus can't yet be imported (the entire class definition must have been processed before the symbol is actually defined).\n... | [
2
] | [] | [] | [
"circular_reference",
"python"
] | stackoverflow_0004065117_circular_reference_python.txt |
Q:
Django Time issues
My app in django requires to tell the user what time an action occurred. Aside from asking the user what timezone he/she is in, is it possible for me to generate the time on the client end?
Off the top of my head, are there a particular representation of time that is timezone independent, (unix time?), and then I can simply paste it into the html and have the client end (browser) findout the timezone and then do the calculation?
A:
I'd make all my times UTC, as that's a good international-level reference point, and you can always shift that to a local time, given that you know the user's TZ.
I'd also use the time on the server (datetime.datetime.now()) rather than rely on the client's system clock, as this makes it easy to fake what time something happened at.
A:
Haven't used it myself, but I think this is what you are looking for.
A:
i think you are looking for L10n (localization) yes ???
| Django Time issues | My app in django requires to tell the user what time an action occurred. Aside from asking the user what timezone he/she is in, is it possible for me to generate the time on the client end?
Off the top of my head, are there a particular representation of time that is timezone independent, (unix time?), and then I can simply paste it into the html and have the client end (browser) findout the timezone and then do the calculation?
| [
"I'd make all my times UTC, as that's a good international-level reference point, and you can always shift that to a local time, given that you know the user's TZ.\nI'd also use the time on the server (datetime.datetime.now()) rather than rely on the client's system clock, as this makes it easy to fake what time so... | [
2,
2,
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0004065157_django_python.txt |
Q:
How to index a Blog as a search engine?
I want to create a simple search engine for learning purpose.
I want to know how to index a simple blog site.
A blog site has many pages and in every page there is a blogpost.
But in every page there are other stuff in common as well ( header, footer, category block and other stuff ).
In your opinion, How can I index this blog ?
The program language doesn't matter obviously.
A:
You can use the quite powerfull Zend Lucene search engine for that (PHP 5).
http://framework.zend.com/manual/en/zend.search.lucene.html
| How to index a Blog as a search engine? | I want to create a simple search engine for learning purpose.
I want to know how to index a simple blog site.
A blog site has many pages and in every page there is a blogpost.
But in every page there are other stuff in common as well ( header, footer, category block and other stuff ).
In your opinion, How can I index this blog ?
The program language doesn't matter obviously.
| [
"You can use the quite powerfull Zend Lucene search engine for that (PHP 5). \nhttp://framework.zend.com/manual/en/zend.search.lucene.html\n"
] | [
0
] | [] | [] | [
"php",
"python",
"search",
"search_engine",
"web_crawler"
] | stackoverflow_0004065359_php_python_search_search_engine_web_crawler.txt |
Q:
How to add a python binding to C#?
When you want to call C from python, you write a module like this:
http://docs.python.org/extending/extending.html
Now, I have a question:
I want to write a module for use in Python with C#.
How can I get C# to interact with native Python ?
(Note: I'm not interested in Python.NET or IronPython).
A:
I know you are probably not gonna like this answer, but honestly: write it in C++, using boost::python or directly in Cython.
It'd be possible to write an extension using C#, but you'd have to convert the data structures used by Python, import a good deal of the Python C API, marshal everything back and forth between managed and unmanaged code, map object lifetimes between both Python's and C#'s garbage collector etc., which is most likely just not worth it.
You would also induce a dependency on the .NET framework, loose platform independence (probably even with Mono) while in general providing little benefit.
If you want to consume C# assemblies in CPython, your best bet actually is pywin32's win32com module on the Python side, and COM Interop on the .NET side. It allows you to expose your C# objects as COM classes with a few added attributes at the source level and easily import them into Python as objects, with events and everything. I had a lot of success integrating both platforms that way.
| How to add a python binding to C#? | When you want to call C from python, you write a module like this:
http://docs.python.org/extending/extending.html
Now, I have a question:
I want to write a module for use in Python with C#.
How can I get C# to interact with native Python ?
(Note: I'm not interested in Python.NET or IronPython).
| [
"I know you are probably not gonna like this answer, but honestly: write it in C++, using boost::python or directly in Cython. \nIt'd be possible to write an extension using C#, but you'd have to convert the data structures used by Python, import a good deal of the Python C API, marshal everything back and forth be... | [
2
] | [] | [] | [
".net",
"c#",
"python",
"python_bindings"
] | stackoverflow_0004065352_.net_c#_python_python_bindings.txt |
Q:
SQLite vague syntax error
Ok, so I'm putting a list of 25 tuples, with each tuple containing 5 items, into an sqlite database. Each time I try the main code to write, I get "apsw.SQLError: SQLError: near "?": syntax error" Here's the code I'm running. Be aware that this is part of a much, much larger server project for a game, so some of the functions will be unknown to you.
def writetable(self,blockoffset,matbefore,matafter,name,date):
self.blocklist.append((blockoffset,matbefore,matafter,name,date))
if len(self.blocklist) > 25:
self.memcursor.executemany("INSERT OR REPLACE INTO main (?,?,?,?,?)",self.blocklist)
blocklist.clear()
print("Memory Database updated")
A:
I believe it should be:
self.memcursor.executemany("INSERT OR REPLACE INTO main VALUES (?,?,?,?,?)",self.blocklist)
A:
You probably forgot the VALUES keyword:
self.memcursor.executemany("INSERT OR REPLACE INTO main VALUES (?,?,?,?,?)",self.blocklist)
Have a look here for the correct syntax.
| SQLite vague syntax error | Ok, so I'm putting a list of 25 tuples, with each tuple containing 5 items, into an sqlite database. Each time I try the main code to write, I get "apsw.SQLError: SQLError: near "?": syntax error" Here's the code I'm running. Be aware that this is part of a much, much larger server project for a game, so some of the functions will be unknown to you.
def writetable(self,blockoffset,matbefore,matafter,name,date):
self.blocklist.append((blockoffset,matbefore,matafter,name,date))
if len(self.blocklist) > 25:
self.memcursor.executemany("INSERT OR REPLACE INTO main (?,?,?,?,?)",self.blocklist)
blocklist.clear()
print("Memory Database updated")
| [
"I believe it should be:\nself.memcursor.executemany(\"INSERT OR REPLACE INTO main VALUES (?,?,?,?,?)\",self.blocklist)\n\n",
"You probably forgot the VALUES keyword:\n self.memcursor.executemany(\"INSERT OR REPLACE INTO main VALUES (?,?,?,?,?)\",self.blocklist)\n\nHave a look here for the correct syntax.\n"
] | [
3,
0
] | [] | [] | [
"database",
"python",
"sqlite"
] | stackoverflow_0004065457_database_python_sqlite.txt |
Q:
How to programmatically merge text files with potential conflicts (ala git or svn, etc)?
As part of a larger project, I want the ability to take two bodies of text and hand them to a merge algorithm which returns either an auto-merged result (in cases where the changes are not conflicting) or throws an error and (potentially) produces a single text document with the conflicting changes highlighted.
Basically, I just want a programmatic way to do what every source control system on the planet does internally, but I'm having a hard time finding it. There are tons of visual GUIs for doing this sort of thing that dominate my search results, but none of them seem to make easily accessible the core merging algorithm. Does everyone rely on some common and well understood algorithm/library and I just don't know the name so I'm having a hard time searching for it? Is this some just minor tweak on diff and I should be looking for diff libraries instead of merge libraries?
Python libraries would be most helpful, but I can live with the overhead of interfacing with some other library (or command line solution) if I have to; this operation should be relatively infrequent.
A:
You're probably searching for merge algorithms like 3-way merging, which you can find in many open source projects, e.g. in the bazaar VCS (merge3.py source).
A:
Did you check out difflib
http://docs.python.org/library/difflib.html
| How to programmatically merge text files with potential conflicts (ala git or svn, etc)? | As part of a larger project, I want the ability to take two bodies of text and hand them to a merge algorithm which returns either an auto-merged result (in cases where the changes are not conflicting) or throws an error and (potentially) produces a single text document with the conflicting changes highlighted.
Basically, I just want a programmatic way to do what every source control system on the planet does internally, but I'm having a hard time finding it. There are tons of visual GUIs for doing this sort of thing that dominate my search results, but none of them seem to make easily accessible the core merging algorithm. Does everyone rely on some common and well understood algorithm/library and I just don't know the name so I'm having a hard time searching for it? Is this some just minor tweak on diff and I should be looking for diff libraries instead of merge libraries?
Python libraries would be most helpful, but I can live with the overhead of interfacing with some other library (or command line solution) if I have to; this operation should be relatively infrequent.
| [
"You're probably searching for merge algorithms like 3-way merging, which you can find in many open source projects, e.g. in the bazaar VCS (merge3.py source).\n",
"Did you check out difflib \n\nhttp://docs.python.org/library/difflib.html\n\n"
] | [
11,
1
] | [] | [] | [
"command_line",
"diff",
"merge",
"python",
"text"
] | stackoverflow_0004065541_command_line_diff_merge_python_text.txt |
Q:
PyGtk - Activating a combo box
If I have a combo box in pyGTK and would like to set a list of strings and then on clicking on one activate a command how would I do it?
At the moment I have:
self.combo_key = gtk.Combo()
self.combo_key.set_popdown_strings(self.keys)
self.combo_key.entry.set_text(db.keys()[0])
self.combo_key.entry.connect("activate", self.key_sel)
But "activate" only calls after selection, and then by pressing enter. I'm also getting a deprecation warning for gtk.Combo() but cannot find any help on using gtk.ComboBoxEntry()
Any help guys?
A:
Try using a gtk.ComboBox instead of gtk.Combo, since the latter is deprecated in favor of the former. To initialise, you can you code like:
liststore = gtk.ListStore(gobject.TYPE_STRING)
for key in self.keys:
liststore.append((key,))
combobox = gtk.ComboBox(liststore)
cell = gtk.CellRendererText()
combobox.pack_start(cell, True)
combobox.add_attribute(cell, 'text', 0)
Now you connect to the changed signal of the combobox and use its get_active() method to ask for the item that was selected.
As you might guess from this explanation, the ComboBox isn't exactly made for this purpose. You probably want to use gtk.Menu.
| PyGtk - Activating a combo box | If I have a combo box in pyGTK and would like to set a list of strings and then on clicking on one activate a command how would I do it?
At the moment I have:
self.combo_key = gtk.Combo()
self.combo_key.set_popdown_strings(self.keys)
self.combo_key.entry.set_text(db.keys()[0])
self.combo_key.entry.connect("activate", self.key_sel)
But "activate" only calls after selection, and then by pressing enter. I'm also getting a deprecation warning for gtk.Combo() but cannot find any help on using gtk.ComboBoxEntry()
Any help guys?
| [
"Try using a gtk.ComboBox instead of gtk.Combo, since the latter is deprecated in favor of the former. To initialise, you can you code like:\nliststore = gtk.ListStore(gobject.TYPE_STRING)\nfor key in self.keys:\n liststore.append((key,))\ncombobox = gtk.ComboBox(liststore)\ncell = gtk.CellRendererText()\ncombo... | [
2
] | [] | [] | [
"combobox",
"gtk",
"pygtk",
"python"
] | stackoverflow_0004065680_combobox_gtk_pygtk_python.txt |
Q:
wx.GenericDirCtrl Event's handling
I'm using this control but I can't to handle control click (and others events).
This is my code:
class BoExplorerPanel(wx.Panel):
def __init__(self, parent):
wx.Panel.__init__(self, parent, wx.ID_ANY)
self.initComponents() # initialize Window components
def initComponents(self):
print "Inizializzo i controlli"
# controls
resizeBox = wx.BoxSizer(wx.VERTICAL)
self.dirBrowser = wx.GenericDirCtrl(self, wx.ID_ANY, style = wx.DIRCTRL_DIR_ONLY)
resizeBox.Add(self.dirBrowser, 1, wx.EXPAND | wx.ALL)
self.SetSizerAndFit(resizeBox)
# events
self.Bind(wx.EVT_TREE_ITEM_ACTIVATED, self.dirBrowser_OnItemSelected, self.dirBrowser)
self.Bind(wx.EVT_TREE_ITEM_RIGHT_CLICK, self.dirBrowser_OnRightClick, self.dirBrowser)
self.Bind(wx.EVT_TREE_SEL_CHANGED, self.dirBrowser_OnSelectionChanged, self.dirBrowser)
# panel's properties
def dirBrowser_OnItemSelected(self, event):
print "CLicked"
def dirBrowser_OnRightClick(self, event):
print "Right Click"
def dirBrowser_OnSelectionChanged(self, event):
print "Selection Changed"
A:
You need to bind to the TreeCtrl of the directory class, not that class itself.
Fixed code below. Note the call to event.Skip() in the event handlers (comment it out to see its effect)
#!/usr/bin/python
import wx
class BoExplorerPanel(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None)
self.initComponents() # initialize Window components
def initComponents(self):
print "Inizializzo i controlli"
# controls
resizeBox = wx.BoxSizer(wx.VERTICAL)
self.dirBrowser = wx.GenericDirCtrl(self, wx.ID_ANY, style = wx.DIRCTRL_DIR_ONLY)
resizeBox.Add(self.dirBrowser, 1, wx.EXPAND | wx.ALL)
self.SetSizerAndFit(resizeBox)
# events
tree = self.dirBrowser.GetTreeCtrl()
self.Bind(wx.EVT_TREE_ITEM_ACTIVATED, self.dirBrowser_OnItemSelected, tree)
self.Bind(wx.EVT_TREE_ITEM_RIGHT_CLICK, self.dirBrowser_OnRightClick, tree)
self.Bind(wx.EVT_TREE_SEL_CHANGED, self.dirBrowser_OnSelectionChanged, tree)
# panel's properties
def dirBrowser_OnItemSelected(self, event):
print "CLicked"
event.Skip()
def dirBrowser_OnRightClick(self, event):
print "Right Click"
event.Skip()
def dirBrowser_OnSelectionChanged(self, event):
print "Selection Changed"
event.Skip()
app = wx.App(False)
f = BoExplorerPanel()
f.Show()
app.MainLoop
| wx.GenericDirCtrl Event's handling | I'm using this control but I can't to handle control click (and others events).
This is my code:
class BoExplorerPanel(wx.Panel):
def __init__(self, parent):
wx.Panel.__init__(self, parent, wx.ID_ANY)
self.initComponents() # initialize Window components
def initComponents(self):
print "Inizializzo i controlli"
# controls
resizeBox = wx.BoxSizer(wx.VERTICAL)
self.dirBrowser = wx.GenericDirCtrl(self, wx.ID_ANY, style = wx.DIRCTRL_DIR_ONLY)
resizeBox.Add(self.dirBrowser, 1, wx.EXPAND | wx.ALL)
self.SetSizerAndFit(resizeBox)
# events
self.Bind(wx.EVT_TREE_ITEM_ACTIVATED, self.dirBrowser_OnItemSelected, self.dirBrowser)
self.Bind(wx.EVT_TREE_ITEM_RIGHT_CLICK, self.dirBrowser_OnRightClick, self.dirBrowser)
self.Bind(wx.EVT_TREE_SEL_CHANGED, self.dirBrowser_OnSelectionChanged, self.dirBrowser)
# panel's properties
def dirBrowser_OnItemSelected(self, event):
print "CLicked"
def dirBrowser_OnRightClick(self, event):
print "Right Click"
def dirBrowser_OnSelectionChanged(self, event):
print "Selection Changed"
| [
"You need to bind to the TreeCtrl of the directory class, not that class itself. \nFixed code below. Note the call to event.Skip() in the event handlers (comment it out to see its effect)\n#!/usr/bin/python\nimport wx\n\nclass BoExplorerPanel(wx.Frame):\n def __init__(self):\n wx.Frame.__init__(self, None)\n\n... | [
2
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0004065734_python_wxpython.txt |
Q:
How do I get a window's current size using Tkinter?
How do I get a windows current size using Tkinter, or possibly with the python standard library?
A:
Use the following universal widget methods (where w is a widget):
w.winfo_height()
w.winfo_width()
You can also use the following:
w.winfo_reqheight()
w.winfo_reqwidth()
Read about Universal widget methods.
| How do I get a window's current size using Tkinter? | How do I get a windows current size using Tkinter, or possibly with the python standard library?
| [
"Use the following universal widget methods (where w is a widget):\nw.winfo_height()\nw.winfo_width()\n\nYou can also use the following:\nw.winfo_reqheight()\nw.winfo_reqwidth()\n\nRead about Universal widget methods.\n"
] | [
31
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0004065783_python_tkinter.txt |
Q:
Amarok 1.4 script: knowing who's running you
I've been using Amarok 1.4 for a long time, switching to Bogdan Butnaru's packages when KDE stopped supporting it, and I'm now giving Pana a try.
I realised that a script I wrote in Python for Amarok 1.4 will not immediately run without changes under Pana. But instead of converting my script, which basically comes down to replacing "amarok" with "pana" in the paths I use, I'd rather make it compatible with both the original Amarok 1.4 and Pana, so that I could be able to distribute only a single version of that script (and possibly modifying it later if other forks become popular).
So, is there a (Python(ic)) way for my script, running from within the player, to find out which program launched it?
A:
import os
pid = os.getppid()
with open("/proc/%s/cmdline" % pid) as f:
print f.readline()
Assuming you are running Linux. Not sure if you need getppid() or getpid() here.
Not so pythonic maybe.
| Amarok 1.4 script: knowing who's running you | I've been using Amarok 1.4 for a long time, switching to Bogdan Butnaru's packages when KDE stopped supporting it, and I'm now giving Pana a try.
I realised that a script I wrote in Python for Amarok 1.4 will not immediately run without changes under Pana. But instead of converting my script, which basically comes down to replacing "amarok" with "pana" in the paths I use, I'd rather make it compatible with both the original Amarok 1.4 and Pana, so that I could be able to distribute only a single version of that script (and possibly modifying it later if other forks become popular).
So, is there a (Python(ic)) way for my script, running from within the player, to find out which program launched it?
| [
"import os\n\npid = os.getppid()\nwith open(\"/proc/%s/cmdline\" % pid) as f:\n print f.readline()\n\nAssuming you are running Linux. Not sure if you need getppid() or getpid() here.\nNot so pythonic maybe.\n"
] | [
1
] | [] | [] | [
"dcop",
"linux",
"python"
] | stackoverflow_0004062911_dcop_linux_python.txt |
Q:
Using the RESTful interface to Google's AJAX Search API for "Did you mean"?
Is it possible to get spelling/search suggestions (i.e. "Did you mean") via the RESTful interface to Google's AJAX search API? I'm trying to access this from Python, though the URL query syntax is all I really need.
Thanks!
A:
the Google AJAX API don't have a spelling check feature see this, you can use the SOAP service but i think it's no longer available .
at last you can look at yahoo API they have a feature for spelling check.
EDIT : check this maybe it can help you:
import httplib
import xml.dom.minidom
data = """
<spellrequest textalreadyclipped="0" ignoredups="0" ignoredigits="1" ignoreallcaps="1">
<text> %s </text>
</spellrequest>
"""
word_to_spell = "gooooooogle"
con = httplib.HTTPSConnection("www.google.com")
con.request("POST", "/tbproxy/spell?lang=en", data % word_to_spell)
response = con.getresponse()
dom = xml.dom.minidom.parseString(response.read())
dom_data = dom.getElementsByTagName('spellresult')[0]
for child_node in dom_data.childNodes:
result = child_node.firstChild.data.split()
print result
A:
if you're just looking for spelling suggestions you might want to check out something like Wordnik: http://docs.wordnik.com/api/methods
| Using the RESTful interface to Google's AJAX Search API for "Did you mean"? | Is it possible to get spelling/search suggestions (i.e. "Did you mean") via the RESTful interface to Google's AJAX search API? I'm trying to access this from Python, though the URL query syntax is all I really need.
Thanks!
| [
"the Google AJAX API don't have a spelling check feature see this, you can use the SOAP service but i think it's no longer available .\nat last you can look at yahoo API they have a feature for spelling check.\nEDIT : check this maybe it can help you:\nimport httplib\nimport xml.dom.minidom\n\ndata = \"\"\"\n<spell... | [
2,
1
] | [] | [] | [
"ajax",
"python",
"rest",
"search"
] | stackoverflow_0004065450_ajax_python_rest_search.txt |
Q:
Queue(maxsize=) not working?
I've implemented some threading into a project I've been working on in another thread, but the comments and questions have grown way off topic of the original post, so I figured best thing to do was to make a new question. The problem is this. I want my program to stop iterating over a while loop after an amount of iterations specified by the command line. I'm passing Queue.Queue(maxsize=10), in the following segments of code:
THREAD_NUMBER = 5
def main():
queue = Queue.Queue(maxsize=sys.argv[2])
mal_urls = set(make_mal_list())
for i in xrange(THREAD_NUMBER):
crawler = Crawler(queue, mal_urls)
crawler.start()
queue.put(sys.argv[1])
queue.join()
And here is the run function:
class Crawler(threading.Thread):
def __init__(self, queue, mal_urls):
self.queue = queue
self.mal_list = mal_urls
self.crawled_links = []
threading.Thread.__init__(self)
def run(self):
while True:
self.crawled = set(self.crawled_links)
url = self.queue.get()
if url not in self.mal_list:
self.crawl(url)
else:
print("Malicious Link Found: {0}".format(url))
self.queue.task_done()
self.crawl is a function which does some lxml.html parsing and then calls another function which does some string handling with the links parsed using lxml, and then calls self.queue.put(link), like so:
def queue_links(self, link, url):
if link.startswith('/'):
link = "http://" + url.netloc + link
elif link.startswith("#"):
return
elif not link.startswith("http"):
link = "http://" + url.netloc + "/" + link
# Add urls extracted from the HTML text to the queue to fetch them
if link not in self.crawled:
self.queue.put(link)
else:
return
Does anyone spot where I might have messed up that would be causing the program to never stop running, and why links that have already been crawled are not being recognized as such?
A:
You're not actually passing the integer 10 as the maxsize. You're passing sys.argv[2]. sys.argv is a list of strings, so at best you're passing "10" as the maxsize argument. And unfortunately, in Python 2.x, any integer is less than any string. You probably want to use int(sys.argv[2]) instead.
| Queue(maxsize=) not working? | I've implemented some threading into a project I've been working on in another thread, but the comments and questions have grown way off topic of the original post, so I figured best thing to do was to make a new question. The problem is this. I want my program to stop iterating over a while loop after an amount of iterations specified by the command line. I'm passing Queue.Queue(maxsize=10), in the following segments of code:
THREAD_NUMBER = 5
def main():
queue = Queue.Queue(maxsize=sys.argv[2])
mal_urls = set(make_mal_list())
for i in xrange(THREAD_NUMBER):
crawler = Crawler(queue, mal_urls)
crawler.start()
queue.put(sys.argv[1])
queue.join()
And here is the run function:
class Crawler(threading.Thread):
def __init__(self, queue, mal_urls):
self.queue = queue
self.mal_list = mal_urls
self.crawled_links = []
threading.Thread.__init__(self)
def run(self):
while True:
self.crawled = set(self.crawled_links)
url = self.queue.get()
if url not in self.mal_list:
self.crawl(url)
else:
print("Malicious Link Found: {0}".format(url))
self.queue.task_done()
self.crawl is a function which does some lxml.html parsing and then calls another function which does some string handling with the links parsed using lxml, and then calls self.queue.put(link), like so:
def queue_links(self, link, url):
if link.startswith('/'):
link = "http://" + url.netloc + link
elif link.startswith("#"):
return
elif not link.startswith("http"):
link = "http://" + url.netloc + "/" + link
# Add urls extracted from the HTML text to the queue to fetch them
if link not in self.crawled:
self.queue.put(link)
else:
return
Does anyone spot where I might have messed up that would be causing the program to never stop running, and why links that have already been crawled are not being recognized as such?
| [
"You're not actually passing the integer 10 as the maxsize. You're passing sys.argv[2]. sys.argv is a list of strings, so at best you're passing \"10\" as the maxsize argument. And unfortunately, in Python 2.x, any integer is less than any string. You probably want to use int(sys.argv[2]) instead.\n"
] | [
1
] | [] | [] | [
"python",
"set",
"threadpool"
] | stackoverflow_0004065885_python_set_threadpool.txt |
Q:
using locals() inside dictionary comprehension
The following code doesn't work, I assume because the locals() variable inside the comprehension will refer to the nested block where comprehension is evaluated:
def f():
a = 1
b = 2
list_ = ['a', 'b']
dict_ = {x : locals()[x] for x in list_}
I could use globals() instead, and it seems to work, but that may come with some additional problems (e.g., if there was a variable from a surrounding scope that happens to have the same name).
Is there anything that would make the dictionary using the variables precisely in the scope of function f?
Note: I am doing this because I have many variables that I'd like to put in a dictionary later, but don't want to complicate the code by writing dict_['a'] instead of a in the meantime.
A:
You could perhaps do this:
def f():
a = 1
b = 2
list_ = ['a', 'b']
locals_ = locals()
dict_ = dict((x, locals_[x]) for x in list_)
However, I would strongly discourage the use of locals() for this purpose.
A:
I believe that you're right: the locals() inside the dict comprehension will refer to the comprehension's namespace.
One possible solution (if it hasn't already occurred to you):
f_locals = locals()
dict_ = {x : f_locals[x] for x in list_}
| using locals() inside dictionary comprehension | The following code doesn't work, I assume because the locals() variable inside the comprehension will refer to the nested block where comprehension is evaluated:
def f():
a = 1
b = 2
list_ = ['a', 'b']
dict_ = {x : locals()[x] for x in list_}
I could use globals() instead, and it seems to work, but that may come with some additional problems (e.g., if there was a variable from a surrounding scope that happens to have the same name).
Is there anything that would make the dictionary using the variables precisely in the scope of function f?
Note: I am doing this because I have many variables that I'd like to put in a dictionary later, but don't want to complicate the code by writing dict_['a'] instead of a in the meantime.
| [
"You could perhaps do this:\ndef f(): \n a = 1 \n b = 2 \n list_ = ['a', 'b'] \n locals_ = locals()\n dict_ = dict((x, locals_[x]) for x in list_)\n\nHowever, I would strongly discourage the use of locals() for this purpose.\n",
"I believe that you're right: the locals() inside the dict comprehensi... | [
8,
4
] | [] | [] | [
"list_comprehension",
"python",
"python_3.x"
] | stackoverflow_0004065976_list_comprehension_python_python_3.x.txt |
Q:
Python 2.x: how to automate enforcing unicode instead of string?
How can I automate a test to enforce that a body of Python 2.x code contains no string instances (only unicode instances)?
Eg.
Can I do it from within the code?
Is there a static analysis tool that has this feature?
Edit:
I wanted this for an application in Python 2.5, but it turns out this is not really possible because:
2.5 doesn't support unicode_literals
kwargs dictionary keys can't be unicode objects, only strings
So I'm accepting the answer that says it's not possible, even though it's for different reasons :)
A:
It seems to me like you really need to parse the code with an honest to goodness python parser. Then you will need to dig through the AST your parser produces to see if it contains any string literals.
It looks like Python comes with a parser out of the box. From this documentation I got this code sample working:
import parser
from token import tok_name
def checkForNonUnicode(codeString):
return checkForNonUnicodeHelper(parser.suite(codeString).tolist())
def checkForNonUnicodeHelper(lst):
returnValue = True
nodeType = lst[0]
if nodeType in tok_name and tok_name[nodeType] == 'STRING':
stringValue = lst[1]
if stringValue[0] != "u": # Kind of hacky. Does this always work?
print "%s is not unicode!" % stringValue
returnValue = False
else:
for subNode in [lst[n] for n in range(1, len(lst))]:
if isinstance(subNode, list):
returnValue = returnValue and checkForNonUnicodeHelper(subNode)
return returnValue
print checkForNonUnicode("""
def foo():
a = 'This should blow up!'
""")
print checkForNonUnicode("""
def bar():
b = u'although this is ok.'
""")
which prints out
'This should blow up!' is not unicode!
False
True
Now doc strings aren't unicode but should be allowed, so you might have to do something more complicated like from symbol import sym_name where you can look up which node types are for class and function definitions. Then the first sub-node that's simply a string, i.e. not part of an assignment or whatever, should be allowed to not be unicode.
Good question!
Edit
Just a follow up comment. Conveniently for your purposes, parser.suite does not actually evaluate your python code. This means that you can run this parser over your Python files without worrying about naming or import errors. For example, let's say you have myObscureUtilityFile.py that contains
from ..obscure.relative.path import whatever
You can
checkForNonUnicode(open('/whoah/softlink/myObscureUtilityFile.py').read())
A:
You can't enforce that all strings are Unicode; even with from __future__ import unicode_literals in a module, byte strings can be written as b'...', as they can in Python 3.
There was an option that could be used to get the same effect as unicode_literals globally: the command-line option -U. However it was abandoned early in the 2.x series because it basically broke every script.
What is your purpose for this? It is not desirable to abolish byte strings. They are not “bad” and Unicode strings are not universally “better”; they are two separate animals and you will need both of them. Byte strings will certainly be needed to talk to binary files and network services.
If you want to be prepared to transition to Python 3, the best tack is to write b'...' for all the strings you really mean to be bytes, and u'...' for the strings that are inherently Unicode. The default string '...' format can be used for everything else, places where you don't care and/or whether Python 3 changes the default string type.
A:
Our SD Source Code Search Engine (SCSE) can provide this result directly.
The SCSE provides a way to search extremely quickly across large sets of files using some of the language structure to enable precise queries and minimize false positives. It handles a wide array
of languages, even at the same time, including Python. A GUI shows search hits and a page of actual text from the file containing a selected hit.
It uses lexical information from the source languages as the basis for queries, comprised of various langauge keywords and pattern tokens that match varying content langauge elements. SCSE knows the types of lexemes available in the langauge. One can search for a generic identifier (using query token I) or an identifier matching some regulatr expression. Similar, on can search for a generic string (using query token "S" for "any kind of string literal") or for a specific
type of string (for Python including "UnicodeStrings", non-unicode strings, etc, which collectively make up the set of Python things comprising "S").
So a search:
'for' ... I=ij*
finds the keyword 'for' near ("...") an identifier whose prefix is "ij" and shows you all the hits. (Language-specific whitespace including line breaks and comments are ignored.
An trivial search:
S
finds all string literals. This is often a pretty big set :-}
A search
UnicodeStrings
finds all string literals that are lexically defined as Unicode Strings (u"...")
What you want are all strings that aren't UnicodeStrings. The SCSE provides a "subtract" operator that subtracts hits of one kind that overlap hits of another. So your question, "what strings aren't unicode" is expressed concisely as:
S-UnicodeStrings
All hits shown will be the strings that aren't unicode strings, your precise question.
The SCSE provides logging facilities so that you can record hits. You can run SCSE from a command line, enabling a scripted query for your answer. Putting this into a command script would provide a tool gives your answer directly.
| Python 2.x: how to automate enforcing unicode instead of string? | How can I automate a test to enforce that a body of Python 2.x code contains no string instances (only unicode instances)?
Eg.
Can I do it from within the code?
Is there a static analysis tool that has this feature?
Edit:
I wanted this for an application in Python 2.5, but it turns out this is not really possible because:
2.5 doesn't support unicode_literals
kwargs dictionary keys can't be unicode objects, only strings
So I'm accepting the answer that says it's not possible, even though it's for different reasons :)
| [
"It seems to me like you really need to parse the code with an honest to goodness python parser. Then you will need to dig through the AST your parser produces to see if it contains any string literals.\nIt looks like Python comes with a parser out of the box. From this documentation I got this code sample working:... | [
1,
1,
0
] | [] | [] | [
"automated_tests",
"enforcement",
"python",
"static_analysis"
] | stackoverflow_0004046853_automated_tests_enforcement_python_static_analysis.txt |
Q:
What does fetch() fetch in GAE?
This is a follow up to my other question.
I thought that
mylist = list(Rep().all().fetch(50))
makes mylist a list. But when I try to get its length I get the message
self.response.out.write(len(P))
TypeError: object of type 'Rep' has no len()
Can anyone explain what I am doing wrong?
Rep().replist = L
Rep().put()
mylist = list(Rep().all().fetch(50))
P = mylist.pop()
self.response.out.write(len(P))
UPDATE
As a reference for others who may encounter the same problem; I post the following table which was very helpful to me. (The original here)
Rep().........................Rep object
Rep.all().....................Query object
list(Rep.all())...............List of Rep objects.
list(Rep.all())[0]............A single Rep object
list(Rep.all())[0].replist....A list
Thanks for all the answers.
A:
Instead of this:
Rep().replist = L
Rep().put()
mylist = list(Rep().all().fetch(50))
P = mylist.pop()
self.response.out.write(len(P))
Try something like this:
r = Rep()
r.replist = L
r.put()
mylist = Rep.all().fetch(50)
P = mylist.pop()
self.response.out.write(len(P.replist))
This code of yours:
Rep().replist = L
Rep().put()
Is creating a Rep instance, then assigning its replist to L. Then it's creating another Rep, and calling put() on it. So the one you are writing to the datastore is a blank Rep - it won't have your list.
In this code:
mylist = list(Rep().all().fetch(50))
You are calling all() on an instance of Rep - you should instead call it directly on the class. Also you don't need to wrap the results in list(), as fetch() already returns a list.
Then below where you have this:
self.response.out.write(len(P))
You are trying to get the length of P (which is a Rep), not the length of P's replist.
Update:
In response to the first comment:
In this code:
r = Rep()
The Rep() is creating an instance of a Rep. The r = is then assigning that instance to the name r. So now the name r refers to that instance of a Rep.
Then in this code:
r.replist = L
It is assigning the replist property of r to refer to the list L.
You are correct, instead of those two lines you can do this:
r = Rep(replist = L)
What this does is pass L to the __init__ function of Rep, with the argument name replist. The __init__ function of Rep is inherited from the db.Model base class. This function assigns the value of any arguments provided to a property of the same name on the model. So in this case, it assigns L to the replist property. So it has the same effect as the original two lines of code, but it works a bit differently.
In response to the second comment:
The = operator in Python means assignment, which is not the same as mathematical equivalence.
So this code:
r = Rep()
Does not mean that r is now equivalent to Rep(), and that you can now use r and Rep() to mean the same thing.
What it means is that r is now equal to the result of Rep(). What Rep() does is allocate a new instance of a Rep. So that makes r a reference to a new Rep. To refer to that same instance later, you therefore need to use r, not Rep() (which would allocate a new instance each time you call it).
A:
Try this:
self.response.out.write(len(mylist))
A:
if you want to print the number of elements of replist property.
self.response.write(len(P.replist));
Hope i can help you :p
| What does fetch() fetch in GAE? | This is a follow up to my other question.
I thought that
mylist = list(Rep().all().fetch(50))
makes mylist a list. But when I try to get its length I get the message
self.response.out.write(len(P))
TypeError: object of type 'Rep' has no len()
Can anyone explain what I am doing wrong?
Rep().replist = L
Rep().put()
mylist = list(Rep().all().fetch(50))
P = mylist.pop()
self.response.out.write(len(P))
UPDATE
As a reference for others who may encounter the same problem; I post the following table which was very helpful to me. (The original here)
Rep().........................Rep object
Rep.all().....................Query object
list(Rep.all())...............List of Rep objects.
list(Rep.all())[0]............A single Rep object
list(Rep.all())[0].replist....A list
Thanks for all the answers.
| [
"Instead of this:\nRep().replist = L \nRep().put() \nmylist = list(Rep().all().fetch(50)) \nP = mylist.pop() \nself.response.out.write(len(P)) \n\nTry something like this:\nr = Rep()\nr.replist = L \nr.put() ... | [
3,
0,
0
] | [] | [] | [
"google_app_engine",
"google_cloud_datastore",
"python"
] | stackoverflow_0004063767_google_app_engine_google_cloud_datastore_python.txt |
Q:
Using Imagemagick without making files?
I'm working in Python to create images from text. I've already been back and forth with PIL and frankly, its font and alignment options need a lot of work.
I can subprocess Imagemagick and it works great, except that it seems to always need to write a file to disk. I would like to subprocess the image creation and just get the data returned to Python, keeping everything in memory.
I've looked into a number of supposed Python wrappers for ImageMagick, but they're all hopelessly years out of date or not documented whatsoever. Even searching extensively on SO doesn't see to clearly point to a defacto way to use ImageMagic with Python. So I think going for subprocessing is the best way forward.
A:
convert and the other ImageMagick commands can output image data to stdout if you specify format:- as the output file. You can capture that output in Python using the subprocess module.
For instance:
cmd = ["convert", "test.bmp", "jpg:-"]
output_stream = subprocess.Popen(cmd, stdout=subprocess.PIPE).stdout
A:
It would be a lot more work than piping data to ImageMagick, but there are several Pango based solutions. I used pango and pygtk awhile back, and I am pretty sure you could develop a headless gtk or gdk application to render text to a pixbuf.
A simpler solution might be to use the python cairo bondings.
Pango works at a pretty low level, so simple stuff can be a lot more complicated, but rendering quality is hard to beat, and it gives you a lot of fine grained control over the layout.
| Using Imagemagick without making files? | I'm working in Python to create images from text. I've already been back and forth with PIL and frankly, its font and alignment options need a lot of work.
I can subprocess Imagemagick and it works great, except that it seems to always need to write a file to disk. I would like to subprocess the image creation and just get the data returned to Python, keeping everything in memory.
I've looked into a number of supposed Python wrappers for ImageMagick, but they're all hopelessly years out of date or not documented whatsoever. Even searching extensively on SO doesn't see to clearly point to a defacto way to use ImageMagic with Python. So I think going for subprocessing is the best way forward.
| [
"convert and the other ImageMagick commands can output image data to stdout if you specify format:- as the output file. You can capture that output in Python using the subprocess module.\nFor instance:\ncmd = [\"convert\", \"test.bmp\", \"jpg:-\"]\noutput_stream = subprocess.Popen(cmd, stdout=subprocess.PIPE).stdou... | [
7,
0
] | [] | [] | [
"imagemagick",
"python"
] | stackoverflow_0004066173_imagemagick_python.txt |
Q:
Python: Syntax Error for imported module - 'codecs.py'
I'm using a script which imports some modules, one being codecs. When the script is executed, I'll get a Traceback (most recent call last): on the import codecs line and SyntaxError: ('no viable alternative at input \'""\'', ('C:\\Python26\\lib\\codecs.py', 268, 17, ' return (b"", 0)\n')). This only occurs when I'm executing my own script which in turn executes the script which imports the codecs module. If I directly execute the script through cmd, the error will not occur.
A:
which in turn executes the script which ...
How does it ‘execute’ the script? You mean an import? A subprocess call? Something else?
Because “no viable alternative at input...” is a distinctive ANTLR parser error, and CPython 2.6 doesn't use that.
Jython 2.5 does. But Jython shouldn't be trying to run the codecs module from CPython 2.6. In this case it fails because of the syntax b"" for byte strings which is new in Python 2.6.
| Python: Syntax Error for imported module - 'codecs.py' | I'm using a script which imports some modules, one being codecs. When the script is executed, I'll get a Traceback (most recent call last): on the import codecs line and SyntaxError: ('no viable alternative at input \'""\'', ('C:\\Python26\\lib\\codecs.py', 268, 17, ' return (b"", 0)\n')). This only occurs when I'm executing my own script which in turn executes the script which imports the codecs module. If I directly execute the script through cmd, the error will not occur.
| [
"\nwhich in turn executes the script which ...\n\nHow does it ‘execute’ the script? You mean an import? A subprocess call? Something else?\nBecause “no viable alternative at input...” is a distinctive ANTLR parser error, and CPython 2.6 doesn't use that.\nJython 2.5 does. But Jython shouldn't be trying to run the c... | [
2
] | [] | [] | [
"python",
"windows_xp"
] | stackoverflow_0004066328_python_windows_xp.txt |
Q:
identifying objects, why does the returned value from id(...) change?
id(object)
This is an integer (or long integer) which is guaranteed to be unique and constant for this object during its lifetime.
Can you explain this output? Why does j's id change?
>>> i=10
>>> id(i)
6337824
>>> j=10
>>> id(j)
6337824
>>> j=j+1
>>> id(j)
6337800
>>> id(i)
6337824
A:
Because integers are immutable, each integer value is a distinct object with a unique id. The integer 10 has a different id from 11. Doing j=j+1 doesn't change the value of an existing integer object, rather it changes j to point to the object for 11.
Check out what happens when we independently create a new variable k and assign it the value 11:
>>> j=10
>>> id(j)
8402204
>>> j=j+1
>>> id(j)
8402192
>>> k=11
>>> id(k)
8402192
Note that it is not always the case that every integer has one and only one corresponding object. This only happens for small integers that Python decides to cache. It does not happen for large integers:
>>> x = 123456789
>>> id(x)
8404568
>>> y = 123456789
>>> id(y)
8404604
See https://docs.python.org/3/c-api/long.html#c.PyLong_FromLong:
The current implementation keeps an array of integer objects for all integers between -5 and 256, when you create an int in that range you actually just get back a reference to the existing object.
A:
This is why 2**8 is 2**8 == True, and 2**9 is 2**9 == False.
Values between -5 and 256 are preallocated.
A:
The same id for different variables is a product of how Python creates variables.
id is a hash of the the location of an object in memory. Python variables are references to an object, not new objects. If several variables reference the same object, they have the same `id.
A:
In CPython, id is generally derived from the Py_Object's pointer value, that is its location in memory.
A:
Python caches immutable objects(read integers and tuples..) - which is why they are immutable
and saves memory if u reference the same immutable in many
places. So small integers, empty tuples and such are actually
cached in Python runtime, so you keep getting back the same object
and hence the same id.
Try this for the list, you don't get the same id.
A:
These are primitive types, so I'm guessing each value gets its own ID. Try creating a true object and I think you'll see the functionality you expect.
If you need an id for a primitive, you could create an object with just one member of that type.
A:
j's id changes because the object named by j changes. First you initialize j to 10, so when you call id(j) you get the id of 10. Then you set j to 11, so after that when you call id(j) you get the id of 11.
| identifying objects, why does the returned value from id(...) change? |
id(object)
This is an integer (or long integer) which is guaranteed to be unique and constant for this object during its lifetime.
Can you explain this output? Why does j's id change?
>>> i=10
>>> id(i)
6337824
>>> j=10
>>> id(j)
6337824
>>> j=j+1
>>> id(j)
6337800
>>> id(i)
6337824
| [
"Because integers are immutable, each integer value is a distinct object with a unique id. The integer 10 has a different id from 11. Doing j=j+1 doesn't change the value of an existing integer object, rather it changes j to point to the object for 11.\nCheck out what happens when we independently create a new vari... | [
34,
14,
2,
1,
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0003402679_python.txt |
Q:
Proper data structure to represent a Sudoku puzzle?
What would be a smart data structure to use to represent a Sudoku puzzle? I.e. a 9X9 square where each "cell" contains either a number or a blank.
Special considerations include:
Ability to compare across row, column, and in 3X3 "group
Ease of implementation (specifically in Python)
Efficiency (not paramount)
I suppose in a pinch, a 2D array might work but that seems to be a less than elegant solution. I just would like to know if there's a better data structure.
A:
Actually, I built such a beast, both a solver and a generator, and I used a 2D array. It worked fine.
You just had to understand the indexes and where they were and that wasn't too difficult to master.
The relative relationships between cells in a row doesn't change depending on the column, same goes for cells in a column, or even cells in a mini-square.
Sometimes, a less "elegant" solution is just fine. Indeed, sometimes, it's preferable :-)
For what it's worth, you may be interested in the algorithms that I used for the solver/generator.
First I wrote the solver part which would first set all cells as being able to be any value then apply all the rules in sequence to see if a individual cell could be solved or otherwise limited, things like:
if the cell was a specific value in the clues, set it to that value.
if there's only one cell left in a row (or column or mini-square), you can set it to the remaining value.
if a cell is marked as being possibly N and N exists in its row/column/mini-square elsewhere, remove that possibility.
if there are two cells in the row/column/mini-square and they have the same two possibilities (and no other possibilities), all other cells in that row/column/mini-square should have that possibility removed.
And so on, adding each rule that I use in solving the real puzzles.
For the generator, I started with:
123 456 789
456 789 123
789 123 456
234 567 891
567 891 234
891 234 567
345 678 912
678 912 345
912 345 678
and then, in a loop of varying size (at least 500), proceeded to swap rows and columns in such a way that it would never produce an invalid puzzle. In other words, swap rows or columns with the group they're in (for example, rows 1, 2 and 3 are a group, so are columns 4, 5 and 6).
This shuffled up the cells well enough to produce a decent puzzle.
Then, I started choosing random cells and setting them as unknown. Once a cell was set as unknown, I would pass the whole puzzle into the solver. If it was solvable, I would continue, otherwise I would re-instate the cell and carry on.
This prevented me getting a puzzle that was logically unsolvable.
Once a large number of random cell removals had been done, I would try to remove all the remaining cells in order using the same method. What was left then was the minimum amount of information required to solve the puzzle.
And, so it wasn't a pain to Sudoku beginners, I would allow them to specify a lower difficulty level which would put a certain number of the unnecessary cells back in.
Not a bad scheme, there may be better ones but that one worked fine for me.
Now, if I could only figure out this Kakuro stuff, I could die happy :-)
A:
Read Peter Norvig's essay Solving Every Sudoku Puzzle. You're unlikely to find a more elegant solution and you'll probably learn some new things about data structures, Python, and performance analysis in the process.
A:
Others have reasonably suggested simply using a 2D array.
I note that a 2D array in most language implementations (anything in which that is implemented as "array of array of X" suffers from additional access time overhead (one access to the top level array, a second to the subarray).
I suggest you implement the data structure abstractly as a 2D array (perhaps even continuing to use 2 indexes), but implement the array as single block of 81 cells, indexed classically by i*9+j. This gives you conceptual clarity, and somewhat more efficient implementation, by avoiding that second memory access.
You should be able to hide the 1D array access behind setters and getters that take 2D indexes. If your language has the capability (dunno if this is true for Python), such small methods can be inlined for additional speed.
A:
Python doesn't have much in the way of data structures. Your best bet is probably just a regular 2D array or to build your own using classes.
You can read more about python data types here.
| Proper data structure to represent a Sudoku puzzle? | What would be a smart data structure to use to represent a Sudoku puzzle? I.e. a 9X9 square where each "cell" contains either a number or a blank.
Special considerations include:
Ability to compare across row, column, and in 3X3 "group
Ease of implementation (specifically in Python)
Efficiency (not paramount)
I suppose in a pinch, a 2D array might work but that seems to be a less than elegant solution. I just would like to know if there's a better data structure.
| [
"Actually, I built such a beast, both a solver and a generator, and I used a 2D array. It worked fine.\nYou just had to understand the indexes and where they were and that wasn't too difficult to master.\nThe relative relationships between cells in a row doesn't change depending on the column, same goes for cells i... | [
11,
8,
2,
0
] | [] | [] | [
"data_structures",
"graph",
"python",
"sudoku"
] | stackoverflow_0004066075_data_structures_graph_python_sudoku.txt |
Q:
Using gevent with python xmlrpclib
Is it possible to use python's standard libs xmlrpclib with gevent? Currently i'm tried to use monkey.patch_all(), but without success.
from gevent import monkey
monkey.patch_all()
import gevent
import time
import xmlrpclib
from SimpleXMLRPCServer import SimpleXMLRPCServer
import urllib2
def fetch(url):
g = gevent.spawn(urllib2.urlopen, url)
return g.get().read()
def is_even(n):
return n%2 == 0
def req(url):
return fetch(url)
server = SimpleXMLRPCServer(("localhost", 8000))
print "Listening on port 8000..."
server.register_function(is_even, "is_even")
server.register_function(req, "req")
server.serve_forever()
urllib2.urlopen is blocking server. It looks to me, that monkey.patch_all did not patched socket, that's why it blocks.
A:
The socket is patched fine, but there are other problems with your code.
First, this
def fetch(url):
g = gevent.spawn(urllib2.urlopen, url)
return g.get().read()
is the same as
def fetch(url):
return urllib2.urlopen(url).read()
You're spawning a new greenlet here but then blocking the current one until that new one is done. It does not make things concurrent. It's exactly the same as just running urlopen and waiting for it to finish.
Second, in order to take advantage of gevent there got to be more than one lightweight thread (greenlet) running at the same time.
SimpleXMLRPCServer, however, is defined as
class SimpleXMLRPCServer(SocketServer.TCPServer,
SimpleXMLRPCDispatcher):
which means it serves one connection at a time.
If you make your own SimpleXMLRPCServer class, but use ThreadingTCPServer instead of TCPServer, you should be able to benefit from using gevent here.
monkey.patch_all() patches threading to become greenlet-based, so such server will spawn a new greenlet for each new connection.
| Using gevent with python xmlrpclib | Is it possible to use python's standard libs xmlrpclib with gevent? Currently i'm tried to use monkey.patch_all(), but without success.
from gevent import monkey
monkey.patch_all()
import gevent
import time
import xmlrpclib
from SimpleXMLRPCServer import SimpleXMLRPCServer
import urllib2
def fetch(url):
g = gevent.spawn(urllib2.urlopen, url)
return g.get().read()
def is_even(n):
return n%2 == 0
def req(url):
return fetch(url)
server = SimpleXMLRPCServer(("localhost", 8000))
print "Listening on port 8000..."
server.register_function(is_even, "is_even")
server.register_function(req, "req")
server.serve_forever()
urllib2.urlopen is blocking server. It looks to me, that monkey.patch_all did not patched socket, that's why it blocks.
| [
"The socket is patched fine, but there are other problems with your code.\nFirst, this\ndef fetch(url):\n g = gevent.spawn(urllib2.urlopen, url)\n return g.get().read()\n\nis the same as \ndef fetch(url):\n return urllib2.urlopen(url).read()\n\nYou're spawning a new greenlet here but then blocking the curr... | [
9
] | [] | [] | [
"gevent",
"python",
"xmlrpclib"
] | stackoverflow_0004065079_gevent_python_xmlrpclib.txt |
Q:
In Python, given a directory of full-size images, how can I generate thumbnails using more than one CPU core?
I have a 16-core machine but my current resizing function only uses one core, which is really inefficient for a large directory of images.
def generateThumbnail(self, width, height):
"""
Generates thumbnails for an image
"""
im = Image.open(self._file)
(detected_width,detected_height) = im.size
#Get cropped box area
bbox = self.getCropArea(detected_width, detected_height, width, height)
#Crop to box area
cropped_image = im.crop(bbox)
#Resize to thumbnail
cropped_image.thumbnail((width, height), Image.ANTIALIAS)
#Save image
cropped_image.save(self._path + str(width) + 'x' +
str(height) + '-' + self._filename, "JPEG")
Any help would be greatly appreciated. Thank you.
A:
This sounds like a good solution for the multiprocessing module, which uses the threading interface, but creates separate processes instead of threads.
| In Python, given a directory of full-size images, how can I generate thumbnails using more than one CPU core? | I have a 16-core machine but my current resizing function only uses one core, which is really inefficient for a large directory of images.
def generateThumbnail(self, width, height):
"""
Generates thumbnails for an image
"""
im = Image.open(self._file)
(detected_width,detected_height) = im.size
#Get cropped box area
bbox = self.getCropArea(detected_width, detected_height, width, height)
#Crop to box area
cropped_image = im.crop(bbox)
#Resize to thumbnail
cropped_image.thumbnail((width, height), Image.ANTIALIAS)
#Save image
cropped_image.save(self._path + str(width) + 'x' +
str(height) + '-' + self._filename, "JPEG")
Any help would be greatly appreciated. Thank you.
| [
"This sounds like a good solution for the multiprocessing module, which uses the threading interface, but creates separate processes instead of threads.\n"
] | [
5
] | [] | [] | [
"multithreading",
"python",
"python_multithreading"
] | stackoverflow_0004066606_multithreading_python_python_multithreading.txt |
Q:
SQLite in Python 2.2.3
I've written a web-app in python using SQLite and it runs fine on my server at home (with apache and python 2.5.2). I'm now trying to upload it to my web host and there servers use python 2.2.3 without SQLite.
Anyone know of a way to use SQLite in python 2.2.3 e.g. a module that I can upload and import? I've tried butchering the module from newer versions of python, but they don't seem to be compatible.
Thanks,
Mike
A:
There is no out-of-the-box solution; you either have to backport the SQLlite module from Python 2.5 to Python 2.2 or ask your web hoster to upgrade to the latest Python version.
Python 2.2 is really ancient! At least for security reasons, they should upgrade (no more security fixes for 2.2 since May 30, 2003!).
Note that you can install several versions of Python in parallel. Just make sure you use "/usr/bin/python25" instead of "/usr/bin/python" in your scripts. To make sure all the old stuff is still working, after installing Python 2.5, you just have to fix the two symbolic links "/usr/bin/python" and "/usr/lib/python" which should now point to 2.5. Bend them back to 2.2 and you're good.
A:
Look here: http://oss.itsystementwicklung.de/download/pysqlite/
From the release notes (http://oss.itsystementwicklung.de/trac/pysqlite/browser/doc/install-source.txt)
Python:
Python 2.3 or later
You may not be able to do what you're trying to do.
A:
If you have shell access to your web server, you can probably build you're own version of Python and SQLite. This will let you use the latest version. Download the source code, then when you configure it, do something like "./configure --prefix=$HOME/packages".
Next, fiddle around with your .profile, or .bashrc or whatever it is to make sure $HOME/packages/bin comes first in your path. This will cause your private Python to override the one installed by your web server.
This page might give you a little more information for how to do this on a server like Dreamhost: http://wiki.dreamhost.com/Python
A:
In case anyone comes across this question, the reason why neither pysqlite nor APSW are available for Python 2.2 is because Python 2.3 added the simplified GIL API. Prior to Python 2.3 it required a lot of code to keep track of the GIL. (The GIL is the lock used by Python to ensure correct behaviour while multi-threading.)
Doing a backport to 2.2 would require ripping out all the threading code. Trying to make it also be thread safe under 2.2 would be a nightmare. There was a reason they introduced the simplified GIL API!
I am still astonished at just how popular older Python versions are. APSW for Python 2.3 is still regularly downloaded.
| SQLite in Python 2.2.3 | I've written a web-app in python using SQLite and it runs fine on my server at home (with apache and python 2.5.2). I'm now trying to upload it to my web host and there servers use python 2.2.3 without SQLite.
Anyone know of a way to use SQLite in python 2.2.3 e.g. a module that I can upload and import? I've tried butchering the module from newer versions of python, but they don't seem to be compatible.
Thanks,
Mike
| [
"There is no out-of-the-box solution; you either have to backport the SQLlite module from Python 2.5 to Python 2.2 or ask your web hoster to upgrade to the latest Python version. \nPython 2.2 is really ancient! At least for security reasons, they should upgrade (no more security fixes for 2.2 since May 30, 2003!).\... | [
2,
1,
0,
0
] | [] | [] | [
"hosting",
"linux",
"python",
"sql",
"sqlite"
] | stackoverflow_0000737511_hosting_linux_python_sql_sqlite.txt |
Q:
Alternative to Connection.iterdump for SQLite in Python?
I found a function that will help me load a disk SQLite database to a memory database, but have found that the module I need, apsw, doesn't support it, while pysqlite does. I need apsw because it has most of the functions I need that pysqlite does not. Is there any work around to completely copying to a database?
A:
As singularity pointed out, APSW provides the backup functionality builtin to SQLite.
The reason you can't continue to use cursors (in practise the underlying SQLite compiled statements) is because the database schema has potentially completed changed as you have overwritten it with a backup. You can use close methods to force items closed.
For some reason many developers seem to treat cursors as a precious commodity and attempt to reuse them and keep them around at every opportunity. Cursors themselves are very lightweight, just slightly more "heavy" than a Python integer. The underlying SQLite compiled statements are more heavyweight but at the Python object level they are switch around for each statement executed. (ie an APSW cursor points to the currently executing SQLite compiled statement.)
BTW APSW also includes the ability to dump the database. You can use the shell class to do the work for you.
http://apidoc.apsw.googlecode.com/hg/shell.html#shell-class
Disclosure: I am the APSW author.
A:
Check the connection.backup() function
| Alternative to Connection.iterdump for SQLite in Python? | I found a function that will help me load a disk SQLite database to a memory database, but have found that the module I need, apsw, doesn't support it, while pysqlite does. I need apsw because it has most of the functions I need that pysqlite does not. Is there any work around to completely copying to a database?
| [
"As singularity pointed out, APSW provides the backup functionality builtin to SQLite.\nThe reason you can't continue to use cursors (in practise the underlying SQLite compiled statements) is because the database schema has potentially completed changed as you have overwritten it with a backup. You can use close m... | [
2,
0
] | [] | [] | [
"database",
"memory",
"python",
"sqlite"
] | stackoverflow_0004038111_database_memory_python_sqlite.txt |
Q:
Query to fetch objects surrounding an object
Lets say I am fetching a specific episode of a series.
What would be the best way to get the surrounding episodes by episode number?
Simplified model:
class Episode(models.Model):
series = models.ForeignKey(Series)
number = models.IntegerField()
For example, episode 10 would fetch episodes 8-12.
Episode 1 would fetch episodes 1-5.
A:
This looks like you're just treating a TV series as an array of episodes. If that's the case, why not something like
Episode.objects.filter(series=some_series,number__gte=epnum-2, number__lte=epnum+2)
to find the episodes surrounding the episode epnum, with special cases for when epnum-2<=0 or epnum+2>Episode.object.filter(series=some_series).order_by('-number')[0].number?
If you want, say, episodes at a season break to be treated differently, you'll need to do something more complicated, like perhaps what @Scott suggests. But otherwise, I believe this simple solution will suffice.
A:
Building on desfido's solution:
class EpisodeManager(models.Manager):
def get_near_objects(self, series, number):
return self.get_query_set().filter(
series=series,
number__gte=number-2,
number__lte=number+2)
use_for_related = True
Then in your model:
class Episode(models.Model):
series = models.ForeignKey(Series)
number = models.IntegerField()
objects = EpisodeManager()
Now, you can use:
Episode.objects.get_near_objects(series="Star Trek: The Original Series", number=7)
| Query to fetch objects surrounding an object | Lets say I am fetching a specific episode of a series.
What would be the best way to get the surrounding episodes by episode number?
Simplified model:
class Episode(models.Model):
series = models.ForeignKey(Series)
number = models.IntegerField()
For example, episode 10 would fetch episodes 8-12.
Episode 1 would fetch episodes 1-5.
| [
"This looks like you're just treating a TV series as an array of episodes. If that's the case, why not something like\nEpisode.objects.filter(series=some_series,number__gte=epnum-2, number__lte=epnum+2)\n\nto find the episodes surrounding the episode epnum, with special cases for when epnum-2<=0 or epnum+2>Episode.... | [
3,
3
] | [] | [] | [
"database",
"django",
"python"
] | stackoverflow_0004066125_database_django_python.txt |
Q:
reading a file in python
I am new to python been using it for graphics but never done it for other problems. My question is how to read this file which is tab or space delimited and has headers in python, i know how to do comma delimted file but not done this on?
ID YR MO DA YrM MoM DaM
100 2010 2 20 2010 8 2010 30
110 2010 4 30 2010 9 2010 12
112 2010 8 20 2010 10 2010 20
Also is there a way to find the difference of number of days between two dates.
A:
Does the same technique for csv modules does not work?
import csv
reader = csv.reader(open("filename"), delimiter="\t")
Delimiter can be "\s" or "\t".
You can also use DictReader this way:
f = open(filename, '')
try:
reader = csv.DictReader(f)
for row in reader:
print row
finally:
f.close()
you can also use brute force technique
for line in open(filename):
listWords = line.split("\t")
Split function:
>>> t = 'ID YR MO DA YrM MoM DaM'
>>> t.split(" ")
['ID', 'YR', 'MO', 'DA', 'YrM', 'MoM', 'DaM']
For calculating no of days, use datetime module : http://docs.python.org/library/datetime.html
>>> import datetime
>>> k = datetime.date(2010, 05, 26) - datetime.date(2010, 02, 10)
>>> k.days
105
>>>
A:
For simple tasks, you can just use the str.split() method. split() takes the delimiter as its parameter, but splits on whitespace if none is given.
>>> lin="a b c d"
>>> lin.split()
['a', 'b', 'c', 'd']
| reading a file in python | I am new to python been using it for graphics but never done it for other problems. My question is how to read this file which is tab or space delimited and has headers in python, i know how to do comma delimted file but not done this on?
ID YR MO DA YrM MoM DaM
100 2010 2 20 2010 8 2010 30
110 2010 4 30 2010 9 2010 12
112 2010 8 20 2010 10 2010 20
Also is there a way to find the difference of number of days between two dates.
| [
"Does the same technique for csv modules does not work? \nimport csv\nreader = csv.reader(open(\"filename\"), delimiter=\"\\t\")\n\nDelimiter can be \"\\s\" or \"\\t\".\nYou can also use DictReader this way:\nf = open(filename, '')\ntry:\n reader = csv.DictReader(f)\n for row in reader:\n print row\nfi... | [
21,
8
] | [] | [] | [
"csv",
"python",
"string"
] | stackoverflow_0004065594_csv_python_string.txt |
Q:
auto collect information in sub_modules when import in python?
Suppose I have below python file structure:
\function_group
|-__init__.py
|-sub_function1
|----|__init__.py
|----|sub_sub_func1.py
|----|sub_sub_func2.py
|----|sub_sub_func3.py
|-sub_function2
|----|__init__.py
|----|sub_sub_func1.py
|----|sub_sub_func2.py
|----|sub_sub_func3.py
In each sub_sub_funcX.py there's a list functions will collect all function name in sub_sub_funcX.py itself,
# sub_sub_funcX.py
# and each sub_sub_funcX.py file has similiar code
import inspect
functions = inspect.getmembers(self?, inspect.isfunction) # how to write the "self" here
def bar(x, y):
return x * y
def bar1(x, y):
return x + y
My questions are
on the above code marked "# how" , what is the right expression for point self? Should it be a "sub_sub_funcX"?
how I can get a full list of all those [functions] when import the top module function_group? I means is it possible each sub_function modules can report to the top it's function list in some how when import?
is there a way I can easy extend modules without adding housekeeping code in __init__ just an easy to hook and easy to remove? for example, I change the structure like this later:
\function_group
|-__init__.py
|-sub_function1
|----|__init__.py
|----|sub_sub_func1.py
|----|sub_sub_func2.py
|----|sub_sub_func3.py
|-sub_function2
|----|__init__.py
|----|sub_sub_func1.py
|----|sub_sub_func2.py
|----|sub_sub_func3.py
|----|sub_sub_func4.py # new added
|-sub_function3 # new added
|----|__init__.py # new added
|----|sub_sub_func1.py # new added
|----|sub_sub_sub_function_31 # new sub added
|--------|__init__.py # new added
|--------|sub_sub_sub_sub_func1.py# new added
A:
1: You need
import inspect
import sys
inspect.getmembers(sys.modules[__name__], inspect.isfunction)
2: The best answer I can think of is to import the submodules, and inspect them in the top-level.
No, the onus is on the top-level package (the one which is imported) to do what it needs to do. You can't import the top package and expect the sub-packages to do their thing, unless they're imported in the top-package. And since you don't want to modify your top-level init.py, that's not going to happen.
Can you tell us exactly what you're trying to do with those functions? I'm getting the feeling that there has to be a better way than this much introspection.
| auto collect information in sub_modules when import in python? | Suppose I have below python file structure:
\function_group
|-__init__.py
|-sub_function1
|----|__init__.py
|----|sub_sub_func1.py
|----|sub_sub_func2.py
|----|sub_sub_func3.py
|-sub_function2
|----|__init__.py
|----|sub_sub_func1.py
|----|sub_sub_func2.py
|----|sub_sub_func3.py
In each sub_sub_funcX.py there's a list functions will collect all function name in sub_sub_funcX.py itself,
# sub_sub_funcX.py
# and each sub_sub_funcX.py file has similiar code
import inspect
functions = inspect.getmembers(self?, inspect.isfunction) # how to write the "self" here
def bar(x, y):
return x * y
def bar1(x, y):
return x + y
My questions are
on the above code marked "# how" , what is the right expression for point self? Should it be a "sub_sub_funcX"?
how I can get a full list of all those [functions] when import the top module function_group? I means is it possible each sub_function modules can report to the top it's function list in some how when import?
is there a way I can easy extend modules without adding housekeeping code in __init__ just an easy to hook and easy to remove? for example, I change the structure like this later:
\function_group
|-__init__.py
|-sub_function1
|----|__init__.py
|----|sub_sub_func1.py
|----|sub_sub_func2.py
|----|sub_sub_func3.py
|-sub_function2
|----|__init__.py
|----|sub_sub_func1.py
|----|sub_sub_func2.py
|----|sub_sub_func3.py
|----|sub_sub_func4.py # new added
|-sub_function3 # new added
|----|__init__.py # new added
|----|sub_sub_func1.py # new added
|----|sub_sub_sub_function_31 # new sub added
|--------|__init__.py # new added
|--------|sub_sub_sub_sub_func1.py# new added
| [
"1: You need\nimport inspect\nimport sys\ninspect.getmembers(sys.modules[__name__], inspect.isfunction)\n\n2: The best answer I can think of is to import the submodules, and inspect them in the top-level.\n\nNo, the onus is on the top-level package (the one which is imported) to do what it needs to do. You can't im... | [
1
] | [] | [] | [
"python",
"python_module"
] | stackoverflow_0004067096_python_python_module.txt |
Q:
Python: translating/replacing in a string words that aren't the ones you want
Basically, I've got a bunch of phrases and I'm only interested in the ones that contain certain words. What I want to do is 1) find out if that word is there and if it is, 2) erase all the other words. I could do this with a bunch of if's and for's but I was wondering if there'd be a short/pythonic approach to it.
A:
A suggested algorithm:
For each phrase
Find whether the interesting word is there
If it is, erase all other words
Otherwise, just continue to the next phrase
Yes, implementing this would take "a bunch of ifs and fors", but you would be surprised how easily and cleanly such logic translates to Python.
A more succinct way to achieve the same would be to use a list comprehension, which flattens this logic somewhat. Given that phrases is a list of phrases:
phrases = [process(p) if isinteresting(p) else p for p in phrases]
For a suitable definition of the process and isinteresting functions.
A:
A regex-based solution:
>>> import re
>>> phrase = "A lot of interesting and boring words"
>>> regex = re.compile(r"\b(?!(?:interesting|words)\b)\w+\W*")
>>> clean = regex.sub("", phrase)
>>> clean
'interesting words'
The regex works as follows:
\b # start the match at a word boundary
(?! # assert that it's not possible to match
(?: # one of the following:
interesting # "interesting"
| # or
words # "words"
) # add more words if desired...
\b # assert that there is a word boundary after our needle matches
) # end of lookahead
\w+\W* # match the word plus any non-word characters that follow.
| Python: translating/replacing in a string words that aren't the ones you want | Basically, I've got a bunch of phrases and I'm only interested in the ones that contain certain words. What I want to do is 1) find out if that word is there and if it is, 2) erase all the other words. I could do this with a bunch of if's and for's but I was wondering if there'd be a short/pythonic approach to it.
| [
"A suggested algorithm:\n\nFor each phrase\n\nFind whether the interesting word is there\nIf it is, erase all other words\nOtherwise, just continue to the next phrase\n\n\nYes, implementing this would take \"a bunch of ifs and fors\", but you would be surprised how easily and cleanly such logic translates to Python... | [
3,
1
] | [] | [] | [
"python",
"text_processing"
] | stackoverflow_0004066667_python_text_processing.txt |
Q:
Alternative to locals() in printing a table with a header
[Python 3.1]
Edit: mistake in the original code.
I need to print a table. The first row should be a header, which consists of column names separated by tabs. The following rows should contain the data (also tab-separated).
To clarify, let's say I have columns "speed", "power", "weight". I originally wrote the following code, with the help from a related question I asked earlier:
column_names = ['speed', 'power', 'weight']
def f(row_number):
# some calculations here to populate variables speed, power, weight
# e.g., power = retrieve_avg_power(row_number) * 2.5
# e.g., speed = math.sqrt(power) / 2
# etc.
locals_ = locals()
return {x : locals_[x] for x in column_names}
def print_table(rows):
print(*column_names, sep = '\t')
for row_number in range(rows):
row = f(row_number)
print(*[row[x] for x in component_names], sep = '\t')
But then I learned that I should avoid using locals() if possible.
Now I'm stuck. I don't want to type the list of all the column names more than once. I don't want to rely on the fact that every dictionary I create inside f() is likely to iterate through its keys in the same order. And I don't want to use locals().
Note that the functions print_table() and f() do a lot of other stuff; so I have to keep them separate.
How should I write the code?
A:
class Columns:
pass
def f(row_number):
c = Columns()
c.power = retrieve_avg_power(row_number) * 2.5
c.speed = math.sqrt(power) / 2
return c.__dict__
This also lets you specify which of the variables are meant as columns, instead of rather being temporary in the function.
A:
You could use an OrderedDict to fix the order of the dictionaries. But as I see it that isn't even necessary. You are always taking the keys from the column_names list (except in the last line, I assume that is a typo), so the order of the values will always be the same.
A:
an alternative to locals() will be to use the inspect module
import inspect
def f(row_number):
# some calculations here to populate variables speed, power, weight
# e.g., power = retrieve_avg_power(row_number) * 2.5
# e.g., speed = math.sqrt(power) / 2
# etc.
locals_ = inspect.currentframe().f_locals
return {x : locals_[x] for x in column_names }
| Alternative to locals() in printing a table with a header | [Python 3.1]
Edit: mistake in the original code.
I need to print a table. The first row should be a header, which consists of column names separated by tabs. The following rows should contain the data (also tab-separated).
To clarify, let's say I have columns "speed", "power", "weight". I originally wrote the following code, with the help from a related question I asked earlier:
column_names = ['speed', 'power', 'weight']
def f(row_number):
# some calculations here to populate variables speed, power, weight
# e.g., power = retrieve_avg_power(row_number) * 2.5
# e.g., speed = math.sqrt(power) / 2
# etc.
locals_ = locals()
return {x : locals_[x] for x in column_names}
def print_table(rows):
print(*column_names, sep = '\t')
for row_number in range(rows):
row = f(row_number)
print(*[row[x] for x in component_names], sep = '\t')
But then I learned that I should avoid using locals() if possible.
Now I'm stuck. I don't want to type the list of all the column names more than once. I don't want to rely on the fact that every dictionary I create inside f() is likely to iterate through its keys in the same order. And I don't want to use locals().
Note that the functions print_table() and f() do a lot of other stuff; so I have to keep them separate.
How should I write the code?
| [
"class Columns:\n pass\n\ndef f(row_number):\n c = Columns()\n c.power = retrieve_avg_power(row_number) * 2.5\n c.speed = math.sqrt(power) / 2\n return c.__dict__\n\nThis also lets you specify which of the variables are meant as columns, instead of rather being temporary in the function.\n",
"You c... | [
2,
0,
0
] | [] | [] | [
"list_comprehension",
"locals",
"python",
"python_3.x"
] | stackoverflow_0004067463_list_comprehension_locals_python_python_3.x.txt |
Q:
Python function with too many arguments with default values, how to make it cleaner?
I have the following function signature, and it looks really ugly, what can I do to make it look cleaner ?
def contact(
request, sender=settings.DEFAULT_FROM_EMAIL,
subj_tmpl='contato/subject.txt',msg_tmpl='contato/msg.html',
template='contato/contato.html', success_template='contato/success.html',
success_redir='/',append_message=None,):
A:
if i were you i think i will do it like this:
def contact(request, sender=None, append_message=None, context=None):
if not sender:
sender = settings.DEFAULT_FROM_EMAIL # i hope that you can access settings here
# The context arg is a dictionary where you can put all the others argument and
# you can use it like so :
subj_tmpl = context.get('subj_tmpl', 'contato/subject.txt')
# ....
hope this will help you.
A:
My proposal is to drop parameters. Do you really need to be able to specify all the templates separately? Wouldn't it be sufficient to just specify the template folder, and then mandate that it has subject.txt, msg.html, etc in it?
If you just want to improve readability, reformat it to have one parameter per line:
def contact(
request,
sender=settings.DEFAULT_FROM_EMAIL,
subj_tmpl='contato/subject.txt',
msg_tmpl='contato/msg.html',
template='contato/contato.html',
success_template='contato/success.html',
success_redir='/',
append_message=None,):
This will allow a reader to more quickly grasp what the parameter names are.
A:
You could rewrite it as:
def contact( request, **kargs):
try:
sender = kwargs.pop ('sender')
except KeyError:
sender=settings.DEFAULT_FROM_EMAIL
try:
subj_tmpl = kwargs.pop ('subj_tmpl')
except KeyError:
subj_tmpl='contato/subject.txt'
# ...
# and so on
# ...
A:
def contact(request, **kwargs):
sender = kwargs.get('sender', settings.DEFAULT_FROM_EMAIL)
subj_template = kwargs.get('subj_template', 'contato/subject.txt')
..
With that said, I think your current solution is waaay better than using **kwargs.
A:
this does not seem so ugly to me: you have a function, you have enough parameters to modify the way the function behave, and you have sensible default values so that you don't need to specify all arguments at each function call.
there is the possibility to package the function in a class: in the class constructor, you specify all those values which are part of the parameter list, and you have a special method without arguments to execute the core feature.
something like this:
class ContactForm(object):
def __init__( self,
subj_tmpl='contato/subject.txt',
msg_tmpl='contato/msg.html',
template='contato/contato.html',
success_template='contato/success.html',
success_redir='/',
append_message=None):
self.subj_tmpl = subj_tmpl
self.msg_tmpl = msg_tmpl
self.template = template
self.success_template = success_template
self.success_redir = success_redir
self.append_message = append_message
def __call__( self, request, sender=settings.DEFAULT_FROM_EMAIL ):
# do something
# use case:
contact = ContactForm()
contact( req, sndr )
(i guessed which values is site specific and which is user specific from the name of the parameters. i don't know your specific application, adapt it the way you want)
| Python function with too many arguments with default values, how to make it cleaner? | I have the following function signature, and it looks really ugly, what can I do to make it look cleaner ?
def contact(
request, sender=settings.DEFAULT_FROM_EMAIL,
subj_tmpl='contato/subject.txt',msg_tmpl='contato/msg.html',
template='contato/contato.html', success_template='contato/success.html',
success_redir='/',append_message=None,):
| [
"if i were you i think i will do it like this:\ndef contact(request, sender=None, append_message=None, context=None):\n\n if not sender:\n sender = settings.DEFAULT_FROM_EMAIL # i hope that you can access settings here\n\n # The context arg is a dictionary where you can put all the others argument and \n... | [
4,
3,
0,
0,
0
] | [] | [] | [
"django",
"django_views",
"python"
] | stackoverflow_0004067520_django_django_views_python.txt |
Q:
Debugging Django when no Debug info is displayed | Django
I'm serving an app through IIS6. An error is occurring preventing the app from working, I am not 100% sure what it might be.
I believe the following is generated by python, but I am not entirely sure.
"A server error has occurred. Please contact the administrator"
Any ideas on figuring out what is actually going on?
A:
It looks more like web server error (500?).
Is debugging enabled? You should be able to see exception message and traceback. Also, check web server error log and define settings.ADMINS. This is usefull in production when debugging is disabled:
When DEBUG=False and a view raises an exception, Django will e-mail these people with the full exception information.
A:
http://docs.python.org/library/logging.html#simple-examples
import logging
logging.debug('foobar')
| Debugging Django when no Debug info is displayed | Django | I'm serving an app through IIS6. An error is occurring preventing the app from working, I am not 100% sure what it might be.
I believe the following is generated by python, but I am not entirely sure.
"A server error has occurred. Please contact the administrator"
Any ideas on figuring out what is actually going on?
| [
"It looks more like web server error (500?).\nIs debugging enabled? You should be able to see exception message and traceback. Also, check web server error log and define settings.ADMINS. This is usefull in production when debugging is disabled:\n\nWhen DEBUG=False and a view raises an exception, Django will e-mail... | [
2,
0
] | [] | [] | [
"debugging",
"django",
"iis",
"python"
] | stackoverflow_0004068210_debugging_django_iis_python.txt |
Q:
Why is python slower compared to Ruby even with this very simple "test"?
See Is there something wrong with this python code, why does it run so slow compared to ruby? for my previous attempt at understanding the differences between python and ruby.
As pointed out by igouy the reasoning I came up with for python being slower could be something else than due to recursive function calls (stack involved).
I made this
#!/usr/bin/python2.7
i = 0
a = 0
while i < 6553500:
i += 1
if i != 6553500:
a = i
else:
print "o"
print a
In ruby it is
#!/usr/bin/ruby
i = 0
a = 0
while i < 6553500
i += 1
if i != 6553500
a = i
else
print "o"
end
end
print a
Python 3.1.2 (r312:79147, Oct 4 2010, 12:45:09)
[GCC 4.5.1] on linux2
time python pytest.py
o
6553499
real 0m3.637s
user 0m3.586s
ruby 1.9.2p0 (2010-08-18 revision 29036) [x86_64-linux]
time ruby rutest.rb
o6553499
real 0m0.618s
user 0m0.610s
Letting it loop higher gives higher differences. Adding an extra 0, ruby finishes in 7s, while python runs for 40s.
This is run on Intel(R) Core(TM) i7 CPU M 620 @ 2.67GHz with 4GB mem.
Why is this so?
A:
First off, note that the Python version you show is incorrect: you're running this code in Python 2.7, not 3.1 (it's not even valid Python3 code). (FYI, Python 3 is usually slower than 2.)
That said, there's a critical problem in the Python test: you're writing it as global code. You need to write it as a function. It runs about twice as fast when written correctly, in both Python 2 and 3:
def main():
i = 0
a = 0
while i < 6553500:
i += 1
if i != 6553500:
a = i
else:
print("o")
print(a)
if __name__ == "__main__":
main()
When you write code globally, you have no locals; all of your variables are global variables. Locals are much faster than globals in Python, because globals are stored in a dict. Locals can be referenced directly by the VM by index, so no hash table lookups are needed.
Also, note that this is such a simple test, what you're really doing is benchmarking a few arbitrary bytecode operations.
A:
Why is this so?
Python's loop (for, while) isn't fast for handle dynamic types. in such a case, it lose the advantage.
but cython becames the salvation
pure python version below borrowed from Glenn Maynard's answer (without print)
cython version is very easy based on this, it's is easy enough for a new python programmer can read :
def main():
cdef int i = 0
cdef int a = 0
while i < 6553500:
i += 1
if i != 6553500:
a = i
else:
pass # print "0"
return a
if __name__ == "__main__":
print main()
on my pc, python version need 2.5s, cython version need 5.5ms:
In [1]: import pyximport
In [2]: pyximport.install()
In [3]: import spam # pure python version
In [4]: timeit spam.main()
1 loops, best of 3: 2.41 s per loop
In [5]: import eggs # cython version
In [6]: timeit eggs.main()
100 loops, best of 3: 5.51 ms per loop
update: as Glenn Maynard point out in the comment, while i < N: i+= 1 is not pythonic.
I test xrange implementation.
spam.py is the same as Glenn Maynard's verison. foo.py's code is:
def main():
for i in xrange(6553500):
pass
a = i
return a
if __name__ == "__main__":
print main()
~/code/note$ time python2.7 spam.py # Glenn Maynard's while version
6553499
real 0m2.128s
user 0m2.080s
sys 0m0.044s
:~/code/note$ time python2.7 foo.py # xrange version, as Glenn Maynard point out in comment
6553499
real 0m0.618s
user 0m0.604s
sys 0m0.016s
A:
On my friend's laptop (Windows7 64 bit, python 2.6, 3GB RAM), python takes only around 1 sec for 6553500 and 10 secs for 65535000 input. I wonder why your computer is taking so much time. It also shaves off some time on the larger input when I use xrange and local variables instead.
I cannot comment on Ruby since it's not installed on this computer.
| Why is python slower compared to Ruby even with this very simple "test"? | See Is there something wrong with this python code, why does it run so slow compared to ruby? for my previous attempt at understanding the differences between python and ruby.
As pointed out by igouy the reasoning I came up with for python being slower could be something else than due to recursive function calls (stack involved).
I made this
#!/usr/bin/python2.7
i = 0
a = 0
while i < 6553500:
i += 1
if i != 6553500:
a = i
else:
print "o"
print a
In ruby it is
#!/usr/bin/ruby
i = 0
a = 0
while i < 6553500
i += 1
if i != 6553500
a = i
else
print "o"
end
end
print a
Python 3.1.2 (r312:79147, Oct 4 2010, 12:45:09)
[GCC 4.5.1] on linux2
time python pytest.py
o
6553499
real 0m3.637s
user 0m3.586s
ruby 1.9.2p0 (2010-08-18 revision 29036) [x86_64-linux]
time ruby rutest.rb
o6553499
real 0m0.618s
user 0m0.610s
Letting it loop higher gives higher differences. Adding an extra 0, ruby finishes in 7s, while python runs for 40s.
This is run on Intel(R) Core(TM) i7 CPU M 620 @ 2.67GHz with 4GB mem.
Why is this so?
| [
"First off, note that the Python version you show is incorrect: you're running this code in Python 2.7, not 3.1 (it's not even valid Python3 code). (FYI, Python 3 is usually slower than 2.)\nThat said, there's a critical problem in the Python test: you're writing it as global code. You need to write it as a funct... | [
16,
2,
1
] | [
"It's too simple test. Maybe in such things Ruby is faster. But Python takes advantage, when you need to work with more complex datatypes and their methods. Python have much more implemented \"ways to do this\", and you must choose the one, which is the simplest and enough. Ruby works with more abstract entities an... | [
-3
] | [
"performance",
"python",
"ruby",
"testing"
] | stackoverflow_0004068122_performance_python_ruby_testing.txt |
Q:
Tkinter window layering
I have two Tkinter windows, How do I keep one window always on top of the other?
A:
There isn't anything you can do AFAIK. According to the official tk documentation,
...there is no reliable way to track
changes to a window's position in the
stacking order.
About the best you could do is to periodically raise one window above the other. I don't recommend that because it may have some really disastrous side effects (for example, making it difficult or impossible for the user to move the window that is always lower than the top-most one)
| Tkinter window layering | I have two Tkinter windows, How do I keep one window always on top of the other?
| [
"There isn't anything you can do AFAIK. According to the official tk documentation, \n\n...there is no reliable way to track\n changes to a window's position in the\n stacking order.\n\nAbout the best you could do is to periodically raise one window above the other. I don't recommend that because it may have some... | [
1
] | [] | [] | [
"python",
"tkinter",
"windows_7"
] | stackoverflow_0004066359_python_tkinter_windows_7.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.