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. Regular expression
How to find everything which goes after symols #TR= and it is inside [ ] using re module. For example #TR=[ dfgg dfgddfg dgfgf dgdgdg dfgfg ]
A:
import re
txt = '#TR=[ dfgg ] a kuku #TR=[ala ma kota]'
If you want to search for just the first occurrence of this pattern, use:
matche... | Python. Regular expression | How to find everything which goes after symols #TR= and it is inside [ ] using re module. For example #TR=[ dfgg dfgddfg dgfgf dgdgdg dfgfg ]
| [
"import re\ntxt = '#TR=[ dfgg ] a kuku #TR=[ala ma kota]'\n\nIf you want to search for just the first occurrence of this pattern, use:\nmatches = re.search('#TR=\\[([^\\]]*)\\]', txt)\nif matches:\n print(repr(matches.group(1)))\n' dfgg dfg '\n\nIf you want to find all occurrences in the text, use:\nmatches = re... | [
5,
1,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0004272091_python_regex.txt |
Q:
Exploitable Python Functions
This question is similar to Exploitable PHP Functions.
Tainted data comes from the user, or more specifically an attacker. When a tainted variable reaches a sink function, then you have a vulnerability. For instance a function that executes a sql query is a sink, and GET/POST vari... | Exploitable Python Functions | This question is similar to Exploitable PHP Functions.
Tainted data comes from the user, or more specifically an attacker. When a tainted variable reaches a sink function, then you have a vulnerability. For instance a function that executes a sql query is a sink, and GET/POST variables are sources of taint.
What ... | [
"eval and exec are the classics. However, open and file can be abused too:\nopen('/proc/kcore', 'w').write('0' * 1000 * 1000 * 1000)\n\nThen there are the os, sys, subprocess, and dircache modules. Pretty much anything that touches the filesystem or can be used to turn data into executable code (like os.system) is ... | [
14,
14,
10,
6,
3
] | [] | [] | [
"auditing",
"python",
"security"
] | stackoverflow_0004207485_auditing_python_security.txt |
Q:
Is it possible to implemet a Ruby-like internal DSL in Python?
Is it possible to implement an internal DSL in a language without macros? Has anyone succeeded in implementing a Ruby-like internal DSL in python?
I am trying to develop a simple state machine with a more intuitive syntax like:
start -> Event -> Next ... | Is it possible to implemet a Ruby-like internal DSL in Python? | Is it possible to implement an internal DSL in a language without macros? Has anyone succeeded in implementing a Ruby-like internal DSL in python?
I am trying to develop a simple state machine with a more intuitive syntax like:
start -> Event -> Next ->Action
| [
"I am having a bit of trouble grokking your question.\nAFAIU, you are asking\n\nCan you implement a Ruby-like internal DSL in a language without macros?\n\nAnd the answer to that is obviously \"Yes\", since Ruby doesn't have macros.\n"
] | [
1
] | [] | [] | [
"dsl",
"python",
"ruby"
] | stackoverflow_0004271939_dsl_python_ruby.txt |
Q:
how to upload muti file using html5 on google app engine(python)
this is my code, the upload.py:
class MyModel(db.Model):
data = db.BlobProperty(required=True)
mimetype = db.StringProperty(required=True)
class BaseRequestHandler(webapp.RequestHandler):
def render_template(self, filename, template_args=N... | how to upload muti file using html5 on google app engine(python) | this is my code, the upload.py:
class MyModel(db.Model):
data = db.BlobProperty(required=True)
mimetype = db.StringProperty(required=True)
class BaseRequestHandler(webapp.RequestHandler):
def render_template(self, filename, template_args=None):
if not template_args:
template_args = {}
path = os... | [
"AFAIK, the request.POST['file'] should be a dictionary of files, i.e. POST['file'] should have keys as names of the files uploaded and the value should be the contents of the files respectively, i.e. POST['file']['avatar.png'] = ... # raw image data.\nI don't know what's the functionality provided by the GAE HTTP ... | [
1,
1
] | [] | [] | [
"google_app_engine",
"html",
"python",
"upload"
] | stackoverflow_0004269565_google_app_engine_html_python_upload.txt |
Q:
Mail send-receive in Google App Engine (reply_to field)
I am reading about mail send/receive in GAE and I have a question about how to use reply_to and the form of the email address replied to.
My register.py simply writes message.sender to database:
class User(db.Model):
userEmail = db.StringProperty()
us... | Mail send-receive in Google App Engine (reply_to field) | I am reading about mail send/receive in GAE and I have a question about how to use reply_to and the form of the email address replied to.
My register.py simply writes message.sender to database:
class User(db.Model):
userEmail = db.StringProperty()
userEmailContent = db.StringProperty()
class Register(InboundM... | [
"The reply_to address should be a canonical email address without the /_ah/mail/ prefix and it follows the same restriction of the sender mail address.\n\nThe sender address of a message must be the\n email address of an administrator for\n the application, the Google Account\n email address of the current user... | [
3,
1
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0004271958_google_app_engine_python.txt |
Q:
How to write PIL image filter for plain pgm format?
How can I write a filter for python imaging library for pgm plain ascii format (P2). Problem here is that basic PIL filter assumes constant number of bytes per pixel.
My goal is to open feep.pgm with Image.open(). See http://netpbm.sourceforge.net/doc/pgm.html o... | How to write PIL image filter for plain pgm format? | How can I write a filter for python imaging library for pgm plain ascii format (P2). Problem here is that basic PIL filter assumes constant number of bytes per pixel.
My goal is to open feep.pgm with Image.open(). See http://netpbm.sourceforge.net/doc/pgm.html or below.
Alternative solution is that I find other well d... | [
"The way I currently deal with this is through numpy:\n\nRead image into a 2D numpy array. You don't need to use numpy, but I've found it easier to use than the regular Python 2D arrays\nConvert 2D numpy array into PIL.Image object using PIL.Image.fromarray\n\nIf you insist on using PIL.Image.open, you could write... | [
6
] | [] | [] | [
"image",
"image_processing",
"python",
"python_imaging_library"
] | stackoverflow_0004270700_image_image_processing_python_python_imaging_library.txt |
Q:
is there a python module can output to teminal like linux "top" or "more"?
May I know is there a such module in python?
Basically I need print database table records to terminal in python supporting page-up and page-down key press.
Also I need a highlighted title bar on top of the screen looks like "top" output, ... | is there a python module can output to teminal like linux "top" or "more"? | May I know is there a such module in python?
Basically I need print database table records to terminal in python supporting page-up and page-down key press.
Also I need a highlighted title bar on top of the screen looks like "top" output, and the output will auto scale to fit the terminal window resize.
Thanks!
| [
"Take a look at this, might be helpful:\n\nhttp://docs.python.org/library/curses.html\n\nAlso, take a look at these question:\n\nText Progress Bar in the Console\n\nand a link from it:\n\nhttp://nadiana.com/animated-terminal-progress-bar-in-python\n\n",
"Python's curses module is a wrapper around GNU's ncurses C ... | [
3,
0
] | [] | [] | [
"python",
"terminal"
] | stackoverflow_0004273254_python_terminal.txt |
Q:
A shorter way to express this? C = A if A else B
I find myself repeating this a lot:
val = x if x else y
Sometimes x goes several levels deep into a class or dictionary so it gets very long:
val = obj.elements[0].something if obj.elements[0].something else y
It looks ugly and forces me to type a lot more. Any kn... | A shorter way to express this? C = A if A else B | I find myself repeating this a lot:
val = x if x else y
Sometimes x goes several levels deep into a class or dictionary so it gets very long:
val = obj.elements[0].something if obj.elements[0].something else y
It looks ugly and forces me to type a lot more. Any known ways to shorten this? Perhaps a builtin like this ... | [
"The or operator returns the first argument that converts to True:\nval = x or y\n\nE.g.:\n>>> None or 'OK'\n'OK'\n\n",
"This to me seems like a case of trying to make code a little too terse. I'd probably do something like this:\nx = a.b.c.d[0]\nval = x if x else y\n\nOne extra line, and a whole lot less to dig... | [
16,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0004272970_python.txt |
Q:
Problem getting emacs to recognize mix of python and html code
I started working on "Django 1.0 Web Site Development" and have gotten my server to work, but when I'm editing my views.py file, I have a difficulty editing the python code in emacs.
The problem seems to be a line that contains the triple quotes ('''):... | Problem getting emacs to recognize mix of python and html code | I started working on "Django 1.0 Web Site Development" and have gotten my server to work, but when I'm editing my views.py file, I have a difficulty editing the python code in emacs.
The problem seems to be a line that contains the triple quotes ('''):
def main_page(request):
output = u'''
<html>
[more lines ... | [
"Take the hint. \nYou're doing it wrong. Get to the templates business in chapter 3 before even thinking about tools to support what you're doing.\nStop trying to embed HTML in your view functions and you'll find that emacs is no longer confused. Move as quickly as possible to the next chapter. Stop messing with... | [
4
] | [] | [] | [
"django",
"emacs",
"html",
"python"
] | stackoverflow_0004273374_django_emacs_html_python.txt |
Q:
Resource use in file read/write with python, options and considerations
I'm developing in python, still new to the game, and I want to make sure I tackle this problem correctly. I'll gladly accept all advice.
Imagine trying to use data stored across multiple flat files, in many cases with a combined size exceedin... | Resource use in file read/write with python, options and considerations | I'm developing in python, still new to the game, and I want to make sure I tackle this problem correctly. I'll gladly accept all advice.
Imagine trying to use data stored across multiple flat files, in many cases with a combined size exceeding 20-35 gb. In the most general case, these files may be delimited (csv, tab... | [
"\nIs there an efficiency gain from using compiled C to do the read operations? \n\nNot really. The limitation will be I/O bandwidth and Python uses the underlying C libraries.\n\nIf the file comes in a .zip or .gz, should the entire file be decompressed prior to reading and writing, or do you leave it compressed ... | [
2
] | [] | [] | [
"mysql",
"performance",
"python",
"python_multithreading"
] | stackoverflow_0004273259_mysql_performance_python_python_multithreading.txt |
Q:
SQLite date storage and conversion
I am having design problems with date storage/retrieval using Python and SQLite.
I understand that a SQLite date column stores dates as text in ISO format
(ie. '2010-05-25'). So when I display a British date (eg. on a web-page) I
convert the date using
datetime.datetime.strptime... | SQLite date storage and conversion | I am having design problems with date storage/retrieval using Python and SQLite.
I understand that a SQLite date column stores dates as text in ISO format
(ie. '2010-05-25'). So when I display a British date (eg. on a web-page) I
convert the date using
datetime.datetime.strptime(mydate,'%Y-%m-%d').strftime('%d/%m/%Y')... | [
"If you set detect_types=sqlite3.PARSE_DECLTYPES in sqlite3.connect,\nthen the connection will try to convert sqlite data types to Python data types\nwhen you draw data out of the database.\nThis is a very good thing since its much nicer to work with datetime objects than\nrandom date-like strings which you then ha... | [
17,
5
] | [] | [] | [
"python",
"sqlite"
] | stackoverflow_0004272908_python_sqlite.txt |
Q:
Automatically echo the result of an assignment statement in IPython
Is there a way to make IPython automatically echo the result of an assignment statement?
For example, in MATLAB, ending an assignment statement without a semicolon prints the result of the assignment, and putting a semicolon at the end of the stat... | Automatically echo the result of an assignment statement in IPython | Is there a way to make IPython automatically echo the result of an assignment statement?
For example, in MATLAB, ending an assignment statement without a semicolon prints the result of the assignment, and putting a semicolon at the end of the statement suppresses any output.
>> b=1+2
b =
3
>> b=1+2;
>>
I want ... | [
"Assignment is purely a statement in Python, so you'd have to compile the code, walk the AST, find the assignment, and then print the variable's repr() after running it.\n"
] | [
0
] | [] | [] | [
"ipython",
"python"
] | stackoverflow_0004273695_ipython_python.txt |
Q:
Python Virtualenv
When creating a virtual environment with no -site packages do I need to install mysql & the mysqldb adapter which is in my global site packages in order to use them in my virtual project environment?
A:
You can also (on UNIX) symlink specific packages from the Python site-packages into your vi... | Python Virtualenv | When creating a virtual environment with no -site packages do I need to install mysql & the mysqldb adapter which is in my global site packages in order to use them in my virtual project environment?
| [
"You can also (on UNIX) symlink specific packages from the Python site-packages into your virtualenv's site-packages.\n",
"Yes. you will need to install then exclusively for this virtualenv.\nSee: http://virtualenv.openplans.org/#the-no-site-packages-option\nIf you build with virtualenv --no-site-packages ENV it ... | [
5,
0
] | [] | [] | [
"python",
"virtualenv"
] | stackoverflow_0004273729_python_virtualenv.txt |
Q:
Python - When duplicate items are identified, which object does a set or frozenset take?
I have a user-defined class MyClass that has a __hash__ and __eq__ implementation that ensures that, for example:
>>> a = MyClass([100, 99, 98, 97])
>>> b = MyClass([99, 98, 97, 100])
>>> a.__hash__() == b.__hash__()
True
>>> ... | Python - When duplicate items are identified, which object does a set or frozenset take? | I have a user-defined class MyClass that has a __hash__ and __eq__ implementation that ensures that, for example:
>>> a = MyClass([100, 99, 98, 97])
>>> b = MyClass([99, 98, 97, 100])
>>> a.__hash__() == b.__hash__()
True
>>> a == b
True
Question: if I do the following:
>>> x = [a, b]
>>> set(x)
can I count on set ke... | [
"In these cases of hash-based things, it uses both __hash__ and __eq__.\nIf __hash__ and __eq__ are both the same, then the first one it gets to in the iterable is taken. When it gets to the next, it checks if it already has it and decides yes.\n>>> class Same(object):\n... def __init__(self, value):\n... ... | [
3,
1,
1
] | [] | [] | [
"hash",
"python",
"set"
] | stackoverflow_0004273686_hash_python_set.txt |
Q:
Python re.sub use non-greedy mode (.*?) with end of string ($) it comes greedy!
Code:
str = '<br><br />A<br />B'
print(re.sub(r'<br.*?>\w$', '', str))
It is expected to return <br><br />A, but it returns an empty string ''!
Any suggestion?
A:
Greediness works from left to right, but not otherwise. It basically ... | Python re.sub use non-greedy mode (.*?) with end of string ($) it comes greedy! | Code:
str = '<br><br />A<br />B'
print(re.sub(r'<br.*?>\w$', '', str))
It is expected to return <br><br />A, but it returns an empty string ''!
Any suggestion?
| [
"Greediness works from left to right, but not otherwise. It basically means \"don't match unless you failed to match\". Here's what's going on:\n\nThe regex engine matches <br at the start of the string.\n.*? is ignored for now, it is lazy.\nTry to match >, and succeeds.\nTry to match \\w and fails. Now it's intere... | [
7,
1
] | [] | [] | [
"python",
"regex",
"regex_greedy"
] | stackoverflow_0004273987_python_regex_regex_greedy.txt |
Q:
Dynamically calling nested functions based on arguments
If I have the following Python class:
class Test(object):
funcs = {
"me" : "action",
"action": "action",
"say" : "say",
"shout" : "say"
}
def dispatch(self, cmd):
def say:
print "Nested Say... | Dynamically calling nested functions based on arguments | If I have the following Python class:
class Test(object):
funcs = {
"me" : "action",
"action": "action",
"say" : "say",
"shout" : "say"
}
def dispatch(self, cmd):
def say:
print "Nested Say"
def action:
print "Nested Action"
... | [
"I would probably do something like this:\ndef register(dict_, *names):\n def dec(f):\n m_name = f.__name__\n for name in names:\n dict_[name] = m_name\n return f\n return dec\n\nclass Test(object):\n\n commands = {}\n\n @register(commands, 'foo', 'fu', 'fOo')\n def _h... | [
4,
2
] | [] | [] | [
"closures",
"nested",
"python"
] | stackoverflow_0004273998_closures_nested_python.txt |
Q:
How can you convert a list of poorly formed data pairs into a dict?
I'd like to take a string containing tuples that are not well separated and convert them into a dictionary.
s = "banana 4 apple 2 orange 4"
d = {'banana':'4', 'apple':'2', 'orange':'4'}
I'm running into a problem because the space is used to separ... | How can you convert a list of poorly formed data pairs into a dict? | I'd like to take a string containing tuples that are not well separated and convert them into a dictionary.
s = "banana 4 apple 2 orange 4"
d = {'banana':'4', 'apple':'2', 'orange':'4'}
I'm running into a problem because the space is used to separate the values as well as the pairs. What's the right trick?
| [
"Simplistic but serves the solution here:\nUse split()\n>>> s = \"banana 4 apple 2 orange 4\"\n>>> s.split()\n['banana', '4', 'apple', '2', 'orange', '4']\n>>> \n\nGroup them ( Some error checks required here)\n>>> k = [(x[t], x[t+1]) for t in range(0, len(x) -1, 2)]\n>>> k\n[('banana', '4'), ('apple', '2'), ('oran... | [
5,
3,
0
] | [
"I don't know python but it should be possible to convert the string into an array , then iterate thru the array to create a dictionary by alternating name & value.\n"
] | [
-1
] | [
"python"
] | stackoverflow_0004274207_python.txt |
Q:
How to order a Dictionary based on the value?
I have a Dictionary like
tel = {'jack': 18, 'sape': 4139, 'sar': 2139, 'mape': 319, 'sipe': 29}
I want to order it based on the value in descending order like
tel = {'sape': 4139, 'sar': 2139, 'mape': 319, 'sipe': 29 'jack': 18}
I searched the web a lot and found un... | How to order a Dictionary based on the value? | I have a Dictionary like
tel = {'jack': 18, 'sape': 4139, 'sar': 2139, 'mape': 319, 'sipe': 29}
I want to order it based on the value in descending order like
tel = {'sape': 4139, 'sar': 2139, 'mape': 319, 'sipe': 29 'jack': 18}
I searched the web a lot and found unrelated results. Is there any built-in function the... | [
"There is no way to order a dict. Either use an ordered dictionary, or some other ordered sequence.\nsorted(tel.iteritems(), key=operator.itemgetter(1), reverse=True)\n\n",
"In python 2.7 or 3.1, you can use OrderedDict:\nfrom collections import OrderedDict\nfrom operator import itemgetter\ntel = {'jack': 18, 'sa... | [
3,
3,
1
] | [] | [] | [
"dictionary",
"django",
"python"
] | stackoverflow_0004274554_dictionary_django_python.txt |
Q:
Mercurial Extension with no/default options
Say I want an extension that I can execute as follows: hg sayhi
I tried the following, but it tells me there are invalid arguments:
def sayhi(ui, repo, node, **opts):
"""Says Hello"""
ui.write("hi")
cmdtable = {
"sayhi": (sayhi, [], ''... | Mercurial Extension with no/default options | Say I want an extension that I can execute as follows: hg sayhi
I tried the following, but it tells me there are invalid arguments:
def sayhi(ui, repo, node, **opts):
"""Says Hello"""
ui.write("hi")
cmdtable = {
"sayhi": (sayhi, [], '')
}
It seems no matter what I do, I need to give... | [
"Ok, got a fix. I removed the node parameter from the method signature and it works.\n"
] | [
5
] | [] | [] | [
"mercurial_extension",
"python"
] | stackoverflow_0004274517_mercurial_extension_python.txt |
Q:
Cannot add new items into python dictionary
Hi I'm new to python. I am trying to add different key value pairs to a dictionary depending on different if statements like the following:
def getContent(file)
for line in file:
content = {}
if line.startswith(titlestart):
line = line.r... | Cannot add new items into python dictionary | Hi I'm new to python. I am trying to add different key value pairs to a dictionary depending on different if statements like the following:
def getContent(file)
for line in file:
content = {}
if line.startswith(titlestart):
line = line.replace(titlestart, "")
line = line.re... | [
"You reinitialize content for every line, move the initialization outside of the loop:\ndef getContent(file)\n\n content = {}\n\n for line in file:\n\netc.\n"
] | [
8
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0004275132_dictionary_python.txt |
Q:
Should I use Perl or Python for network monitoring?
I want to have some work done on the Network front, pinging numerous computers on a LAN and retrieving data about the response time. Which would be the most useful and productive to work with: Perl or Python?
A:
I agree that it is pretty subjective which progra... | Should I use Perl or Python for network monitoring? | I want to have some work done on the Network front, pinging numerous computers on a LAN and retrieving data about the response time. Which would be the most useful and productive to work with: Perl or Python?
| [
"I agree that it is pretty subjective which programming language you use - essentially I would rather get the job done as quickly and efficiently as possible which making it supportable - so that depends on your infrastructure...\nCan I suggest that you look at Nagios rather than re-inventing the wheel yourself? \n... | [
22,
14,
12,
7,
3,
2,
1,
1
] | [
"I'd say that if you need something quick and dirty that's up and running by this afternoon, then perl is probably the better language.\nHowever for developing solid application that's easy to maintain and extend and that you can build on over time, I'd go with python.\nThis is of course assuming you know both lang... | [
-1
] | [
"networking",
"perl",
"python",
"scripting_language"
] | stackoverflow_0000491380_networking_perl_python_scripting_language.txt |
Q:
my url pattern throwing an error
my url pattern is www.example.com/[any digit or number] say www.eaxmple.com/slug
my urls.py is:
url(r'^(?P<[a-z0-9>+)/$', mymethod),
But is saying:- bad character in group name
another query is that i want to process the slug coming with the url. Based on that value i will render... | my url pattern throwing an error | my url pattern is www.example.com/[any digit or number] say www.eaxmple.com/slug
my urls.py is:
url(r'^(?P<[a-z0-9>+)/$', mymethod),
But is saying:- bad character in group name
another query is that i want to process the slug coming with the url. Based on that value i will render different template. Is it possible? H... | [
"I don't know python, so can't say what the url function does, but your regex should probably look like this:\nurl(r'^(?P<someName>[a-z0-9]+)/$', mymethod)\n\nThis will capture the the [a-z0-9] Group of characters under the name \"someName\".\nBTW: What about upper case characters?\n"
] | [
7
] | [] | [] | [
"django",
"python"
] | stackoverflow_0004275545_django_python.txt |
Q:
call a function in Python syntax
Hey im writing a small program in python 2.6 and i have defined
2 helper functions which does almost all i want, for instance
def helper1:
...
def helper2:
...
Now my problem is that i want to make a new function that gather the two functions in one function so i dont ha... | call a function in Python syntax | Hey im writing a small program in python 2.6 and i have defined
2 helper functions which does almost all i want, for instance
def helper1:
...
def helper2:
...
Now my problem is that i want to make a new function that gather the two functions in one function so i dont have to write (in shell):
list(helper1(... | [
"def function(arg1, arg2):\n return list(helper1(helper2(arg1, arg2)))\n\nshould work.\n",
"function = lambda x, y: list(helper1(helper2(x, y)))\n\n",
"This is an example of the higher order function compose. It's handy to have laying around\ndef compose(*functions):\n \"\"\" Returns the composition of fu... | [
8,
2,
2
] | [] | [] | [
"python",
"syntax"
] | stackoverflow_0004275764_python_syntax.txt |
Q:
Regular expression for Indian landline Phone numbers
Indian landline phone numbers are in one of the following format.
080 25478965
0416-2565478
08172-268032
Whats the simplest Regex to accommodate all these. The space between the city code and the phone number can be a whitespace or a "-". It would be great if t... | Regular expression for Indian landline Phone numbers | Indian landline phone numbers are in one of the following format.
080 25478965
0416-2565478
08172-268032
Whats the simplest Regex to accommodate all these. The space between the city code and the phone number can be a whitespace or a "-". It would be great if the regex can accommodate the case without the separator be... | [
"For these three formats exactly:\n^\\d{3}([ -]\\d\\d|\\d[ -]\\d|\\d\\d[ -])\\d{6}$\n\nAnother, more liberal option, is to allow a space or a dash after each digit (except maybe the last):\n^(\\d[ -]?){10}\\d$\n\n",
"I'd probably just use /^(\\d+[ \\-]+\\d+)$/ if you don't need to verify the number of digits etc.... | [
4,
2,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0004276057_python_regex.txt |
Q:
How to download a webpage that require username and password?
For example, I want to download this page after inserting username and password:
http://forum.ubuntu-it.org/
I have tryed with wget but doesn't work.
Is there a solution with python ?
You can test with these username and password:
username: johnconnor
... | How to download a webpage that require username and password? | For example, I want to download this page after inserting username and password:
http://forum.ubuntu-it.org/
I have tryed with wget but doesn't work.
Is there a solution with python ?
You can test with these username and password:
username: johnconnor
password: hellohello
| [
"You can use the urllib2 module and with that it is possible do to basic and form based authentication (with cookies support).\nHere is a nice tutorial on your issue.\n",
"Try the mechanize module. It's basically a programmatic browser interface.\n",
"Like @robert says, use mechanize. \nTo get you started:\nfr... | [
2,
1,
1
] | [] | [] | [
"python",
"urllib",
"urllib2"
] | stackoverflow_0004275955_python_urllib_urllib2.txt |
Q:
os.walk exclude .svn folders
I got a script that I want to use to change a repeated string throughout a project folder structure. Once changed then I can check this into SVN. However when I run my script it goes into the .svn folders which I want it to ingore. How can I achieve this? Code below, thanks.
import os
... | os.walk exclude .svn folders | I got a script that I want to use to change a repeated string throughout a project folder structure. Once changed then I can check this into SVN. However when I run my script it goes into the .svn folders which I want it to ingore. How can I achieve this? Code below, thanks.
import os
import sys
replacement = "newStri... | [
"Try this:\nfor root, subFolders, files in os.walk(rootdir):\n if '.svn' in subFolders:\n subFolders.remove('.svn')\n\nAnd then continue processing. \n",
"Err... what?\n\nWhen topdown is True, the caller can modify the dirnames list in-place (perhaps using del or slice assignment), and walk() will only re... | [
31,
8
] | [] | [] | [
"python"
] | stackoverflow_0004276255_python.txt |
Q:
How to convert Python threading code to multiprocessing code?
I need to convert a threading application to a multiprocessing application for multiple reasons (GIL, memory leaks). Fortunately the threads are quite isolated and only communicate via Queue.Queues. This primitive is also available in multiprocessing so... | How to convert Python threading code to multiprocessing code? | I need to convert a threading application to a multiprocessing application for multiple reasons (GIL, memory leaks). Fortunately the threads are quite isolated and only communicate via Queue.Queues. This primitive is also available in multiprocessing so everything looks fine. Now before I enter this minefield I'd like ... | [
"Answer to part 1:\nEverything that has to pass through a multiprocessing.Queue (or Pipe or whatever) has to be picklable. This includes basic types such as tuples, lists and dicts. Also classes are supported if they are top-level and not too complicated (check the details). Trying to pass lambdas around will fail ... | [
5
] | [] | [] | [
"gil",
"multiprocessing",
"multithreading",
"python"
] | stackoverflow_0004097227_gil_multiprocessing_multithreading_python.txt |
Q:
help to convert python ctypes struct to 64bit
I found this script attached to a thread in the fontforge-users mailing list. It does exactly what I want. However, it seems only to work on 32bit systems, and I would really like to use it on my 64bit system.
I've done a little reading but I can't work out how I s... | help to convert python ctypes struct to 64bit | I found this script attached to a thread in the fontforge-users mailing list. It does exactly what I want. However, it seems only to work on 32bit systems, and I would really like to use it on my 64bit system.
I've done a little reading but I can't work out how I should modify this script (presumably the stuct?) to... | [
"The question is whether FONTFORGE_CONFIG_USE_LONGDOUBLE is defined or not in /usr/include/fontforge/config.h. If it is defined, then the code's definition is correct. On my amd64 linux installation, neither FONTFORGE_CONFIG_USE_LONGDOUBLE nor FONTFORGE_CONFIG_USE_DOUBLE are defined, so I needed to change\nreal = ... | [
2
] | [] | [] | [
"32bit_64bit",
"ctypes",
"python",
"struct"
] | stackoverflow_0004275556_32bit_64bit_ctypes_python_struct.txt |
Q:
Tried to embed python in a visual studio 2010 c++ file, exits with code 1
I am trying to embed some python code in a c++ application i am developing with ms visual studio c++ 2010. But when i run the program, it exits with code 0x01 when i call Py_initialize().
I dont know how to find out what went wrong. the help... | Tried to embed python in a visual studio 2010 c++ file, exits with code 1 | I am trying to embed some python code in a c++ application i am developing with ms visual studio c++ 2010. But when i run the program, it exits with code 0x01 when i call Py_initialize().
I dont know how to find out what went wrong. the help file says, Py_Initialize can't return an error value, it only fails fataly.
Bu... | [
"Is there simple 'hello world' type example of the Py_Initilize code in the python sdk you can start with?\nThat will at least tell you if you have the compiler environment setup correctly, or if the error is in your usage.\n",
"Well, i finally found out what went wrong.\nI did compile my python27_d.dll with the... | [
0,
0
] | [] | [] | [
"c++",
"python",
"python_c_api",
"python_embedding",
"visual_studio_2010"
] | stackoverflow_0004216988_c++_python_python_c_api_python_embedding_visual_studio_2010.txt |
Q:
Nested conversation list with django
Hay I have a model like this
def Photo(models.Model):
# Photo object fields...
def PhotoThread(models.Model):
photo = models.ForeignKey(Photo)
message = models.TextField(blank=True)
reply_to = models.ForeignKey('self', related_name='replies', null=True, blank=T... | Nested conversation list with django | Hay I have a model like this
def Photo(models.Model):
# Photo object fields...
def PhotoThread(models.Model):
photo = models.ForeignKey(Photo)
message = models.TextField(blank=True)
reply_to = models.ForeignKey('self', related_name='replies', null=True, blank=True)
votes = models.IntegerField()
As... | [
"Welcome to recursion. Here's a common solution\ndef thread_plus_replies( someThread ):\n return someThread, [ thread_plus_replies(r) for r in someThread.replies.ordered('votes').all() ]\n\nThis kind of thing returns a list of 2-tuples for each thread and all of it's replies. \nIf a reply has no subsidiary thr... | [
2,
1
] | [] | [] | [
"django",
"foreign_keys",
"list",
"nested",
"python"
] | stackoverflow_0004277243_django_foreign_keys_list_nested_python.txt |
Q:
Which text editor for python development?
Possible Duplicate:
What IDE to use for Python?
Which is the preferred text editor for python development, Vim, emacs or any other ?
A:
There is no preferred editor for anything. It's whatever your personal preference is. I personally prefer emacs with python-mode beca... | Which text editor for python development? |
Possible Duplicate:
What IDE to use for Python?
Which is the preferred text editor for python development, Vim, emacs or any other ?
| [
"There is no preferred editor for anything. It's whatever your personal preference is. I personally prefer emacs with python-mode because it makes indenting easier (and indenting is kind of important in python), but anything will work.\n",
"VIM! And not for Python only.\n",
"The best editor is the one that work... | [
0,
0,
0
] | [] | [] | [
"editor",
"ide",
"python",
"text"
] | stackoverflow_0004278223_editor_ide_python_text.txt |
Q:
CPython from Java?
I need to call CPython code from Java. What tools/APIs/libraries exist out there to help me do this?
Jython is not an option since the Python code is heavily dependent upon numpy.
edit 1: The main() function should be Java, not Python (i.e. I need to embed CPython into Java, not vice versa.)
edi... | CPython from Java? | I need to call CPython code from Java. What tools/APIs/libraries exist out there to help me do this?
Jython is not an option since the Python code is heavily dependent upon numpy.
edit 1: The main() function should be Java, not Python (i.e. I need to embed CPython into Java, not vice versa.)
edit 2: I should also menti... | [
"You can take a look at using Jepp to embed CPython into Java. Read documentation here.\nedit: For windows the project has prebuilt binaries for Python 2.4, 2.5, and 2.6. For Linux/Unix systems, you have to build it yourself.\n"
] | [
4
] | [
"You probably want to read the docs on embedding a CPython interpreter. Also, on how to load native libraries in Java (was that called JNI?)\n"
] | [
-1
] | [
"cpython",
"java",
"jython",
"numpy",
"python"
] | stackoverflow_0004278182_cpython_java_jython_numpy_python.txt |
Q:
Python GUI with custom render/drawing
I am looking for a Python GUI library that I can rewrite the rendering / drawing.
It has to support basic widgets (buttons, combo boxes, list boxes, text editors, scrolls,), layout management, event handling
The thing that I am looking for is to use my custom Direct3D and Open... | Python GUI with custom render/drawing | I am looking for a Python GUI library that I can rewrite the rendering / drawing.
It has to support basic widgets (buttons, combo boxes, list boxes, text editors, scrolls,), layout management, event handling
The thing that I am looking for is to use my custom Direct3D and OpenGL renderer for all of the GUI's drawing / ... | [
"I don't know what are you working at, so maybe this is not what you're looking for, but:\nHave you considered using Blender + its Game Engine?\nIt supports Python scripting, and provides some APIs to create \"standard\" GUIs too, while allowing you to do a lot of cool stuff with 3d models. This could be especially... | [
2,
1,
1,
0,
0
] | [] | [] | [
"directx",
"opengl",
"python",
"user_interface"
] | stackoverflow_0004203614_directx_opengl_python_user_interface.txt |
Q:
Vix API in python
I need to import VIX api libs in ubuntu using ctypes module.
When I do:
vix = CDLL('libvix.so')
It fails: "cannot open..."
what´s the problem??? libvix.so and python module are in the same directory
thanks!!
A:
If the rest of the error is something like
OSError: libvix.so: cannot open shared... | Vix API in python | I need to import VIX api libs in ubuntu using ctypes module.
When I do:
vix = CDLL('libvix.so')
It fails: "cannot open..."
what´s the problem??? libvix.so and python module are in the same directory
thanks!!
| [
"If the rest of the error is something like \nOSError: libvix.so: cannot open shared object file: No such file or directory\n\nThen you probably need to put the location of the libvix.so in the LD_LIBRARY_PATH environment variable.\n"
] | [
0
] | [] | [] | [
"python",
"vix"
] | stackoverflow_0004277895_python_vix.txt |
Q:
Python: Selecting numbers with associated probabilities
Possible Duplicates:
Random weighted choice
Generate random numbers with a given (numerical) distribution
I have a list of list which contains a series on numbers and there associated probabilities.
prob_list = [[1, 0.5], [2, 0.25], [3, 0.05], [4, 0.01], [5... | Python: Selecting numbers with associated probabilities |
Possible Duplicates:
Random weighted choice
Generate random numbers with a given (numerical) distribution
I have a list of list which contains a series on numbers and there associated probabilities.
prob_list = [[1, 0.5], [2, 0.25], [3, 0.05], [4, 0.01], [5, 0.09], [6, 0.1]]
for example in prob_list[0] the number 1... | [
"I'm going to assume the probabilities all add up to 1. If they don't, you're going to have to scale them accordingly so that they do.\nFirst generate a uniform random variable [0, 1] using random.random(). Then pass through the list, summing the probabilities. The first time the sum exceeds the random number, retu... | [
5,
3,
1,
1
] | [] | [] | [
"probability",
"python",
"random",
"statistics"
] | stackoverflow_0004276787_probability_python_random_statistics.txt |
Q:
making a python gui for ffdshow
I was thinking that for a learning project for myself, I would try to make a GUI for ffdshow on linux, using tkinter. Wanted to make sure this project would be feasible first, before I get halfway through and run into something that cant be done in python.
Basic idea is to have a si... | making a python gui for ffdshow | I was thinking that for a learning project for myself, I would try to make a GUI for ffdshow on linux, using tkinter. Wanted to make sure this project would be feasible first, before I get halfway through and run into something that cant be done in python.
Basic idea is to have a single GUI window with a bunch of drop ... | [
"That is precisely the type of thing that python and Tkinter excel at. And yes, a relative newbie can easily do a task like that.\n"
] | [
1
] | [] | [] | [
"ffdshow",
"python",
"tkinter",
"user_interface"
] | stackoverflow_0004278461_ffdshow_python_tkinter_user_interface.txt |
Q:
Removing unknown characters from a text file
I have a large number of files containing data I am trying to process using a Python script.
The files are in an unknown encoding, and if I open them in Notepad++ they contain numerical data separated by a load of 'null' characters (represented as NULL in white on black... | Removing unknown characters from a text file | I have a large number of files containing data I am trying to process using a Python script.
The files are in an unknown encoding, and if I open them in Notepad++ they contain numerical data separated by a load of 'null' characters (represented as NULL in white on black background in Notepad++).
In order to handle this... | [
"You are opening the file in text mode. That means that the first Ctrl-Z character is considered as an end-of-file character. Specify 'rb' instead of 'r' in open().\n",
"I don't know if this will work for sure, but you could try using the IO methods in the codec module:\nimport codec\n\ninFile = codec.open(<SAME ... | [
5,
1,
1
] | [] | [] | [
"character_encoding",
"python",
"windows"
] | stackoverflow_0004278636_character_encoding_python_windows.txt |
Q:
ImportError: cannot import name output
iam using fabric 0.9.1 version on windows to do some deployment related stuff.
But the moment iam about to run "fab hello" iam facing the following error
D:\pythonscripts>fab hello
Traceback (most recent call last):
File "C:\Python26\Scripts\fab-script.py", line 8, in <mod... | ImportError: cannot import name output | iam using fabric 0.9.1 version on windows to do some deployment related stuff.
But the moment iam about to run "fab hello" iam facing the following error
D:\pythonscripts>fab hello
Traceback (most recent call last):
File "C:\Python26\Scripts\fab-script.py", line 8, in <module>
load_entry_point('fabric==0.9.1', '... | [
"It seems to be this issue: http://code.fabfile.org/issues/show/194, probably it's not Fabric related but PyCrypto or Python64. If it is PyCrypto then the easiest thing is to download a binary version from http://www.voidspace.org.uk/python/modules.shtml#pycrypto and install it and download pywin32 from http://sour... | [
1
] | [] | [] | [
"fabric",
"python"
] | stackoverflow_0003051387_fabric_python.txt |
Q:
Tracing an IP address in Python
For a college project for my course on Introduction to Programming, I decided to make a small software that traces the IP address and puts them nicely on a GUI (PyQt). Not a big deal I know, but still I like the idea.
So I Googled around and found MaxMind's IP and their free offerin... | Tracing an IP address in Python | For a college project for my course on Introduction to Programming, I decided to make a small software that traces the IP address and puts them nicely on a GUI (PyQt). Not a big deal I know, but still I like the idea.
So I Googled around and found MaxMind's IP and their free offering and the pygeoip, which is an API fo... | [
"I would have preferred \"pygeoip\", because it allows you to develop a complete solution locally. Of course, you will need to keep the database.\nIf you do not want to keep the database locally, you will have to depend on an external service to query for location of an IP. This will keep your solution small but de... | [
2,
1
] | [] | [] | [
"ip_address",
"python"
] | stackoverflow_0004279583_ip_address_python.txt |
Q:
coordinates changed when migrating from pygame+rabbyt to pyglet+rabbyt
I'm working on a 2D game and decided to switch from SDL to OpenGL. I took rabbyt as an opengl wrapper for rendering my sprites and using pymunk (chipmunk) for my physics. I used pygame for creating the window and rabbyt for drawing the sprit... | coordinates changed when migrating from pygame+rabbyt to pyglet+rabbyt | I'm working on a 2D game and decided to switch from SDL to OpenGL. I took rabbyt as an opengl wrapper for rendering my sprites and using pymunk (chipmunk) for my physics. I used pygame for creating the window and rabbyt for drawing the sprites on the screen.
I discovered that with pygame+rabbyt the (0,0) coordinate ... | [
"As l33tnerd suggested the origin can be placed at the center with glTranslatef...\nI added the following below my screen initialization code:\npyglet.gl.glTranslatef(width/2, height/2, 0)\n\nThanks!\n"
] | [
0
] | [] | [] | [
"opengl",
"pygame",
"pyglet",
"python"
] | stackoverflow_0004279516_opengl_pygame_pyglet_python.txt |
Q:
I need a good web development framework for Python
I'm a C/C++ developer and I also have experience developing web apps with C#, ASP.NET MVC and fluent nhibernate. I'm looking for non-MS alternatives for web development and I'm really interested in python so I went out after Django but I've been told that Django m... | I need a good web development framework for Python | I'm a C/C++ developer and I also have experience developing web apps with C#, ASP.NET MVC and fluent nhibernate. I'm looking for non-MS alternatives for web development and I'm really interested in python so I went out after Django but I've been told that Django makes it difficult for me to personalize my HTML (not sur... | [
"go for django.\n\ndoes all you wanted,\nhas perfect docs and even free book,\npartially runs on appengine,\nhas really large user base,\nit is mature: \n\n\ndb sharding, (With model router)\nxss protection in forms\nmemcache, \nlocalisation, \nwell tested support for unicode, \nreally easy to learn because of leve... | [
7,
2,
1,
1,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0004260324_python.txt |
Q:
danger of recursive functions
Often people say that it's not recommended to use recursive functions in python (recursion depth restrictions, memory consumption, etc)
I took a permutation example from this question.
def all_perms(str):
if len(str) <=1:
yield str
else:
for perm in all_perms(str[1:]):
... | danger of recursive functions | Often people say that it's not recommended to use recursive functions in python (recursion depth restrictions, memory consumption, etc)
I took a permutation example from this question.
def all_perms(str):
if len(str) <=1:
yield str
else:
for perm in all_perms(str[1:]):
for i in range(len(perm)+1):
... | [
"Recursion is good for problems that lend themselves to clean, clear, recursive implementations. But like all programming you must perform some algorithm analysis to understand the performance characteristics. In the case of recursion, besides number of operations you must also estimate the maximum stack depth.\nMo... | [
8,
8,
2,
0
] | [] | [] | [
"python",
"recursion"
] | stackoverflow_0004278327_python_recursion.txt |
Q:
Python, how to setup hooks for tracing I/O Events
My app downloads files, creates files as final/intermediate data. I would like to setup a hook (outside the app), to alert/log whenever my app does any I/O events - like writing a file, deleting a file, downloading a file from the file server. I use the urllib to r... | Python, how to setup hooks for tracing I/O Events | My app downloads files, creates files as final/intermediate data. I would like to setup a hook (outside the app), to alert/log whenever my app does any I/O events - like writing a file, deleting a file, downloading a file from the file server. I use the urllib to retrieve fits files from the data servers.
| [
"If you know where the file will be downloaded to, one solution could be to use inotify. In particular, pyinotify seems interesting. I don't know if CentOS has a recent enough version of the Linux kernel for this to work though.\n",
"If you want a list of your process file operations, you can use FileMon or Pro... | [
2,
1
] | [] | [] | [
"centos",
"events",
"hook",
"io",
"python"
] | stackoverflow_0004277743_centos_events_hook_io_python.txt |
Q:
how to customize django admin?
I have a two field in models.py
password_protected = models.BooleanField(default=False)
password = models.CharField(max_length=50)
I want to write admin.py in such a manner:
-- if password_protected is True: Then the password field should be enable.
-- if password_protected is False... | how to customize django admin? | I have a two field in models.py
password_protected = models.BooleanField(default=False)
password = models.CharField(max_length=50)
I want to write admin.py in such a manner:
-- if password_protected is True: Then the password field should be enable.
-- if password_protected is False: Then the password field should be ... | [
"You can try what @luc suggested, but you can also try adding a widget to password_protected field:\npassword = models.CharField(default=False, widget=forms.TextInput())\n\n-- and adjust its attributes:\nform = MyForm(request.POST)\nif form.is_valid():\n # do some nice stuff here\nelse:\n if form['password_pr... | [
1,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0004274707_django_python.txt |
Q:
Ordering from a method
Hay all, i have a simple model like this
def Article(models.Model):
upvotes = models.ManyToManyField(User, related_name='article_upvotes')
downvotes = models.ManyToManyField(User, related_name='article_downvotes')
def votes(self):
return self.upvotes - self.downvotes
Wi... | Ordering from a method | Hay all, i have a simple model like this
def Article(models.Model):
upvotes = models.ManyToManyField(User, related_name='article_upvotes')
downvotes = models.ManyToManyField(User, related_name='article_downvotes')
def votes(self):
return self.upvotes - self.downvotes
With the view i can do things ... | [
"You can sort the list after the query returns the results:\narticle_votes = sorted(article.votes, key=lambda a: a.votes())\n\nsorted takes a list and sorts it. You can provide a custom function that takes an element and returns the value to use when comparing elements. lambda a: a.votes() is an anonymous functio... | [
2,
0
] | [] | [] | [
"django",
"function",
"python",
"sql_order_by"
] | stackoverflow_0004270675_django_function_python_sql_order_by.txt |
Q:
Is there an easier way to package with Python?
I tried to package a django app today. It's a big baby, and with the setup file, I have to manually write all packages and sub packages in the 'package' parameter. Then I have to find a way to copy fixtures, htmls / Css / image files, documentations, etc.
It's a terri... | Is there an easier way to package with Python? | I tried to package a django app today. It's a big baby, and with the setup file, I have to manually write all packages and sub packages in the 'package' parameter. Then I have to find a way to copy fixtures, htmls / Css / image files, documentations, etc.
It's a terrible way to work. We are computer scientists, we auto... | [
"At the very least if you use setuptools (an alternative to the stdlib's distutils) you get an awesome function called find_packages() which when ran from the package root returns a list of package names in dot-notation suitable for the packages parameter.\nHere is an example:\n# setup.py\n\nfrom setuptools import ... | [
5,
1,
0
] | [
"I've been doing a bit of research myself on Django deployment methods recently.\nI found these two resources very useful:\n\nhttp://www.caktusgroup.com/blog/2010/04/22/basic-django-deployment-with-virtualenv-fabric-pip-and-rsync/ - A basic overview of how to use virtualenv, pip and fabric to do easy Django deploym... | [
-1
] | [
"django",
"installation",
"package",
"pip",
"python"
] | stackoverflow_0003885504_django_installation_package_pip_python.txt |
Q:
Python's underlying hash data structure for dictionaries
I am build a very large dictionary and I am performing many checks to see if a key is in the structure and then adding if it unique or incrementing a counter if it is identical.
Python uses a hash data structure to store dictionaries (not to be confused wit... | Python's underlying hash data structure for dictionaries | I am build a very large dictionary and I am performing many checks to see if a key is in the structure and then adding if it unique or incrementing a counter if it is identical.
Python uses a hash data structure to store dictionaries (not to be confused with a cryptographic hash function). Lookups are O(1), but if ... | [
"The only way to be sure would be to implement both and check, but my informed guess is that the dictionary will be faster, because a binary search tree has cost O(log(n)) for lookup and insertion, and I think that except under the most pessimal of situations (such as massive hash collisions) the hash table's O(1) ... | [
27,
4,
4,
2,
2
] | [] | [] | [
"algorithm",
"data_structures",
"performance",
"python"
] | stackoverflow_0004279358_algorithm_data_structures_performance_python.txt |
Q:
Python: how to cut off sequences of more than 2 equal characters in a string
I'm looking for an efficient way to chance a string such that all sequences of more than 2 equal characters are cut off after the first 2.
Some input->output examples are:
hellooooooooo -> helloo
woooohhooooo -> woohhoo
I'm currently lo... | Python: how to cut off sequences of more than 2 equal characters in a string | I'm looking for an efficient way to chance a string such that all sequences of more than 2 equal characters are cut off after the first 2.
Some input->output examples are:
hellooooooooo -> helloo
woooohhooooo -> woohhoo
I'm currently looping over the characters, but it's a bit slow. Does anyone have another solution ... | [
"Edit: after applying helpful comments\nimport re\n\ndef ReplaceThreeOrMore(s):\n # pattern to look for three or more repetitions of any character, including\n # newlines.\n pattern = re.compile(r\"(.)\\1{2,}\", re.DOTALL) \n return pattern.sub(r\"\\1\\1\", s)\n\n\n(original response here) \nTry somethi... | [
8,
2,
1,
0,
0
] | [] | [] | [
"python",
"regex",
"string"
] | stackoverflow_0004278313_python_regex_string.txt |
Q:
Is there a more pythonic way to find the point in a list which is closest to another point?
I have a list of 2d points, and would like to find the one which is closest to a given point. The code (get_closest_point()) below does what I want. But is there a nicer way to do this in python?
class Circle(object):
... | Is there a more pythonic way to find the point in a list which is closest to another point? | I have a list of 2d points, and would like to find the one which is closest to a given point. The code (get_closest_point()) below does what I want. But is there a nicer way to do this in python?
class Circle(object):
def __init__(self, pos):
self.position = pos
class Point(object):
..
def comput... | [
"You can use the key argument to the min() function:\nEdit: after some consideration, this should be a method of your Point class, and i'll fix some other obvious deficiencies:\nclass Point(object):\n def get_closest_point(self, points):\n return min(points, key=self.compute_distance_to)\n\nor, to do this... | [
19
] | [] | [] | [
"python"
] | stackoverflow_0004280554_python.txt |
Q:
receiving a linux signal and interating with threads
hello to you all :)
i have a program that have a n number of threads(could be a lot) and they do a pretty extensive job. My problem is that sometimes some people turn off or reboot the server(the program runs all day in the company servers) i know that there is... | receiving a linux signal and interating with threads | hello to you all :)
i have a program that have a n number of threads(could be a lot) and they do a pretty extensive job. My problem is that sometimes some people turn off or reboot the server(the program runs all day in the company servers) i know that there is a way to make a handler for the linux signals i want to k... | [
"The best way of handling this is not requiring any shutdown actions at all.\nFor example, your signal handler for (e.g.) SIGTERM or SIGQUIT can just call _exit and quit the process with no clean-up.\nUnder Linux (with non-ancient threads) when one thread calls _exit (or exit if you really want) other threads get s... | [
3,
1,
1
] | [] | [] | [
"linux",
"multithreading",
"python",
"signals"
] | stackoverflow_0004280432_linux_multithreading_python_signals.txt |
Q:
raw_input causing EOFError after creating exe with py2exe
After creating an exe from a script with py2exe raw_input() is causing an EOFError.
How can I avoid this?
File "test.py", line 143, in main
raw_input("\nPress ENTER to continue ")
EOFError: EOF when reading a line
A:
>>> help(raw_input)
Help on built... | raw_input causing EOFError after creating exe with py2exe | After creating an exe from a script with py2exe raw_input() is causing an EOFError.
How can I avoid this?
File "test.py", line 143, in main
raw_input("\nPress ENTER to continue ")
EOFError: EOF when reading a line
| [
">>> help(raw_input)\nHelp on built-in function raw_input in module __builtin__:\n\nraw_input(...)\n raw_input([prompt]) -> string\n\n Read a string from standard input. The trailing newline is stripped.\n If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.\n On Unix, GNU readlin... | [
4
] | [] | [] | [
"eoferror",
"py2exe",
"python"
] | stackoverflow_0004280889_eoferror_py2exe_python.txt |
Q:
Python web application: How to keep state
I wrote a WSGI compatible web application using web.py that loads a few dozen MB data into memory during startup.
It works quite well with the web.py integrated server.
However, using Apache 2 + mod_wsgi, every single request reloads the data, essentially starting the prog... | Python web application: How to keep state | I wrote a WSGI compatible web application using web.py that loads a few dozen MB data into memory during startup.
It works quite well with the web.py integrated server.
However, using Apache 2 + mod_wsgi, every single request reloads the data, essentially starting the program again. Due to the loading time of several s... | [
"\"Is it inherent to mod_wsgi?\" No. It's inherent in HTTP \nSince you didn't post your mod_wsgi configuration, it's impossible to say what you did wrong.\nI can only guess that you didn't use daemon mode.\nSee http://code.google.com/p/modwsgi/wiki/ConfigurationGuidelines#Defining_Process_Groups for more informatio... | [
1
] | [] | [] | [
"apache",
"mod_wsgi",
"python",
"web.py"
] | stackoverflow_0004281102_apache_mod_wsgi_python_web.py.txt |
Q:
What specific issue try zope folks to solve with TAL, TALES & METAL
TAL, TALES and METAL are all three the zope templating language. The thing that I don't understand is why so much troubles. I don't understand the spirit of ZTL, any tips ?
one more question : is there a standalone library that try to achieve the ... | What specific issue try zope folks to solve with TAL, TALES & METAL | TAL, TALES and METAL are all three the zope templating language. The thing that I don't understand is why so much troubles. I don't understand the spirit of ZTL, any tips ?
one more question : is there a standalone library that try to achieve the same thing that ZTL but outside the Zope ecosystem ?
| [
"The core idea of tal/tales is to have proper valid (x)html. All the template functionality is in attributes or namespaced elements. HTML editors should work just fine with these templates. Let's give an example. First tal/tales:\n<ul>\n <li tal:repeat=\"customer customers\">\n <a href=\"\"\n tal:attri... | [
4,
1
] | [] | [] | [
"python",
"template_metal",
"template_tal",
"zope",
"zpt"
] | stackoverflow_0004281275_python_template_metal_template_tal_zope_zpt.txt |
Q:
Python framework for visualising/animating particles in cartesian space
I have data representing the position of particles for multiple time steps and need to create an animation showing the movement of these particles.
Are there any frameworks or toolkits (ideally Python based) out there does something like this ... | Python framework for visualising/animating particles in cartesian space | I have data representing the position of particles for multiple time steps and need to create an animation showing the movement of these particles.
Are there any frameworks or toolkits (ideally Python based) out there does something like this out of the box, or at least something that makes it easy to quickly plot spri... | [
"Pyprocessing is a Python treatment of the processing Java animation library. The processing development environment includes some very nice examples of implementing a particle system.\n",
"Houdini by Side Effects Software is an industry-grade 3D animation application with excellent Python bindings, Python expre... | [
4,
2,
2,
2,
1
] | [] | [] | [
"3d",
"animation",
"opengl",
"python",
"visualization"
] | stackoverflow_0004277564_3d_animation_opengl_python_visualization.txt |
Q:
Best Python IDE on Linux
Possible Duplicate:
What IDE to use for Python?
Can anybody suggest me good Python IDE for Linux?
A:
Probably the new PyCharm from the makers of IntelliJ and ReSharper.
A:
I haven't played around with it much but eclipse/pydev feels nice.
| Best Python IDE on Linux |
Possible Duplicate:
What IDE to use for Python?
Can anybody suggest me good Python IDE for Linux?
| [
"Probably the new PyCharm from the makers of IntelliJ and ReSharper.\n",
"I haven't played around with it much but eclipse/pydev feels nice.\n"
] | [
21,
8
] | [] | [] | [
"python"
] | stackoverflow_0004281612_python.txt |
Q:
List Search Optimization
first = [(1, text, text, 1, 2, 3),
(1, text, text, 1, 0, 3), ... (6054, text, text, 2, 2, 3)]
second = (1, 2, 3, 4, 5 ... 5412)
Is there a faster way to do this:
data = [x for x in first if x[0] in second]
A:
Try this:
first = [(1, text, text, 1, 2, 3),
(1, text, tex... | List Search Optimization | first = [(1, text, text, 1, 2, 3),
(1, text, text, 1, 0, 3), ... (6054, text, text, 2, 2, 3)]
second = (1, 2, 3, 4, 5 ... 5412)
Is there a faster way to do this:
data = [x for x in first if x[0] in second]
| [
"Try this:\nfirst = [(1, text, text, 1, 2, 3), \n (1, text, text, 1, 0, 3), ... (1054, text, text, 2, 2, 3)]\nsecond = (1, 2, 3, 4, 5 ... 5412)\nsecond_set = set(second)\ndata = [x for x in first if x[0] in second_set]\n\nAssume first has m elements and second has n elements.\nSets are hashed, so searching ... | [
6,
1
] | [] | [] | [
"optimization",
"python"
] | stackoverflow_0004281679_optimization_python.txt |
Q:
PyNotify not working from cron?
I've written a script that uses pynotify to give an alert. it works just fine when I run it (python script.py), but when run from cron with 00 * * * * myname python ~/scripts/script.py, it doesn't work! I haven't a clue why. Here's the snippet:
if os.path.isfile(os.path.expa... | PyNotify not working from cron? | I've written a script that uses pynotify to give an alert. it works just fine when I run it (python script.py), but when run from cron with 00 * * * * myname python ~/scripts/script.py, it doesn't work! I haven't a clue why. Here's the snippet:
if os.path.isfile(os.path.expanduser('~/.thumbnails/normal')+'/'+th... | [
"I'm not that deep into cron jobs, but I know a bit about pynotify. It uses libnotify and some DBUS stuff, so somewhere it makes the call to the DBUS and iirc it also passes the display id on which the notification should be shown.\nNow, by default cron's don't work with GUI applications, you have to specify a disp... | [
5
] | [] | [] | [
"cron",
"pynotify",
"python"
] | stackoverflow_0004281821_cron_pynotify_python.txt |
Q:
What's the relationship between numbers.Integral and int in builtins module in Python 3
I am a newbie for Python, I am a little confuse of the relationship between numbers.Integral and int in builtins module.
Then my questions are:
What the relationship between numbers.Integral and int? Is it similiar with the re... | What's the relationship between numbers.Integral and int in builtins module in Python 3 | I am a newbie for Python, I am a little confuse of the relationship between numbers.Integral and int in builtins module.
Then my questions are:
What the relationship between numbers.Integral and int? Is it similiar with the relationship between Integer and int in Java (Integer is just a wrapper class for int)?
When to... | [
"Since you sound like you know Java: numbers.Integral defines the \"interface\" (it's really a generalization of interfaces, called \"Abstract Base Class\" (ABC)) for integral numbers. It's not a concrete type that you can instantiate.\nThe only builtin type that implements this interface is int. \nWith isinstance(... | [
3
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0004281955_python_python_3.x.txt |
Q:
Unexpected output when filtering Python list: What am I doing wrong?
I am trying to filter a list, here is the code:
test=['aaa','bbb','ccc','ddd','footer','header']
def rm_hf(x): return x != 'footer'
filter(rm_hf,test)
Results in :
>>>['aaa','bbb','ccc','ddd','header']
That is expected result, finding 'foo... | Unexpected output when filtering Python list: What am I doing wrong? | I am trying to filter a list, here is the code:
test=['aaa','bbb','ccc','ddd','footer','header']
def rm_hf(x): return x != 'footer'
filter(rm_hf,test)
Results in :
>>>['aaa','bbb','ccc','ddd','header']
That is expected result, finding 'footer' in the list and remove it.
Now I want to remove both 'header' and 'fo... | [
"Your logic is correct because you think like a human. Your computer does not. He reads every element from your list, then stumbles upon 'footer'. \"Is footer different than footer?\", he says. \"NO! It's the same string! It's evaluated to false. Let's see the next condition\". \"Is footer different than header? YE... | [
7,
4,
2,
1
] | [] | [] | [
"filtering",
"list",
"logic",
"python",
"sequence"
] | stackoverflow_0004281875_filtering_list_logic_python_sequence.txt |
Q:
Python MySQLDB executemany() works on mac, does nothing on linux
I run a number of SQL scripts in this manner:
db_conn = (created earlier)
cursor = db_conn.cursor()
script_file = open(join(script_path, script_name))
script_text = script_file.read()
script_file.close()
num_rows = cursor.executemany(script_text, ... | Python MySQLDB executemany() works on mac, does nothing on linux | I run a number of SQL scripts in this manner:
db_conn = (created earlier)
cursor = db_conn.cursor()
script_file = open(join(script_path, script_name))
script_text = script_file.read()
script_file.close()
num_rows = cursor.executemany(script_text, None)
This works like a charm on my Mac, but fails on Linux, executem... | [
"Check if you upgraded properly to 1.2.3 ... I remember reading that 1.2.2 had a bug that caused problems with executemany.\n"
] | [
0
] | [] | [] | [
"linux",
"macos",
"mysql",
"python"
] | stackoverflow_0004200691_linux_macos_mysql_python.txt |
Q:
Populate templates using list,detail generic views
I am creating a list of users present in my database, they are being displayed in user_list.html template through the use of generic views, but my models inherit many of its properties from other classes in the model. Now I want that when a user clicks on his name... | Populate templates using list,detail generic views | I am creating a list of users present in my database, they are being displayed in user_list.html template through the use of generic views, but my models inherit many of its properties from other classes in the model. Now I want that when a user clicks on his name he should be redirected to the user_detail.html page an... | [
"If i understand you correctly, you want to display information about the employee which is stored in other models.\nI assume you know that you can pre-filter in the view and send an extra context variable with a queryset. using your existing line extra_context =\"EC_list\": EmergencyContact.objects.all() selects t... | [
0
] | [] | [] | [
"django",
"generics",
"python",
"views"
] | stackoverflow_0004274666_django_generics_python_views.txt |
Q:
Django: How to "extend" Group creation using Signals?
I am not sure if I am asking the right question. But is it possible to add "behaviors" when creating a Group in Django? I want want to create directories/files after creating a Group in the admin panel.
The "additional" behaviors (creating the directory/file) c... | Django: How to "extend" Group creation using Signals? | I am not sure if I am asking the right question. But is it possible to add "behaviors" when creating a Group in Django? I want want to create directories/files after creating a Group in the admin panel.
The "additional" behaviors (creating the directory/file) can happen after the Group was successfully added in the dat... | [
"Yes. Catch the post_save signal for the Group model, then do your processing in there.\n"
] | [
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0004282805_django_python.txt |
Q:
Using Django-openid-auth
I'm trying to implement openid login with Django and having some trouble. The library I'm trying to use now is Django-openid-auth. I haven't found any django+openid libraries that have much documentation. How can I actually go about using this as a login and store the information I need fo... | Using Django-openid-auth | I'm trying to implement openid login with Django and having some trouble. The library I'm trying to use now is Django-openid-auth. I haven't found any django+openid libraries that have much documentation. How can I actually go about using this as a login and store the information I need for my app based on the users th... | [
"The OpenID identity verification process most commonly uses the\n following steps:\n\nThe user enters their OpenID into a field on the consumer'ssite, and hits a login button.\nThe consumer site discovers the user's OpenID provider using\nthe Yadis protocol.\nThe consumer site sends the browser a redirect to the... | [
4
] | [] | [] | [
"django",
"openid",
"python"
] | stackoverflow_0004282056_django_openid_python.txt |
Q:
Catch PyGTK TreeView reorder
I have a simple gtk.TreeView with a gtk.ListStore model and set_reorderable(True), I want to catch the signal/event emited when the user reorder through drag&drop the list, but the documentation does not help much:
"The application can listen to these changes by connecting to the mode... | Catch PyGTK TreeView reorder | I have a simple gtk.TreeView with a gtk.ListStore model and set_reorderable(True), I want to catch the signal/event emited when the user reorder through drag&drop the list, but the documentation does not help much:
"The application can listen to these changes by connecting to the model's signals"
So I tried to connect... | [
"There is no way to do that in PyGTK currently. \"rows-reordered\" is the correct signal, but it is impossible to derive any information from it in PyGTK other than \"somehow reordered\". In C GTK+ you could use the same signal and get the required information in callback, but not in Python.\n",
"I too had this... | [
3,
0
] | [] | [] | [
"gtk",
"gtktreeview",
"pygtk",
"python"
] | stackoverflow_0002831779_gtk_gtktreeview_pygtk_python.txt |
Q:
Finding the consecutive substring match
I have say two strings;
str1="wild animals are trying to escape the deserted jungle to the sandy island"
str2="people are trying to escape from the smoky mountain to the sandy road"
In order to find the match between these two strings, kgrams of certain length(here 10) are ... | Finding the consecutive substring match | I have say two strings;
str1="wild animals are trying to escape the deserted jungle to the sandy island"
str2="people are trying to escape from the smoky mountain to the sandy road"
In order to find the match between these two strings, kgrams of certain length(here 10) are produced, their hashes are produced and the h... | [
"First make yourself a coverage mask consisting of 0 and 1 (or other characters if you prefer), then find the longest run of 1s with itertools.groupby().\n",
"Code following Ignacio's idea:\n#!/usr/bin/env python\n\nfrom itertools import groupby\n\nstr1 = 'wild animals are trying to escape the deserted jungle to ... | [
2,
0
] | [] | [] | [
"algorithm",
"python"
] | stackoverflow_0004280202_algorithm_python.txt |
Q:
Python process file and return specific items
Say i have a dict, dict is a dictonary with dictonary as value
dict = {'**Leon**':{'Name':'Leon L','**follow**':['Apple', 'PPy','Jack','Tommy']},'**Jack**':{'name':'Jack Y','**follow**':['Apple','Cruise','Jay']},'**Tommy**':{'name':'Tommy T','**follow**':['Hill']},'**... | Python process file and return specific items | Say i have a dict, dict is a dictonary with dictonary as value
dict = {'**Leon**':{'Name':'Leon L','**follow**':['Apple', 'PPy','Jack','Tommy']},'**Jack**':{'name':'Jack Y','**follow**':['Apple','Cruise','Jay']},'**Tommy**':{'name':'Tommy T','**follow**':['Hill']},'**Apple**':{'name':'Apple A','**follow**':['Jack']},*... | [
"I would suggest using a state machine, or more specifically pushdown automata. You would initialize the machine with the data dict, then for every line in the input file, you will transition into a new state and do the work specified, storing the result in the stack. Every step can access the data returned from th... | [
0
] | [] | [] | [
"file",
"python",
"python_twitter",
"twitter"
] | stackoverflow_0004281615_file_python_python_twitter_twitter.txt |
Q:
Convert a space-delimited tree to useful dict in python
I have an output (a list) of items, like such:
Root
Branch1
LeafA
LeafB
Branch2
LeafC
LeafZ
LeafD
They are all two-space delimited.
I want build a logical representation of this list without the leading spaces, and retain the parent... | Convert a space-delimited tree to useful dict in python | I have an output (a list) of items, like such:
Root
Branch1
LeafA
LeafB
Branch2
LeafC
LeafZ
LeafD
They are all two-space delimited.
I want build a logical representation of this list without the leading spaces, and retain the parent-child relationshiop.
A final possible result:
aDict = {
... | [
"Try this:\ntree = \"\"\"Root\n Branch1\n LeafA\n LeafB\n Branch2\n LeafC\n LeafZ\n LeafD\"\"\"\n\naDict = {}\niDict = {}\nfor line in tree.split(\"\\n\"):\n key = line.lstrip(\" \")\n indent = (len(line) - len(key)) / 2\n if indent == 0:\n aDict[key] = None\n else:\n aD... | [
4,
0
] | [] | [] | [
"python",
"whitespace"
] | stackoverflow_0004270970_python_whitespace.txt |
Q:
Including Psyco Files in distribution
I'm developing a game server in python. Since this server is distributed to other people who don't have much coding experience(or common sense) I try to include any modules I can into a pre-reqs folder in the project, so users can run the code without installing things. I trie... | Including Psyco Files in distribution | I'm developing a game server in python. Since this server is distributed to other people who don't have much coding experience(or common sense) I try to include any modules I can into a pre-reqs folder in the project, so users can run the code without installing things. I tried out python on my program, and noticed a s... | [
"The canonical way to distribute Python packages is to use distutils (for now anyway). You can specify psyco as a dependency and when people install your package, it will get pulled in. \n"
] | [
0
] | [] | [] | [
"distribution",
"packaging",
"psyco",
"python",
"windows"
] | stackoverflow_0004282474_distribution_packaging_psyco_python_windows.txt |
Q:
Installing python modules in GNU/Linux
installing python modules in GNU/Linux. Are there any good PDFs on installing modules? I would like to install some of these Python: 50 modules for all needs. I tried PIL http://effbot.org/downloads/Imaging-1.1.7.tar.gz but it did not work.
PS: what does community wiki mean?
... | Installing python modules in GNU/Linux | installing python modules in GNU/Linux. Are there any good PDFs on installing modules? I would like to install some of these Python: 50 modules for all needs. I tried PIL http://effbot.org/downloads/Imaging-1.1.7.tar.gz but it did not work.
PS: what does community wiki mean?
| [
"Most of those are probably already available as packages in your Linux distribution. You didn't mention which one you used. Typically, \"apt-get\" or \"yum\" would cover most current distributions. Read the man pages for those tools, and use the search features to find packages containing the name \"python\", or t... | [
4,
0
] | [] | [] | [
"linux",
"module",
"python"
] | stackoverflow_0003759810_linux_module_python.txt |
Q:
How can I start a python subprocess command on linux shell from within Django web app?
I have a web app which reads and displays log files generated by python test files. Currently I can launch the python files from cli and it works fine.
However I would like to be able to launch python tests from within the appl... | How can I start a python subprocess command on linux shell from within Django web app? | I have a web app which reads and displays log files generated by python test files. Currently I can launch the python files from cli and it works fine.
However I would like to be able to launch python tests from within the application.
At the minute I have a "Launch test" button which calls a function in the views.py ... | [
"There is not enough information here to give a proper answer, but a common problem here is that the web front-end (e.g. apache) is running as a different user than what you run under. Therefore the web handler doesn't have the permissions to ready the files in your home directory. It probably also lacks some impor... | [
1
] | [] | [] | [
"django",
"django_views",
"linux",
"python"
] | stackoverflow_0003750181_django_django_views_linux_python.txt |
Q:
Globally accessible object across all Celery workers / memory cache in Django
I have pretty standard Django+Rabbitmq+Celery setup with 1 Celery task and 5 workers.
Task uploads the same (I simplify a bit) big file (~100MB) asynchronously to a number of remote PCs.
All is working fine at the expense of using lots o... | Globally accessible object across all Celery workers / memory cache in Django | I have pretty standard Django+Rabbitmq+Celery setup with 1 Celery task and 5 workers.
Task uploads the same (I simplify a bit) big file (~100MB) asynchronously to a number of remote PCs.
All is working fine at the expense of using lots of memory, since every task/worker load that big file into memory separatelly.
What ... | [
"Why not simply stream the upload(s) from disk instead of loading the whole file in memory ?\n",
"It seems to me that what you need is memcached backed for django. That way each task in Celery will have access to it.\n",
"Maybe you can use threads instead of processes for this particular task. Since threads al... | [
2,
1,
0
] | [] | [] | [
"caching",
"celery",
"django",
"global_variables",
"python"
] | stackoverflow_0002500799_caching_celery_django_global_variables_python.txt |
Q:
Want to remove illegal tags from mp3 file using Python
How to acheive this in my mp3 files.
Artist:www.xyz.com
---->
Artist: Artist:free
downloads,free music,xyzhi.com
----> Artist:
Artist:Kurukuru Kan (Amma Na) -
www.musicxyx.com - ® Danaa
collections ®
----> Artist:
Kurukuru Kan (A... | Want to remove illegal tags from mp3 file using Python | How to acheive this in my mp3 files.
Artist:www.xyz.com
---->
Artist: Artist:free
downloads,free music,xyzhi.com
----> Artist:
Artist:Kurukuru Kan (Amma Na) -
www.musicxyx.com - ® Danaa
collections ®
----> Artist:
Kurukuru Kan (Amma Na) Artist:
Nan Pogiren - - ® Danna collections ®
... | [
"First you'll need a library to understand the MP3 format and allow you to edit the tags, maybe: http://id3-py.sourceforge.net/\nBeyond that, you'll just need to work on the string replacements.\nFor the ones you specified (including weird space requirements):\n#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nEXPECT... | [
0
] | [] | [] | [
"mp3",
"python",
"regex",
"string"
] | stackoverflow_0004283868_mp3_python_regex_string.txt |
Q:
check files for equality
what's the most elegant way to check to files for equality in Python?
Checksum? Bytes comparing? Think files wont' be larger than 100-200 MB
A:
What about filecmp module? It can do file comparison in many different ways with different tradeoffs.
And even better, it is part of the standar... | check files for equality | what's the most elegant way to check to files for equality in Python?
Checksum? Bytes comparing? Think files wont' be larger than 100-200 MB
| [
"What about filecmp module? It can do file comparison in many different ways with different tradeoffs.\nAnd even better, it is part of the standard library:\nhttp://docs.python.org/library/filecmp.html\n",
"use hashlib to get the md5 of each file, and compare the results. \n#! /bin/env python\nimport hashlib\ndef... | [
9,
6,
4,
1
] | [
"I would do checksum with MD5 (for example) instead of byte comaprasion plus the date check and depend on you needs name check.\n",
"What about shelling out to cmp?\nimport commands\nstatus, output = commands.getstatusoutput(\"/usr/bin/cmp file1 file2\")\nif (status == 0):\n print \"files are same\"\nelif (statu... | [
-2,
-2
] | [
"equality",
"file",
"python"
] | stackoverflow_0004283639_equality_file_python.txt |
Q:
Do i need Node.js in Python like I would with PHP?
I have been using PHP for some time now. And I have been thinking about learning Node.js to go along with it to use the non blocking idea for creating an online game or app. There is quite a bit of info on using the two together. Using Node as part of the back end... | Do i need Node.js in Python like I would with PHP? | I have been using PHP for some time now. And I have been thinking about learning Node.js to go along with it to use the non blocking idea for creating an online game or app. There is quite a bit of info on using the two together. Using Node as part of the back end of a game could really speed up some aspects of the gam... | [
"While Python can definitely be used for Asynchronous Programming, it doesn't feel natural, even with Twisted, if you compare it to Node.js it just doesn't look or feel that nice.\nSince you're planing on doing a real-time Web Game, you'll most likely will end up using WebSockets.\nWebSockets are based on HTTP and ... | [
9,
2,
2,
1,
0
] | [] | [] | [
"node.js",
"nonblocking",
"php",
"python",
"twisted"
] | stackoverflow_0004276205_node.js_nonblocking_php_python_twisted.txt |
Q:
How to use urllib2 to open an 'infinite' jpg?
I'm using urllib2 open to download some web pages. Unfortunately one page is an infinite stream (a set of live video frames) and urllib2 will not timeout because the open call succeeds, while the 'read' call hangs forever. Example code:
res = opener.open(encoded, tim... | How to use urllib2 to open an 'infinite' jpg? | I'm using urllib2 open to download some web pages. Unfortunately one page is an infinite stream (a set of live video frames) and urllib2 will not timeout because the open call succeeds, while the 'read' call hangs forever. Example code:
res = opener.open(encoded, timeout=timeout)
log('opened', url)
contents = res.rea... | [
"This sounds like a job for generators!\nImagine you have an infinate text file... lets call it test.txt now open('test.txt').read() will hang the machine and eventually crash, so why not yield line for line in this infinate stream in a generator e.g.\ndef yield_line(file):\n with open(file) as inp:\n for... | [
3,
3,
2,
0
] | [] | [] | [
"download",
"python",
"sockets",
"urllib2"
] | stackoverflow_0004284480_download_python_sockets_urllib2.txt |
Q:
Python (pygame): How can I delete a line?
I'm using pygame to create a small scene. Right now, I'm working with lines.
I have an array of lines which are drawn to the screen and when a line is deleted from the array, I would like the line to disappear from the screen.
The problem I've found is that the line is dr... | Python (pygame): How can I delete a line? | I'm using pygame to create a small scene. Right now, I'm working with lines.
I have an array of lines which are drawn to the screen and when a line is deleted from the array, I would like the line to disappear from the screen.
The problem I've found is that the line is drawn on the screen and remains static. I can't ... | [
"Although it does not seem very efficient, I think that the easiest and also the best way of doing it is by redrawing everything. In many many games the screen is totally redrawn at every frame, even without 3D cards (remember the old Doom games?). So drawing a few lines over a background will be very fast, even ... | [
4,
1,
0
] | [] | [] | [
"line",
"pygame",
"python"
] | stackoverflow_0004276342_line_pygame_python.txt |
Q:
Python: Recursion
although there's quite a bit of information about recursion on the web, I haven't found anything that I was able to apply to my problem. I am still very new to programming so please excuse me if my question is rather trivial.
Thanks for helping out :)
This is what I want to end up with:
listVaria... | Python: Recursion | although there's quite a bit of information about recursion on the web, I haven't found anything that I was able to apply to my problem. I am still very new to programming so please excuse me if my question is rather trivial.
Thanks for helping out :)
This is what I want to end up with:
listVariations(listOfItems, numb... | [
"You can use the product() function in itertools\n",
"from itertools import combinations_with_replacement\n\nThis function does exactly what you want.\n",
"You can use itertools.permutations to do this.\nfrom itertools import permutations\n\ndef listVariations(listOfItems, numberOfDigits):\n return [''.join(... | [
5,
0,
0
] | [] | [] | [
"concatenation",
"python",
"recursion"
] | stackoverflow_0004284719_concatenation_python_recursion.txt |
Q:
Which is the best python framework for developing Facebook application as on now
We are developing Facebook applications in python, my query is which is the best python framework for developing Facebook application as on now. which will run easily with GAE as well as with Django...
Thank you very much.
** edit ** ... | Which is the best python framework for developing Facebook application as on now | We are developing Facebook applications in python, my query is which is the best python framework for developing Facebook application as on now. which will run easily with GAE as well as with Django...
Thank you very much.
** edit **
I think my query was misunderstood.. We are looking for a best python based facebook ... | [
"Let's remove the facebook buzzword from the equation. If you need/want to leverage google's infrastructure, you use appengine. There are projects for django that allow you to access appengine services at a higher level of abstraction such as the datastore, blobstore etc... \nhttp://www.allbuttonspressed.com/projec... | [
0
] | [] | [] | [
"django",
"facebook",
"facebook_graph_api",
"python"
] | stackoverflow_0004282855_django_facebook_facebook_graph_api_python.txt |
Q:
Grabbing all files in a query using Python
I'm processing a large amount of files using Python. Data related to each other through their file names.
If I was to perform CMD command to perform this (in windoes) it would look something like:
DIR filePrefix_??.txt
And this would return all the file names I would nee... | Grabbing all files in a query using Python | I'm processing a large amount of files using Python. Data related to each other through their file names.
If I was to perform CMD command to perform this (in windoes) it would look something like:
DIR filePrefix_??.txt
And this would return all the file names I would need for that group.
Is there a similar function th... | [
"Have a look at the glob module.\nglob.glob(\"filePrefix_??.txt\")\n\nreturns a list of matching file names.\n"
] | [
5
] | [] | [] | [
"python"
] | stackoverflow_0004285567_python.txt |
Q:
Django forms
I had asked a question pertaining to this. But I think it would be better to ask my question directly.
I have a "User" table with manytomany relationship with two other tables "Domain" and "Groups".
So in the admin interface I see the Groups and Domains as 2 ModelMultipleChoiceFields.
But I want to pr... | Django forms | I had asked a question pertaining to this. But I think it would be better to ask my question directly.
I have a "User" table with manytomany relationship with two other tables "Domain" and "Groups".
So in the admin interface I see the Groups and Domains as 2 ModelMultipleChoiceFields.
But I want to present them on the ... | [
"I think the built-in widget CheckboxSelectMultiple does what you want. If it doesn't, you're going to have to create your own widget. The documentation for widgets is a good place to start. The easiest way to start is by copying an existing widget from the Django source and modifying it.\n",
"Well to be precise ... | [
2,
2,
1,
0,
0
] | [] | [] | [
"django",
"django_admin",
"python"
] | stackoverflow_0000627772_django_django_admin_python.txt |
Q:
Google App Engine - How to get a list of all app administrators?
I want to programmatically retrieve a list of all the app administrators from within the app. However, I've found no APIs in User Service section that can accomplish this. Is there any way or any undocumented API to do this?
A:
No, there is not an ... | Google App Engine - How to get a list of all app administrators? | I want to programmatically retrieve a list of all the app administrators from within the app. However, I've found no APIs in User Service section that can accomplish this. Is there any way or any undocumented API to do this?
| [
"No, there is not an API to programatically get a list of administrators for your app. However, you could create an augmented user model which includes extra information like this.\nI'm not sure why you need a list of all admins, but if you just wanted to e-mail them then you could use the send_mail_to_admins() fu... | [
2
] | [] | [] | [
"django",
"google_app_engine",
"python"
] | stackoverflow_0004285723_django_google_app_engine_python.txt |
Q:
Test out small snippets of Django code
I am still in the development phase of a Django App. Before even writing my views.py, I test them out to see if my models are correctly defined. This I do it in the terminal by invoking
python manage.py shell
But oh so often I make some syntax error prompting me to abort the... | Test out small snippets of Django code | I am still in the development phase of a Django App. Before even writing my views.py, I test them out to see if my models are correctly defined. This I do it in the terminal by invoking
python manage.py shell
But oh so often I make some syntax error prompting me to abort the shell ctrl-D & retype everything. This proc... | [
"How about writing unit tests? You can execute them easily with one command. You can probably get started by reading the django manual chapter on testing\n",
"By all means create a trial.py for simple experimentation, then after doing\npython manage.py shell\n\nyou can do\n>>> import trial\n\nand then invoke the ... | [
5,
2,
1,
1,
1,
0
] | [] | [] | [
"django",
"django_models",
"django_testing",
"django_views",
"python"
] | stackoverflow_0004279885_django_django_models_django_testing_django_views_python.txt |
Q:
pythonic way to collect specific data from complex dict
i need to collect some data from complext dict based on Dot Notation key names
for example
sample data
data = {
'name': {'last': 'smith', 'first': 'bob'},
'address':{'city': 'NY', 'state': 'NY'},
'contact':{'phone':{'self':'1234', 'home':'222'}},
'age... | pythonic way to collect specific data from complex dict | i need to collect some data from complext dict based on Dot Notation key names
for example
sample data
data = {
'name': {'last': 'smith', 'first': 'bob'},
'address':{'city': 'NY', 'state': 'NY'},
'contact':{'phone':{'self':'1234', 'home':'222'}},
'age':38,
'other':'etc'
}
keys = ['contact.phone.self', 'name.... | [
"[reduce(dict.get, key.split(\".\"), data) for key in keys]\n\n",
"How about this?\ndef fetch( some_dict, key_iter ):\n for key in key_iter:\n subdict= some_dict\n for field in key.split('.'):\n subdict = subdict[field]\n yield subdict\n\na_dict = {\n 'name': {'last': 'smith', ... | [
4,
0,
0,
0
] | [] | [] | [
"coding_style",
"python"
] | stackoverflow_0004095386_coding_style_python.txt |
Q:
Rendering json as dictionary in template
I have a JSON object returned from server. It looks like this :
{"1":{"id":"1","name":"autos"},
"2":{"id":"2","name":"business"},
"3":{"id":"3","name":"cities"},
"4":{"id":"4","name":"drama"},
"5":{"id":"5","name":"movies"},
"6":{"id":"6","name":"finance"},
"7":{"id":"7","n... | Rendering json as dictionary in template | I have a JSON object returned from server. It looks like this :
{"1":{"id":"1","name":"autos"},
"2":{"id":"2","name":"business"},
"3":{"id":"3","name":"cities"},
"4":{"id":"4","name":"drama"},
"5":{"id":"5","name":"movies"},
"6":{"id":"6","name":"finance"},
"7":{"id":"7","name":"electronics"}}
So I'm rendering a templ... | [
"It looks like the template variable interests is just a string with the json response. The string gets escaped in the template, that's why you end up with all the \". Check if the response from the server is correctly parsed.\nTo verify the type, you can use the type class, i.e. type(ResultDict).\n",
"Do you do ... | [
0,
0
] | [] | [] | [
"dictionary",
"django",
"html",
"json",
"python"
] | stackoverflow_0004284890_dictionary_django_html_json_python.txt |
Q:
python how to fetch these string
text=u’<a href="#5" accesskey="5"></a><a href="#1" accesskey="1"><font color="#667755">\ue689</font></a><a href="#2" accesskey="2"><font color="#667755">\ue6ec</font></a><a href="#3" accesskey="3"><font color="#667755">\ue6f6</font></a>‘
I am a python new hand.
I wanna get \ue6ec... | python how to fetch these string | text=u’<a href="#5" accesskey="5"></a><a href="#1" accesskey="1"><font color="#667755">\ue689</font></a><a href="#2" accesskey="2"><font color="#667755">\ue6ec</font></a><a href="#3" accesskey="3"><font color="#667755">\ue6f6</font></a>‘
I am a python new hand.
I wanna get \ue6ec、\ue6f6、\ue6ec,how to fetch these stri... | [
"Regexp is not good tool to work with HTML. Use the Beautiful Soup.\n",
">>> from BeautifulSoup import BeautifulSoup\n>>> text=u'<a href=\"#5\" accesskey=\"5\"></a><a href=\"#1\" accesskey=\"1\"><font color=\"#667755\">\\ue689</font></a><a href=\"#2\" accesskey=\"2\"><font color=\"#667755\">\\ue6ec</font></a><a h... | [
2,
2,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0004283155_python.txt |
Q:
pygame: custom classes inheriting from pygame.Surface
I'm playing with pygame for the first time (and am kind of a newb about python in general), and wondering if anyone could help me with this...
I'm making a little shootem-up game and want to be able to create a class for bad guys. My thought was that the class ... | pygame: custom classes inheriting from pygame.Surface | I'm playing with pygame for the first time (and am kind of a newb about python in general), and wondering if anyone could help me with this...
I'm making a little shootem-up game and want to be able to create a class for bad guys. My thought was that the class should inherit from pygame.Surface, but that's giving me al... | [
"You didn't call the inherited constructor:\nclass Zombie(pygame.Surface):\n def __init__(self, x, y):\n pygame.Surface.__init__(self, size=(w,h))\n\nAnd you're assigning to self. That's not going to work.\n",
"I see that this question was asked one month ago, but maybe it's not too late...\nWhat I see ... | [
4,
3
] | [] | [] | [
"class",
"inheritance",
"pygame",
"python"
] | stackoverflow_0004002019_class_inheritance_pygame_python.txt |
Q:
Write lines longer than 80 chars in output file [Python]
I've got a pretty basic question. I'm using Python to calculate an n×12 vector
y = numpy.array([V1,V2,V3,V4,V5,V6,V7,V8,V9,V10,V11,V12])
which I append after each loop calculation.
My problem is that when I try to save it to a file or print it
Python automa... | Write lines longer than 80 chars in output file [Python] | I've got a pretty basic question. I'm using Python to calculate an n×12 vector
y = numpy.array([V1,V2,V3,V4,V5,V6,V7,V8,V9,V10,V11,V12])
which I append after each loop calculation.
My problem is that when I try to save it to a file or print it
Python automatically breaks the result in three lines as my
output usually ... | [
"You can use numpy.savetxt() to save an array to a text file while controlling the formatting. To print it to the screen, you have different options to control the linewidth. One would be to call\nnumpy.set_printoptions(linewidth=200)\n\nto set the linewidth to a higher value.\n"
] | [
24
] | [] | [] | [
"file_io",
"numpy",
"python"
] | stackoverflow_0004286544_file_io_numpy_python.txt |
Q:
Find gaps in a sequence of Strings
I have got a sequence of strings - 0000001, 0000002, 0000003.... upto 2 million. They are not contiguous. Meaning there are gaps. Say after 0000003 the next string might be 0000006. I need to find out all these gaps. In the above case (0000004, 0000005).
This is what I have done ... | Find gaps in a sequence of Strings | I have got a sequence of strings - 0000001, 0000002, 0000003.... upto 2 million. They are not contiguous. Meaning there are gaps. Say after 0000003 the next string might be 0000006. I need to find out all these gaps. In the above case (0000004, 0000005).
This is what I have done so far -
gaps = list()
total = len(cur... | [
"You could sort the list of ids and then step through it once only:\ndef find_gaps(ids):\n \"\"\"Generate the gaps in the list of ids.\"\"\"\n j = 1\n for id_i in sorted(ids):\n while True:\n id_j = '%07d' % j\n j += 1\n if id_j >= id_i:\n break\n ... | [
11,
3,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0004284740_python.txt |
Q:
How to loop through list in Django Template
I am having a list in the name 'bestforproglist'. Also I had a for loop like this
{% for act in activities %}
<div style="float:left;">{{ act.spotcategoryactivity }}</div>
<div class="progit">
<div class="prog_c" >
<div id="prog_p" st... | How to loop through list in Django Template | I am having a list in the name 'bestforproglist'. Also I had a for loop like this
{% for act in activities %}
<div style="float:left;">{{ act.spotcategoryactivity }}</div>
<div class="progit">
<div class="prog_c" >
<div id="prog_p" style="width:20%;"></div>
</div>
... | [
"What is mylist? If you want to iterate over multiple lists, perhaps you should zip them and pass them into the template? Then you can use something like\n {% for x,y in zipped_list %} \n\nand use both the items rather than the indexing thing you're trying.\n",
"If it's important to have activities and bestforpro... | [
5,
1,
0
] | [] | [] | [
"django",
"django_templates",
"html",
"python"
] | stackoverflow_0004274374_django_django_templates_html_python.txt |
Q:
Recursive Error when introducing setattr in python
I am trying to write a simple object in python that will load up settings using ConfigParser, get all the items as a dictionary, then set those as attributes for the object.
This seems to work if I don't include a __setattr__ method. I can call "settings.top_trave... | Recursive Error when introducing setattr in python | I am trying to write a simple object in python that will load up settings using ConfigParser, get all the items as a dictionary, then set those as attributes for the object.
This seems to work if I don't include a __setattr__ method. I can call "settings.top_travel" and get the answer back. However, as soon as I try an... | [
"The problem is that setting self.configuration invokes self.__setattr__\nYou can circumvent that by changing the assignment to a call to __setattr__ of the super class:\nclass settingsFile(object):\n\n def __init__(self):\n ...\n # Return all the \"config\" section as a list and convert to a dicti... | [
5,
5
] | [
"Whatever clever stuff you're doing with ConfigParser is recursing infinitely. I can't be certain because I don't see the code, but if you're using recursion, make sure you cover all of your base cases.\n"
] | [
-3
] | [
"configuration",
"python",
"setattribute"
] | stackoverflow_0004286648_configuration_python_setattribute.txt |
Q:
Make unicode from variable containing QString
I have QPlainTextEdit field with data containing national characters (iso-8859-2).
tmp = self.ui.field.toPlainText() (QString type)
When I do:
tmp = unicode(tmp, 'iso-8859-2')
I get question marks instead of national characters. How can I convert properly the data ... | Make unicode from variable containing QString | I have QPlainTextEdit field with data containing national characters (iso-8859-2).
tmp = self.ui.field.toPlainText() (QString type)
When I do:
tmp = unicode(tmp, 'iso-8859-2')
I get question marks instead of national characters. How can I convert properly the data in QPlainTextEdit field to unicode?
| [
"As it was said QPlainTextEdit.toPlainText() returns QString which should be UTF-16, whereas unicode() constructor expects a byte string. Below is a small example:\ntmp = self.field.toPlainText()\nprint 'field.toPlainText: ', tmp\n\ncodec0 = QtCore.QTextCodec.codecForName(\"UTF-16\");\ncodec1 = QtCore.QTextCodec.co... | [
3
] | [] | [] | [
"pyqt",
"python",
"qt",
"qt4"
] | stackoverflow_0004281116_pyqt_python_qt_qt4.txt |
Q:
Python go to def
Hi there
First of all just let me say that I'm new in Python and this is for a school work so this should be done without advanced programing and global functions. Using Python 2.6.6 and WingIDE 101
I need a program to present the user with a menu. The user must pick an option and accordingly to i... | Python go to def | Hi there
First of all just let me say that I'm new in Python and this is for a school work so this should be done without advanced programing and global functions. Using Python 2.6.6 and WingIDE 101
I need a program to present the user with a menu. The user must pick an option and accordingly to is pick the program doe... | [
"There are lots of things wrong with this, so we will take up one by one.\nsum is a built-in function in Python. So you cannot name your function sum. You have to call yourself something else, like sum_foo. Or _sum.\nAlso, your code is executed from top to bottom. So if you are calling a function say X in a functio... | [
1,
0,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0004287122_python.txt |
Q:
Sort list of strings by integer suffix
I have a list of strings:
[song_1, song_3, song_15, song_16, song_4, song_8]
I would like to sort them by the # at the end, unfortunately since the lower numbers aren't "08" and are "8", they are treated as larger than 15 in lexicographical order.
I know I have to pass a key... | Sort list of strings by integer suffix | I have a list of strings:
[song_1, song_3, song_15, song_16, song_4, song_8]
I would like to sort them by the # at the end, unfortunately since the lower numbers aren't "08" and are "8", they are treated as larger than 15 in lexicographical order.
I know I have to pass a key to the sort function, I saw this somewhere ... | [
"You're close.\nsorted(the_list, key = lambda x: int(x.split(\"_\")[1]))\n\nshould do it. This splits on the underscore, takes the second part (i.e. the one after the first underscore), and converts it to integer to use as a key.\n",
"Well, you want to sort by the filename first, then on the int part:\ndef splitt... | [
22,
7,
3,
1
] | [] | [] | [
"python"
] | stackoverflow_0004287209_python.txt |
Q:
NameError in defining python multi-level package
I'm trying to create a simple multi-level package:
test_levels.py
level1/
__init__.py (empty file)
level2/
__init__.py (only contents: __all__ = ["leaf"])
leaf.py
leaf.py:
class Leaf(object):
print("read Leaf cla... | NameError in defining python multi-level package | I'm trying to create a simple multi-level package:
test_levels.py
level1/
__init__.py (empty file)
level2/
__init__.py (only contents: __all__ = ["leaf"])
leaf.py
leaf.py:
class Leaf(object):
print("read Leaf class")
pass
if __name__ == "__main__":
x = Leaf... | [
"try to add\nfrom leaf import *\n\nin file level1/level2/__init__.py\nupd: as in previous comment, add dot before module name, and remove \"__all__\" declaration.\n$ cat level1/level2/__init__.py\nfrom .leaf import Leaf\n$ cat level1/level2/leaf.py\nclass Leaf:\n def __init__(self):\n print(\"hello\")\n$ ... | [
0,
0,
0
] | [] | [] | [
"nameerror",
"package",
"python"
] | stackoverflow_0004286999_nameerror_package_python.txt |
Q:
What's a good name for this kind of object?
I have an associative array of element IDs to counts of each element.
e.g. (in python):
myObject = { 'a': 5, 'b': 3 }
It should support addition and subtraction. For example:
myObject - { 'a': 3 }
Should evaluate to:
{ 'a': 2, 'b': 3 }
For context, this is supporting ... | What's a good name for this kind of object? | I have an associative array of element IDs to counts of each element.
e.g. (in python):
myObject = { 'a': 5, 'b': 3 }
It should support addition and subtraction. For example:
myObject - { 'a': 3 }
Should evaluate to:
{ 'a': 2, 'b': 3 }
For context, this is supporting a costs system. Each element is a resource type, ... | [
"This collection type is already in Python 2.7 and 3.1. It's called a Counter.\n",
"I'd go for ResourceVector or ResourceTuple I guess.\n",
"I would call that a Matrix, without knowing the extent of what you want to do.\n"
] | [
8,
1,
0
] | [] | [] | [
"data_structures",
"naming",
"python",
"terminology"
] | stackoverflow_0004287388_data_structures_naming_python_terminology.txt |
Q:
Gui Library in Python
I am in need of making an interface for Automata Construction. For those who are unaware of what an automata is, I basically need circles and arrows, extending them on the user interface and then various text to describe it. For example :- http://en.wikipedia.org/wiki/File:DFAexample.svg
I wa... | Gui Library in Python | I am in need of making an interface for Automata Construction. For those who are unaware of what an automata is, I basically need circles and arrows, extending them on the user interface and then various text to describe it. For example :- http://en.wikipedia.org/wiki/File:DFAexample.svg
I was wondering if there is any... | [
"I've used PyQt4 to produce something like this:\nhttp://doc.qt.nokia.com/4.6/graphicsview-diagramscene.html\nwhich is the C++ version. Draw boxes, draw arrows, drag them around and so forth. Actually I think I pretty much ported the C++ version line-by-line to Python. Or someone else did.\n",
"PySide (Qt), WxPyt... | [
2,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0004287469_python.txt |
Q:
Python: How to get an updated Entry text to use in a command binded to it?
Consider the following code:
text = Entry(); text.pack()
def show(e):
print text.get()
text.bind('<Key>', show)
Let's say I put the letters ABC in the Entry, one by one. The output would be:
>>>
>>> A
>>> AB
Note that when pressing A... | Python: How to get an updated Entry text to use in a command binded to it? | Consider the following code:
text = Entry(); text.pack()
def show(e):
print text.get()
text.bind('<Key>', show)
Let's say I put the letters ABC in the Entry, one by one. The output would be:
>>>
>>> A
>>> AB
Note that when pressing A, it prints an empty string. When I press B, it prints A, not AB. If i don't pre... | [
"You could replace the <Key> event with the <KeyRelease> event. That should work.\nHere is a list of events: http://infohost.nmt.edu/tcc/help/pubs/tkinter/events.html#event-types\n",
"The reason for this has to do with Tk \"bindtags\". Bindings are associated with tags, and the bindings are processed in tag order... | [
3,
2
] | [] | [] | [
"python",
"tkinter",
"tkinter_entry"
] | stackoverflow_0004287553_python_tkinter_tkinter_entry.txt |
Q:
How to customize the look and feel of django admin
How to customize the look and feel of django admin?
A:
You should create ModelAdmin classes to customize the django admin site.
See this page in the django book for details:
http://www.djangobook.com/en/2.0/chapter06/
A:
try Django Grappelli
Bye!
A:
Have you... | How to customize the look and feel of django admin | How to customize the look and feel of django admin?
| [
"You should create ModelAdmin classes to customize the django admin site.\nSee this page in the django book for details:\nhttp://www.djangobook.com/en/2.0/chapter06/\n",
"try Django Grappelli\nBye!\n",
"Have you set up the tables in the DB yet? As per http://docs.djangoproject.com/en/1.2/intro/tutorial01/?\n",
... | [
1,
1,
0,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0004285388_django_python.txt |
Q:
Improving run time of simple query
Gurus:
I have a very simple data model relating two different kinds of Users via an Interaction:
# myapp/models.py
class C1(models.Model):
user = models.ForeignKey(User)
class C2(models.Model):
user = models.ForeignKey(User)
class Interaction(models.Model):
c1 = models.Forei... | Improving run time of simple query | Gurus:
I have a very simple data model relating two different kinds of Users via an Interaction:
# myapp/models.py
class C1(models.Model):
user = models.ForeignKey(User)
class C2(models.Model):
user = models.ForeignKey(User)
class Interaction(models.Model):
c1 = models.ForeignKey(C1)
c2 = models.ForeignKey(C2)
d... | [
"If you'd like to store additional information related to your users, Django provides a method to specify a site-specific related model -- termed a \"user profile\" -- for this purpose.\nTo make use of this feature, define a model with fields for the additional information you'd like to store, or additional methods... | [
4,
0
] | [] | [] | [
"database_design",
"django",
"python"
] | stackoverflow_0004287801_database_design_django_python.txt |
Q:
Lazily sample random results in python
Python question. I'm generating a large array of objects, which I only need to make a small random sample. Actually generating the objects in question takes a while, so I wonder if it would be possible to somehow skip over those objects that don't need generating and only exp... | Lazily sample random results in python | Python question. I'm generating a large array of objects, which I only need to make a small random sample. Actually generating the objects in question takes a while, so I wonder if it would be possible to somehow skip over those objects that don't need generating and only explicitly create those objects that have been ... | [
"There does not seem a way that avoids figuring out how the indices map to your permutations. If you don't know this, how would you create a random object from your array? You could either use the trick using xrange() you suggested yourself, or implement a class defining the __getitem__() and __len__() methods an... | [
2,
0,
0,
0
] | [] | [] | [
"lazy_evaluation",
"python",
"random",
"sampling"
] | stackoverflow_0004286862_lazy_evaluation_python_random_sampling.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.