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:
Python data structure/object to model static multidimensional table
I'm just getting back into coding after a few year hiatus and I'm trying to model multi-tiered static forms in a way that lets me grab and perform operations on a specific form level or an entire sub-tree.
Example Form hierarchy:
MyForm
Question... | Python data structure/object to model static multidimensional table | I'm just getting back into coding after a few year hiatus and I'm trying to model multi-tiered static forms in a way that lets me grab and perform operations on a specific form level or an entire sub-tree.
Example Form hierarchy:
MyForm
Question 1
Part 1
Question 1.1
Part 2
Question 2.1
SubPart 1
Question 2.1... | [
"I'd store such hierarchical data in XML on the storage. You can use the xml.etree.ElementTree standard module to load such an XML file into a hierarchical data structure in Python, make changes to it, then save it back to a file. This way you don't have to bother with the actual data structure, since it is built b... | [
2,
2,
0
] | [] | [] | [
"class",
"data_modeling",
"data_structures",
"inner_classes",
"python"
] | stackoverflow_0001781207_class_data_modeling_data_structures_inner_classes_python.txt |
Q:
how to simulate the concept of object identity in Haskell
I am considering the design of an interpreter for Python like object oriented language in Haskell. One particular problem I am facing is related to the concept of object identity. If we consider Python's id(object) function, the definition suggests that it ... | how to simulate the concept of object identity in Haskell | I am considering the design of an interpreter for Python like object oriented language in Haskell. One particular problem I am facing is related to the concept of object identity. If we consider Python's id(object) function, the definition suggests that it returns the "identity" of an object. This is an integer (or lon... | [
"I assume that your interpreter will work within the State monad. Probably the state will consist of a collection of live objects and whatnot. What you can do, is keep track of a list of available (non-used) ids (represented as Ints) and annotate every Object with an Int, namely its id. This id was taken from the l... | [
4,
3
] | [] | [] | [
"haskell",
"interpreter",
"python"
] | stackoverflow_0001795186_haskell_interpreter_python.txt |
Q:
paste.httpserver and slowdown with HTTP/1.1 Keep-alive; tested with httperf and ab
I have a web server based on paste.httpserver as an adapater between HTTP and WSGI. When I do performance measurements with httperf, I can do over 1,000 requests per second if I start a new request each time using --num-conn. If I i... | paste.httpserver and slowdown with HTTP/1.1 Keep-alive; tested with httperf and ab | I have a web server based on paste.httpserver as an adapater between HTTP and WSGI. When I do performance measurements with httperf, I can do over 1,000 requests per second if I start a new request each time using --num-conn. If I instead reuse the connection using --num-call then I get about 11 requests per second, 1/... | [
"After some effort, it seems to be either Nagle's algorithm or the delayed ACK, or the interactions between them. It goes away if I do something like\nserver.socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)\n\nHow did I track it down? First, I instrumented every 'recv' in socket.py, so I could figure ou... | [
6
] | [] | [] | [
"httperf",
"httpserver",
"keep_alive",
"paste",
"python"
] | stackoverflow_0001781766_httperf_httpserver_keep_alive_paste_python.txt |
Q:
Accessing xrange internal structure
I'm trying to use ctypes to extract data from internal python structures. Namely, I'm trying to read the 4 fields in an xrange:
typedef struct {
PyObject_HEAD
long start;
long step;
long len;
} rangeobject;
Is there any standard way of getting at such ... | Accessing xrange internal structure | I'm trying to use ctypes to extract data from internal python structures. Namely, I'm trying to read the 4 fields in an xrange:
typedef struct {
PyObject_HEAD
long start;
long step;
long len;
} rangeobject;
Is there any standard way of getting at such fields within python itself?
| [
"You can access data you need without ctypes:\n>>> obj = xrange(1,11,2)\n>>> obj.__reduce__()[1]\n(1, 11, 2)\n>>> len(obj)\n5\n\nNote, that __reduce__() method is exactly for serialization. Read this chapter in documentation for more information.\nUpdate: But sure you can access internal data with ctypes too:\nfrom... | [
5,
0
] | [] | [] | [
"cpython",
"ctypes",
"python",
"xrange"
] | stackoverflow_0001794346_cpython_ctypes_python_xrange.txt |
Q:
python code to convert mail from pst to eml format
Is there any python code to convert outlook pst mails to eml format. Please also suggest for any such code in some other language. Thank you.
A:
import subprocess
def convert_pst_to_mbox(pstfilename, outputfolder):
subprocess.call(['readpst', '-o', outputf... | python code to convert mail from pst to eml format | Is there any python code to convert outlook pst mails to eml format. Please also suggest for any such code in some other language. Thank you.
| [
"import subprocess\n\ndef convert_pst_to_mbox(pstfilename, outputfolder):\n subprocess.call(['readpst', '-o', outputfolder, '-r', pstfilename])\n\nOf course, you must install libpst utilities for that to work.\n"
] | [
1
] | [] | [] | [
"eml",
"pst",
"python"
] | stackoverflow_0001795202_eml_pst_python.txt |
Q:
Python nested lists and recursion problem
I posted this question under an alter yesterday not realising my account was still active after 9 months, sorry for the double post, i've fixed an error in my example pointed out by jellybean and i'll elaborate further on the context of the problem.
I'm trying to process a... | Python nested lists and recursion problem | I posted this question under an alter yesterday not realising my account was still active after 9 months, sorry for the double post, i've fixed an error in my example pointed out by jellybean and i'll elaborate further on the context of the problem.
I'm trying to process a first order logic formula represented as neste... | [
"First, two general remarks about your code:\n\nUse return True instead of return 1.\nUse isinstance(form, list) instead of isinstance(form, type([])).\n\nSecond, some other observations:\n\nI assume you also want to get rid of double negations. Currently your code doesn't do that.\nLikewise, you'll need to apply o... | [
3,
0
] | [] | [] | [
"boolean_logic",
"python",
"recursion"
] | stackoverflow_0001793603_boolean_logic_python_recursion.txt |
Q:
When I send a post request in python...how do I
Have a "check"?
For example...
I would have a dictionary with the parameters to sent to the POST.
params = {'text':'how are you?', 'subject':'hi'}
then I would have
opener.open('theurl',urllib.urlencode(params))
The question is...those parameters work well with te... | When I send a post request in python...how do I | Have a "check"?
For example...
I would have a dictionary with the parameters to sent to the POST.
params = {'text':'how are you?', 'subject':'hi'}
then I would have
opener.open('theurl',urllib.urlencode(params))
The question is...those parameters work well with text-boxes, since I just put the value in there. How a... | [
"Radio buttons has values too\n<input type=\"radio\" name=\"music\" value=\"Rock\" checked=\"checked\"> Rock<br>\n<input type=\"radio\" name=\"music\" value=\"Pop\"> Pop<br>\n<input type=\"radio\" name=\"music\" value=\"Metal\"> Metal<br>\n\nfor that case {\"music\":\"Rock\"} in params\n"
] | [
2
] | [] | [] | [
"http",
"post",
"python",
"send"
] | stackoverflow_0001796109_http_post_python_send.txt |
Q:
In Google App Engine, what happens when I change the Class related to a persisted object?
My model class looks as follows:
from google.appengine.ext import db
class SnapShotBase(db.Model):
'''
The base class from which all entity snapshots will inherit.
'''
version = db.IntegerProperty()
def _... | In Google App Engine, what happens when I change the Class related to a persisted object? | My model class looks as follows:
from google.appengine.ext import db
class SnapShotBase(db.Model):
'''
The base class from which all entity snapshots will inherit.
'''
version = db.IntegerProperty()
def __init__(self):
pass
Imagine I already have persisted instances of this class i... | [
"Model instances aren't stored using standard serialization such as Pickle. The properties (such as 'version' in your example) are encoded and stored as a Protocol Buffer, and when you load an entity from the datastore, the Protocol Buffer is decoded and used to build a new Model instance.\nAs a result, you can mod... | [
3
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0001795668_google_app_engine_python.txt |
Q:
Validating Uploaded Files in Django
A Django app that I am working has an Event model. An Event may have associated photos, static html files and pdf files.
I would like to allow trusted users to upload these files, but I am wary about security, especially having read the following in the Django docs (link).
Note... | Validating Uploaded Files in Django | A Django app that I am working has an Event model. An Event may have associated photos, static html files and pdf files.
I would like to allow trusted users to upload these files, but I am wary about security, especially having read the following in the Django docs (link).
Note that whenever you deal with
uploaded f... | [
"All the answers are focusing on validating files. This is pretty much impossible.\nThe Django devs aren't asking you to validate whether files can be executed as cgi files. They are just telling you not to put them in a place where they will be executed.\nYou should put all Django stuff in a specially Django direc... | [
19,
14,
6,
5,
1,
1
] | [] | [] | [
"django",
"file_upload",
"python",
"security"
] | stackoverflow_0001745743_django_file_upload_python_security.txt |
Q:
Point Django at different Python version
Django application requires a later version of Python. I just installed it to 2.5 (from 2.4) and now when I do a python at the command line, it says 2.5.2.
Having said that, Django still says Python Version: 2.4.3.
How do I correct this? I've rebooted / restarted / redepl... | Point Django at different Python version | Django application requires a later version of Python. I just installed it to 2.5 (from 2.4) and now when I do a python at the command line, it says 2.5.2.
Having said that, Django still says Python Version: 2.4.3.
How do I correct this? I've rebooted / restarted / redeployed to no avail.
| [
"You have it backwards.\nDjango is added to Python's environment.\nWhen you install a new Python, you must reinstall everything -- including Django -- for the new Python.\nOnce you have the new Django in the new Python, your PATH settings determine which Python you're using. \nThe version of Python (and the PYTHON... | [
6,
4,
0
] | [] | [] | [
"django",
"path",
"python"
] | stackoverflow_0001796105_django_path_python.txt |
Q:
Python SSH paramiko issue - ssh from inside of ssh session
import paramiko
client = paramiko.SSHClient()
client.load_system_host_keys()
ip = '192.168.100.6'
client.connect(ip, username='root', password='mima')
i, o, e = client.exec_command('apt-get install sl -y --force-yes')
print o.read(), e.read()
client.close... | Python SSH paramiko issue - ssh from inside of ssh session | import paramiko
client = paramiko.SSHClient()
client.load_system_host_keys()
ip = '192.168.100.6'
client.connect(ip, username='root', password='mima')
i, o, e = client.exec_command('apt-get install sl -y --force-yes')
print o.read(), e.read()
client.close()
i used this example.. it is working fine but i want after lo... | [
"can't you call the ssh command from inside of your client.exec_command?\nlike:\nclient.exec_command('ssh user@host2 \"apt-get install sl -y --force-yes\"')\n\n",
"You exec the command \"ssh\" in the client, and not apt-get.\nYou can't really start a paramiko session on the client as long as your python program i... | [
4,
0
] | [] | [] | [
"paramiko",
"python",
"ssh"
] | stackoverflow_0001796441_paramiko_python_ssh.txt |
Q:
sorl.thumbnail : 'thumbnail' is not a valid tag library?
I am trying to install sorl.thumbnail but am getting the following error message:
'thumbnail' is not a valid tag library: Could not load template library from django.templatetags.thumbnail, No module named PIL
This error popped up in this question as well
ne... | sorl.thumbnail : 'thumbnail' is not a valid tag library? | I am trying to install sorl.thumbnail but am getting the following error message:
'thumbnail' is not a valid tag library: Could not load template library from django.templatetags.thumbnail, No module named PIL
This error popped up in this question as well
need help solving sorl-thumbnail error: "'thumbnail' is not a va... | [
"Is is a typo in your question? You have mis-spelled 'thumbnails' - for the installed apps you have two l's, i.e.\n'sorl.thumbnaills'\nrather than \n'sorl.thumbnails'\n\nif you run sync.db does it return an error?\n",
"(Editing this, since I didn't read carefully enough)\ndjango.templatetags.thumbnail is not, I t... | [
1,
0,
0
] | [] | [] | [
"django",
"google_app_engine",
"python",
"sorl_thumbnail"
] | stackoverflow_0001687530_django_google_app_engine_python_sorl_thumbnail.txt |
Q:
How create jinja2 extension?
I try to make extension for jinja2. I has written such code:
http://dumpz.org/12996/
But I receive exception: 'NoneType' object is not iterable. Where is a bug?
That should return parse. Also what should accept and return _media?
A:
You're using a CallBlock, which indicates that you ... | How create jinja2 extension? | I try to make extension for jinja2. I has written such code:
http://dumpz.org/12996/
But I receive exception: 'NoneType' object is not iterable. Where is a bug?
That should return parse. Also what should accept and return _media?
| [
"You're using a CallBlock, which indicates that you want your extension to act as a block. E.g.\n{% mytest arg1 arg2 %}\nstuff\nin\nhere\n{% endmytest %}\n\nnodes.CallBlock expects that you pass it a list of nodes representing the body (the inner statements) for your extension. Currently this is where you're pass... | [
11
] | [] | [] | [
"jinja2",
"python",
"templates"
] | stackoverflow_0001521909_jinja2_python_templates.txt |
Q:
Interpolation in SciPy: Finding X that produces Y
Is there a better way to find which X gives me the Y I am looking for in SciPy? I just began using SciPy and I am not too familiar with each function.
import numpy as np
import matplotlib.pyplot as plt
from scipy import interpolate
x = [70, 80, 90, 100, 110]
y = [... | Interpolation in SciPy: Finding X that produces Y | Is there a better way to find which X gives me the Y I am looking for in SciPy? I just began using SciPy and I am not too familiar with each function.
import numpy as np
import matplotlib.pyplot as plt
from scipy import interpolate
x = [70, 80, 90, 100, 110]
y = [49.7, 80.6, 122.5, 153.8, 163.0]
tck = interpolate.splr... | [
"The UnivariateSpline class in scipy makes doing splines much more pythonic.\nx = [70, 80, 90, 100, 110]\ny = [49.7, 80.6, 122.5, 153.8, 163.0]\nf = interpolate.UnivariateSpline(x, y, s=0)\nxnew = np.arange(70,111,1)\n\nplt.plot(x,y,'x',xnew,f(xnew))\n\nTo find x at y then do:\nyToFind = 140\nyreduced = np.array(y)... | [
18,
3,
0
] | [] | [] | [
"interpolation",
"numpy",
"python",
"scientific_computing",
"scipy"
] | stackoverflow_0001029207_interpolation_numpy_python_scientific_computing_scipy.txt |
Q:
How to make these dynamically typed functions type-safe?
Is there any programming language (or type system) in which you could express the following Python-functions in a statically typed and type-safe way (without having to use casts, runtime-checks etc)?
#1:
# My function - What would its type be?
def Apply(x):... | How to make these dynamically typed functions type-safe? | Is there any programming language (or type system) in which you could express the following Python-functions in a statically typed and type-safe way (without having to use casts, runtime-checks etc)?
#1:
# My function - What would its type be?
def Apply(x):
return x(x)
# Example usage
print Apply(lambda _: 42)
#... | [
"1#\nThis is not typeable with a finite type. This means that very few (if any) programming languages will be able to type this.\nHowever, as you have demonstrated, there is a specific type for x that allows the function to be typed:\nx :: t -> B\n\nWhere B is some concrete type. This results in apply being typed a... | [
4,
2,
0
] | [] | [] | [
"language_agnostic",
"python",
"type_theory"
] | stackoverflow_0001079120_language_agnostic_python_type_theory.txt |
Q:
Strange numpy.float96 behaviour
What am I missing:
In [66]: import numpy as np
In [67]: np.float(7.0 / 8)
Out[67]: 0.875 #OK
In [68]: np.float32(7.0 / 8)
Out[68]: 0.875 #OK
In [69]: np.float96(7.0 / 8)
Out[69]: -2.6815615859885194e+154 #WTF
In [70]: sys.version
Out[70]: '2.5.4 (r254:67916, Dec 23 2008, 15:10:5... | Strange numpy.float96 behaviour | What am I missing:
In [66]: import numpy as np
In [67]: np.float(7.0 / 8)
Out[67]: 0.875 #OK
In [68]: np.float32(7.0 / 8)
Out[68]: 0.875 #OK
In [69]: np.float96(7.0 / 8)
Out[69]: -2.6815615859885194e+154 #WTF
In [70]: sys.version
Out[70]: '2.5.4 (r254:67916, Dec 23 2008, 15:10:54) [MSC v.1310 32 bit (Intel)]'
Edit... | [
"This works fine for me:\nIn [1]: import numpy as np\n\nIn [2]: np.float(7.0/8)\nOut[2]: 0.875\n\nIn [3]: np.float96(7.0/8)\nOut[3]: 0.875\n\nWhat Numpy are you using? I'm using Python 2.6.2 and Numpy 1.3.0 and I'm on 64 bit Vista.\nI tried this same thing on another computer that is running 32 bit XP with Python ... | [
2,
2,
1
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0001565731_numpy_python.txt |
Q:
recursive function for a django model instance
i want to make message view show all other messages that led up to that message. the original message will not have a response_to value and should terminate the recursion. is there a better way to do this? (i'm looking at memory over speed, because a thread shouldn't ... | recursive function for a django model instance | i want to make message view show all other messages that led up to that message. the original message will not have a response_to value and should terminate the recursion. is there a better way to do this? (i'm looking at memory over speed, because a thread shouldn't typically be more than 10 - 20 messages long).
def g... | [
"Yes. not using recursion.\ndef get_thread(msg):\n messages = [] # empty message set\n\n while msg.response_to: \n messages.append(msg)\n msg = msg.response_to\n\n messages.append(msg) # will append the original message\n\n return messages\n\n",
"If you want to limit recursion depth, ... | [
4,
0
] | [] | [] | [
"django",
"python",
"recursion"
] | stackoverflow_0001797586_django_python_recursion.txt |
Q:
Python and BeautifulSoup, not finding 'a'
Here's a piece of HTML code (from delicious):
<h4>
<a rel="nofollow" class="taggedlink " href="http://imfy.us/" >Generate Secure Links with Anonymous Referers & Anti-Bot Protection</a>
<span class="saverem">
<em class="bookmark-actions">
<strong><a class="inlines... | Python and BeautifulSoup, not finding 'a' | Here's a piece of HTML code (from delicious):
<h4>
<a rel="nofollow" class="taggedlink " href="http://imfy.us/" >Generate Secure Links with Anonymous Referers & Anti-Bot Protection</a>
<span class="saverem">
<em class="bookmark-actions">
<strong><a class="inlinesave action" href="/save?url=http%3A%2F%2Fimfy.u... | [
"If you want to look for an anchor with exactly those two classes you'd, have to use a regexp, I think:\ntags = soup.findAll('a', attrs={'class': re.compile(r'\\binlinesave\\b.*\\baction\\b')})\n\nKeep in mind that this regexp won't work if the ordering of the class names is reversed (class=\"action inlinesave\"). ... | [
1,
0,
0,
0
] | [] | [] | [
"beautifulsoup",
"html",
"python"
] | stackoverflow_0001796725_beautifulsoup_html_python.txt |
Q:
basic python module design question
I have:
lib/
lib/__init__.py
lib/game.py
In __init__.py I'd like to define a variable that can be accessed by any class inside lib, like so:
BASE = 'http://www.whatever.com'
And then inside game.py, acces it inside in the Game class:
class Game:
def __init__(self, game_id):
... | basic python module design question | I have:
lib/
lib/__init__.py
lib/game.py
In __init__.py I'd like to define a variable that can be accessed by any class inside lib, like so:
BASE = 'http://www.whatever.com'
And then inside game.py, acces it inside in the Game class:
class Game:
def __init__(self, game_id):
self.game_id = game_id
url = '%sy... | [
"See http://docs.python.org/tutorial/modules.html#intra-package-references\nSo you could have a lib/settings.py file which contains the line\nBASE = 'http://www.whatever.com'\n\nand then say\nfrom settings import *\n\nin game.py you should then be able to write\nurl = '%syear_%s/month_%s/day_%s/%s/' % (BASE, year, ... | [
4
] | [] | [] | [
"python"
] | stackoverflow_0001798656_python.txt |
Q:
Overcoming Python's limitations regarding instance methods
It seems that Python has some limitations regarding instance methods.
Instance methods can't be copied.
Instance methods can't be pickled.
This is problematic for me, because I work on a very object-oriented project in which I reference instance methods,... | Overcoming Python's limitations regarding instance methods | It seems that Python has some limitations regarding instance methods.
Instance methods can't be copied.
Instance methods can't be pickled.
This is problematic for me, because I work on a very object-oriented project in which I reference instance methods, and there's use of both deepcopying and pickling. The pickling ... | [
"You might be able to do this using copy_reg.pickle. In Python 2.6:\nimport copy_reg\nimport types\n\ndef reduce_method(m):\n return (getattr, (m.__self__, m.__func__.__name__))\n\ncopy_reg.pickle(types.MethodType, reduce_method)\n\nThis does not store the code of the method, just its name; but that will work co... | [
15,
3
] | [
"pickle the instance and then access the method after unpickling it. Pickling a method of an instance doesn't make sense because it relies on the instance. If it doesn't, then write it as an independent function. \nimport pickle\n\nclass A:\n def f(self):\n print 'hi'\n\nx = A()\nf = open('tmp', 'w')\nr... | [
-3
] | [
"copy",
"instance_method",
"oop",
"python"
] | stackoverflow_0001798450_copy_instance_method_oop_python.txt |
Q:
Download file using partial download (HTTP)
Is there a way to download huge and still growing file over HTTP using the partial-download feature?
It seems that this code downloads file from scratch every time it executed:
import urllib
urllib.urlretrieve ("http://www.example.com/huge-growing-file", "huge-growing-fi... | Download file using partial download (HTTP) | Is there a way to download huge and still growing file over HTTP using the partial-download feature?
It seems that this code downloads file from scratch every time it executed:
import urllib
urllib.urlretrieve ("http://www.example.com/huge-growing-file", "huge-growing-file")
I'd like:
To fetch just the newly-written ... | [
"It is possible to do partial download using the range header, the following will request a selected range of bytes:\nreq = urllib2.Request('http://www.python.org/')\nreq.headers['Range'] = 'bytes=%s-%s' % (start, end)\nf = urllib2.urlopen(req)\n\nFor example:\n>>> req = urllib2.Request('http://www.python.org/')\n>... | [
43,
2
] | [
"If I understand your question correctly, the file is not changing during download, but is updated regularly. If that is the question, rsync is the answer.\nIf the file is being updated continually including during download, you'll need to modify rsync or a bittorrent program. They split files into separate chunk... | [
-1
] | [
"http",
"partial",
"python"
] | stackoverflow_0001798879_http_partial_python.txt |
Q:
Python, thread and gobject
I am writing a program by a framework using pygtk. The main program doing the following things:
Create a watchdog thread to monitor some resource
Create a client to receive data from socket
call gobject.Mainloop()
but it seems after my program enter the Mainloop, the watchdog thread a... | Python, thread and gobject | I am writing a program by a framework using pygtk. The main program doing the following things:
Create a watchdog thread to monitor some resource
Create a client to receive data from socket
call gobject.Mainloop()
but it seems after my program enter the Mainloop, the watchdog thread also won't run.
My workaround is ... | [
"Can you post some code? It could be that you have problems with the Global Interpreter Lock.\nYour problem solved by someone else :). I could copy-paste the article here, but in short gtk's c-threads clash with Python threads. You need to disable c-threads by calling gobject.threads_init() and all should be fine.\... | [
9,
2
] | [] | [] | [
"multithreading",
"pygtk",
"python"
] | stackoverflow_0001796588_multithreading_pygtk_python.txt |
Q:
Launching default application for given type of file, OS X
I'm writing a python script that generates html file. Every time I run this script I'd like at the end to open default system browser for this file. It's all in OS X environment.
What python code can launch Safari/Firefox/whatever is system default html vi... | Launching default application for given type of file, OS X | I'm writing a python script that generates html file. Every time I run this script I'd like at the end to open default system browser for this file. It's all in OS X environment.
What python code can launch Safari/Firefox/whatever is system default html viewer and open given file? subprocess.call doesn't seem to do the... | [
"\nWhat python code can launch\n Safari/Firefox/whatever is system\n default html viewer and open given\n file?\n\nThere is a webbrowser module in python, try this:\nimport webbrowser\nwebbrowser.open('file://%s' % path)\n\nThis will open a new tab in the default browser.\nThere are methods to open a new tab, ne... | [
3,
1,
0
] | [] | [] | [
"python",
"subprocess"
] | stackoverflow_0001798351_python_subprocess.txt |
Q:
Web service: PHP or Ruby on Rails or Python?
I am a .Net / SQL Server developer via my daytime job, and on the side I do some objective C development for the iPhone. I would like to develop a web service and since dreamhost supports mySql, python, ruby on rails and PHP5, I would like to create it using one of tho... | Web service: PHP or Ruby on Rails or Python? | I am a .Net / SQL Server developer via my daytime job, and on the side I do some objective C development for the iPhone. I would like to develop a web service and since dreamhost supports mySql, python, ruby on rails and PHP5, I would like to create it using one of those languages. If you had no experience in either ... | [
"Ruby-on-rails, Python and PHP would all be excellent choices for developing a web service in. All the languages are capable (with of course Ruby being the language that Ruby on Rails is written in), have strong frameworks if that is your fancy (Django being a good python example, and something like Drupal or Cake... | [
11,
6,
2,
1,
0
] | [] | [] | [
"php",
"python",
"ruby_on_rails"
] | stackoverflow_0001183420_php_python_ruby_on_rails.txt |
Q:
suggestions for a daemon that accepts zip files for processing
im looking to write a daemon that:
reads a message from a queue (sqs, rabbit-mq, whatever ...) containing a path to a zip file
updates a record in the database saying something like "this job is processing"
reads the aforementioned archive's contents ... | suggestions for a daemon that accepts zip files for processing | im looking to write a daemon that:
reads a message from a queue (sqs, rabbit-mq, whatever ...) containing a path to a zip file
updates a record in the database saying something like "this job is processing"
reads the aforementioned archive's contents and inserts a row into a database w/ information culled from file me... | [
"I've used Beanstalkd as a queueing daemon to very good effect (some near-time processing and image resizing - over 2 million so far in the last few weeks). Throw a message into the queue with the zip filename (maybe from a specific directory) [I serialise a command and parameters in JSON], and when you reserve the... | [
1,
1,
1
] | [] | [] | [
"daemon",
"django",
"python",
"zip"
] | stackoverflow_0000758466_daemon_django_python_zip.txt |
Q:
Python: print doesn't work, script hangs endlessly
Using Python 2.6, I wrote a script in Windows XP.
The script does the following:
Input: Domain name (ie: amazon.com)
The script queries DNS via the dnspython module and returns any A record IP Addresses.
The output is in a special format needed for a specific appl... | Python: print doesn't work, script hangs endlessly | Using Python 2.6, I wrote a script in Windows XP.
The script does the following:
Input: Domain name (ie: amazon.com)
The script queries DNS via the dnspython module and returns any A record IP Addresses.
The output is in a special format needed for a specific application which utilizes this data.
This works fine in Win... | [
"Apparently dnspython wants 16 bytes of high-quality random numbers at startup. Getting them (from /dev/random) can block.\nIf you hit Ctrl+C, it actually catches the KeyboardInterupt exception and falls back on less-secure random numbers (taken from the current system time). Then your program finishes running.\nTh... | [
5,
1
] | [] | [] | [
"printing",
"python"
] | stackoverflow_0001799462_printing_python.txt |
Q:
Trouble Upgrading Python / Django on CentOS
As you can see by reading my other thread today here, I'm having some troubles upgrading Python.
At the moment I have Python 2.4 with Django installed on a CentOS machine. However I've recently deployed an application that requires 2.5 which has resulted in me installing... | Trouble Upgrading Python / Django on CentOS | As you can see by reading my other thread today here, I'm having some troubles upgrading Python.
At the moment I have Python 2.4 with Django installed on a CentOS machine. However I've recently deployed an application that requires 2.5 which has resulted in me installing that and getting into a whole load of mess. My o... | [
"I don't know anything about CentOS, but if you have multiple Python version installed and you wan't to install packages using easy_install, you just need to call it with the corresponding Python interpreter. This should install the packing into the site-package directory of Python 2.5:\n# /path/to/python-2.5 easy_... | [
2,
1,
0,
0
] | [] | [] | [
"centos",
"django",
"python"
] | stackoverflow_0001797017_centos_django_python.txt |
Q:
Regular Expression to match a string only when certain characters don't exist
So, here's my question:
I have a crawler that goes and downloads web pages and strips those of URLs (for future crawling). My crawler operates from a whitelist of URLs which are specified in regular expressions, so they're along the lin... | Regular Expression to match a string only when certain characters don't exist | So, here's my question:
I have a crawler that goes and downloads web pages and strips those of URLs (for future crawling). My crawler operates from a whitelist of URLs which are specified in regular expressions, so they're along the lines of:
(http://www.example.com/subdirectory/)(.*?)
...which would allow URLs that f... | [
"(http://www.example.com/)([^=?#]*?)\n\nShould do it, this will allow any URL that does not contain the characters you don't want. \nIt might however be a little bit hard to extend this approach. A better option is to have the system work two-tiered, i.e. one set of matching regex, and one set of blocking regex. Th... | [
1,
0,
0,
0,
0
] | [] | [] | [
"python",
"regex",
"url"
] | stackoverflow_0001796053_python_regex_url.txt |
Q:
Are there any good summarizers for a web-page?
Suppose I give you a URL...can you analyze the words and spit out the "keywords" of that page?
(besides using meta-tags)
Are there good open-source summarizers out there? (preferably Python)
A:
A simple text summarizer: http://pythonwise.blogspot.com/2008/01/simple-... | Are there any good summarizers for a web-page? | Suppose I give you a URL...can you analyze the words and spit out the "keywords" of that page?
(besides using meta-tags)
Are there good open-source summarizers out there? (preferably Python)
| [
"A simple text summarizer: http://pythonwise.blogspot.com/2008/01/simple-text-summarizer.html\nAlgorithm:\n1. For each word, calculate it's frequency in the document\n2. For each sentence in the document \n score(sentence) = sum([freq(word) for word in sentence])\n3. Print X top sentences such that their size ... | [
2,
1
] | [] | [] | [
"python",
"text"
] | stackoverflow_0001795520_python_text.txt |
Q:
Selenium - Pop Up window
I am testing the Router UI using selenium. I am using cisco routers. I am pinging a website and the router opens a pop up window showing the Ping statistics. The selenium ide is recording the popup window as " Ping table " but when i am running it the ide shows an error.
I want to verify a... | Selenium - Pop Up window | I am testing the Router UI using selenium. I am using cisco routers. I am pinging a website and the router opens a pop up window showing the Ping statistics. The selenium ide is recording the popup window as " Ping table " but when i am running it the ide shows an error.
I want to verify and validate the data in the po... | [
"I'd need to reproduce this locally to be able to answer definitively. The only thing that comes to mind right now is that you say the IDE identifies it as \"Ping table\" but in your python you refer to it as \"PingTable\". It might be a typo on your behalf, but maybe not.\n"
] | [
0
] | [] | [] | [
"popup",
"python",
"selenium",
"window"
] | stackoverflow_0001800291_popup_python_selenium_window.txt |
Q:
Genshi table loop
What is wrong with this Genshi template:
<html xmlns:py="http://genshi.edgewall.org/">
<head>
<title py:content="title"></title>
</head>
<body>
<left>
<table py: for="i in range(1, len(ctabl))">
<li py: for="e in ctabl[i]">
${e}
</li>
</ta... | Genshi table loop | What is wrong with this Genshi template:
<html xmlns:py="http://genshi.edgewall.org/">
<head>
<title py:content="title"></title>
</head>
<body>
<left>
<table py: for="i in range(1, len(ctabl))">
<li py: for="e in ctabl[i]">
${e}
</li>
</table>
</body>
</html>
... | [
"I've never used Genshi, but their list of allowed processing directives do not have any spaces between py, the :, and the for. Try removing that space. And anyway, Line 7, Column 14 is on the colon or the space, depending on whether you count from 0 or 1, right?\n"
] | [
2
] | [] | [] | [
"genshi",
"python"
] | stackoverflow_0001800508_genshi_python.txt |
Q:
Local timezone problem in GAE working with Google Data API
I am working in a small app in the Google App Engine (Python), which uses the Google Data API in order to create a new calendar in a Google account and populate it with some events.
The events that I am using are parsed from another place, and they have th... | Local timezone problem in GAE working with Google Data API | I am working in a small app in the Google App Engine (Python), which uses the Google Data API in order to create a new calendar in a Google account and populate it with some events.
The events that I am using are parsed from another place, and they have the date in the Europe/Stockholm timezone, (I think it is CEST or ... | [
"I posted something related to this subject on my blog last year. Basically, it converts all times to UTC when storing them in the datastore, and attaches the UTC timezone to them when read out. You can feel free to modify it to then convert the values to whatever local timezone you want.\nThis code sample may be o... | [
1,
0
] | [] | [] | [
"gdata_api",
"google_app_engine",
"python"
] | stackoverflow_0001728415_gdata_api_google_app_engine_python.txt |
Q:
Most pythonic way of ignoring output
I've got a class which uses the context management protocol to have a silent stderr stream for a while (mainly used for py2exe deployments, where the app writing anything to stderr causes ugly dialogs when the app is closed, and I'm doing something that I know will have some st... | Most pythonic way of ignoring output | I've got a class which uses the context management protocol to have a silent stderr stream for a while (mainly used for py2exe deployments, where the app writing anything to stderr causes ugly dialogs when the app is closed, and I'm doing something that I know will have some stderr output)
import sys
import os
from con... | [
"I think the latter solution is the more elegant. You avoid going to the system environment, potentially wasting an fd. Why go out the operating system when it's not needed?\n",
"I feel that the nullWriter class would be more \"Pythonic\" because it uses the Python interfaces already in place (that you can assign... | [
4,
3,
2,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0001800396_python.txt |
Q:
Munging non-printable characters to dots using string.translate()
So I've done this before and it's a surprising ugly bit of code for such a seemingly simple task.
The goal is to translate any non-printable character into a . (dot). For my purposes "printable" does exclude the last few characters from string.prin... | Munging non-printable characters to dots using string.translate() | So I've done this before and it's a surprising ugly bit of code for such a seemingly simple task.
The goal is to translate any non-printable character into a . (dot). For my purposes "printable" does exclude the last few characters from string.printable (new-lines, tabs, and so on). This is for printing things like t... | [
"Here's another approach using a list comprehension:\nfilter = ''.join([['.', chr(x)][chr(x) in string.printable[:-5]] for x in xrange(256)])\n\n",
"Broadest use of \"ascii\" here, but you get the idea\n>>> import string\n>>> ascii=\"\".join(map(chr,range(256)))\n>>> filter=\"\".join(('.',x)[x in string.printable... | [
5,
4,
1,
1
] | [] | [] | [
"code_golf",
"python"
] | stackoverflow_0001800790_code_golf_python.txt |
Q:
Windows with Plesk Panel installs ActiveState Python 2.5.0 - any thoughts?
I expect to run Pylons on a Windows Server 2003 and IIS 6 on a Virtual Private Server (VPS). Most work with the VPS is done through the Plesk 8.6 panel. The Plesk panel has a lot of maintenance advantages for us. However, this Plesk configu... | Windows with Plesk Panel installs ActiveState Python 2.5.0 - any thoughts? | I expect to run Pylons on a Windows Server 2003 and IIS 6 on a Virtual Private Server (VPS). Most work with the VPS is done through the Plesk 8.6 panel. The Plesk panel has a lot of maintenance advantages for us. However, this Plesk configuration installs ActiveState Python 2.5.0. The Parallels Plesk documents for 8.6 ... | [
"The default Python install location is something like c:\\python26. I think it's likely you could install the latest python there, without it conflicting with the ActiveState Python. (You may have to deal with path issues or conflicts over which copy 'owns' python source files in Explorer, though.)\n"
] | [
0
] | [] | [] | [
"activestate",
"plesk",
"pylons",
"python",
"virtualenv"
] | stackoverflow_0001744243_activestate_plesk_pylons_python_virtualenv.txt |
Q:
How does wsgi handle multiple request headers with the same name?
In WSGI headers are represented in the environ as 'HTTP_XXX' values. For example the value Cookie: header is stored at the HTTP_COOKIE key of the environ.
How are multiple request headers with the same header name represented?
A:
Multiple cookies ... | How does wsgi handle multiple request headers with the same name? | In WSGI headers are represented in the environ as 'HTTP_XXX' values. For example the value Cookie: header is stored at the HTTP_COOKIE key of the environ.
How are multiple request headers with the same header name represented?
| [
"Multiple cookies are combined into a single header, separated by semicolons.\nMultiple headers are allowed by the HTTP spec, but only for certain kinds of headers, and it is always permissible to combine those headers into one (though using commas, not semicolons)\n",
"I thought the answer to this one would be t... | [
8,
3
] | [] | [] | [
"http",
"python",
"wsgi"
] | stackoverflow_0001801124_http_python_wsgi.txt |
Q:
Is smtplib pure python or implemented in C?
Is smtplib pure python or implemented in C?
A:
In [32]: import smtplib
In [33]: smtplib
Out[33]: <module 'smtplib' from '/usr/lib/python2.6/smtplib.pyc'>
Therefore, smtplib is written in python.
A:
smtplib itself is implemented in python but socket is based on C, s... | Is smtplib pure python or implemented in C? | Is smtplib pure python or implemented in C?
| [
"In [32]: import smtplib\n\nIn [33]: smtplib\nOut[33]: <module 'smtplib' from '/usr/lib/python2.6/smtplib.pyc'>\n\nTherefore, smtplib is written in python.\n",
"smtplib itself is implemented in python but socket is based on C, so its means both.\n",
"Basically pure Python (as the underlying implementation if yo... | [
8,
4,
2
] | [] | [] | [
"c",
"python",
"smtplib"
] | stackoverflow_0001801271_c_python_smtplib.txt |
Q:
Is os.popen really deprecated in Python 2.6?
The on-line documentation states that os.popen is now deprecated. All other deprecated functions duly raise a DeprecationWarning. For instance:
>>> import os
>>> [c.close() for c in os.popen2('ps h -eo pid:1,command')]
__main__:1: DeprecationWarning: os.popen2 is deprec... | Is os.popen really deprecated in Python 2.6? | The on-line documentation states that os.popen is now deprecated. All other deprecated functions duly raise a DeprecationWarning. For instance:
>>> import os
>>> [c.close() for c in os.popen2('ps h -eo pid:1,command')]
__main__:1: DeprecationWarning: os.popen2 is deprecated. Use the subprocess module.
[None, None]
Th... | [
"Here is the PEP.\n\nDeprecated modules and functions in the standard library:\n\n - buildtools\n - cfmfile\n - commands.getstatus()\n - macostools.touched()\n - md5\n - MimeWriter\n - mimify\n - popen2, os.popen[234]()\n - posixfile\n - sets\n - sha\n\n\n",
"one thing that I can ... | [
5,
4,
3,
0
] | [] | [] | [
"deprecated",
"python",
"std"
] | stackoverflow_0001098257_deprecated_python_std.txt |
Q:
Anyone know where I can download a zipped Python distribution?
Yeah, kind of random, but I was wondering if anyone could link me to a .zip file containing a Python distribution. I know I could download the installer, so please don't suggest that. :P.
A:
I didn't exactly understand what you want. Is Portable Pyth... | Anyone know where I can download a zipped Python distribution? | Yeah, kind of random, but I was wondering if anyone could link me to a .zip file containing a Python distribution. I know I could download the installer, so please don't suggest that. :P.
| [
"I didn't exactly understand what you want. Is Portable Python enough for you? If it isn't, check Python's official download website where you have a lot of options - including compressed source tarballs. You can downlod the tarballs, extract and create a zip file. \n",
"Can you use the official Source Distributi... | [
4,
2
] | [] | [] | [
"download",
"python"
] | stackoverflow_0001801286_download_python.txt |
Q:
Django Html email adds extra characters to the email body
I'm using Django to send an e-mail which has a text part, and an HTML part. Here's the code:
subject = request.session.get('email_subject', None)
from_email = request.session.get('user_email', None)
to = request.session.get('user_email', None)
... | Django Html email adds extra characters to the email body | I'm using Django to send an e-mail which has a text part, and an HTML part. Here's the code:
subject = request.session.get('email_subject', None)
from_email = request.session.get('user_email', None)
to = request.session.get('user_email', None)
bcc = [email.strip() for email in request.session.get('emai... | [
"You are generating html_content and text_content with render_to_response, which returns an HttpResponse object. \nHowever you want html_content and text_content to be strings, so use render_to_string instead.\nYou can import render_to_string with the following line:\nfrom django.template.loader import render_to_st... | [
5,
2
] | [] | [] | [
"django",
"email",
"python"
] | stackoverflow_0001801008_django_email_python.txt |
Q:
The Pythonic way of organizing modules and packages
I come from a background where I normally create one file per class. I organize common classes under directories as well. This practice is intuitive to me and it has been proven to be effective in C++, PHP, JavaSript, etc.
I am having trouble bringing this metap... | The Pythonic way of organizing modules and packages | I come from a background where I normally create one file per class. I organize common classes under directories as well. This practice is intuitive to me and it has been proven to be effective in C++, PHP, JavaSript, etc.
I am having trouble bringing this metaphor into Python: files are not just files anymore, but th... | [
"Think in terms of a \"logical unit of packaging\" -- which may be a single class, but more often will be a set of classes that closely cooperate. Classes (or module-level functions -- don't \"do Java in Python\" by always using static methods when module-level functions are also available as a choice!-) can be gr... | [
39,
11,
7,
4,
3
] | [] | [] | [
"module",
"package",
"project_organization",
"python"
] | stackoverflow_0001801878_module_package_project_organization_python.txt |
Q:
Using a hash function to give a memorable personality to objects
(Note: The project is in Python.)
I'm running a simulation in which I have many objects that I want to show on the screen and manipulate with. There needs to be a way to identify each object, because they'll be moving from place to place abruptly and... | Using a hash function to give a memorable personality to objects | (Note: The project is in Python.)
I'm running a simulation in which I have many objects that I want to show on the screen and manipulate with. There needs to be a way to identify each object, because they'll be moving from place to place abruptly and I want to be able to track which object moved where.
What I've been t... | [
"use a uuid (module uuid in python >= 2.5).\nThis uuid, in version 4, is by definition random on all fields (except one)\n>>> uuid.uuid4()\nUUID('9d477dc7-a986-4e3d-aa4f-6e57f690be78')\n\nYou can decompose the fields properly to create a color or a name (by mapping a bucket of names to a specific field). Of course ... | [
2
] | [] | [] | [
"hash",
"identification",
"python"
] | stackoverflow_0001802094_hash_identification_python.txt |
Q:
Python MySQLdb: Update if exists, else insert
I am looking for a simple way to query an update or insert based on if the row exists in the first place. I am trying to use Python's MySQLdb right now.
This is how I execute my query:
self.cursor.execute("""UPDATE `inventory`
SET `quantity` =... | Python MySQLdb: Update if exists, else insert | I am looking for a simple way to query an update or insert based on if the row exists in the first place. I am trying to use Python's MySQLdb right now.
This is how I execute my query:
self.cursor.execute("""UPDATE `inventory`
SET `quantity` = `quantity`+{1}
WHERE `item... | [
"Mysql DOES allow you to have unique indexes, and INSERT ... ON DUPLICATE UPDATE will do the update if any unique index has a duplicate, not just the PK.\nHowever, I'd probably still go for the \"two queries\" approach. You are doing this in a transaction, right?\n\nDo the update\nCheck the rows affected, if it's 0... | [
2
] | [] | [] | [
"python",
"sql",
"sql_insert",
"sql_update"
] | stackoverflow_0001802172_python_sql_sql_insert_sql_update.txt |
Q:
Large Sqlite database search
How is it possible to implement an efficient large Sqlite db search (more than 90000 entries)?
I'm using Python and SQLObject ORM:
import re
...
def search1():
cr = re.compile(ur'foo')
for item in Item.select():
if cr.search(item.name) or cr.sea... | Large Sqlite database search | How is it possible to implement an efficient large Sqlite db search (more than 90000 entries)?
I'm using Python and SQLObject ORM:
import re
...
def search1():
cr = re.compile(ur'foo')
for item in Item.select():
if cr.search(item.name) or cr.search(item.skim):
pr... | [
"The best way would be to rework your logic to do the selection in the database instead of in your python program.\nInstead of doing Item.select(), you should rework it to do Item.select(\"\"\"name LIKE ....\nIf you do this, and make sure you have the name and skim columns indexed, it will return very quickly. 900... | [
3,
2,
0,
0,
0,
0
] | [] | [] | [
"database",
"performance",
"python",
"search",
"sql"
] | stackoverflow_0001002953_database_performance_python_search_sql.txt |
Q:
django embedding user id into URL template best practice
I'm building a navigation menu in my django app, and one of the options is "My Account". There are different roles I have for users, but in order for them all to view their profile, I use a generic URL such as http://mysite/user//profile.
What's a Django bes... | django embedding user id into URL template best practice | I'm building a navigation menu in my django app, and one of the options is "My Account". There are different roles I have for users, but in order for them all to view their profile, I use a generic URL such as http://mysite/user//profile.
What's a Django best practice for building this url using templates?
Is it simply... | [
"Look into named URLs, you can find the official django documentation here.\nBasically you can name your URLs in your URL conf as such:\nurl(r'^user/(?P<user_id>\\d+)/profile/$', 'yourapp.views.view', name='user_url')\n\nAnd then in any template, you can do this:\n<a href=\"{% url user_url user.id %}\">\n\nHowever,... | [
8,
2
] | [
"Your first try matches the url listed in your URLconf. I'd also use that aproach.\n"
] | [
-2
] | [
"django",
"python"
] | stackoverflow_0001801350_django_python.txt |
Q:
What the mechanism use to integrate python with other languages (.Net, Java ....)
Somebody talking the python's code can embed into C#'s code. What the mechanism to do that? please explain for me.
Thanks a lot
A:
There are several approaches to this, depending on which languages you want to interoperate with.
.... | What the mechanism use to integrate python with other languages (.Net, Java ....) | Somebody talking the python's code can embed into C#'s code. What the mechanism to do that? please explain for me.
Thanks a lot
| [
"There are several approaches to this, depending on which languages you want to interoperate with.\n\n.Net/CLR Languages - Iron Python provides an implementation of Python running on the CLR. Allows you to use other CLR assemblies and embed a python scripting engine in your code \nJava/JVM Based Languages - Jython ... | [
6,
5,
2
] | [] | [] | [
".net",
"embed",
"java",
"python"
] | stackoverflow_0001802256_.net_embed_java_python.txt |
Q:
What is paste script?
I'm trying to understand what paste script and paster are. The website is far from clear.
I used paster to generate pre-made layouts for projects, but I don't get the big picture.
As far as I understand, and from the wikipedia entry, it says it's a framework for web frameworks, but that seem... | What is paste script? | I'm trying to understand what paste script and paster are. The website is far from clear.
I used paster to generate pre-made layouts for projects, but I don't get the big picture.
As far as I understand, and from the wikipedia entry, it says it's a framework for web frameworks, but that seems reductive. paster create ... | [
"Paste got several components:\n\nPaste Core: various modules to aid in creating wsgi web apps or frameworks (module index). Includes stuff like request and response objects. From the web site: \"The future of these pieces is to split them into independent packages, and refactor the internal Paste dependencies to r... | [
14,
4
] | [] | [] | [
"paste",
"paster",
"python"
] | stackoverflow_0001802282_paste_paster_python.txt |
Q:
How to identify whether a variable is a class or an object
I am working at a bit lower level writing a small framework for creating test fixtures for my project in Python. In this I want to find out whether a particular variable is an instance of a certain class or a class itself and if it is a class, I want to kn... | How to identify whether a variable is a class or an object | I am working at a bit lower level writing a small framework for creating test fixtures for my project in Python. In this I want to find out whether a particular variable is an instance of a certain class or a class itself and if it is a class, I want to know if it is a subclass of a certain class defined by my framewor... | [
"Use the inspect module.\n\nThe inspect module provides several useful functions to help get information about live objects such as modules, classes, methods, functions, tracebacks, frame objects, and code objects. For example, it can help you examine the contents of a class, retrieve the source code of a method, e... | [
11,
4,
3,
1
] | [] | [] | [
"python"
] | stackoverflow_0001802480_python.txt |
Q:
Python nested lists and recursion problem
I'm trying to process a first order logic formula represented as nested lists and strings in python so that that its in disjunctive normal form,
i.e ['&', ['|', 'a', 'b'], ['|', 'c', 'd']]
turns into
['|' ['&', ['&', 'a', 'c'], ['&', 'b', 'c']], ['&', ['&', 'a', 'd'], [... | Python nested lists and recursion problem | I'm trying to process a first order logic formula represented as nested lists and strings in python so that that its in disjunctive normal form,
i.e ['&', ['|', 'a', 'b'], ['|', 'c', 'd']]
turns into
['|' ['&', ['&', 'a', 'c'], ['&', 'b', 'c']], ['&', ['&', 'a', 'd'], ['&', 'b', 'd']]]
where | is 'or' and & is 'and'... | [
"Okay, here is an actual solution that seems to work.\nI do not understand your code, and I hadn't heard of DNF, so I started out by studying the problem some more.\nThe Wikipedia page on DNF was very helpful. It included a grammar that describes DNF.\nBased on that, I wrote a simple set of recursive functions tha... | [
1,
0
] | [] | [] | [
"logic",
"python"
] | stackoverflow_0001787576_logic_python.txt |
Q:
How to get the arch string that distutils uses for builds?
When I build a c extension using python setup.py build, the result is created under a directory named
build/lib.linux-x86_64-2.6/
where the part after lib. changes by the OS, CPU and Python version.
Is there a way I can access the appropriate string for m... | How to get the arch string that distutils uses for builds? | When I build a c extension using python setup.py build, the result is created under a directory named
build/lib.linux-x86_64-2.6/
where the part after lib. changes by the OS, CPU and Python version.
Is there a way I can access the appropriate string for my current architecture from python? Hopefully in a way that is g... | [
">>> from distutils import util\n>>> util.get_platform()\n'linux-x86_64'\n\n>>> import sys\n>>> '%s.%s' % sys.version_info[:2]\n2.6\n\n"
] | [
3
] | [] | [] | [
"distutils",
"python",
"python_c_extension"
] | stackoverflow_0001802534_distutils_python_python_c_extension.txt |
Q:
Is there a cross-platform python low-level API to capture or generate keyboard events?
I am trying to write a cross-platform python program that would run in the background, monitor all keyboard events and when it sees some specific shortcuts, it generates one or more keyboard events of its own. For example, this... | Is there a cross-platform python low-level API to capture or generate keyboard events? | I am trying to write a cross-platform python program that would run in the background, monitor all keyboard events and when it sees some specific shortcuts, it generates one or more keyboard events of its own. For example, this could be handy to have Ctrl-@ mapped to "my.email@address", so that every time some program... | [
"There is no such API. My solution was to write a helper module which would use a different helper depending on the value of os.name.\nOn Windows, use the Win32 extensions.\nOn Linux, things are a bit more complex since real OSes protect their users against keyloggers[*]. So here, you will need a root process which... | [
8,
7,
1,
0,
0,
0
] | [] | [] | [
"cross_platform",
"keyboard_events",
"low_level_api",
"python"
] | stackoverflow_0000676713_cross_platform_keyboard_events_low_level_api_python.txt |
Q:
Match UserProperty() with StringProperty()
I want to match StringProperty() with UserProperty and I can't change property so how can I achieve it? Please help me out.
A:
You seem to be talking about Google App Engine's model properties. To the best of my knowledge, you can't query a UserProperty with a string, b... | Match UserProperty() with StringProperty() | I want to match StringProperty() with UserProperty and I can't change property so how can I achieve it? Please help me out.
| [
"You seem to be talking about Google App Engine's model properties. To the best of my knowledge, you can't query a UserProperty with a string, because a User is not a string. Instead, try creating a brand new User object; you just need the email address of the user. Then you can query for users matching that user.\... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0001802728_python.txt |
Q:
Why does SWIG crash Python when linked to gtkglext?
Anything I link to gtkglext using SWIG crashes Python on exit. Why does this crash?
test.i:
%module test
%{
void test() { printf("Test.\n"); }
%}
void test();
Session:
$ swig -python test.i
$ g++ -I/usr/include/python2.6 -shared -fPIC -o _test.so test_wrap.c -... | Why does SWIG crash Python when linked to gtkglext? | Anything I link to gtkglext using SWIG crashes Python on exit. Why does this crash?
test.i:
%module test
%{
void test() { printf("Test.\n"); }
%}
void test();
Session:
$ swig -python test.i
$ g++ -I/usr/include/python2.6 -shared -fPIC -o _test.so test_wrap.c -lpython2.6
$ python -c 'import test; test.test()'
Test.
... | [
"You need to init gtk properly.\n$ cat test.i \n%module test\n%{\nvoid test() { printf(\"Test.\\n\"); }\n%}\nvoid test();\n$ swig -python test.i ; gcc -I/usr/include/python2.5 -shared -fPIC -o _test.so test_wrap.c -lpython2.5 `pkg-config --libs gtkglext-1.0`\n$ python -c 'import test; test.test()'\nTest.\nSegmentat... | [
1
] | [] | [] | [
"python",
"scripting",
"swig"
] | stackoverflow_0001801518_python_scripting_swig.txt |
Q:
python for in control structure
I am a php programmer trying to understand python's for in syntax
I get the basic for in
for i in range(0,5):
in php would be
for ($i = 0; $i < 5; $i++){
but what does this do
for x, y in z:
and what would be the translation to php?
This is the full code i am translating to php:
... | python for in control structure | I am a php programmer trying to understand python's for in syntax
I get the basic for in
for i in range(0,5):
in php would be
for ($i = 0; $i < 5; $i++){
but what does this do
for x, y in z:
and what would be the translation to php?
This is the full code i am translating to php:
def preProcess(self):
""" plan f... | [
"self._v_scaleInfo: is an array of tuples, presumably, like [(x,y),(x,y),...] so \nfor width, height in self._v_scaleInfo: loops through the array filling width and height with the tuple values.\nphp would go something like:\n$scaleInfo = array(array(x,y), array(x,y),...);\n\nfor( $i = 0; $i < count($scaleInfo); $i... | [
1,
1,
0,
0,
0,
0,
0
] | [] | [] | [
"for_loop",
"php",
"python"
] | stackoverflow_0001802415_for_loop_php_python.txt |
Q:
Parsing a hex formated DEC 32 bit single precision floating point value in python
I'm having problems parsing a hex formatted DEC 32bit single precision floating point value in python, the value I'm parsing is represented as D44393DB in hex. The original floating point value is ~108, read from a display of the sen... | Parsing a hex formated DEC 32 bit single precision floating point value in python | I'm having problems parsing a hex formatted DEC 32bit single precision floating point value in python, the value I'm parsing is represented as D44393DB in hex. The original floating point value is ~108, read from a display of the sending unit.
The format is specified as:
1bit sign + 8bit exponent + 23bit mantissa.
Byte... | [
"Is it possible that the bytes got shuffled somehow? The arrangements of bits that you describe (sign bit in byte 2, LSB of exponent in byte 1) is different from Appendix O that you link to. It looks like byte 1 and 2 were exchanged. \nI'll assume that byte 3 and 4 were also exchanged, so that the real hex value is... | [
4,
1,
1,
0
] | [] | [] | [
"floating_point",
"python"
] | stackoverflow_0001797806_floating_point_python.txt |
Q:
Problem with SPARQLWrapper (Python)
I'm making a SPARQL query against the Sesame store in localhost, using SPARQLWrapper:
sparql = SPARQLWrapper('http://localhost:8080/openrdf-sesame/repositories/rep/statements')
sparql.setQuery(query)
sparql.setReturnFormat(JSON)
results = sparql.query().convert()
Howeve... | Problem with SPARQLWrapper (Python) | I'm making a SPARQL query against the Sesame store in localhost, using SPARQLWrapper:
sparql = SPARQLWrapper('http://localhost:8080/openrdf-sesame/repositories/rep/statements')
sparql.setQuery(query)
sparql.setReturnFormat(JSON)
results = sparql.query().convert()
However, I'm getting:
File "build/bdist.linux-i... | [
"For SPARQLWrapper you don't normally have to add the statements bit in the URI. I.e., this should work:\nsparql = SPARQLWrapper('http://localhost:8080/openrdf-sesame/repositories/rep')\n\nAnd then just continue with the rest of your code.\n"
] | [
3
] | [
"I've solved the problem by doing the SPARQL wrapping myself...\n"
] | [
-1
] | [
"python",
"rdf",
"sparql"
] | stackoverflow_0001684197_python_rdf_sparql.txt |
Q:
importing cx_Oracle and kinterbasdb returns error
Greetings, everybody.
I'm trying to import the following libraries in python: cx_Oracle and kinterbasdb.
But, when I try, I get a very similar message error.
*for cx_Oracle:
Traceback (most recent call last):
File "", line 1, in
ImportError: DLL load failed: Não... | importing cx_Oracle and kinterbasdb returns error | Greetings, everybody.
I'm trying to import the following libraries in python: cx_Oracle and kinterbasdb.
But, when I try, I get a very similar message error.
*for cx_Oracle:
Traceback (most recent call last):
File "", line 1, in
ImportError: DLL load failed: Não foi possível encontrar o procedimento especificado.
(t... | [] | [] | [
"oracle is a complete pain. i don't know the details for windows, but for unix you need ORACLE_HOME and LD_LIBRARY_PATH to both be defined before cx_oracle will work. in windows this would be your environment variables, i guess. so check those.\nalso, check that they are defined in the environment in which the p... | [
-1
] | [
"cx_oracle",
"kinterbasdb",
"python"
] | stackoverflow_0001799475_cx_oracle_kinterbasdb_python.txt |
Q:
Fast Graphics with XServer
I am working on embedded linux platform with limited system resources.
I want to do fullscreen slideshow with simple transistions (like slide in-out, fade in-out ).
I tried PyGtk+GTK+Cairo but its very slow, when I animate GTK image controls I get just two or three frames per second. But... | Fast Graphics with XServer | I am working on embedded linux platform with limited system resources.
I want to do fullscreen slideshow with simple transistions (like slide in-out, fade in-out ).
I tried PyGtk+GTK+Cairo but its very slow, when I animate GTK image controls I get just two or three frames per second. But smplayer is playing video at go... | [
"I would try this first using just PyCairo, not using GTK controls at all.\nHowever, if that does not give you the speed that you need, then you might want to try PyGame which gives you access to SDL including OpenGL backends. PyGame is very actively developed and used in building applications that include full scr... | [
2
] | [] | [] | [
"linux",
"python"
] | stackoverflow_0001803458_linux_python.txt |
Q:
Multiple CouchDB Document fetch with couchdb-python
How to fetch multiple documents from CouchDB, in particular with couchdb-python?
A:
Easiest way is to pass a include_docs=True arg to Database.view. Each row of the results will include the doc. e.g.
>>> db = couchdb.Database('http://localhost:5984/test')
>>> r... | Multiple CouchDB Document fetch with couchdb-python | How to fetch multiple documents from CouchDB, in particular with couchdb-python?
| [
"Easiest way is to pass a include_docs=True arg to Database.view. Each row of the results will include the doc. e.g.\n>>> db = couchdb.Database('http://localhost:5984/test')\n>>> rows = db.view('_all_docs', keys=['docid1', 'docid2', 'missing'], include_docs=True)\n>>> docs = [row.doc for row in rows]\n>>> docs\n[<D... | [
22,
4,
-7
] | [] | [] | [
"couchdb",
"python"
] | stackoverflow_0001640054_couchdb_python.txt |
Q:
Python regular expression matching a multiline block of text but not replacing it
Ok so i have this piece of code:
def findNReplaceRegExp(file_name, regexp, replaceString, verbose=True, confirmationNeeded=True):
'''Replaces the oldString with the replaceString in the file given,\
returns the number of replaces
... | Python regular expression matching a multiline block of text but not replacing it | Ok so i have this piece of code:
def findNReplaceRegExp(file_name, regexp, replaceString, verbose=True, confirmationNeeded=True):
'''Replaces the oldString with the replaceString in the file given,\
returns the number of replaces
'''
# initialize local variables
cregexp = re.compile(regexp, re.MULTILINE | re... | [
"You're finding with cregexp, which has the multiline option set, but then replacing with regexp, which may or may not.\n"
] | [
1
] | [] | [] | [
"multiline",
"python",
"regex",
"replace"
] | stackoverflow_0001803713_multiline_python_regex_replace.txt |
Q:
Error codes returned by urllib/urllib2 and the actual page
the normal behavior of urllib/urllib2 is if an error code is sent in the header of the response (i.e 404) an Exception is raised.
How do you look for specific errors i.e (40x, or 50x) based on the different errors, do different things. Also, how do you re... | Error codes returned by urllib/urllib2 and the actual page | the normal behavior of urllib/urllib2 is if an error code is sent in the header of the response (i.e 404) an Exception is raised.
How do you look for specific errors i.e (40x, or 50x) based on the different errors, do different things. Also, how do you read the actual data being returned HTML/JSON etc (The data usuall... | [
"urllib2 raises a HTTPError when HTTP errors happen. You can get to the response code using code on the exception object. You can get the response data using read():\n\n>>> req = urllib2.Request('http://www.python.org/fish.html')\n>>> try:\n>>> urllib2.urlopen(req)\n>>> except urllib2.HTTPError, e:\n>>> pri... | [
9,
1
] | [] | [] | [
"error_handling",
"python"
] | stackoverflow_0001803741_error_handling_python.txt |
Q:
communicate with a process in utf-8 on a cp1252 consoless
I need to control a program by sending commands in utf-8 encoding to its standard input. For this I run the program using subprocess.Popen():
proc = Popen("myexecutable.exe", shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE)
proc.stdin.write(u'ééé'.encode('... | communicate with a process in utf-8 on a cp1252 consoless | I need to control a program by sending commands in utf-8 encoding to its standard input. For this I run the program using subprocess.Popen():
proc = Popen("myexecutable.exe", shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE)
proc.stdin.write(u'ééé'.encode('utf_8'))
If I run this from a cygwin utf-8 console, it works. ... | [
"I wonder if this caveat, from the subprocess documentation, is relevant:\n\nThe only reason you would need to specify shell=True on Windows is where the command you wish to execute is actually built in to the shell, eg dir, copy. You don’t need shell=True to run a batch file, nor to run a console-based executable.... | [
0,
0
] | [] | [] | [
"cp1252",
"python",
"utf_8",
"windows"
] | stackoverflow_0001803675_cp1252_python_utf_8_windows.txt |
Q:
Python: Can you make this __eq__ easy to understand?
I have another question for you.
I have a python class with a list 'metainfo'. This list contains variable names that my class might contain. I wrote a __eq__ method that returns True if the both self and other have the same variables from metainfo and those var... | Python: Can you make this __eq__ easy to understand? | I have another question for you.
I have a python class with a list 'metainfo'. This list contains variable names that my class might contain. I wrote a __eq__ method that returns True if the both self and other have the same variables from metainfo and those variables have the same value.
Here is my implementation:
de... | [
"I would add a docstring which explains what it compares, as you did in your question.\n",
"Use getattr's third argument to set distinct default values:\ndef __eq__(self, other):\n return all(getattr(self, a, Ellipsis) == getattr(other, a, Ellipsis)\n for a in self.metainfo)\n\nAs the default val... | [
9,
9,
5,
3,
3,
1,
1,
1,
0
] | [] | [] | [
"equality",
"python"
] | stackoverflow_0001803710_equality_python.txt |
Q:
Process two files at the same time in Python
I have information about 12340 cars. This info is stored sequentially in two different files:
car_names.txt, which contains one line for the name of each car
car_descriptions.txt, which contains the descriptions of each car. So 40 lines for each one, where the 6th line... | Process two files at the same time in Python | I have information about 12340 cars. This info is stored sequentially in two different files:
car_names.txt, which contains one line for the name of each car
car_descriptions.txt, which contains the descriptions of each car. So 40 lines for each one, where the 6th line reads @CAR_NAME
I would like to do in python: to... | [
"First, make a generator that retrieves the car name from a sequence. You could yield every 7th line; I've made mine yield whatever line follows the line that starts with @CAR_NAME:\ndef car_names(seq):\n yieldnext=False\n for line in seq:\n if yieldnext: yield line\n yieldnext = line.startswit... | [
9,
8,
4,
1,
0,
0
] | [] | [] | [
"python",
"string"
] | stackoverflow_0001731102_python_string.txt |
Q:
PyAudio.open, how to use?
I'm trying to make a pyaudio input stream but can't figure out how to make it.
What I did is:
a = pyaudio.PyAudio()
Then tried to call a.open() but I don't know the arguments I should type in. It asks me to check Stream.init for a reference, but I don't know what a PA_MANAGER is and the ... | PyAudio.open, how to use? | I'm trying to make a pyaudio input stream but can't figure out how to make it.
What I did is:
a = pyaudio.PyAudio()
Then tried to call a.open() but I don't know the arguments I should type in. It asks me to check Stream.init for a reference, but I don't know what a PA_MANAGER is and the documentation isn't useful at a... | [
"Perhaps you could start by modfying some of the examples?\n"
] | [
4
] | [] | [] | [
"audio",
"python"
] | stackoverflow_0001803894_audio_python.txt |
Q:
Running methods on different cores on python
Is there any easy way to make 2 methods, let's say MethodA() and MethodB() run in 2 different cores? I don't mean 2 different threads. I'm running in Windows, but I'd like to know if it is possible to be platform independent.
edit: And what about
http://docs.python.org/... | Running methods on different cores on python | Is there any easy way to make 2 methods, let's say MethodA() and MethodB() run in 2 different cores? I don't mean 2 different threads. I'm running in Windows, but I'd like to know if it is possible to be platform independent.
edit: And what about
http://docs.python.org/dev/library/multiprocessing.html
and
parallel pyth... | [
"You have to use separate processes (because of the often-mentioned GIL). The multiprocessing module is here to help.\nfrom multiprocessing import Process\nfrom somewhere import A, B \nif __name__ == '__main__':\n procs = [ Process(target=t) for t in (A,B) ]\n\n for p in procs: \n p.start()\n\n for ... | [
8,
0,
0,
0
] | [] | [] | [
"multicore",
"python"
] | stackoverflow_0001803955_multicore_python.txt |
Q:
How to set User-Agent in python-twitter?
i'm writing a small script to tweet messages from the monitoring systems. The only issue i ran into so far is that i can't set the User-Agent correctly, all tweets show up as "from API" which ain't a huge deal but i wonder what I'm doing wrong.
An example to reproduce this... | How to set User-Agent in python-twitter? | i'm writing a small script to tweet messages from the monitoring systems. The only issue i ran into so far is that i can't set the User-Agent correctly, all tweets show up as "from API" which ain't a huge deal but i wonder what I'm doing wrong.
An example to reproduce this behavior:
import sys
import twitter
USERNAME... | [
"In order to get Twitter to recognize your application you have to use OAuth nowadays and register your application.\nSee this FAQ entry and Twitter's application registration form.\n"
] | [
2
] | [] | [] | [
"python",
"python_twitter",
"twitter",
"user_agent"
] | stackoverflow_0001803669_python_python_twitter_twitter_user_agent.txt |
Q:
Writing crawler that stay logged in with any server
I am writing a crawler. Once after the crawler logs into a website I want to make the crawler to "stay-always-logged-in". How can I do that? Is a client (like browser, crawler etc.,) make a server to obey this rule? This scenario could occur when the server allow... | Writing crawler that stay logged in with any server | I am writing a crawler. Once after the crawler logs into a website I want to make the crawler to "stay-always-logged-in". How can I do that? Is a client (like browser, crawler etc.,) make a server to obey this rule? This scenario could occur when the server allows limited logins in day.
| [
"\"Logged-in state\" is usually represented by cookies. So what your have to do is to store the cookie information sent by that server on login, then send that cookie with each of your subsequent requests (as noted by Aiden Bell in his message, thx).\nSee also this question:\nHow to \"keep-alive\" with cookielib an... | [
5
] | [] | [] | [
"c#",
"http",
"python",
"session",
"web_crawler"
] | stackoverflow_0001804258_c#_http_python_session_web_crawler.txt |
Q:
Defining models in a top level Django directory
I've noticed that in order for me to define models, I need to do something like:
python manage.py startapp app_name
Is there anyway to avoid this convention and be able to create a models.py directly in the top level site that django-admin.py has created for me? Som... | Defining models in a top level Django directory | I've noticed that in order for me to define models, I need to do something like:
python manage.py startapp app_name
Is there anyway to avoid this convention and be able to create a models.py directly in the top level site that django-admin.py has created for me? Sometimes I'm building a site that can be put together i... | [
"Not really. The django admin programs expect app/models.py file names.\n"
] | [
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0001804591_django_python.txt |
Q:
Appengine reference order
I have declared models in AppEngine's models.py:
class Post(db.Model):
topic = db.ReferenceProperty(Topic, collection_name='posts', verbose_name=_('Topic'))
(..)
class Topic(db.Model):
(..)
last_post = db.ReferenceProperty(Post, collection_name='last_topic_post')
Problem is ReferencePro... | Appengine reference order | I have declared models in AppEngine's models.py:
class Post(db.Model):
topic = db.ReferenceProperty(Topic, collection_name='posts', verbose_name=_('Topic'))
(..)
class Topic(db.Model):
(..)
last_post = db.ReferenceProperty(Post, collection_name='last_topic_post')
Problem is ReferenceProperty must have Model class but... | [
"ReferenceProperty accepts None in place of a model class, which means \"no type restriction\" on that field. It is not a nice solution, however.\nSee:\nhttp://code.google.com/appengine/docs/python/datastore/typesandpropertyclasses.html#ReferenceProperty\nHaving such cyclic references in your model is not a good id... | [
2
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0001804573_django_django_models_python.txt |
Q:
How to save double to file in python?
Let's say I need to save a matrix(each line corresponds one row) that could be loaded from fortran later. What method should I prefer? Is converting everything to string is the only one approach?
A:
You can save them in binary format as well. Please see the documentation on ... | How to save double to file in python? | Let's say I need to save a matrix(each line corresponds one row) that could be loaded from fortran later. What method should I prefer? Is converting everything to string is the only one approach?
| [
"You can save them in binary format as well. Please see the documentation on the struct standard module, it has a pack function for converting Python object into binary data.\nFor example:\nimport struct\n\nvalue = 3.141592654\ndata = struct.pack('d', value)\nopen('file.ext', 'wb').write(data)\n\nYou can convert ea... | [
6,
2,
1,
1
] | [] | [] | [
"double",
"file",
"numbers",
"python"
] | stackoverflow_0001804049_double_file_numbers_python.txt |
Q:
Reading socket buffer using asyncore
I'm new to Python (I have been programming in Java for multiple years now though), and I am working on a simple socket-based networking application (just for fun). The idea is that my code connects to a remote TCP end-point and then listens for any data being pushed from the se... | Reading socket buffer using asyncore | I'm new to Python (I have been programming in Java for multiple years now though), and I am working on a simple socket-based networking application (just for fun). The idea is that my code connects to a remote TCP end-point and then listens for any data being pushed from the server to the client, and perform some parsi... | [
"TCP is a stream, and you are not guaranteed that your buffer will not contain the end of one message and the beginning of the next. \nSo, checking for \\n\\r at the end of the buffer will not work as expected in all situations. You have to check each byte in the stream.\nAnd, I would strongly recommend that you us... | [
6,
6
] | [] | [] | [
"asyncore",
"buffer",
"python",
"sockets"
] | stackoverflow_0001804980_asyncore_buffer_python_sockets.txt |
Q:
Lpr -module in Python
How can you call lpr in Python?
It is not in the sys -module which is surprising.
I aim to use the lpr as follows shown by pseudo-code
10*i for i in range(77):
lpr --pages(i,i+1) file.pdf
A:
First of, I don't understand your pseudo code. (What does 10*i for i in range(77... | Lpr -module in Python | How can you call lpr in Python?
It is not in the sys -module which is surprising.
I aim to use the lpr as follows shown by pseudo-code
10*i for i in range(77):
lpr --pages(i,i+1) file.pdf
| [
"First of, I don't understand your pseudo code. (What does 10*i for i in range(77): mean in this case?)\nGenerally, you use subprocess.Popen to run external commands. ActiveState recipe 511505 shows an example specifically with lpr. Basically, you can invoke lpr like this:\nsubprocess.Popen(['lpr', 'some_filename']... | [
5,
2,
0
] | [] | [] | [
"lpr",
"printing",
"python"
] | stackoverflow_0001804365_lpr_printing_python.txt |
Q:
Pythonic way to select first variable that evaluates to True
I have some variables and I want to select the first one that evaluates to True, or else return a default value.
For instance I have a, b, and c. My existing code:
result = a if a else (b if b else (c if c else default))
Another approach I was consideri... | Pythonic way to select first variable that evaluates to True | I have some variables and I want to select the first one that evaluates to True, or else return a default value.
For instance I have a, b, and c. My existing code:
result = a if a else (b if b else (c if c else default))
Another approach I was considering:
result = ([v for v in (a, b, c) if v] + [default])[0]
But the... | [
"Did you mean returning first value for what bool(value)==True? Then you can just rely on the fact that boolean operators return last evaluated argument:\nresult = a or b or c or default\n\n",
"If one variable is not \"defined\", you can't access its name. So any reference to 'a' raises a NameError Exception.\nIn... | [
25,
17,
5,
2,
1,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0001803302_python.txt |
Q:
Python JSON parse_float=decimal.Decimal not working
I have a string with a floating point number in it, but I can't get JSON to load it as a decimal.
x = u'{"14": [4.5899999999999999, "susan"]}'
json.loads(x, parse_float = decimal.Decimal)
This returns:
{u'14': [Decimal('4.5899999999999999'), u'susan']}
Any idea... | Python JSON parse_float=decimal.Decimal not working | I have a string with a floating point number in it, but I can't get JSON to load it as a decimal.
x = u'{"14": [4.5899999999999999, "susan"]}'
json.loads(x, parse_float = decimal.Decimal)
This returns:
{u'14': [Decimal('4.5899999999999999'), u'susan']}
Any idea how I can make it into the actual "4.59"?
| [
"You need to define a function that performs whatever rounding you desire, then uses the altered string to build the Decimal. Your current solution does work perfectly well: it just does exactly what you tell it to, i.e., use the entire string, as opposed to what you desire (and have not told either the code, or u... | [
11,
4
] | [] | [] | [
"json",
"python"
] | stackoverflow_0001805072_json_python.txt |
Q:
Django / Python / PIL / sorl-thumbnail generation in bulk - memory error
I'm trying to bulk generate 4 thumnails for each of around 40k images with sorl-thumbnail for my django app. I iterate through all django objects with an ImageWithThumbnailsFieldFile, and then call its generate_thumbnails() function.
This wor... | Django / Python / PIL / sorl-thumbnail generation in bulk - memory error | I'm trying to bulk generate 4 thumnails for each of around 40k images with sorl-thumbnail for my django app. I iterate through all django objects with an ImageWithThumbnailsFieldFile, and then call its generate_thumbnails() function.
This works fine, except that after a few hundred iterations, I run out of memory and m... | [
"Your problem relates to how Django caches the results of a queryset as you loop through them. Django keeps all the objects in memory so that next time you iterate through the same queryset you don't have to hit the database again to get all the data.\nWhat you need to do is use the iterator() method. So:\nall = ... | [
4
] | [] | [] | [
"django",
"memory",
"python",
"python_imaging_library",
"sorl_thumbnail"
] | stackoverflow_0001805256_django_memory_python_python_imaging_library_sorl_thumbnail.txt |
Q:
How to fix value produced by Random?
I got an issue which is, in my code,anyone can help will be great.
this is the example code.
from random import *
from numpy import *
r=array([uniform(-R,R),uniform(-R,R),uniform(-R,R)])
def Ft(r):
for i in range(3):
do something here, call r
return somethi... | How to fix value produced by Random? | I got an issue which is, in my code,anyone can help will be great.
this is the example code.
from random import *
from numpy import *
r=array([uniform(-R,R),uniform(-R,R),uniform(-R,R)])
def Ft(r):
for i in range(3):
do something here, call r
return something
however I found that in python shell, ... | [
"Do you mean that you want the calls to randon.uniform() to return the same sequence of values each time you run the function?\nIf so, you need to call random.seed() to set the start of the sequence to a fixed value. If you don't, the current system time is used to initialise the random number generator, which is i... | [
15,
1
] | [] | [] | [
"python",
"random"
] | stackoverflow_0001805265_python_random.txt |
Q:
Scrapy spider index error
This is the code for Spyder1 that I've been trying to write within Scrapy framework:
from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
from scrapy.selector import HtmlXPathSelector
from scrapy.item import Item
from firm.i... | Scrapy spider index error | This is the code for Spyder1 that I've been trying to write within Scrapy framework:
from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
from scrapy.selector import HtmlXPathSelector
from scrapy.item import Item
from firm.items import FirmItem
class Spi... | [
"SgmlLinkExtractor doesn't support selectors in its \"allow\" argument.\nSo this is wrong:\nSgmlLinkExtractor(allow=[\"hxs.select('//td[@class='altRow'] ...')\"])\n\nThis is right:\nSgmlLinkExtractor(allow=[r\"product\\.php\"])\n\n",
"The parse function is called for each match of your SgmlLinkExtractor.\nAs Pabl... | [
1,
0,
0
] | [] | [] | [
"python",
"scrapy",
"web_crawler"
] | stackoverflow_0001805050_python_scrapy_web_crawler.txt |
Q:
What is the performance cost of named keys or "pre-generated" keys in Google App Engine?
If you used named keys in Google App Engine, does this incur any additional cost? Put another way, is it any more expensive to create a new entity with a named key rather than a randomly generated id?
In a similar line of reas... | What is the performance cost of named keys or "pre-generated" keys in Google App Engine? | If you used named keys in Google App Engine, does this incur any additional cost? Put another way, is it any more expensive to create a new entity with a named key rather than a randomly generated id?
In a similar line of reasoning, I note that you can ask Google App Engine to give you a set of keys that will not be us... | [
"There is no intrinsic penalty to using a key name instead of an auto-generated ID, except the overhead of a (potentially) longer key on the entity and any ReferenceProperties that reference it.\nIn certain cases, in fact, using auto-allocated IDs can have a performance penalty: If you insert new entities at a very... | [
4
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0001805555_google_app_engine_python.txt |
Q:
How to write a simple spider in Python?
I've been trying to write this spider for weeks but without success. What is the best way for me to code this in Python:
1) Initial url: http://www.whitecase.com/Attorneys/List.aspx?LastName=A
2) from initial url pick up these urls with this regex:
hxs.select('//td[@class="a... | How to write a simple spider in Python? | I've been trying to write this spider for weeks but without success. What is the best way for me to code this in Python:
1) Initial url: http://www.whitecase.com/Attorneys/List.aspx?LastName=A
2) from initial url pick up these urls with this regex:
hxs.select('//td[@class="altRow"][1]/a/@href').re('/.a\w+')
[u'/cabel',... | [
"http://www.ibm.com/developerworks/linux/library/l-spider/ IBM article with good description \nor\nhttp://code.activestate.com/recipes/576551/ Python cookbook, better code but less explanation\n",
"Also, I suggest you read:\nRegEx match open tags except XHTML self-contained tags\nBefore you try to parse HTML with... | [
4,
0
] | [] | [] | [
"python",
"scrapy",
"web_crawler"
] | stackoverflow_0001805231_python_scrapy_web_crawler.txt |
Q:
Django template URL function not matching in app
I have a Django project set up with an app called pub. I'm trying to set it up so that I can include urls.py from each app (there will be more as I go) in the top-level urls.py. I've also got a template that uses the 'url' function to resolve a URL on a view, defi... | Django template URL function not matching in app | I have a Django project set up with an app called pub. I'm trying to set it up so that I can include urls.py from each app (there will be more as I go) in the top-level urls.py. I've also got a template that uses the 'url' function to resolve a URL on a view, defined in the openidgae module. The problem is that after... | [
"I don't understand what the problem is that you're facing, but just by looking at your urls.py files, you should probably change the top level urls.py to something like\nfrom django.conf.urls.defaults import *\n\nurlpatterns = patterns('',\n (r'', include('openidgae.urls')),\n (r'^pub/', include('pub.urls')), ... | [
1,
0
] | [] | [] | [
"django",
"google_app_engine",
"python"
] | stackoverflow_0001801165_django_google_app_engine_python.txt |
Q:
Where/How should I do validation and transformations on entities in Google App Engine?
In Ruby on Rails, each model entity has a "validate_on_something" hook method, that will be called before the entity is actually persisted to the database. I would like similar functionality in Google App Engine. I am aware that... | Where/How should I do validation and transformations on entities in Google App Engine? | In Ruby on Rails, each model entity has a "validate_on_something" hook method, that will be called before the entity is actually persisted to the database. I would like similar functionality in Google App Engine. I am aware that you can do validation on individual Properties by passing arguments to them in their declar... | [
"The best answer depends on what sort of transformations you need to do. There's no generalized pre-/post- put methods for models, but there are several other options:\n\nAs you mentioned, you can pass validation functions to Property class constructors\nYou can use a custom property class that generates values pro... | [
2,
1
] | [] | [] | [
"google_app_engine",
"python",
"transformation",
"validation"
] | stackoverflow_0001805830_google_app_engine_python_transformation_validation.txt |
Q:
How to deal with rounding errors of floating types for financial calculations in Python SQLite?
I'm creating a financial app and it seems my floats in sqlite are floating around. Sometimes a 4.0 will be a 4.000009, and a 6.0 will be a 6.00006, things like that. How can I make these more exact and not affect my f... | How to deal with rounding errors of floating types for financial calculations in Python SQLite? | I'm creating a financial app and it seems my floats in sqlite are floating around. Sometimes a 4.0 will be a 4.000009, and a 6.0 will be a 6.00006, things like that. How can I make these more exact and not affect my financial calculations?
Values are coming from Python if that matters. Not sure which area the messed ... | [
"Please use Decimal \nhttp://docs.python.org/library/decimal.html\n",
"Seeing as this is a financial application, if you only have calculations up to 2 or 3 decimal places, you can store all the data internally as integers, and only convert them to float for presentation purposes.\nE.g.\n6.00 -> 600\n4.35 -> 435\... | [
9,
4,
3,
1,
1,
0
] | [] | [] | [
"floating_point",
"python",
"sqlite"
] | stackoverflow_0001801307_floating_point_python_sqlite.txt |
Q:
Problems PUTting binary data to Django
I am trying to build a RESTful api with Django to share mp3s -- right up front: it's a toy app, never going into production, so it doesn't need to scale or worry (I hope) about copyright devils.
My problem now is that I have a Django view that I want to be the endpoint for H... | Problems PUTting binary data to Django | I am trying to build a RESTful api with Django to share mp3s -- right up front: it's a toy app, never going into production, so it doesn't need to scale or worry (I hope) about copyright devils.
My problem now is that I have a Django view that I want to be the endpoint for HTTP PUT requests. The headers of the PUT wil... | [
"It does appear that the issue is in the dev server's handling of large requests. After deploying to apache with mod_wsgi, this problem goes away. Still lots of open questions for me about RESTful file uploads...\n"
] | [
0
] | [] | [] | [
"django",
"http",
"python"
] | stackoverflow_0001793556_django_http_python.txt |
Q:
Calculate percent at runtime
I have this problem where I have to "audit" a percent of my transtactions.
If percent is 100 I have to audit them all, if is 0 I have to skip them all and if 50% I have to review the half etc.
The problem ( or the opportunity ) is that I have to perform the check at runtime.
What I t... | Calculate percent at runtime | I have this problem where I have to "audit" a percent of my transtactions.
If percent is 100 I have to audit them all, if is 0 I have to skip them all and if 50% I have to review the half etc.
The problem ( or the opportunity ) is that I have to perform the check at runtime.
What I tried was:
audit = 100/percent
So... | [
"Why not do it randomly. For each transaction, pick a random number between 0 and 100. If that number is less than your \"percent\", then audit the transaction. If the number is greater than your \"percent\", then don't. I don't know if this satisfies your requirements, but over an extended period of time, you ... | [
17,
3,
3,
2,
1,
1,
0,
0
] | [] | [] | [
"algorithm",
"c#",
"java",
"language_agnostic",
"python"
] | stackoverflow_0001806143_algorithm_c#_java_language_agnostic_python.txt |
Q:
Suppose I have 2 vectors. What algorithms can I use to compare them?
Company 1 has this vector:
['books','video','photography','food','toothpaste','burgers'] ... ...
Company 2 has this vector:
['video','processor','photography','LCD','power supply', 'books'] ... ...
Suppose this is a frequency distribution (I co... | Suppose I have 2 vectors. What algorithms can I use to compare them? | Company 1 has this vector:
['books','video','photography','food','toothpaste','burgers'] ... ...
Company 2 has this vector:
['video','processor','photography','LCD','power supply', 'books'] ... ...
Suppose this is a frequency distribution (I could make it a tuple but too much to type).
As you can see...these vectors ... | [
"I would suggest you a book called Programming Collective Intelligence. It's a very nice book on how you can retrieve information from simple data like this one. There are code examples included (in Python :)\nEdit:\nJust replying to gbjbaanb: This is Python!\na = ['books','video','photography','food','toothpaste',... | [
3,
3,
2,
0,
0
] | [
"You could use the set_intersection algorithm. The 2 vectors must be sorted first (use sort call), then pass in 4 iterators and you'll get a collection back with the common elements inserted into it. There are a few others that operate similarly. \n"
] | [
-1
] | [
"list",
"python",
"text",
"vector"
] | stackoverflow_0001805987_list_python_text_vector.txt |
Q:
Grouping by Nested Object Keys in MongoDB
Is it possible to group results by a key found in an array of objects in a list?
For example, lets say I have a table of survey responses (survey_responses), and each entry represents a single response. One or more of the questions in the survey is a multiple choice, so th... | Grouping by Nested Object Keys in MongoDB | Is it possible to group results by a key found in an array of objects in a list?
For example, lets say I have a table of survey responses (survey_responses), and each entry represents a single response. One or more of the questions in the survey is a multiple choice, so the answers stored could resemble:
survey_respons... | [
"It seems that your only option is to do this in your own Python code:\nsong_points = {}\nfor response in survey_responses.find():\n for song in response['favorite_songs_of_2009']:\n title = song['title']\n song_points[title] = song_points.get(title, 0) + song['points']\n\nYou'll get your results i... | [
0
] | [] | [] | [
"mongodb",
"python"
] | stackoverflow_0001806705_mongodb_python.txt |
Q:
"Permission Denied" in Django template using Djapian
I've followed the Djapian tutorial and setup everything "by the book" so that the indexshell commandline supplied by Djapian shows successful queries.
However, when integrating the sample search from the Djapian tutorial I get this nonsense error:
TemplateSynta... | "Permission Denied" in Django template using Djapian | I've followed the Djapian tutorial and setup everything "by the book" so that the indexshell commandline supplied by Djapian shows successful queries.
However, when integrating the sample search from the Djapian tutorial I get this nonsense error:
TemplateSyntaxError at /search/
Caught an exception while rendering: (1... | [
"Please figure out what is the exact file path involved in this error. I guess it involves a write operation to some template cache, but you should make sure.\nThen you just need to check the UNIX permissions on the file accessed or on the directory for that file in the case of a newly created file.\nAnother possib... | [
2
] | [] | [] | [
"django",
"django_templates",
"python",
"search",
"xapian"
] | stackoverflow_0001806449_django_django_templates_python_search_xapian.txt |
Q:
Openlayers + Mapnik + Tilecache configuration problem
I am trying to setup Mapnik + tilecache but can't see any tiles in the browser when I set bbox parameters in both Tilecache.cfg and Openlayers but when I don't specify the bbox everything works fine and I can see actual map tiles.
I was wondering if anyone can ... | Openlayers + Mapnik + Tilecache configuration problem | I am trying to setup Mapnik + tilecache but can't see any tiles in the browser when I set bbox parameters in both Tilecache.cfg and Openlayers but when I don't specify the bbox everything works fine and I can see actual map tiles.
I was wondering if anyone can point out the problem in the code. I think I have tried eve... | [
"The OpenLayers.Bounds constructor parameters are in the order left, bottom, right top. Taking the bounds that you're using change your JavaScript to be:\n var options = {\n numZoomLevels:20,\n maxResolution: 360/512,\n projection: \"EPSG:4326\",\n ... | [
3,
1
] | [] | [] | [
"maps",
"openlayers",
"proj4js",
"python",
"tilecache"
] | stackoverflow_0001783081_maps_openlayers_proj4js_python_tilecache.txt |
Q:
Terminate long running python threads
What is the recommended way to terminate unexpectedly long running threads in python ? I can't use SIGALRM, since
Some care must be taken if both
signals and threads are used in the
same program. The fundamental thing to
remember in using signals and threads
simultane... | Terminate long running python threads | What is the recommended way to terminate unexpectedly long running threads in python ? I can't use SIGALRM, since
Some care must be taken if both
signals and threads are used in the
same program. The fundamental thing to
remember in using signals and threads
simultaneously is: always perform
signal() operati... | [
"Since abruptly killing a thread that's in a blocking call is not feasible, a better approach, when possible, is to avoid using threads in favor of other multi-tasking mechanisms that don't suffer from such issues.\nFor the OP's specific case (the threads' job is to download web pages, and some threads block foreve... | [
6,
5,
1,
1
] | [] | [] | [
"multithreading",
"python"
] | stackoverflow_0001226091_multithreading_python.txt |
Q:
Python: urllib2 multipart/form-data and proxies
The Objective: A script which cycles through a list of proxies and sends a post request, containing a file to a PHP page on my server, which then calculates delivery time. It's a pretty useless script, but I am using it to teach myself about urllib2.
The Problem: So ... | Python: urllib2 multipart/form-data and proxies | The Objective: A script which cycles through a list of proxies and sends a post request, containing a file to a PHP page on my server, which then calculates delivery time. It's a pretty useless script, but I am using it to teach myself about urllib2.
The Problem: So far I have got multipart/form-data sending correctly ... | [
"you could add proxy installer like this, before requesting the page. \nfrom urllib2 import ProxyHandler,build_opener,install_opener\n\nPROXY=\"http://USERNAME:PASSWD@ADDRESS:PORT\"\n\nopener = build_opener(ProxyHandler({\"http\" : PROXY}))\n\ninstall_opener(opener)\n\n"
] | [
5
] | [] | [] | [
"multipartform_data",
"poster",
"proxy",
"python",
"urllib2"
] | stackoverflow_0001806729_multipartform_data_poster_proxy_python_urllib2.txt |
Q:
Read from source.sql write to destiantion.sql with python script?
I Have a file source.sql
INSERT INTO `Tbl_ABC` VALUES (1, 0, 'MMB', '2 MB INTERNATIONAL', NULL, NULL, 0)
INSERT INTO `Tbl_ABC` VALUES (2, 12, '3D STRUCTURES', '3D STRUCTURES', NULL, NULL, 0)
INSERT INTO `Tbl_ABC` VALUES (2, 0, '2 STRUCTURES', '2D ST... | Read from source.sql write to destiantion.sql with python script? | I Have a file source.sql
INSERT INTO `Tbl_ABC` VALUES (1, 0, 'MMB', '2 MB INTERNATIONAL', NULL, NULL, 0)
INSERT INTO `Tbl_ABC` VALUES (2, 12, '3D STRUCTURES', '3D STRUCTURES', NULL, NULL, 0)
INSERT INTO `Tbl_ABC` VALUES (2, 0, '2 STRUCTURES', '2D STRUCTURES', NULL, NULL, 0)
INSERT INTO `Tbl_ABC` VALUES (2, 111, '2D STR... | [
"You can read line by line and check if it is ends with 0) and match with regex for the other one.\nimport re\ndest=open(\"destination.sql\",\"w+\")\nfor line in open(\"source.sql\",\"r\"):\n if line.strip().endswith(\"0)\") and re.search(\"\\(\\d+, 0,\",line):\n dest.write(line)\n\n",
"Something like t... | [
1,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0001806761_python.txt |
Q:
CDN options for image resizing
Background:
I working on an application on Google App Engine. Its been going really well until I hit one of their limitations in file size -- 1MB. One of the components of my application resizes images, which have been uploaded by users. The files are directly uploaded to S3 (http://... | CDN options for image resizing | Background:
I working on an application on Google App Engine. Its been going really well until I hit one of their limitations in file size -- 1MB. One of the components of my application resizes images, which have been uploaded by users. The files are directly uploaded to S3 (http://developer.amazonwebservices.com/conn... | [
"Looks like I have found a service that provides what I am indeed looking for. Nirvanix provides an image resize API and even has a nice library for Google App Engine to use with their API. Just thought I would share my findings.\n",
"SteadyOffload does it as well.\n"
] | [
3,
3
] | [] | [] | [
"cdn",
"google_app_engine",
"image_manipulation",
"python",
"rest"
] | stackoverflow_0000493981_cdn_google_app_engine_image_manipulation_python_rest.txt |
Q:
Initialize a list of objects in Python
I'm a looking to initialize an array/list of objects that are not empty -- the class constructor generates data. In C++ and Java I would do something like this:
Object lst = new Object[100];
I've dug around, but is there a Pythonic way to get this done?
This doesn't work li... | Initialize a list of objects in Python | I'm a looking to initialize an array/list of objects that are not empty -- the class constructor generates data. In C++ and Java I would do something like this:
Object lst = new Object[100];
I've dug around, but is there a Pythonic way to get this done?
This doesn't work like I thought it would (I get 100 references ... | [
"There isn't a way to implicitly call an Object() constructor for each element of an array like there is in C++ (recall that in Java, each element of a new array is initialised to null for reference types).\nI would say that your list comprehension method is the most Pythonic:\nlst = [Object() for i in range(100)]\... | [
45,
16,
2,
0
] | [] | [] | [
"arrays",
"initialization",
"list",
"python"
] | stackoverflow_0001807026_arrays_initialization_list_python.txt |
Q:
Scrapy BaseSpider: How does it work?
This is the BaseSpider example from the Scrapy tutorial:
from scrapy.spider import BaseSpider
from scrapy.selector import HtmlXPathSelector
from dmoz.items import DmozItem
class DmozSpider(BaseSpider):
domain_name = "dmoz.org"
start_urls = [
"http://www.dmoz.org/... | Scrapy BaseSpider: How does it work? | This is the BaseSpider example from the Scrapy tutorial:
from scrapy.spider import BaseSpider
from scrapy.selector import HtmlXPathSelector
from dmoz.items import DmozItem
class DmozSpider(BaseSpider):
domain_name = "dmoz.org"
start_urls = [
"http://www.dmoz.org/Computers/Programming/Languages/Python/Boo... | [
"Probably you meant item = FirmItem() instead of item = FirmItem?\n"
] | [
17
] | [] | [] | [
"python",
"scrapy",
"web_crawler"
] | stackoverflow_0001806235_python_scrapy_web_crawler.txt |
Q:
App Engine model filtering with Django
hi i am using django app engine patch i have set up a simple model as follows
class Intake(db.Model):
intake=db.StringProperty(multiline=False, required=True)
#@permerlink
def get_absolute_url(self):
return "/timekeeper/%s/" % self.intake
class Meta:
... | App Engine model filtering with Django | hi i am using django app engine patch i have set up a simple model as follows
class Intake(db.Model):
intake=db.StringProperty(multiline=False, required=True)
#@permerlink
def get_absolute_url(self):
return "/timekeeper/%s/" % self.intake
class Meta:
db_table = "Intake"
verbose_nam... | [
"You need to insert a space between the field name and the operator in your filter arguments - eg, use .filter('intake =') instead of .filter('intake='). With an equality filter, you can also leave it out entirely, as in .filter('intake'). Without the space, the equals sign is taken to be part of the field name.\n"... | [
2
] | [] | [] | [
"django",
"django_models",
"google_app_engine",
"python"
] | stackoverflow_0001807545_django_django_models_google_app_engine_python.txt |
Q:
Why do I need to save this model before adding it to another one?
In django, I'm trying to do something like this:
# if form is valid ...
article = form.save(commit=False)
article.author = req.user
product_name = form.cleaned_data['product_name']
try:
article.product = Component.objects.get(name=product_name)... | Why do I need to save this model before adding it to another one? | In django, I'm trying to do something like this:
# if form is valid ...
article = form.save(commit=False)
article.author = req.user
product_name = form.cleaned_data['product_name']
try:
article.product = Component.objects.get(name=product_name)
except:
article.product = Component(name=product_name)
article.sa... | [
"The way the Django ManyToManyField works is that it creates an extra table. So say you have two models, ModelA and ModelB. If you did...\nModelA.model_b = models.ManyToManyField(ModelB)\n\nWhat Django actually does behind the scenes is it creates a table... app_modela_modelb with three columns: id, model_a_id, ... | [
4,
1,
1
] | [] | [] | [
"django",
"models",
"python"
] | stackoverflow_0001806937_django_models_python.txt |
Q:
Split UTF-8 encoded string got from unichr
I have a set of unicode numbers , I need to convert them to UTF-8 and print the result in to split them in to hex values.
eg: Unicode 0x80 should be converted to UTF-8 and printed as (0xc2,0x80)
I tried following
str(unichr(0x80).encode('utf-8')).split(r'\x')[0]
But it d... | Split UTF-8 encoded string got from unichr | I have a set of unicode numbers , I need to convert them to UTF-8 and print the result in to split them in to hex values.
eg: Unicode 0x80 should be converted to UTF-8 and printed as (0xc2,0x80)
I tried following
str(unichr(0x80).encode('utf-8')).split(r'\x')[0]
But it does get split in to ['c2','80']. But it gives me... | [
"You want like this? could be done with list comprehensions.\n>>> [\"%x\"%ord(x) for x in unichr(0x80).encode('utf-8')]\n['c2', '80']\n\n",
"To generate a list of the hexadecimal values of the characters in your UTF8-encoded string, use the following:\n>>> [hex(ord(x)) for x in unichr(0x80).encode('utf-8')]\n['0x... | [
2,
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0001808223_python.txt |
Q:
how pylons decorator works
from decorator import decorator
from pylons.decorators.util import get_pylons
def allowed_roles(roles):
def wrapper(func, *args, **kwargs):
session = get_pylons(args).session
# edit pylons session here.
return func(*args, **kwargs)
return decorator(wrappe... | how pylons decorator works | from decorator import decorator
from pylons.decorators.util import get_pylons
def allowed_roles(roles):
def wrapper(func, *args, **kwargs):
session = get_pylons(args).session
# edit pylons session here.
return func(*args, **kwargs)
return decorator(wrapper)
Can anyone explain how it wo... | [
"Like any other decorator works - \nA decorator is a function which receives a function as an argument, and returns another function. \nThe returned function will \"take the place\" from the original function.\nSince the desired effect with a decoratos is usually to be able to run some code before and after the ori... | [
2
] | [] | [] | [
"pylons",
"python"
] | stackoverflow_0001807760_pylons_python.txt |
Q:
python and Oracle
I would like to be able to connect to Oracle 10.1.0.2.0 (which is installed on different machine) via python.
My comp is running on Ubuntu 9.04 Jaunty with Python 2.6 installed.
I have downloaded and unpacked instantclient-basic-linux32-10.1.0.5-20060511.zip , set LD_LIBRARY_PATH and ORACLE_HOME ... | python and Oracle | I would like to be able to connect to Oracle 10.1.0.2.0 (which is installed on different machine) via python.
My comp is running on Ubuntu 9.04 Jaunty with Python 2.6 installed.
I have downloaded and unpacked instantclient-basic-linux32-10.1.0.5-20060511.zip , set LD_LIBRARY_PATH and ORACLE_HOME to point to the directo... | [
"I believe OCIClientVersion requires Oracle 10g release 2, but you're using release 1.\nIt looks like cx_Oracle binary you downloaded has been compiled with -DORACLE_10GR2 which makes it include the OCIClientVersion call. Since this is a compile-time-only option there should really be downloads for 10g and 10gR2 se... | [
4,
2
] | [] | [] | [
"django",
"oracle",
"python"
] | stackoverflow_0001796198_django_oracle_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.