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:
Auto complete box implemented using appengine
I am developing an application using python version of appengine. I would like to implement a auto complete box in my application. The suggestions for the auto-complete options will be derived from a string property in my data model. Please help by providing an example... | Auto complete box implemented using appengine | I am developing an application using python version of appengine. I would like to implement a auto complete box in my application. The suggestions for the auto-complete options will be derived from a string property in my data model. Please help by providing an example of a similar implementation.
| [
"\nYUI-Django-AutoComplete\nYUI Autocomplete in Django snippet http://www.djangosnippets.org/users/pigletto/ pigletto\nWill Larson's http://lethain.com/entry/2007/dec/01/using-jquery-django-autocomplete-fields/ Using JQuery with Django for Autocomplete Fields\nhttp://www.djangosnippets.org/users/skam/ skam 's JQuer... | [
1,
0
] | [] | [] | [
"autocomplete",
"google_app_engine",
"python"
] | stackoverflow_0005274247_autocomplete_google_app_engine_python.txt |
Q:
Having a field named 'created' within a model - Django
I have a model such as the following:
class Item(models.Model):
name = models.CharField(max_length=150)
created = models.DateTimeField(auto_now_add=True)
the admin class is the following:
class ItemAdmin(admin.ModelAdmin):
list_display = ('name'... | Having a field named 'created' within a model - Django | I have a model such as the following:
class Item(models.Model):
name = models.CharField(max_length=150)
created = models.DateTimeField(auto_now_add=True)
the admin class is the following:
class ItemAdmin(admin.ModelAdmin):
list_display = ('name', 'created')
the created field does not seem to exist
Is th... | [
"When you say the field does not exist, do you mean that it is not showing on the admin change form? This is expected behaviour when using auto_now_add. If you want the field to get a default value on creation but still be editable, use default=datetime.datetime.now instead.\n",
"Strange. I tried out your example... | [
5,
1,
0
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0003635486_django_django_models_python.txt |
Q:
Python: The best way to get complex dictionary values
I've a dictionary in following format
{'array': [[{u'unsigned': 15.0}], [{u'octet-string': 12.0}], [{u'octet-string': 12.0}], [{u'octet-string': 12.0}], [{u'octet-string': 45.0}], [{u'octet-string': 78.0}], [{u'octet-string': 89.0}], [{u'octet-string': 65.0}],... | Python: The best way to get complex dictionary values | I've a dictionary in following format
{'array': [[{u'unsigned': 15.0}], [{u'octet-string': 12.0}], [{u'octet-string': 12.0}], [{u'octet-string': 12.0}], [{u'octet-string': 45.0}], [{u'octet-string': 78.0}], [{u'octet-string': 89.0}], [{u'octet-string': 65.0}], [{u'octet-string': 352.0}], [{u'octet-string': 45.0}], [{u... | [
"This is making all kinds of assumptions about the data you're dealing with, but in the example you give you could do this:\n[ a[0].values()[0] for a in d['array'] ]\n\n... where d is your dictionary as above. That evaluates to:\n[15.0, 12.0, 12.0, 12.0, 45.0, 78.0, 89.0, 65.0, 352.0,\n 45.0, 12.0, 45.0, 78.0, 98.... | [
4,
0,
0
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0005297736_dictionary_python.txt |
Q:
Python zipfile module: difference between zipfile.ZIP_DEFLATED and zipfile.ZIP_STORED
I have difficulty understanding the difference between zipfile.ZIP_DEFLATED and zipfile.ZIP_STORED compression modes of the zipfile module.
A:
ZIP_DEFLATED correspond to an archive member (a file inside the archive) which is co... | Python zipfile module: difference between zipfile.ZIP_DEFLATED and zipfile.ZIP_STORED | I have difficulty understanding the difference between zipfile.ZIP_DEFLATED and zipfile.ZIP_STORED compression modes of the zipfile module.
| [
"ZIP_DEFLATED correspond to an archive member (a file inside the archive) which is compressed (or deflated). ZIP_STORED correspond to an archive member which is simply stored, without being compressed, quite the same as an archive member inside a tar file.\n"
] | [
26
] | [] | [] | [
"python",
"python_zipfile"
] | stackoverflow_0005298169_python_python_zipfile.txt |
Q:
What would be an appropriate constrained optimization solver in python for this problem; and type error problem
I am looking to use python (in place of excel) for an assignment in a non-programming related engineering class. I am trying to find the optimum number of tubes in a heat exchanger for several different... | What would be an appropriate constrained optimization solver in python for this problem; and type error problem | I am looking to use python (in place of excel) for an assignment in a non-programming related engineering class. I am trying to find the optimum number of tubes in a heat exchanger for several differently sized tubes. This number depends on half a dozen related quantities and has a few constraints. Few of these equa... | [
"Second question: it looks like somewhere you have \"x ** y\" where y is a float, but x is a NoneType. That probably means nre, npr, vsb, or vsw is a NoneType by the time it is passed into nnuf(). Try printing these variables and see.\n",
"If you let the optimizer work with float values, perhaps you can assume th... | [
1,
1,
1
] | [] | [] | [
"optimization",
"python",
"scipy"
] | stackoverflow_0005294484_optimization_python_scipy.txt |
Q:
In Java, does something comparable to Python's socketserver exists?
I'm implementing a simple TCP client and TCP server in Java at the moment, and when searching for examples, I've stumbled across this nice Python framework:
http://docs.python.org/library/socketserver.html
EDIT
I'm looking for a solution where yo... | In Java, does something comparable to Python's socketserver exists? | I'm implementing a simple TCP client and TCP server in Java at the moment, and when searching for examples, I've stumbled across this nice Python framework:
http://docs.python.org/library/socketserver.html
EDIT
I'm looking for a solution where you can create a TCP-Server by doing a call like this:
TCPServer server = n... | [
"Not in the core language, no. You have to do the normal things you would do in most languages where you set up the listener, accept connections, check for input, etc.\nI'm sure somewhere someone has built a generic \"framework\" for this, but in all honestly, it's about 40 lines of code and there's umteen tutorial... | [
3,
1,
0,
0
] | [] | [] | [
"java",
"python",
"sockets",
"tcp"
] | stackoverflow_0005296518_java_python_sockets_tcp.txt |
Q:
msiexec scripting in python
Most of this is background, skip the next 3 paragraphs for the question:
I have developed a tool that calls some installers, changes registry items, and moves files around to help me test a product which has a fairly fast update cycle. So far so good, I have a GUI which runs in a sepa... | msiexec scripting in python | Most of this is background, skip the next 3 paragraphs for the question:
I have developed a tool that calls some installers, changes registry items, and moves files around to help me test a product which has a fairly fast update cycle. So far so good, I have a GUI which runs in a separate process to the business logi... | [
"I'm not sure about the _winreg module being all that slow. I suppose if you were trying to enumerate the entire registry to find all instances of a string that might take a while, but with a decently targeted query it seems reasonably fast.\nHere's an example:\nfrom _winreg import *\n\ndef get_guid_by_name(name):\... | [
1
] | [] | [] | [
"pyqt",
"pyqt4",
"python",
"windows",
"windows_installer"
] | stackoverflow_0005297937_pyqt_pyqt4_python_windows_windows_installer.txt |
Q:
izip_longest in itertools: what's going on here?
I'm struggeling to understand how the below code works. It's from http://docs.python.org/library/itertools.html#itertools.izip_longest, and is the pure-python equivalent of the izip_longest iterator. I'm especially mystified by the sentinel function, how does it wor... | izip_longest in itertools: what's going on here? | I'm struggeling to understand how the below code works. It's from http://docs.python.org/library/itertools.html#itertools.izip_longest, and is the pure-python equivalent of the izip_longest iterator. I'm especially mystified by the sentinel function, how does it work?
def izip_longest(*args, **kwds):
# izip_longest... | [
"Ok, we can do this. About the sentinel. The expression ([fillvalue]*(len(args)-1)) creates a list that contains one fill value for each iterable in args, minus one. So, for the example above ['-']. counter is then assigned the pop-function of that list. sentinel itself is a generator that pops one item from that l... | [
6,
5,
2
] | [] | [] | [
"python",
"python_itertools"
] | stackoverflow_0005298705_python_python_itertools.txt |
Q:
How to efficiently left-shift a tuple?
I'm looking for an efficient way to left-shift a tuple.
What I've done so far:
def leftShift(tup, n):
length = len(tup)
if length != 0:
n = n % length
else:
return tuple()
return tup[n:] + tup[0:n]
sample = (1,2,3,4)
sample2 = ()
print(leftSh... | How to efficiently left-shift a tuple? | I'm looking for an efficient way to left-shift a tuple.
What I've done so far:
def leftShift(tup, n):
length = len(tup)
if length != 0:
n = n % length
else:
return tuple()
return tup[n:] + tup[0:n]
sample = (1,2,3,4)
sample2 = ()
print(leftShift(sample, 5)) #prints (2, 3, 4, 1)
print(l... | [
"What you're doing is absolute micro-optimization, which is a total waste of time if you don't know exactly what you're aiming for. \nThe first version of you code is probably faster because it uses one less function call, but both are fine. If you really care about speed you should figure out how to use a profiler... | [
9,
6
] | [] | [] | [
"python",
"shift",
"tuples"
] | stackoverflow_0005299135_python_shift_tuples.txt |
Q:
Raw UDP packets using Twisted
I'm currently using Twisted 10.1 to receive and parse UDP packets, but the standard implementation of reactor.listenUDP() only gives me access to the packet data, and I need to get the packet length from the UDP headers.
I've tried out Twisted's pairudp.py example, but it fails with ... | Raw UDP packets using Twisted | I'm currently using Twisted 10.1 to receive and parse UDP packets, but the standard implementation of reactor.listenUDP() only gives me access to the packet data, and I need to get the packet length from the UDP headers.
I've tried out Twisted's pairudp.py example, but it fails with an "ImportError: No module named eu... | [
"As Glyph pointed out, you're trying to solve a problem in a complex manner that can be solved simply. Since you can get the length of the packet data using len(data), and since the length of a UDP packet header is 8 bytes, totalSizeOfUdpPacket = 8 + len(data).\n"
] | [
2
] | [] | [] | [
"python",
"twisted",
"udp"
] | stackoverflow_0005276755_python_twisted_udp.txt |
Q:
Python First Letter of a word Upper CASE
I'm looking for some very clever and fast way of transforming every first character of a word in a string with the upper case.
ac milan > Ac Milan
paris saint germain > Paris Saint Germain
A:
Use the title method of str:
'ac milan'.title()
A:
Is this what you're looking... | Python First Letter of a word Upper CASE | I'm looking for some very clever and fast way of transforming every first character of a word in a string with the upper case.
ac milan > Ac Milan
paris saint germain > Paris Saint Germain
| [
"Use the title method of str:\n'ac milan'.title()\n\n",
"Is this what you're looking for?\n>>> \"how now brown cow\".title()\n'How Now Brown Cow'\n\n"
] | [
59,
8
] | [] | [] | [
"python"
] | stackoverflow_0005299294_python.txt |
Q:
using urllib and beautifulsoup to find values inside "hidden" tags
i want to know if it is possible to display the values of hidden tags. im using urllib and beautifulsoup but i cant seem to get what i want.
the html code im using is written below: (saved as hiddentry.html)
<html>
<head>
<script type="text/ja... | using urllib and beautifulsoup to find values inside "hidden" tags | i want to know if it is possible to display the values of hidden tags. im using urllib and beautifulsoup but i cant seem to get what i want.
the html code im using is written below: (saved as hiddentry.html)
<html>
<head>
<script type="text/javascript">
//change hidden elem value
function changeVal... | [
"beautifulsoup parses the html that it gets from the server. If you want to see generated values, you need to somehow execute the embedded javascript on the page before passing the string to beautifulsoup. Once you run the javascript, you'll pass the modified DOM html to beautifulsoup.\nAs far as browser emulatio... | [
2
] | [] | [] | [
"beautifulsoup",
"python",
"urllib"
] | stackoverflow_0005299419_beautifulsoup_python_urllib.txt |
Q:
Program, that chooses the best out of 10
I need to make a program in python that chooses cars from an array, that is filled with the mass of 10 cars. The idea is that it fills a barge, that can hold ~8 tonnes most effectively and minimum space is left unfilled. My idea is, that it makes variations of the masses an... | Program, that chooses the best out of 10 | I need to make a program in python that chooses cars from an array, that is filled with the mass of 10 cars. The idea is that it fills a barge, that can hold ~8 tonnes most effectively and minimum space is left unfilled. My idea is, that it makes variations of the masses and chooses one, that is closest to the max weig... | [
"This is a 1D bin-packing problem. It's a NP problem and there isn't an optimal solution. However there is a way to solve this with greedy algorithm. Most likely you want to try my bin-packing solver at phpclasses.org (bin-packing).\nIf I have a graph unweigthed and undirected and each node is connected which each ... | [
1,
1,
-1
] | [] | [] | [
"algorithm",
"python"
] | stackoverflow_0005299280_algorithm_python.txt |
Q:
Filter applause from videos
I am currently watching a video from 27C3 and I would like to filter the applause, as it is very loud. Is this possible? I have heard something like this was made for Vuvuzelas.
I use Ubuntu. If this filter would work via ffmpeg this would be great. If it is written in Python it would a... | Filter applause from videos | I am currently watching a video from 27C3 and I would like to filter the applause, as it is very loud. Is this possible? I have heard something like this was made for Vuvuzelas.
I use Ubuntu. If this filter would work via ffmpeg this would be great. If it is written in Python it would also be ok.
Here is an example: ht... | [
"You could use a dynamic range compressor, this will not filter out the applause, but at least it will smooth out the loudness. You can give it a threshold so that it doesn't affect sound below that threshold.\n",
"No, this isn't possible. The sound of applause covers a very wide band. Filtering vuvuzelas was s... | [
1,
1,
1
] | [] | [] | [
"audio",
"ffmpeg",
"python"
] | stackoverflow_0005299338_audio_ffmpeg_python.txt |
Q:
python: how to interrupt a regex match
I iterate over the lines in a large number of downloaded text files and do a regex match on each line. Usually, the match takes less than a second. However, at times a match takes several minutes, sometimes the match does not finish at all and the code just hangs (waited an h... | python: how to interrupt a regex match | I iterate over the lines in a large number of downloaded text files and do a regex match on each line. Usually, the match takes less than a second. However, at times a match takes several minutes, sometimes the match does not finish at all and the code just hangs (waited an hour a couple of times, then gave up). Theref... | [
"You are running into catastrophic backtracking; not because of nested quantifiers but because your quantified characters also can match the separators, and since there are a lot of them, you'll get exponential time in certain cases.\nAside from the fact that it looks more like a job for a CSV parser, try the follo... | [
8,
2,
2,
1
] | [] | [] | [
"multithreading",
"python",
"regex",
"signals",
"timeout"
] | stackoverflow_0005298033_multithreading_python_regex_signals_timeout.txt |
Q:
mod_wsgi cannot load mysql
First I will list my environment and status:
Environment:
System: Mac OS 10.6
Python: 2.6
Apache: 2.2
mod_wsgi: 3.3
mysql: 5.x
php: 3.5
trac:0.12
Status:
I can run trac as alone-server without problem.
Now I integrate trac to apache, problem come out. mod_wsgi can run normal wsgi page... | mod_wsgi cannot load mysql | First I will list my environment and status:
Environment:
System: Mac OS 10.6
Python: 2.6
Apache: 2.2
mod_wsgi: 3.3
mysql: 5.x
php: 3.5
trac:0.12
Status:
I can run trac as alone-server without problem.
Now I integrate trac to apache, problem come out. mod_wsgi can run normal wsgi page correctly, but cannot load mysq... | [
"Try LD_LIBRARY_PATH instead:\nexport LD_LIBRARY_PATH=/usr/local/mysql/lib/mysql:$LD_LIBRARY_PATH\n\n",
"The problem is that your Apache is running as 64 bit and you are using 32 bit version of MySQL, or Apache is running as 32 bit and you are using 64 bit version of MySQL.\nRun the 'file' command on 'libmysqlcli... | [
0,
0
] | [] | [] | [
"apache",
"mod_wsgi",
"mysql",
"python",
"trac"
] | stackoverflow_0005292350_apache_mod_wsgi_mysql_python_trac.txt |
Q:
Boost python export singleton
I have a singleton (from boost::serialization):
class LogManager : public boost::serialization::singleton<LogManager> { ... };
And wrapper for getting instance:
inline LogManager &logManager() { return LogManager::get_mutable_instance(); }
What's the right way to bind this into boos... | Boost python export singleton | I have a singleton (from boost::serialization):
class LogManager : public boost::serialization::singleton<LogManager> { ... };
And wrapper for getting instance:
inline LogManager &logManager() { return LogManager::get_mutable_instance(); }
What's the right way to bind this into boost.python module?
I tried:
class_< L... | [
"In addition to using bases<...> in the second argument as Autopulated pointed out, I think you also want to specifiy boost::noncopyable as the third template argument, e.g.\nbp::class_<LogManager, bp::bases<boost::serialization::singleton<LogManager> >, boost::noncopyable>(\"LogManager\", bp::no_init)\n\nEdit:\nAl... | [
4,
1
] | [] | [] | [
"boost",
"c++",
"python",
"singleton"
] | stackoverflow_0005299179_boost_c++_python_singleton.txt |
Q:
Best practice for serving static files
I am developing on a python webserver (Tornado). I plan to place this in a production instance with nginx in front. This will be my first time placing something into a production environment on my own. My question is how to setup files/directories for static serving. For inst... | Best practice for serving static files | I am developing on a python webserver (Tornado). I plan to place this in a production instance with nginx in front. This will be my first time placing something into a production environment on my own. My question is how to setup files/directories for static serving. For instance my application, allows users to upload ... | [
"Best practice is use shared storage, but if can't use it, than you can use \"proxy_store\" option from nginx. Example from nginx doc:\nlocation /images/ {\n root /data/www;\n error_page 404 = @fetch;\n}\n\nlocation @fetch {\n internal;\n\n proxy_pass http://backend;\... | [
0
] | [] | [] | [
"file",
"nginx",
"python",
"serving",
"static"
] | stackoverflow_0005299533_file_nginx_python_serving_static.txt |
Q:
Separating Progress Tracking and Loop Logic
Suppose i want to track the progress of a loop using the progress bar printer ProgressMeter (as described in this recipe).
def bigIteration(collection):
for element in collection:
doWork(element)
I would like to be able to switch the progress bar on and off... | Separating Progress Tracking and Loop Logic | Suppose i want to track the progress of a loop using the progress bar printer ProgressMeter (as described in this recipe).
def bigIteration(collection):
for element in collection:
doWork(element)
I would like to be able to switch the progress bar on and off. I also want to update it only every x steps for... | [
"It seems like this code would benefit from the null object pattern.\n# a progress bar that uses ProgressMeter\nclass RealProgressBar:\n pm = Nothing\n def setMaximum(self, max):\n pm = progress.ProgressMeter(total=max)\n pc = 0\n def progress(self):\n pc += 1\n if pc % 100... | [
6,
2,
1
] | [] | [] | [
"oop",
"python",
"separation_of_concerns"
] | stackoverflow_0005299950_oop_python_separation_of_concerns.txt |
Q:
Python: How do I save something that printed in a terminal as a variable to compare later?
import imaplib
import pprint
IMAP_SERVER='imap.gmail.com'
IMAP_PORT=993
M = imaplib.IMAP4_SSL(IMAP_SERVER, IMAP_PORT)
rc, resp = M.login('user@gmail.com', 'password')
print rc, resp
M.select()
for msg_num in M.search(None... | Python: How do I save something that printed in a terminal as a variable to compare later? | import imaplib
import pprint
IMAP_SERVER='imap.gmail.com'
IMAP_PORT=993
M = imaplib.IMAP4_SSL(IMAP_SERVER, IMAP_PORT)
rc, resp = M.login('user@gmail.com', 'password')
print rc, resp
M.select()
for msg_num in M.search(None, "UNDELETED")[1][0].split():
msg = M.fetch('1', '(BODY.PEEK[TEXT])')
print msg[1][0][1... | [
"Simply assign the message to a variable before you print it:\nfor msg_num in M.search(None, \"UNDELETED\")[1][0].split():\n msg = M.fetch('1', '(BODY.PEEK[TEXT])') \n a = msg[1][0][1][139:161]\n print a\n\n# later..\nif a == 'this is just a test...':\n # your code here\n pass\n\nObviously, you should ... | [
2
] | [] | [] | [
"gmail_imap",
"imaplib",
"python"
] | stackoverflow_0005300134_gmail_imap_imaplib_python.txt |
Q:
"Fatal Python error: deallocating None" and urlgrabber
I'm trying to fetch 1m+ pages over HTTP from single site. urlgrabber seemed like fast solution using "keep alive" connections. However, after a while my script fails without any stack trace with: "Fatal Python error: deallocating None"
Here is isolated python ... | "Fatal Python error: deallocating None" and urlgrabber | I'm trying to fetch 1m+ pages over HTTP from single site. urlgrabber seemed like fast solution using "keep alive" connections. However, after a while my script fails without any stack trace with: "Fatal Python error: deallocating None"
Here is isolated python code that fails (for simplification, file:// URL is used, gi... | [
"As somebody else mentioned, urlgrabber's got issues when you run this many grabs. Also, this is going to be unhappily slow if you're really grabbing hundreds of thousands of URLs. As an alternative, consider either the trusty wget.\nOf course, you're going to say that you want a Python solution, and for that, you ... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0004890785_python.txt |
Q:
What is the idiomatic way to share a logger instance between modules in my Python script?
I have created my own simple logger class which uses COM interop to redirect to a company-standard logger. I would like to create logger instance near the beginning of my script and then use this logger to allow all modules i... | What is the idiomatic way to share a logger instance between modules in my Python script? | I have created my own simple logger class which uses COM interop to redirect to a company-standard logger. I would like to create logger instance near the beginning of my script and then use this logger to allow all modules in my script to log centrally.
Is there an idiomatic way to share this logger instance between a... | [
"Why don't you use Python standard logging and write a handler to interface with your company-standard logging system? Python logging is specifically designed so you don't need to pass logger instances between layers of your code - Python loggers are essentially singletons already.\nHandlers for stdlib logging are ... | [
6,
1
] | [] | [] | [
"python",
"singleton"
] | stackoverflow_0005300563_python_singleton.txt |
Q:
Parsing a log file to find most active times
I have a logfile that looks like this:
Sun Mar 13 23:45:01 EDT 2011 - 2
game(s) running
It updates every 15 minutes.
I want to write code (was going to use Python) that'll parse this and tell me what time is the most active.
I understand this is a bit vague, but I w... | Parsing a log file to find most active times | I have a logfile that looks like this:
Sun Mar 13 23:45:01 EDT 2011 - 2
game(s) running
It updates every 15 minutes.
I want to write code (was going to use Python) that'll parse this and tell me what time is the most active.
I understand this is a bit vague, but I wanted to hear different approaches I could take.
| [
"For parsing times, you probably want time.strptime (http://docs.python.org/library/time.html#time.strptime). For breaking down each line from the logfile, you could use a regular expression or just something like splitting on \" - \" and then parsing the number of games ad hoc.\nFor finding most-active times, how ... | [
2,
0
] | [] | [] | [
"parsing",
"python"
] | stackoverflow_0005300611_parsing_python.txt |
Q:
how to calculate the local time from gmtoffset
im using this wrapper (pyipinfodb) for ipinfodb API. I just want to know how to calculate the local time from IP based in this response:
{u'City': u'San Diego',
u'CountryCode': u'US',
u'CountryName': u'United States',
u'Dstoffset': u'0',
u'Gmtoffset': u'-25200',
... | how to calculate the local time from gmtoffset | im using this wrapper (pyipinfodb) for ipinfodb API. I just want to know how to calculate the local time from IP based in this response:
{u'City': u'San Diego',
u'CountryCode': u'US',
u'CountryName': u'United States',
u'Dstoffset': u'0',
u'Gmtoffset': u'-25200',
u'Ip': u'76.192.218.153',
u'Isdst': u'1',
u'Latitu... | [
"Do this:\nimport datetime\n\n#parse json to get offset(import json; json.load(resonse); etc.)\n#offset is gmtoffset + dstoffset\ndatetime.datetime.utcnow() + datetime.timedelta(seconds = offset)\n\nNote that this will be the local time of the ip at the moment you execute utcnow.\nCode would have to be modified to ... | [
2
] | [] | [] | [
"python",
"timezone"
] | stackoverflow_0005300508_python_timezone.txt |
Q:
Developing a game with complex (and undefined) rules?
How would you develop a game that could end up with complex rules but you need to work on the rules (add, tweak, balance) a lot? I have looked at rule-based languages but I haven't found quite useful enough information regarding this.
UI etc. will be developed ... | Developing a game with complex (and undefined) rules? | How would you develop a game that could end up with complex rules but you need to work on the rules (add, tweak, balance) a lot? I have looked at rule-based languages but I haven't found quite useful enough information regarding this.
UI etc. will be developed later, first I'd need to iteratively develop the rules and ... | [
"Whatever you'll do, in this sort of program you'll end up implementing half of Prolog anyway. Check out the forward-chaining, backward-chaining, and backtracking algorithms.\nA pure-Java version of Prolog called Jekejeke was recently released. I can't comment on its quality.\nPython makes it much easier than Java ... | [
3,
2,
1,
0
] | [] | [] | [
"java",
"python",
"rules"
] | stackoverflow_0005299445_java_python_rules.txt |
Q:
Download several parts of one file concurrently with Python?
I know how to use urllib to download a file. However, it's much faster, if the server allows it, to download several part of the same file simultaneously and then merge them.
How do you do that in Python? If you can't do it easily with the standard lib, ... | Download several parts of one file concurrently with Python? | I know how to use urllib to download a file. However, it's much faster, if the server allows it, to download several part of the same file simultaneously and then merge them.
How do you do that in Python? If you can't do it easily with the standard lib, any lib that would let you do it?
| [
"Although I agree with Gregory's suggestion of using an existing library, it's worth noting that you can do this by using the Range HTTP header. If the server accepts byte-range requests, you can start several threads to download multiple parts of the file in parallel. This snippet, for example, will only download ... | [
18,
6
] | [] | [] | [
"download",
"python"
] | stackoverflow_0005299968_download_python.txt |
Q:
Python __iter__ and for loops
As I understand it, I can use the for loop construction on an object with a __iter__ method that returns an iterator. I have an object for which I implement the following __getattribute__ method:
def __getattribute__(self,name):
if name in ["read","readlines","readline","seek","_... | Python __iter__ and for loops | As I understand it, I can use the for loop construction on an object with a __iter__ method that returns an iterator. I have an object for which I implement the following __getattribute__ method:
def __getattribute__(self,name):
if name in ["read","readlines","readline","seek","__iter__","closed","fileno","flush",... | [
"There's a subtle implementation detail getting in your way: __iter__ isn't actually an instance method, but a class method. That is, obj.__class__.__iter__(obj) is called, rather than obj.__iter__().\nThis is due to slots optimizations under the hood, allowing the Python runtime to set up iterators faster. This ... | [
12,
4
] | [] | [] | [
"for_loop",
"iterable",
"python"
] | stackoverflow_0005300988_for_loop_iterable_python.txt |
Q:
How to send an email to a list of email in a kind in Google app engine?
HY!
I have a list in GAE, around 300 entries and I would like to send an email to everyone.
I've already prepared a script that get all enterprises and then makes a loop for each one and in each iteration it sends an email.
Now im concerned wi... | How to send an email to a list of email in a kind in Google app engine? | HY!
I have a list in GAE, around 300 entries and I would like to send an email to everyone.
I've already prepared a script that get all enterprises and then makes a loop for each one and in each iteration it sends an email.
Now im concerned with timeout. If I do all the thing in one step, it might take too much time an... | [
"I suggest you to delegate this task to a taskqueue that provides a fairly high timeout set to 10 minutes.\n"
] | [
1
] | [] | [] | [
"email",
"google_app_engine",
"python"
] | stackoverflow_0005300672_email_google_app_engine_python.txt |
Q:
Problem while trying to create python generator
I am trying to learn how to use generators, so I wrote this one, but it just prints the same value all the time. Why?
I want it to generate values from 999 down to 100.
>>> def gen_a():
a=999
while a>99:
yield a
a-=1
>>> gen_... | Problem while trying to create python generator | I am trying to learn how to use generators, so I wrote this one, but it just prints the same value all the time. Why?
I want it to generate values from 999 down to 100.
>>> def gen_a():
a=999
while a>99:
yield a
a-=1
>>> gen_a().next()
999
>>> gen_a().next()
999
>>> gen_a().ne... | [
"Because you are generating the generator over and over.\nTry:\nf = gen_a()\nf.next()\nf.next()\n\n",
"You're creating a new generator each time. Try this instead:\n>>> g = gen_a()\n>>> g.next()\n999\n>>> g.next()\n998\n>>> g.next()\n997\n\n"
] | [
8,
6
] | [] | [] | [
"generator",
"python"
] | stackoverflow_0005301614_generator_python.txt |
Q:
Need help finishing a program
I need some help finishing this code. I don't expect you to give me the full answer, I just need some hint about the 2 functions. thanks
class Trie(object):
"""A Trie of TrieNodes. Trie has the following attributes:
-- _root: a TrieNode; the root of this Trie.
"""
de... | Need help finishing a program | I need some help finishing this code. I don't expect you to give me the full answer, I just need some hint about the 2 functions. thanks
class Trie(object):
"""A Trie of TrieNodes. Trie has the following attributes:
-- _root: a TrieNode; the root of this Trie.
"""
def __init__(self):
"""Create... | [
"If all you want is a hint, take a look at Wikipedia's entry for the trie, which tells you everything you need to know about how tries work. \nOkay, here's another hint: every node of the trie will contain a dictionary whose keys are characters and whose values are trie nodes. The insert method will look at word... | [
2,
0
] | [] | [] | [
"data_structures",
"python"
] | stackoverflow_0005301407_data_structures_python.txt |
Q:
Set a kind name independently of the model name (App Engine datastore)
As a Python programmer, I like my code to be reusable, I'm trying to avoid kind name conflicts in my code (where two different models share the same kind name).
Currently I just prepend some meaningful text to the model's class name, but this i... | Set a kind name independently of the model name (App Engine datastore) | As a Python programmer, I like my code to be reusable, I'm trying to avoid kind name conflicts in my code (where two different models share the same kind name).
Currently I just prepend some meaningful text to the model's class name, but this is awfully unpythonic.
Being able to explicitly set the model's kind will sol... | [
"Just override the kind() method of your class:\nclass MyModel(db.Model):\n @classmethod\n def kind(cls):\n return 'prefix_%s' % super(MyModel, cls).kind()\n\nYou can define a custom baseclass that does this for you:\nclass ModuleModel(db.Model):\n @classmethod\n def kind(cls):\n return '%s_%s' % (cls.__m... | [
10
] | [] | [] | [
"google_app_engine",
"google_cloud_datastore",
"python"
] | stackoverflow_0005300387_google_app_engine_google_cloud_datastore_python.txt |
Q:
django-sorl produces IOError when using template syntax
I've set up django-sorl and I truly think I'm overlooking something simple. I keep getting the following error (TEMPLATE_DEBUG = True and THUMBNAIL_DEBUG = True)
Request Method: GET Request URL:
http://localhost:8000/events/edit/1
Django Version: 1.2... | django-sorl produces IOError when using template syntax | I've set up django-sorl and I truly think I'm overlooking something simple. I keep getting the following error (TEMPLATE_DEBUG = True and THUMBNAIL_DEBUG = True)
Request Method: GET Request URL:
http://localhost:8000/events/edit/1
Django Version: 1.2.4 Exception Type:
TemplateSyntaxError Exception Value:
C... | [
"The documentation was a bit weak in this field, but after importing the python debugger, I was able to find out where the problem was.\nThere are 2 potential solutions to this issue. The first one that fixed everything for me was to alter my template to read:\n{% load thumbnail %}\n...\n{% thumbnail image.path \"... | [
1,
1
] | [] | [] | [
"django",
"ioerror",
"python"
] | stackoverflow_0005227125_django_ioerror_python.txt |
Q:
Remove duplicate elements of a list when a different element matches - Python
Two lists of lists, h & i.
The length of h[0] is equal to h[1] and equal to h[2]. Same goes for i[0], i[1], and i[2].
The length of h[0] may not be equal to i[0].
When h[0][x] = i[0][y], "compare" h[2][x] & i[2][y].
The function "compar... | Remove duplicate elements of a list when a different element matches - Python |
Two lists of lists, h & i.
The length of h[0] is equal to h[1] and equal to h[2]. Same goes for i[0], i[1], and i[2].
The length of h[0] may not be equal to i[0].
When h[0][x] = i[0][y], "compare" h[2][x] & i[2][y].
The function "compare" means the following:
Split both x & y into lists when encountering a '\n' with... | [
"This works but is probably not the most efficient or pythonic code.\nimport string\ndef list_difference(list1, list2):\n \"\"\"Uses list1 as the reference, returns list of items not in list2.\"\"\"\n diff_list = []\n for item in list1:\n if not item in list2:\n diff_list.append(item)\n ... | [
0
] | [] | [] | [
"list",
"python"
] | stackoverflow_0005299494_list_python.txt |
Q:
Is it "more pythonic" to have all imports at the top, or on demand?
Possible Duplicate:
Good or bad practice in Python: import in the middle of a file
I'm used to languages like Java that mandate that all import statements appear at the top of the class/file.
Which is considered more pythonic/"beautiful" - havin... | Is it "more pythonic" to have all imports at the top, or on demand? |
Possible Duplicate:
Good or bad practice in Python: import in the middle of a file
I'm used to languages like Java that mandate that all import statements appear at the top of the class/file.
Which is considered more pythonic/"beautiful" - having them all at the top, or on demand, as they're needed?
| [
"It depends.\nMost of the time you want it at the top. This isn't because of PEP-8 (anyone who cites PEP-8 as a justification in and of itself misunderstands design rationale), but for the practical reasons underlying PEP-8's recommendation:\nIf you put imports inside functions, and those imports aren't available,... | [
10
] | [] | [] | [
"import",
"python"
] | stackoverflow_0005302274_import_python.txt |
Q:
Python initialization segfault
I'm building app with boost.python. I have some singleton class named ScriptsManager, it has function initPython which does:
mMainModule = bp::import("__main__");
mMainNamespace = bp::import("__dict__");
bp::object ignored = bp::exec("hello = file('hello.txt', 'w')\n"
... | Python initialization segfault | I'm building app with boost.python. I have some singleton class named ScriptsManager, it has function initPython which does:
mMainModule = bp::import("__main__");
mMainNamespace = bp::import("__dict__");
bp::object ignored = bp::exec("hello = file('hello.txt', 'w')\n"
"hello.write('Hello world!')\n"
... | [
"I think what you want is the following:\nint main (int argc, char** argv)\n{\n try\n {\n // If you're going to use threads: PyEval_InitThreads();\n Py_Initialize();\n PySys_SetArgv(argc, argv);\n\n bp::object mMainModule = bp::import('__main__');\n bp::object mMainNamespace... | [
3
] | [] | [] | [
"boost",
"c++",
"initialization",
"python",
"segmentation_fault"
] | stackoverflow_0005302076_boost_c++_initialization_python_segmentation_fault.txt |
Q:
How to call a variable of a method in another method of the same class
I'm trying to access a variable of a method in another method of the SAME class and for some reason it prints nothing.
class Colors:
def blue(self):
var = "This is blue"
def red(self):
b = self.blue
p... | How to call a variable of a method in another method of the same class | I'm trying to access a variable of a method in another method of the SAME class and for some reason it prints nothing.
class Colors:
def blue(self):
var = "This is blue"
def red(self):
b = self.blue
print(b.var)
I've also tried print(self.blue.var).
| [
"Local variables are, well, local to the scope of a function. They don't even exist when the function is not currently being executed, so there is nothing to access.\nIf you want the variable to have a bigger scope, well, just give it a bigger scope:\ndef blue(self):\n self.var = \"This is blue\"\n\ndef red(sel... | [
10,
3,
1,
1,
0
] | [] | [] | [
"python",
"variables"
] | stackoverflow_0005302104_python_variables.txt |
Q:
Packing 4 Integers as ONE INTEGER?
Possible Duplicate:
Packing 4 Integers as ONE BYTE?
I have four integers {a, b, c, d} that can have the following range of values:
a - {0 or 1} (1 bit)
b - {0 or 1} (1 bit)
c - {0, 1, 2, ..., 7} (3 bits)
d - {0, 1, 2, ..., 7} (3 bits)
Is it possible to 'convert' the... | Packing 4 Integers as ONE INTEGER? |
Possible Duplicate:
Packing 4 Integers as ONE BYTE?
I have four integers {a, b, c, d} that can have the following range of values:
a - {0 or 1} (1 bit)
b - {0 or 1} (1 bit)
c - {0, 1, 2, ..., 7} (3 bits)
d - {0, 1, 2, ..., 7} (3 bits)
Is it possible to 'convert' them to ONE INTEGER (between 0 - 255) with... | [
"If you mean that you don't want to do the bit packing and unpacking, ctypes.Structure provides these facilites.\nFor example:\nfrom ctypes import *\nclass Int(Structure):\n _fields_ = [(\"a\", c_int, 1), (\"b\", c_int, 1),\n (\"c\", c_int, 3), (\"d\", c_int, 3)]\n\np = Int()\np.a = 1\np.b = 0\np.... | [
6,
5,
0
] | [] | [] | [
"binary",
"python"
] | stackoverflow_0005302562_binary_python.txt |
Q:
Can I write to terminal and a given file with one command in Python?
I have seen this question answered in reference to Bash, but can't find one for Python. Apologies if this is repeating something.
Is it possible to print to the terminal and an output file with one command? I'm familiar with using print >> and sy... | Can I write to terminal and a given file with one command in Python? | I have seen this question answered in reference to Bash, but can't find one for Python. Apologies if this is repeating something.
Is it possible to print to the terminal and an output file with one command? I'm familiar with using print >> and sys.stdout = WritableObject, but I'd like to avoid having to double print co... | [
"Replace sys.stdout.\nclass PrintAndLog(object):\n def __init__(self, fileOrPath): # choose which makes more sense\n self._file = ...\n\n def write(s):\n sys.stdout.write(s)\n self._file.write(s)\n\n def close(self):\n self._file.close()\n # insert wrappers for .flush, .write... | [
6,
2,
0
] | [] | [] | [
"python",
"python_2.6",
"python_idle",
"windows"
] | stackoverflow_0005302770_python_python_2.6_python_idle_windows.txt |
Q:
How do I supply latitude longitude info (got by JS ) on client machine to Python running on server?
I tried using Google's GEOLOCATION api and html5 to get device location. Both methods get data using JavaScript.
I also know I am able to get street/city name information from Google's GEOCODING api using JSON.
I ... | How do I supply latitude longitude info (got by JS ) on client machine to Python running on server? |
I tried using Google's GEOLOCATION api and html5 to get device location. Both methods get data using JavaScript.
I also know I am able to get street/city name information from Google's GEOCODING api using JSON.
I am also able to fetch map tiles from openstreetmaps/cloudemade from a specific latitude, longitude.
Big... | [
"If you are running Javascript code in your browser that needs to communicate with some Python code running somewhere else, then the easiest way to get them to communicate is by settings up an HTTPServer in Python. The javascript will then be able to make HTTP Requests to the Python server.\nYou'll probably be able... | [
0
] | [] | [] | [
"geolocation",
"python"
] | stackoverflow_0005302649_geolocation_python.txt |
Q:
How can I perform ten-fold cross validation with LibSVM?
Where can I find an example of using LibSVM (Java/Python) to perform 10-fold cross validation on a data set?
A:
In case of Java;
You can use svm_cross_validation() method which is provided by libsvm.
double[] target = new double[svmProblem.l];
svm.svm_cros... | How can I perform ten-fold cross validation with LibSVM? | Where can I find an example of using LibSVM (Java/Python) to perform 10-fold cross validation on a data set?
| [
"In case of Java;\nYou can use svm_cross_validation() method which is provided by libsvm.\ndouble[] target = new double[svmProblem.l];\nsvm.svm_cross_validation(svmProblem, svmParameter, 10, target );\n\nYou should have created your svm_problem and svm_parameter instances (svmProblem and svmParameter in the sample)... | [
5,
0
] | [] | [] | [
"java",
"libsvm",
"python",
"validation"
] | stackoverflow_0005282198_java_libsvm_python_validation.txt |
Q:
g++ linking and swig
I have a cpp file with functions that I'm using in python with SWIG. I use the following commands to compile the source and create the file to use with python.
swig -c++ -python mini.i
g++ -O2 -c mini.cpp -I/usr/include/python2.4 -I/usr/lib/python2.4
g++ -O2 -c mini_wrap.cxx -I/usr/include... | g++ linking and swig | I have a cpp file with functions that I'm using in python with SWIG. I use the following commands to compile the source and create the file to use with python.
swig -c++ -python mini.i
g++ -O2 -c mini.cpp -I/usr/include/python2.4 -I/usr/lib/python2.4
g++ -O2 -c mini_wrap.cxx -I/usr/include/python2.4 -I/usr/lib/pyth... | [
"Swig does no linking, as the warning message states. Put the -lgsl etc. on the link command, which is your last g++ command.\n"
] | [
1
] | [] | [] | [
"compiler_construction",
"gsl",
"linker",
"python",
"swig"
] | stackoverflow_0005302933_compiler_construction_gsl_linker_python_swig.txt |
Q:
matching parentheses in python regular expression
I have something like
store(s)
ending line like "1 store(s)".
I want to match it using Python regular expression.
I tried something like re.match('store\(s\)$', text)
but it's not working.
This is the code I tried:
import re
s = '1 store(s)'
if re.match('store\(... | matching parentheses in python regular expression | I have something like
store(s)
ending line like "1 store(s)".
I want to match it using Python regular expression.
I tried something like re.match('store\(s\)$', text)
but it's not working.
This is the code I tried:
import re
s = '1 store(s)'
if re.match('store\(s\)$', s):
print('match')
| [
"In more or less direct reply to your comment\n\nTry this\nimport re\ns = '1 stores(s)'\nif re.match('store\\(s\\)$',s):\n print('match')\n\n\nThe solution is to use re.search instead of re.match as the latter tries to match the whole string with the regexp while the former just tries to find a substring inside ... | [
6,
1,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0005302942_python_regex.txt |
Q:
Packing 4 Integers as ONE BYTE?
I have four integers {a, b, c, d} that can have the following range of values:
a - {0 or 1} (1 bit)
b - {0 or 1} (1 bit)
c - {0, 1, 2, ..., 7} (3 bits)
d - {0, 1, 2, ..., 7} (3 bits)
at first, I would like to pack them into a one byte that can be then written to a binary... | Packing 4 Integers as ONE BYTE? | I have four integers {a, b, c, d} that can have the following range of values:
a - {0 or 1} (1 bit)
b - {0 or 1} (1 bit)
c - {0, 1, 2, ..., 7} (3 bits)
d - {0, 1, 2, ..., 7} (3 bits)
at first, I would like to pack them into a one byte that can be then written to a binary file.
later, I would like to unpack ... | [
"Use shift and bitwise OR, then convert to a character to get a \"byte\":\nx = chr(a | (b << 1) | (c << 2) | (d << 5))\n\nTo unpack this byte again, first convert to an integer, then shift and use bitwise AND:\ni = ord(x)\na = i & 1\nb = (i >> 1) & 1\nc = (i >> 2) & 7\nd = (i >> 5) & 7\n\nExplanation: Initially, y... | [
32,
10,
5,
4
] | [] | [] | [
"binary",
"python",
"struct"
] | stackoverflow_0005302374_binary_python_struct.txt |
Q:
randomizing a list in python manually
Here's some code for shuffling a deck of cards manually. I understand it up to the point where cards[pos], cards[randpos] = cards[randpos], cards[pos]. What is happening here? What is the point of assigning cards[pos] to cards[randpos]?
self.cards is a list of playing cards... | randomizing a list in python manually | Here's some code for shuffling a deck of cards manually. I understand it up to the point where cards[pos], cards[randpos] = cards[randpos], cards[pos]. What is happening here? What is the point of assigning cards[pos] to cards[randpos]?
self.cards is a list of playing cards in standard order.
def shuffle(self):
... | [
"The values of cards[pos] and cards[randpos] are being switched. This is a common Python idiom: you can switch two or more variables' values by saying a, b = b, a.\nNote that the standard library implementation of shuffling (random.shuffle()) is quite similar.\n",
"It's swapping the positions of the cards in pos ... | [
3,
1,
1,
1,
1,
0
] | [] | [] | [
"list",
"python",
"random"
] | stackoverflow_0005303727_list_python_random.txt |
Q:
Python utilizing multiple processors
Lets say I have a big list of music of varying length that needs to be converted or images of varying sizes that need to be resized or something like that. The order doesn't matter so it is perfect for splitting across multiple processors.
If I use multiprocessing.Pool's map f... | Python utilizing multiple processors | Lets say I have a big list of music of varying length that needs to be converted or images of varying sizes that need to be resized or something like that. The order doesn't matter so it is perfect for splitting across multiple processors.
If I use multiprocessing.Pool's map function it seems like all the work is divi... | [
"There is a Queue class within the multiprocessing module specifically for this purpose.\nEdit: If you are looking for a complete framework for parallel computing which features a map() function using a task queue, have a look at the parallel computing facilities of IPython. In particlar, you can use the TaskClien... | [
6,
2,
1,
1,
0
] | [] | [] | [
"batch_file",
"multiprocessing",
"multithreading",
"python",
"queue"
] | stackoverflow_0004838738_batch_file_multiprocessing_multithreading_python_queue.txt |
Q:
500 internal server error when importing a python module in wsgi
I've got a Python script that is executing functions asynchronously by using PEST wsgi library. However, when I try to import another module it simply results in a 500 error.
The way I try to reference it is:
from foo import *
from foo import Foo
... | 500 internal server error when importing a python module in wsgi | I've got a Python script that is executing functions asynchronously by using PEST wsgi library. However, when I try to import another module it simply results in a 500 error.
The way I try to reference it is:
from foo import *
from foo import Foo
where foo is a file .py in which I have the object that I want to ref... | [
"Apache's 500 error just tells you that the Python script is returning an error. My guess is that in the Apache environment, Python can't find that module. Try a simple script that prints sys.path and makes sure it has the directories in it you expect.\n",
"Adding \nWSGIPythonPath /path/to/my/py/files/folder\n\n... | [
3,
2,
1,
0
] | [] | [] | [
"apache2",
"cgi",
"mod_wsgi",
"python",
"wsgi"
] | stackoverflow_0005284362_apache2_cgi_mod_wsgi_python_wsgi.txt |
Q:
Python - return a region of a list based on calculated percentages
I have a fairly long list in python which I want to return parts of it in a single, shorter list based on 3 percentages. If the first percentage was 30%, it would need to return the first 30% of the values and if the 3rd percentage was 50% it would... | Python - return a region of a list based on calculated percentages | I have a fairly long list in python which I want to return parts of it in a single, shorter list based on 3 percentages. If the first percentage was 30%, it would need to return the first 30% of the values and if the 3rd percentage was 50% it would need to return the last half of the values of my long list.
This is wha... | [
"If I understand correctly, you want to keep three lists, based on a certain percentage at the start and end plus the \"in between\":\ndef split_list(mylist, a, b):\n l = len(mylist)\n return ( mylist[:int(a*l/100)], \n mylist[int(a*l/100):-int(b*l/100)],\n mylist[-int(b*l/100):] )\n\n... | [
2,
1
] | [] | [] | [
"list",
"python"
] | stackoverflow_0005302927_list_python.txt |
Q:
Caching calendar data from Google Calendar
I need to pull events from a Google Calendar in order to present them on a site built with Django. I'm not sure what's the best way of doing it, but I believe the data should be cached (my site/app doesn't use any caching today).
As I don't need an event archive, I'm want... | Caching calendar data from Google Calendar | I need to pull events from a Google Calendar in order to present them on a site built with Django. I'm not sure what's the best way of doing it, but I believe the data should be cached (my site/app doesn't use any caching today).
As I don't need an event archive, I'm want to avoid using the db.
This is the approach I'm... | [
"My approach would be to avoid caching by making ajax calls and the javascript version of the gdata client library.\nAre there features of \"iCalendar\" (is this a python module for manipulating this kind of data?) you can't replicate using javascript?\nThis approach would save you storage and processing and most l... | [
2,
2
] | [] | [] | [
"caching",
"django",
"google_calendar_api",
"icalendar",
"python"
] | stackoverflow_0005303002_caching_django_google_calendar_api_icalendar_python.txt |
Q:
Finding number of colored shapes from picture using Python
My problem has to do with recognising colours from pictures. Doing microbiology I need to count the number of cell nuclei present on a picture taken with a microscope camera. I've used GIMP to tag the nuclei with dots of red colour. Now I'd need to make a ... | Finding number of colored shapes from picture using Python | My problem has to do with recognising colours from pictures. Doing microbiology I need to count the number of cell nuclei present on a picture taken with a microscope camera. I've used GIMP to tag the nuclei with dots of red colour. Now I'd need to make a script in python, which, given an image, would tell me how many ... | [
"Count nuclei\nThe code adapted from Python Image Tutorial. Input image with nuclei from the tutorial:\n\n#!/usr/bin/env python\nimport scipy\nfrom scipy import ndimage\n\n# read image into numpy array\n# $ wget http://pythonvision.org/media/files/images/dna.jpeg\ndna = scipy.misc.imread('dna.jpeg') # gray-scale im... | [
16,
4,
2
] | [] | [] | [
"image_processing",
"python"
] | stackoverflow_0005298884_image_processing_python.txt |
Q:
Having too many specialized exceptions; is this an issue?
Is there a potential problem with having a large amount of different exceptions if they are all derived from some package specific exception? For example, I have FooException. From there, I then have OutOfRangeOfSomethingException, RanOutOfBufferException, ... | Having too many specialized exceptions; is this an issue? | Is there a potential problem with having a large amount of different exceptions if they are all derived from some package specific exception? For example, I have FooException. From there, I then have OutOfRangeOfSomethingException, RanOutOfBufferException, OverflowMapBoundaryException all from that package specific bas... | [
"The more exception types you have, the more exception types you have to maintain. It's a matter of how fine-grained the control you require over your exceptions is versus how much you want to have to continue maintaining that fine-level grain across the board. There's no real performance penalty for having a mor... | [
4
] | [] | [] | [
"exception",
"exception_handling",
"python"
] | stackoverflow_0005304190_exception_exception_handling_python.txt |
Q:
Python: How do I install django-extensions into a virtualenv?
I've created a virtualenv with -no-sitepackages. I'd like to install django-extensions into this virtualenv. The thing is when I run:
python setyp.py install
from within the virtualenv, it creates and writes to
/usr/local/lib/python2.6/dist-packages/... | Python: How do I install django-extensions into a virtualenv? | I've created a virtualenv with -no-sitepackages. I'd like to install django-extensions into this virtualenv. The thing is when I run:
python setyp.py install
from within the virtualenv, it creates and writes to
/usr/local/lib/python2.6/dist-packages/django_extensions-0.4.1.egg-info.
What's the correct way to get d... | [
"Run pip install -E your_virtualenv_here django-extensions, then just activate and you're set.\n",
"Are you sure you have activated your virtualenv? Usually you use source <virtualenv_path>/bin/activate. Check for a $VIRTUAL_ENV environment variable as well.\n"
] | [
3,
0
] | [] | [] | [
"python",
"virtualenv"
] | stackoverflow_0005303557_python_virtualenv.txt |
Q:
Sqlalchemy adds unwanted columns to query when a foreign key table is added
In a Sqlalchemy query, you can select specific rows like this:
q = session.query(Equipment.name)
That will return one column for each row. You can add more column descriptors from model. The value of len(q.column_descriptions) is one in t... | Sqlalchemy adds unwanted columns to query when a foreign key table is added | In a Sqlalchemy query, you can select specific rows like this:
q = session.query(Equipment.name)
That will return one column for each row. You can add more column descriptors from model. The value of len(q.column_descriptions) is one in this case.
However, as soon as you add a column that is a foreign key you suddenly... | [
"\"name\" is a column. \"model\" is not - its a relationship() (based on the observed behavior above). The current default __clause_element__() for relationship is the full table so that's why all columns get spit out. As you noted in ticket #1328 this is related, but the proposal there is that you'd be getti... | [
3
] | [] | [] | [
"python",
"sqlalchemy"
] | stackoverflow_0005298498_python_sqlalchemy.txt |
Q:
Create a list of defaultdict in python
I am doing the following :
recordList=[lambda:defaultdict(str)]
record=defaultdict(str)
record['value']='value1'
record['value2']='value2'
recordList.append(record)
for record in recordList:
params = (record['value'],record['value2'],'31')
i am getting the error :
Type... | Create a list of defaultdict in python | I am doing the following :
recordList=[lambda:defaultdict(str)]
record=defaultdict(str)
record['value']='value1'
record['value2']='value2'
recordList.append(record)
for record in recordList:
params = (record['value'],record['value2'],'31')
i am getting the error :
TypeError: 'function' object is not
subscripta... | [
"recordList=[lambda:defaultdict(str)]\n\ncreates a list with a function that returns defaultdict(str). So it's basically equivalent to:\ndef xy ():\n return defaultdict(str)\n\nrecordList = [] \nrecordList.append( xy )\n\nAs such, when you start your for loop, you get the first element from the list, which is... | [
3,
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0005304325_python.txt |
Q:
How to Translate XML into HTML using XSL Stylesheet in Python?
I have an XSL stylesheet template that transforms my XML file into HTML. How can I perform such processing using Python?
...and here's the link to really simple solution:)
A:
Use lxml, which supports XSLT 1.0.
| How to Translate XML into HTML using XSL Stylesheet in Python? | I have an XSL stylesheet template that transforms my XML file into HTML. How can I perform such processing using Python?
...and here's the link to really simple solution:)
| [
"Use lxml, which supports XSLT 1.0.\n"
] | [
3
] | [] | [] | [
"html",
"python",
"xml",
"xslt"
] | stackoverflow_0005304449_html_python_xml_xslt.txt |
Q:
Pythonic loops--how to get multiple elements while iterating a list
I want to iterate over my list and do something with multiple elements, not just one element. I want to take the first element and some elements after it (they could be sequential or maybe the 3rd element from the one returned).
l = ['a', 'b', 'c'... | Pythonic loops--how to get multiple elements while iterating a list | I want to iterate over my list and do something with multiple elements, not just one element. I want to take the first element and some elements after it (they could be sequential or maybe the 3rd element from the one returned).
l = ['a', 'b', 'c', 'd', 'e']
for items in l:
print items[:3]
The output should be:
... | [
"l = ['a', 'b', 'c', 'd', 'e']\nsubarraysize = 3\nfor i in range(len(l)-subarraysize+1):\n print l[i:i+subarraysize]\n\nOutput:\n['a', 'b', 'c']\n['b', 'c', 'd']\n['c', 'd', 'e']\n\nNot very Pythonic I know, but in its favour it does actually work.\n",
"You can use zip and slicing:\nl = range(5)\nfor grp in zi... | [
3,
3,
3,
2,
2,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0005292226_python.txt |
Q:
Django locale setting on Linux and Windows for number formatting
I have a Django custom template tag
@register.filter("numformat")
@stringfilter
def numformat(value, uLocale=''):
if uLocale.count('%') > 0 :
return str((float(value)) *100) + "%"
uLocale = uLocale.encode('utf8').strip("%")
try... | Django locale setting on Linux and Windows for number formatting | I have a Django custom template tag
@register.filter("numformat")
@stringfilter
def numformat(value, uLocale=''):
if uLocale.count('%') > 0 :
return str((float(value)) *100) + "%"
uLocale = uLocale.encode('utf8').strip("%")
try :
locale.setlocale(locale.LC_ALL, uLocale)
except :
... | [
"Using setlocale() this way might prove problematic, particularly because of threads (IIRC, setlocale() applies program-wide and should be called before spawning new threads). babel (http://babel.edgewall.org/) does what you are trying to achieve and works with Django.\n"
] | [
2
] | [] | [] | [
"django",
"locale",
"python"
] | stackoverflow_0005302475_django_locale_python.txt |
Q:
How to pass a binary buffer via python ctypes to a c function
I'd like to wrap the following c function bar() in python 2.x and invoke
it via the ctypes module, both on Linux and Windows:
#include <stdio.h>
#ifdef FOO_DLL
#define FOO_API __declspec(dllexport)
#else
#define FOO_API extern
#endif
FOO_API unsigned... | How to pass a binary buffer via python ctypes to a c function | I'd like to wrap the following c function bar() in python 2.x and invoke
it via the ctypes module, both on Linux and Windows:
#include <stdio.h>
#ifdef FOO_DLL
#define FOO_API __declspec(dllexport)
#else
#define FOO_API extern
#endif
FOO_API unsigned int bar(const void* data, unsigned int len)
{
printf("%p (%d b... | [
"Both Windows and Linux should use cdll which results in the C calling convention. The Python code at present calls your Windows DLL using stdcall but it's really a cdecl function. The difference between cdll and windll is just the calling convention used.\nThat error message is a textbook calling convention mismat... | [
1
] | [] | [] | [
"ctypes",
"python",
"wrapper"
] | stackoverflow_0005305003_ctypes_python_wrapper.txt |
Q:
Initiating a method in a class
I'm new to both Django and Python.. I just started using them a few days ago and I can't quite figure out how to call a method other than the __init__ method for a class.
Here is the code for user.py
class User:
def __init__(self, number):
self.num = number
class Create:... | Initiating a method in a class | I'm new to both Django and Python.. I just started using them a few days ago and I can't quite figure out how to call a method other than the __init__ method for a class.
Here is the code for user.py
class User:
def __init__(self, number):
self.num = number
class Create:
def __init__(self, something):
... | [
"Good news - it's a simple one! To call other() on create, you'd do this:\nlist = [3, 4, 5]\ny = Create(list)\ny.other('one')\n\nYou just need to pass the parameters inside the parentheses, after the name of the method.\nEDIT: I've just noticed you want to call other from inside the Create class. That'd look like t... | [
2
] | [] | [] | [
"django",
"python"
] | stackoverflow_0005305000_django_python.txt |
Q:
content_for equivalent for Django templating
Is there any way of replicating Rails' content_for in Django?
The use case is as follows:
# base.html
<html>
<head>
<script type='text/javascript' src='jquery.js'></script>
{% yield 'head' %}
</head>
<body>
{% block content %}{% endblock %}
</body>
<... | content_for equivalent for Django templating | Is there any way of replicating Rails' content_for in Django?
The use case is as follows:
# base.html
<html>
<head>
<script type='text/javascript' src='jquery.js'></script>
{% yield 'head' %}
</head>
<body>
{% block content %}{% endblock %}
</body>
</html>
# page.html
{% extends 'base.html' %}
{% c... | [
"Try extending widget.html from page.html template.\nAlso take a look at templates in Admin app @/site-packages/django/contrib/admin/templates (e.g base_site.html, change_form.html)\n# base.html\n<html>\n <head>\n <script type='text/javascript' src='jquery.js'></script>\n {% block extrahead %}{% endblock %}\... | [
1,
0
] | [] | [] | [
"django",
"django_templates",
"python"
] | stackoverflow_0005302206_django_django_templates_python.txt |
Q:
Find minimum element in a dictionary of dictionaries
I need to find what element of apple has the minimum size.
Tnx for all answers. But there is one problem: I use Python 2.4.2 (I can't change it) and function min haven't key arg. Yes, I need key of apple
apple = {1:{'size':12,'color':'red'},2:{'size':10,'color':... | Find minimum element in a dictionary of dictionaries | I need to find what element of apple has the minimum size.
Tnx for all answers. But there is one problem: I use Python 2.4.2 (I can't change it) and function min haven't key arg. Yes, I need key of apple
apple = {1:{'size':12,'color':'red'},2:{'size':10,'color':'green'}}
| [
"import operator\nmin(apple.values(), key=operator.itemgetter('size'))\n\nwill return you \n{'color': 'green', 'size': 10}\n\nUPDATE: to get the index:\nmin(apple, key=lambda k: apple[k]['size'])\n\n",
"Python has a very nice parameter for the min function that allows using an arbitrary function to be minified in... | [
12,
10,
3,
1,
1,
0
] | [] | [] | [
"multidimensional_array",
"python",
"python_2.4"
] | stackoverflow_0005083340_multidimensional_array_python_python_2.4.txt |
Q:
Getting smallest number in array python
I am trying to program in python
I have an array which holds data like
[A,20,False] [B,1,False] [C, 8, False]
I want to be able to loop through the array by getting the element with the lowest middle number so e.g. the next element to be worked on would be B because it has t... | Getting smallest number in array python | I am trying to program in python
I have an array which holds data like
[A,20,False] [B,1,False] [C, 8, False]
I want to be able to loop through the array by getting the element with the lowest middle number so e.g. the next element to be worked on would be B because it has the smallest number one. Then this gets delete... | [
">>> myList = [[\"A\", 20, False], [\"B\", 1, False], [\"C\", 8, False]]\n>>> smallest = min(myList, key=lambda L: L[1])\n>>> smallest\n['B', 1, False]\n\nIf you'd like to sort it using that element you can do the same thing with sorted:\n>>> sorted(myList, key=lambda L: L[1])\n[['B', 1, False], ['C', 8, False], ['... | [
5,
2,
0
] | [] | [] | [
"arrays",
"for_loop",
"loops",
"minimum",
"python"
] | stackoverflow_0005305343_arrays_for_loop_loops_minimum_python.txt |
Q:
python zlib output to c++ string
I am trying to write the output of python zlib's output to a c++ string. The question is very similar to Python zlib output, how to recover out of mysql utf-8 table? here however, the difference is that my python script generates a C++ header file where the compressed data should b... | python zlib output to c++ string | I am trying to write the output of python zlib's output to a c++ string. The question is very similar to Python zlib output, how to recover out of mysql utf-8 table? here however, the difference is that my python script generates a C++ header file where the compressed data should be stored as a string. However, because... | [
"You need to escape the non-printable characters in the string using octal notation.\nFor example, \nimport string\n....\nsafe_string = \"\"\nfor ch in compressed_string:\n if ch in string.printable and ch != '\\\\':\n safe_string += ch\n else:\n safe_string += \"\\%o\" % ord(ch)\ncontent = \".....\\\... | [
3,
2
] | [] | [] | [
"c",
"c++",
"python",
"zlib"
] | stackoverflow_0005305007_c_c++_python_zlib.txt |
Q:
Python mysqldb on Mac OSX 10.6 not working
I am using Python 2.7 and trying to get a Django project running on a MySQL backend.
I have downloaded mysqldb and followed the guide here:http://cd34.com/blog/programming/python/mysql-python-and-snow-leopard/
Yet when I go to run the django project the following tracebac... | Python mysqldb on Mac OSX 10.6 not working | I am using Python 2.7 and trying to get a Django project running on a MySQL backend.
I have downloaded mysqldb and followed the guide here:http://cd34.com/blog/programming/python/mysql-python-and-snow-leopard/
Yet when I go to run the django project the following traceback occurs:
Traceback (most recent call last):
... | [
"I eventually managed to solve the problem by Installing python 2.7 with Mac Ports and installing mysqldb using Mac Ports - was pretty simple after that.\n",
"you needed to add the MySQL client libraries to the LD_LIBRARY_PATH.\n"
] | [
2,
0
] | [] | [] | [
"django",
"macos",
"mysql",
"python"
] | stackoverflow_0005072066_django_macos_mysql_python.txt |
Q:
Python string replace in a file without touching the file if no substitution was made
What does Python's string.replace return if no string substitution was made?
Does Python's file.open(f, 'w') always touch the file even if no changes were made?
Using Python, I'm trying to replace occurrences of 'oldtext' with 'n... | Python string replace in a file without touching the file if no substitution was made | What does Python's string.replace return if no string substitution was made?
Does Python's file.open(f, 'w') always touch the file even if no changes were made?
Using Python, I'm trying to replace occurrences of 'oldtext' with 'newtext' in a set of files. If a file contains 'oldtext', I want to do the replacement and ... | [
"\nWhat does Python's string.replace\n return if no string substitution was\n made?\n\nIt returns the original string.\n\nDoes Python's file.open(f, 'w') always\n touch the file even if no changes were\n made?\n\nMore than merely touching the file, it destroys any content f used to contain.\nSo, you can test if... | [
14,
4,
3
] | [] | [] | [
"file_io",
"python",
"replace"
] | stackoverflow_0005286020_file_io_python_replace.txt |
Q:
Using pyobjc imports in PyDev in Eclipse on Mac OS X
I've installed and configured PyDev version 1.6.5.2011020317 inside Eclipse, running on Mac OS X 10.6.6:
Version: Helios Service Release 1
Build id: 20100917-0705
I used 'Auto Config' to set up my Python interpreter: it correctly found /usr/bin/python (which... | Using pyobjc imports in PyDev in Eclipse on Mac OS X | I've installed and configured PyDev version 1.6.5.2011020317 inside Eclipse, running on Mac OS X 10.6.6:
Version: Helios Service Release 1
Build id: 20100917-0705
I used 'Auto Config' to set up my Python interpreter: it correctly found /usr/bin/python (which is Python version 2.6.1) and added various system folders... | [
"Why does this happen?: PyDev has no support for parsing the PyObjC scripting bridge metadata, and therefore has no way of introspecting / extracting symbols for many of the PyObjC classes.\nWhat to do to fix it: In the PyDev source code there are several Python scripts which handle discovery of this metadata. The ... | [
4
] | [] | [] | [
"eclipse",
"macos",
"pydev",
"pyobjc",
"python"
] | stackoverflow_0005234647_eclipse_macos_pydev_pyobjc_python.txt |
Q:
Excel win32com programming with Python. Passing Parameters to function
I suspect there is an easy answer for this question but I can't find it anywhere! I am writing a function to plot a lot of data in excel and I am controlling the plotting with Python. I have generated all of the charts and each chart is its o... | Excel win32com programming with Python. Passing Parameters to function | I suspect there is an easy answer for this question but I can't find it anywhere! I am writing a function to plot a lot of data in excel and I am controlling the plotting with Python. I have generated all of the charts and each chart is its own sheet, but they are out of order. The VBA code for this is:
Sheets("Char... | [
"Here's a very simple example:\nfrom win32com import client\n\nexcel=client.Dispatch(\"Excel.Application\")\nexcel.Visible=True\nbook=excel.Workbooks.Open(\"c:/desktop/test.xlsx\", False, True)\nsheet=book.Worksheets(1)\nchart=book.Charts.Add()\nchart.SetSourceData(sheet.Range(\"$A:$B\"))\n\nchart.Move(Before=book.... | [
4
] | [] | [] | [
"excel",
"python",
"win32com"
] | stackoverflow_0005305297_excel_python_win32com.txt |
Q:
Edit configuration file through python
I need to edit a configuration file through python and i tried searching on stackoverflow and google and they don't cover my situation, since i need to replace lines in the file and perform matches in my search.
Also, what i found covers how to do it for one line, i will be p... | Edit configuration file through python | I need to edit a configuration file through python and i tried searching on stackoverflow and google and they don't cover my situation, since i need to replace lines in the file and perform matches in my search.
Also, what i found covers how to do it for one line, i will be performing at least 8 line replacements in th... | [
"import re \npat = re.compile('ENABLEPRINTER|PRINTERLIST|PRNT1.PORT')\n\ndef jojo(mat,dic = {'ENABLEPRINTER':'y',\n 'PRINTERLIST':'PRNT3',\n 'PRNT1.PORT':'734'} ):\n return dic[mat.group()]\n\nwith open('configfile','rb+') as f:\n content = f.read()\n f.seek(0,0)\n ... | [
7,
4
] | [] | [] | [
"configuration_files",
"file_io",
"python",
"python_3.x",
"text_manipulation"
] | stackoverflow_0005299092_configuration_files_file_io_python_python_3.x_text_manipulation.txt |
Q:
Django auth group model m2m
Recently, I have been working in a generic inscription system to help students to register in a class or a lab. But I have problems with the logic of ManyToManyField in the Lab class.
from django.db import models
from django.contrib.auth.models import User
class Day(models.Model):
... | Django auth group model m2m | Recently, I have been working in a generic inscription system to help students to register in a class or a lab. But I have problems with the logic of ManyToManyField in the Lab class.
from django.db import models
from django.contrib.auth.models import User
class Day(models.Model):
name = models.CharField(max_lengt... | [
"Ah, see that's MUCH clearer. \nI would re-write {'id__in' : Group.objects.all().get(name='Teachers').user_set.all()}\nto: \n{'groups__name' : 'Teachers' }\nAlso, if you would like to keep your admin functionality separated from your models more (did you know Admin was originally completely in the models?), you ca... | [
2
] | [] | [] | [
"django",
"python"
] | stackoverflow_0005304361_django_python.txt |
Q:
Python Online Form Submision
I am using Python 2.7.1 to access an online website. I need to load a URL, then submit a POST request to that URL that causes the website to redirect to a new URL. I would then like to POST some data to the new URL. This would be easy to do, except that the website in question does not... | Python Online Form Submision | I am using Python 2.7.1 to access an online website. I need to load a URL, then submit a POST request to that URL that causes the website to redirect to a new URL. I would then like to POST some data to the new URL. This would be easy to do, except that the website in question does not allow the user to use browser nav... | [
"Have you taken a look at mechanize? I believe it has the functionality you need.\n",
"You're probably getting to that page by posting something via that Next button. You'll have to take a look at the POST parameters sent when pressing that button and add all of these post parameters to your call.\nThe website co... | [
0,
0
] | [] | [] | [
"authentication",
"forms",
"python"
] | stackoverflow_0005305664_authentication_forms_python.txt |
Q:
Python: How do I convert from binary to base 64 and back?
Lets say I have some binary value:
0b100
and want to convert it to base64
doing base64.b64decode(0b100) tells me that it is expecting a string, not an int.... now, I don't want to work with strings.
So, could anyone point me in the right direction for conv... | Python: How do I convert from binary to base 64 and back? | Lets say I have some binary value:
0b100
and want to convert it to base64
doing base64.b64decode(0b100) tells me that it is expecting a string, not an int.... now, I don't want to work with strings.
So, could anyone point me in the right direction for converting binary numbers to base64 numbers? thanks!
=D
| [
"Depending on how you represent the value 0b100\n>>> import struct\n>>> val = 0b100\n>>> print struct.pack('I', val).encode('base64')\nBAAAAA==\n\nThis will turn your value into a 4-byte integer in native endianness, and encode that value into base64. You need to specify the width of your data as base64 is really m... | [
6,
1,
0
] | [] | [] | [
"base64",
"binary",
"python"
] | stackoverflow_0005305456_base64_binary_python.txt |
Q:
Python: How do I convert an array of strings to an array of numbers?
Possible Duplicate:
What is the easiest way to convert list with str into list with int?
current array: ['1','-1','1']
desired array: [1,-1,1]
A:
Use int which converts a string to an int, inside a list comprehension, like this:
desired_array... | Python: How do I convert an array of strings to an array of numbers? |
Possible Duplicate:
What is the easiest way to convert list with str into list with int?
current array: ['1','-1','1']
desired array: [1,-1,1]
| [
"Use int which converts a string to an int, inside a list comprehension, like this:\ndesired_array = [int(numeric_string) for numeric_string in current_array]\n\n",
"List comprehensions are the way to go (see @sepp2k's answer). Possible alternative with map:\nlist(map(int, ['1','-1','1']))\n\n",
"Let's see if I... | [
76,
55,
0
] | [] | [] | [
"python"
] | stackoverflow_0005306079_python.txt |
Q:
How to delete a line in file1 that appeared once or multiple times in file2 in python?
I have two text files: file1 has 40 lines and file2 has 1.3 million lines
I would like to compare every line in file1 with file2.
If a line in file1 appeared once or multiple times in file2,
this line(lines) should be deleted... | How to delete a line in file1 that appeared once or multiple times in file2 in python? | I have two text files: file1 has 40 lines and file2 has 1.3 million lines
I would like to compare every line in file1 with file2.
If a line in file1 appeared once or multiple times in file2,
this line(lines) should be deleted from file2 and remaining lines of file2 return to a third file3.
I could painfully delete ... | [
"Read file1; put the lines into a set or dict (it'll have to be a dict if you're using a really old version of Python); now go through file2 and say something like if line not in things_seen_in_file_1: outfile.write(line) for each line.\nIncidentally, in recent Python versions you shouldn't bother calling readlines... | [
2,
2,
0
] | [
"what you can do is load file1 completely into memory (since it is small) and check each line in file2 if it matches a line in file1. if it doesn't then write it to file three. Sort of like this:\nfile1 = open('file1')\nfile2 = open('file2')\nfile3 = open('file3','w')\n\nlines_from_file1 = []\n# Read in all lines f... | [
-1
] | [
"python"
] | stackoverflow_0005300882_python.txt |
Q:
WSGI with .pyc files
I'm trying to migrate to wsgi but I'm getting ImportError exceptions all the time.
I have my modules installed only with .pyc files, I don't have the .py files in the server (I can't change that, sorry). When I add some .py files the ImportError moves away to some other import line.
Is there a... | WSGI with .pyc files | I'm trying to migrate to wsgi but I'm getting ImportError exceptions all the time.
I have my modules installed only with .pyc files, I don't have the .py files in the server (I can't change that, sorry). When I add some .py files the ImportError moves away to some other import line.
Is there a way to make WSGI use the ... | [
"You might need to put all the python files on that machine, then convert them to .pyc or .pyo then delete the .py's\nI'm suspecting maybe the .pys were generated on a different version of python maybe.\nAlso paste the import errors .. that might help in diagnoses.\n"
] | [
0
] | [] | [] | [
"python",
"wsgi"
] | stackoverflow_0005305119_python_wsgi.txt |
Q:
SWIG wrapped vector of vectors (C++ to python) - how to recognise the inner vector as a proxy object?
I'm facing a similar issue to Wrap std::vector of std::vectors, C++ SWIG Python - but it's not just simple C++ parsing. I have the following in my C++ code
namespace ns {
typedef unsigned long long uint64_t;
... | SWIG wrapped vector of vectors (C++ to python) - how to recognise the inner vector as a proxy object? | I'm facing a similar issue to Wrap std::vector of std::vectors, C++ SWIG Python - but it's not just simple C++ parsing. I have the following in my C++ code
namespace ns {
typedef unsigned long long uint64_t;
typedef std::vector<uint64_t> Vector;
typedef std::vector<Vector> VectorOfVectors;
class MyClas... | [
"I worked on this with a colleague of mine, and we have managed to come up with some solutions.\nFirst of all, in the SWIG .i file, it's important to define this preprocessor variable:\n%{\n# define SWIG_PYTHON_EXTRA_NATIVE_CONTAINERS \n%}\n\nAnd then, to ensure that the references returned from methods such as f... | [
12
] | [] | [] | [
"c++",
"python",
"swig",
"vector"
] | stackoverflow_0005265637_c++_python_swig_vector.txt |
Q:
Python: what is the fastest / most elegant way to see if every number in two arrays is the same?
ie, compare:
1,-1,1
to
1.0,-1, 1
should be the same
print("the input and the output are " + ( (input == calc_out) ? "the same" : "not the same"))
but it give a lexical error =\
A:
==
A:
The docs indicate var... | Python: what is the fastest / most elegant way to see if every number in two arrays is the same? | ie, compare:
1,-1,1
to
1.0,-1, 1
should be the same
print("the input and the output are " + ( (input == calc_out) ? "the same" : "not the same"))
but it give a lexical error =\
| [
"==\n",
"The docs indicate various ways you can compare sequences and other types:\n(1, 2, 3) < (1, 2, 4)\n[1, 2, 3] < [1, 2, 4]\n'ABC' < 'C' < 'Pascal' < 'Python'\n(1, 2, 3, 4) < (1, 2, 4)\n(1, 2) < (1, 2, -1)\n(1, 2, 3) == (1.0, 2.0, 3.0)\n(1, 2, (... | [
3,
3,
0
] | [] | [] | [
"python"
] | stackoverflow_0005306232_python.txt |
Q:
Scheme to Python: most elegant translation of a recursive procedure?
I recent read again the beautiful intro to recursion in the 'simply scheme' book (here's the link to the relevant chapter), where this recursive procedure is introduced (in the scheme language):
(define (downup wd)
(if (= (count wd) 1)
(s... | Scheme to Python: most elegant translation of a recursive procedure? | I recent read again the beautiful intro to recursion in the 'simply scheme' book (here's the link to the relevant chapter), where this recursive procedure is introduced (in the scheme language):
(define (downup wd)
(if (= (count wd) 1)
(se wd)
(se wd (downup (bl wd)) wd)))
> (downup 'toe)
(TOE TO T TO TO... | [
"If you want to closely represent the original recursive Scheme function:\ndef downup(word):\n if len(word) <= 1:\n return [word]\n return [word] + downup(s[1:]) + [word]\n\nNote that your own function returns a string if the length of the passed in string is 1 and a list otherwise. This could lead to... | [
4,
2,
1,
0
] | [] | [] | [
"python",
"recursion",
"scheme"
] | stackoverflow_0005300242_python_recursion_scheme.txt |
Q:
Piping latin-1 encoded output of a program to a Python 3 script
I want to process the output of a running program line-by-line (think tail -f) with a Python 3 script (on Linux).
The programs output, which is getting piped to the script, is encoded in latin-1, so, in Python 2, I used the codecs module to decode the... | Piping latin-1 encoded output of a program to a Python 3 script | I want to process the output of a running program line-by-line (think tail -f) with a Python 3 script (on Linux).
The programs output, which is getting piped to the script, is encoded in latin-1, so, in Python 2, I used the codecs module to decode the input of sys.stdin properly:
#!/usr/bin/env python
import sys, codec... | [
"import sys\nimport io\n\nwith io.open(sys.stdin.fileno(),'r',encoding='latin-1') as sin:\n for line in sin:\n print ('type:{0} line:{1}'.format(type (line), line))\n\nyields\ntype:<class 'str'> line:Hi! öäß\n\n",
"Take a look at this link in the documentation: sys.stdin. The relevant part is:\n\nThe s... | [
4,
2
] | [] | [] | [
"python",
"python_3.x",
"stdin"
] | stackoverflow_0005306259_python_python_3.x_stdin.txt |
Q:
python SyntaxError: unexpected EOF while parsing
So I have this code
m, b = eval(input())
the aim is to have a whole bunch of comma separated values inputted and then have python unpack the tuple into the variables
but when i run i get this error
x, y = eval(input())
File "<string>", line 1
1,2
... | python SyntaxError: unexpected EOF while parsing | So I have this code
m, b = eval(input())
the aim is to have a whole bunch of comma separated values inputted and then have python unpack the tuple into the variables
but when i run i get this error
x, y = eval(input())
File "<string>", line 1
1,2
^
SyntaxError: unexpected EOF while parsing
what... | [
"You should not use eval for things like this. It will be impossible to write it in a way such that the user can't break it (by mistake or on purpose). Do something like this instead:\ndata = input()\nm, b = (int(var) for var in data.split(\",\"))\n\n"
] | [
2
] | [] | [] | [
"eval",
"exception",
"input",
"python",
"syntax_error"
] | stackoverflow_0005306308_eval_exception_input_python_syntax_error.txt |
Q:
How to use Twisted to get an IRC channel's user list
I'm trying to get channel's user list using {{self.say(channel, "WHO",100)}}. How can I get the response? Which method I should override?
A:
Here are some additional methods which should help you get further along. You handle a given reply RPL_NAME by defining... | How to use Twisted to get an IRC channel's user list | I'm trying to get channel's user list using {{self.say(channel, "WHO",100)}}. How can I get the response? Which method I should override?
| [
"Here are some additional methods which should help you get further along. You handle a given reply RPL_NAME by defining a method irc_RPL_NAME. So for RPL_WHOREPLY you define irc_WHOREPLY:\n def who(self, channel):\n \"List the users in 'channel', usage: client.who('#testroom')\"\n self.sendLine('W... | [
7
] | [] | [] | [
"python",
"twisted"
] | stackoverflow_0005305050_python_twisted.txt |
Q:
lxml python 2.5 ElementMaker syntax error
I have the following code:
from lxml.builder import ElementMaker
E = ElementMaker()
params = [E.param('1'), E.param('2')]
E.p( *params, count='2')
This works fine in python 2.6, but when I run it with python 2.5, I get the following error:
E.p( *params, count='2')
... | lxml python 2.5 ElementMaker syntax error | I have the following code:
from lxml.builder import ElementMaker
E = ElementMaker()
params = [E.param('1'), E.param('2')]
E.p( *params, count='2')
This works fine in python 2.6, but when I run it with python 2.5, I get the following error:
E.p( *params, count='2')
^ SyntaxError: invalid syntax
I c... | [
"You can't follow * with keyword arguments in Python before 2.6. You can try:\nE.p(*params, **{'count': '2'})\n\nor if you'd rather:\nE.p(*params, **dict(count='2')})\n\n"
] | [
1
] | [] | [] | [
"lxml",
"python",
"python_2.5",
"python_2.6"
] | stackoverflow_0005306703_lxml_python_python_2.5_python_2.6.txt |
Q:
Usage message string that optparse makes in python?
I use optparse module to parse the options that I make, and it automatically generates usage message to print with -h option.
How can I get the usage message as a string in a python script? I'd like to print out it when something's wrong with parsing.
A:
If you... | Usage message string that optparse makes in python? | I use optparse module to parse the options that I make, and it automatically generates usage message to print with -h option.
How can I get the usage message as a string in a python script? I'd like to print out it when something's wrong with parsing.
| [
"If you use parser.error(...) (where parser is your OptionParser object) you'll get your usage message.\nFor example:\nfrom optparse import OptionParser\n\nparser = OptionParser('usage: %prog [options] target source [source ...]')\n[...]\n\n(opts, args) = parser.parse_args()\n\nif len(args) < 2:\n parser.error('... | [
2,
1
] | [] | [] | [
"optparse",
"python"
] | stackoverflow_0005306852_optparse_python.txt |
Q:
How do I pass a python object using a remote manager?
I'm developing a simple client-server application in python. I'm using a manager to set up shared queues, but I can't figure out how to pass an arbitrary object from the server to the client. I suspect it has something to do with the manager.register function... | How do I pass a python object using a remote manager? | I'm developing a simple client-server application in python. I'm using a manager to set up shared queues, but I can't figure out how to pass an arbitrary object from the server to the client. I suspect it has something to do with the manager.register function, but it's not very well explained in the multiprocessing d... | [
"You're encountering this issue because the parameter attribute on your MyObject() class is not a callable.\nThe documentation states that, _exposed_ is used to specify a sequence of method names which proxies for this typeid. In the case where no exposed list is specified, all “public methods” of the shared object... | [
2
] | [] | [] | [
"multiprocessing",
"python",
"python_multiprocessing"
] | stackoverflow_0005306362_multiprocessing_python_python_multiprocessing.txt |
Q:
Kickstarter clone in Drupal?
I would like to create a Kickstarter type clone in terms of functionality.
Can Drupal produce a crude prototype?
Or suck it up, hit the books and learn python/django or ruby/rails.
I appreciate any and all input.
A:
Drupal would likely handle the basic concept of listings rather ad... | Kickstarter clone in Drupal? | I would like to create a Kickstarter type clone in terms of functionality.
Can Drupal produce a crude prototype?
Or suck it up, hit the books and learn python/django or ruby/rails.
I appreciate any and all input.
| [
"Drupal would likely handle the basic concept of listings rather adeptly, but you'd need to write plenty of glue code to make it match the exact functionality you want. It would, in fact, be easier to write it from scratch than to force a tool to do a different job.\nGo for a full-fledged web app framework.\n"
] | [
1
] | [] | [] | [
"django",
"drupal",
"python",
"ruby",
"ruby_on_rails"
] | stackoverflow_0005307039_django_drupal_python_ruby_ruby_on_rails.txt |
Q:
How to save new data in tree model view
I'm trying to modify the excellent example of pyqt4 called "Editabletreemodel" but I have a problem I can't manage: after I add a new row in the model, how can I save or update the data I've inserted to a text file?
Or more in general, how is it possible to save data from th... | How to save new data in tree model view | I'm trying to modify the excellent example of pyqt4 called "Editabletreemodel" but I have a problem I can't manage: after I add a new row in the model, how can I save or update the data I've inserted to a text file?
Or more in general, how is it possible to save data from the model/view into a file?
Thank you for your ... | [
"I guess the easies way would be to iterate though model items and save save to file via QDataStream. QDataStream supports reading\\writing QVariant's and you can get\\set the model item's data as QVariant. Below is a small example, I'm using QStandardItemModel for simplicity:\nimport sys\nfrom PyQt4 import QtGui, ... | [
2
] | [] | [] | [
"pyqt",
"python",
"treeview"
] | stackoverflow_0005304570_pyqt_python_treeview.txt |
Q:
Get a Global Variable while a Python Program is running
I write a Python 2.5 Command Line program on CentOS 5.5 and it has been running for 1 day and is still running. Now I want to end this program but get the value of a global variable.
I have done some Google. It seems the only way to get the value of a global ... | Get a Global Variable while a Python Program is running | I write a Python 2.5 Command Line program on CentOS 5.5 and it has been running for 1 day and is still running. Now I want to end this program but get the value of a global variable.
I have done some Google. It seems the only way to get the value of a global variable is to attach the Python program to a GDB.
Suppose th... | [
"This is possible to do, but is extremely tricky, and a single wrong move will cause the program to crash (or be lost in an indeterminate state).\nYou can use the C function PyEval_GetGlobals() to return the dictionary of globals (as it would if you called globals() in python), and then use PyObject_Print() to prin... | [
6,
0
] | [] | [] | [
"command_line",
"debugging",
"gdb",
"python"
] | stackoverflow_0005306959_command_line_debugging_gdb_python.txt |
Q:
Use substitution cipher in python to encrypt and decrypt a .txt file and output to a new .txt file
I am able to open the rules file and create a dictionary to use for my encryption. I have to also create a dictionary to use for decrypting text. I assume it's basically the same function with minor changes. The e... | Use substitution cipher in python to encrypt and decrypt a .txt file and output to a new .txt file | I am able to open the rules file and create a dictionary to use for my encryption. I have to also create a dictionary to use for decrypting text. I assume it's basically the same function with minor changes. The encrypt works fine, but I can't get the decrypt to work. My second problem is that while I encrypted the... | [
"Your first problem is that you're not actually writing your encrypted text to a file, instead you're just printing it to sys.stdout. Incidentally, print appends a \\n to it's output by default.\nYou could rewrite your decrypt function as follows:\n#function for decrypting file\ndef decryptfile(openFile2, outfile):... | [
0
] | [] | [] | [
"dictionary",
"encryption",
"python"
] | stackoverflow_0005306976_dictionary_encryption_python.txt |
Q:
Pathological regex that blows up (time & memory)?
What's a pathological regex that blows up many parsers (both in time & memory)?
and which parsers? Bonus points the more basic and standard the regex is, and the more likely that a non-malicious user might innocently come up with it.
Feel free to post actual time a... | Pathological regex that blows up (time & memory)? | What's a pathological regex that blows up many parsers (both in time & memory)?
and which parsers? Bonus points the more basic and standard the regex is, and the more likely that a non-malicious user might innocently come up with it.
Feel free to post actual time and memory data, and parser version.
(I seem to remember... | [
"Adapted from the first example in the article Regular Expression Matching Can Be Simple And Fast\n(but is slow in Java, Perl, PHP, Python, Ruby, ...):\nperl -e '$n=29; (\"a\" x $n) =~ ((\"a?\" x $n).(\"a\" x $n))'\n\nWhich takes 40+ seconds on my system. Then do $n++ for exponentially increasing fun...\n",
"Fro... | [
4,
3,
0
] | [] | [] | [
"perl",
"php",
"python",
"regex"
] | stackoverflow_0005307143_perl_php_python_regex.txt |
Q:
Is this the best way to ensure that a python unicode "string" is encoded in utf-8?
Given in arbitrary "string" from a library I do not have control over, I want to make sure the "string" is a unicode type and encoded in utf-8. I would like to know if this is the best way to do this:
import types
input = <some va... | Is this the best way to ensure that a python unicode "string" is encoded in utf-8? | Given in arbitrary "string" from a library I do not have control over, I want to make sure the "string" is a unicode type and encoded in utf-8. I would like to know if this is the best way to do this:
import types
input = <some value from a lib I dont have control over>
if isinstance(input, types.StringType):
in... | [
"A Unicode object is not encoded (it is internally but this should be transparent to you as a Python user). The line input.encode(\"utf-8\").decode(\"utf-8\") does not make much sense: you get the exact same sequence of Unicode characters at the end that you had in the beginning.\nif isinstance(input, str):\n in... | [
6,
2,
2,
0
] | [] | [] | [
"python",
"unicode"
] | stackoverflow_0005304720_python_unicode.txt |
Q:
Python submit and display on one click
I'm new to app engine. With python.
My question is: I want to submit and display same record on add button click. As I'm using lightbox to display my records.
My html file: where add button is there.
<td><a href='/display?patients_id={{patient_display.key.id}}&key={{patient_d... | Python submit and display on one click | I'm new to app engine. With python.
My question is: I want to submit and display same record on add button click. As I'm using lightbox to display my records.
My html file: where add button is there.
<td><a href='/display?patients_id={{patient_display.key.id}}&key={{patient_display.key}}' class='display' ><input type="... | [
"Seems to me you're using Google App Engine, just process form data , insert in db then redirect to your showRecord page getting id from last row id from cursor\n",
"You should divide the page in to two parts. One containing the form and the other to display the records. Use ajax to submit to the datastore and th... | [
1,
0
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0005299132_google_app_engine_python.txt |
Q:
How to manipulate the following text
I was wondering how to convert text similar to the following:
Chapter 3 Convex Functions 97
3.1 Definitions 98
3.2 Basic Properties 103
to:
("Chapter 3 Convex Functions 97" "#97")
("3.1 Definitions 98" "#98")
("3.2 Basic Properties 103" "#103")
by using some convenient yet po... | How to manipulate the following text | I was wondering how to convert text similar to the following:
Chapter 3 Convex Functions 97
3.1 Definitions 98
3.2 Basic Properties 103
to:
("Chapter 3 Convex Functions 97" "#97")
("3.1 Definitions 98" "#98")
("3.2 Basic Properties 103" "#103")
by using some convenient yet powerful text manipulation languages and/or ... | [
"Here's a Perl solution:\nwhile (<DATA>) {\n s/^(.+ (\\d+))$/(\"$1\" \"#$2\")/;\n print;\n}\n\n__DATA__\nChapter 3 Convex Functions 97\n3.1 Definitions 98\n3.2 Basic Properties 103\n\nprints:\n(\"Chapter 3 Convex Functions 97\" \"#97\")\n(\"3.1 Definitions 98\" \"#98\")\n(\"3.2 Basic Properties 103\" \"#103\"... | [
5,
2,
2,
2,
1,
1,
1
] | [] | [] | [
"awk",
"perl",
"python",
"regex",
"sed"
] | stackoverflow_0005306790_awk_perl_python_regex_sed.txt |
Q:
GTK Drag-and-drop Validation X11 Cursor lock up within drag_get_data
I have been unable to get drag and drop validation working in pygtk. I am out of ideas and would like a second opinion.
My goal is to only allow files which contain .jpg to be dropped.
Specifically, whenever I call widget.drag_get_data within the... | GTK Drag-and-drop Validation X11 Cursor lock up within drag_get_data | I have been unable to get drag and drop validation working in pygtk. I am out of ideas and would like a second opinion.
My goal is to only allow files which contain .jpg to be dropped.
Specifically, whenever I call widget.drag_get_data within the drag-motion callback The X11 cursor locks up. Making debugging tedious an... | [
"I think you must do something like this in drag_data_received_cb\ndef drag_data_received_cb(self, obj, context, x, y, selection, target_id, etime):\n try:\n dtype = selection.get_data_type()\n except AttributeError:## Old PyGTK\n dtype = selection.type\n if dtype=='image/jpeg':\n imag... | [
0
] | [] | [] | [
"drag_and_drop",
"gtk",
"linux",
"pygtk",
"python"
] | stackoverflow_0005303233_drag_and_drop_gtk_linux_pygtk_python.txt |
Q:
How to prohibit back or refresh using django
this is my code :
def to_complete(request):
return MobileResponseRedirect('/battle/complete/')
def complete(request):
do_something()
return MobileResponse(html)
but this method can not prevent back,
i do a Important thing in complete (like Increase in mon... | How to prohibit back or refresh using django | this is my code :
def to_complete(request):
return MobileResponseRedirect('/battle/complete/')
def complete(request):
do_something()
return MobileResponse(html)
but this method can not prevent back,
i do a Important thing in complete (like Increase in money in a game)
and i dont want user to refresh the ... | [
"A simple idea would be to use a session variable, like this:\ndef to_complete(request):\n if request.session.has_key(\"complete_pending\"):\n return HttpResponseForbidden()\n request.session[\"complete_pending\"] = True\n return MobileResponseRedirect('/battle/complete/')\n\ndef complete(request):\... | [
1,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0005307991_django_python.txt |
Q:
Python socket.accept nonblocking?
Is there a way I can use python's socket.accept() in a non-blocking way that simply runs it and lets me just check if it got any new connections? I really don't want to use threading.
Thanks.
A:
You probably want something like select.select() (see documentation). You supply sel... | Python socket.accept nonblocking? | Is there a way I can use python's socket.accept() in a non-blocking way that simply runs it and lets me just check if it got any new connections? I really don't want to use threading.
Thanks.
| [
"You probably want something like select.select() (see documentation). You supply select() with three lists of sockets: sockets you want to monitor for readability, writability, and error states. The server socket will be readable when a new client is waiting.\nThe select() function will block until one of the sock... | [
39,
4
] | [] | [] | [
"nonblocking",
"python",
"sockets",
"tcp"
] | stackoverflow_0005308080_nonblocking_python_sockets_tcp.txt |
Q:
Sorting nested python dictionary
I have a python dictionary with the following format.
{'KEY': (NUMBER, [DATE1, DATE2]}
For example, {'a': (10, ['2010/04/11','2009/03/11'])}
How can I sort this dictionary by the DATE1(the first element in the list)?
EDIT
Can I sorted again when the date is the same? For exampl... | Sorting nested python dictionary | I have a python dictionary with the following format.
{'KEY': (NUMBER, [DATE1, DATE2]}
For example, {'a': (10, ['2010/04/11','2009/03/11'])}
How can I sort this dictionary by the DATE1(the first element in the list)?
EDIT
Can I sorted again when the date is the same? For example.
{'a': (10, ['2010/04/11','2009/03/1... | [
"Dictionaries are unsortable. If you want a sorted list of 2-tuples:\nsorted(D.iteritems(), key=lambda x: x[1][1][0])\n\nPass the expression to datetime.strptime() if you want it in date order instead of string order (not that there is a huge difference given the existing date format...).\n",
"If you're using Pyt... | [
4,
3
] | [] | [] | [
"dictionary",
"python",
"sorting"
] | stackoverflow_0005307473_dictionary_python_sorting.txt |
Q:
Plotting 3D mesh plot, accessing points in mesh plot array?
I'm trying to plot a graph in matplotlib using numpy and meshgrid.
I want to make a region in the center of the array filled with 'ones' and elsewhere zeros. I tried setting up the array, but the for loop doesn't seem to ever enter (print statements don'... | Plotting 3D mesh plot, accessing points in mesh plot array? | I'm trying to plot a graph in matplotlib using numpy and meshgrid.
I want to make a region in the center of the array filled with 'ones' and elsewhere zeros. I tried setting up the array, but the for loop doesn't seem to ever enter (print statements don't print inside for loops). Any pointers?
import numpy as np
impor... | [
"Here is the code I think you want. You want to avoid loops and you can't index that way (see the comments below).\nimport numpy as np\nimport pylab as py\nfrom scipy import * # it is better practice to do: from scipy import module1, module2, etc...\nfrom numpy.fft import fft\nimport mpl_toolkits.mplot3d.axes3d a... | [
0
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0005308250_matplotlib_python.txt |
Q:
Displaying a messge when search not found
I have done a filtering method using Django. The filtering is based on a choice selected from a drop down menu and a text input. the filtering is working fine. Now i want to display a message if the search is not found. Can somebody help me to solve this. Will post my code... | Displaying a messge when search not found | I have done a filtering method using Django. The filtering is based on a choice selected from a drop down menu and a text input. the filtering is working fine. Now i want to display a message if the search is not found. Can somebody help me to solve this. Will post my code here.
def filter(request):
val3=''
if... | [
"check newdata in filter view or in html ... if its empty show your msg\nexample :\n{% if newData %}\n newData\n{% else %}\n error\n{% endif %}\n\n\nanything is anything you want check is empty?\n\n",
"How about display a message if the flag was not set to true or if newData is null when you can't find anyt... | [
2,
1,
1
] | [] | [] | [
"django",
"django_models",
"django_templates",
"django_views",
"python"
] | stackoverflow_0005308294_django_django_models_django_templates_django_views_python.txt |
Q:
how to convert a simple python code weekday check
Okay, i wrote this code myself awhile ago
but now im having trouble conerting it so it only does this years dates, ie the user would only have to type MM-DD instead of YYYY-MM-DD because we are going to assume its 2011
A:
import datetime
def weekday(dateinput):
... | how to convert a simple python code weekday check | Okay, i wrote this code myself awhile ago
but now im having trouble conerting it so it only does this years dates, ie the user would only have to type MM-DD instead of YYYY-MM-DD because we are going to assume its 2011
| [
"import datetime\ndef weekday(dateinput):\n a = dateinput.split(\"-\")\n b = datetime.date(datetime.date.today().year, int(a[0]), int(a[1]))\n c = b.strftime(\"%A\")\n return c\n#- test harness: do not modify -#\ndateinput = raw_input('Enter a date (\"MM-DD\"): ')\nprint \"That's a \" + weekday(dateinpu... | [
3,
0
] | [] | [] | [
"python",
"weekday"
] | stackoverflow_0005308731_python_weekday.txt |
Q:
Forward class declaration in Python
I have two classes in order:
class A(models):
...
class B(models):
a = models.ManyToManyField(A)
Now I have to change my model to one below:
class A(models):
b = models.ManyToManyField(B)
class B(models):
...
I have to use south migrations. I wanted to create... | Forward class declaration in Python | I have two classes in order:
class A(models):
...
class B(models):
a = models.ManyToManyField(A)
Now I have to change my model to one below:
class A(models):
b = models.ManyToManyField(B)
class B(models):
...
I have to use south migrations. I wanted to create new many to many field in class A, migra... | [
"At least SQLAlchemy allows you to use a string instead of a class. Try if django-orm allows that, too.\na = models.ManyToManyField('A')\n# ...\nb = models.ManyToManyField('B')\n\nUpdate: According to Django/Python Circular model reference that's exactly the way to go.\n"
] | [
9
] | [] | [] | [
"django",
"django_models",
"django_south",
"python"
] | stackoverflow_0005308895_django_django_models_django_south_python.txt |
Q:
find multiple string occurrences in Python
is there a way to do something like this?
if ['hel','ell','orl'] in 'hello world' :
I want to see if all of these strings occur in the word. If possible in a shorter way than completely writing a multiline foor loop.
A:
You could do:
if all( x in 'hello world' for x in... | find multiple string occurrences in Python | is there a way to do something like this?
if ['hel','ell','orl'] in 'hello world' :
I want to see if all of these strings occur in the word. If possible in a shorter way than completely writing a multiline foor loop.
| [
"You could do:\nif all( x in 'hello world' for x in ['hel','ell','orl'] ):\n print \"Found all of them\"\n\nThe built-in functions all and any are useful for this kind of thing.\n",
"if all(substr in 'hello world' for substr in ('hel','ell','orl')):\n # all are contained\n\nThe advantage of all() is that it... | [
11,
4,
0
] | [] | [] | [
"python",
"string"
] | stackoverflow_0005309204_python_string.txt |
Q:
Python code to scan network to obtain the computer name
I need to run a network scan to obtain the computer name of the PCs connected to the network.
This is to run a software compliance scan on these systems.
We require the name of the system in order to connect to their registry to obtain information.
How do we... | Python code to scan network to obtain the computer name | I need to run a network scan to obtain the computer name of the PCs connected to the network.
This is to run a software compliance scan on these systems.
We require the name of the system in order to connect to their registry to obtain information.
How do we obtain computer name or is their any other way to connect to... | [
"You can probably just use an IP address rather than a name. System calls in Windows that requires a machine name will generally also accept a numeric address just the same.\ne.g. these both work:\n>>> import _winreg\n>>> c = _winreg.ConnectRegistry(\"SOMEMACHINE\", _winreg.HKEY_CLASSES_ROOT)\n>>> c = _winreg.Conne... | [
2,
0
] | [] | [] | [
"networking",
"programming_languages",
"python"
] | stackoverflow_0005307824_networking_programming_languages_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.