title stringlengths 10 172 | question_id int64 469 40.1M | question_body stringlengths 22 48.2k | question_score int64 -44 5.52k | question_date stringlengths 20 20 | answer_id int64 497 40.1M | answer_body stringlengths 18 33.9k | answer_score int64 -38 8.38k | answer_date stringlengths 20 20 | tags listlengths 1 5 |
|---|---|---|---|---|---|---|---|---|---|
python ORM allowing for table creation and bulk inserting? | 1,013,282 | <p>I'm looking for an ORM that allows me to do bulk inserts, as well as create code based on python classes. I tried sqlobject, it worked fine for creating the tables but inserting was unacceptibly slow for the amount of data I wanted to insert. If such an ORM doesn't exist any pointers on classes that can help with th... | 1 | 2009-06-18T15:16:00Z | 1,013,315 | <p>I believe sqlalchemy has bulk inserts, but I haven't ever used it. However, it stacks up favorably in benchmark tests according to this <a href="http://pyinsci.blogspot.com/2007/07/fastest-python-database-interface.html" rel="nofollow">this reviewer</a>.</p>
<p>EDIT: It doesn't seem clear how he's using SQLAlchem... | 0 | 2009-06-18T15:20:31Z | [
"python",
"database",
"orm"
] |
python ORM allowing for table creation and bulk inserting? | 1,013,282 | <p>I'm looking for an ORM that allows me to do bulk inserts, as well as create code based on python classes. I tried sqlobject, it worked fine for creating the tables but inserting was unacceptibly slow for the amount of data I wanted to insert. If such an ORM doesn't exist any pointers on classes that can help with th... | 1 | 2009-06-18T15:16:00Z | 1,016,006 | <p>I'm not familiar with sqlobject, but for bulk inserts typically you want to make sure this is done in a transaction, so your not commiting for each manipulation.</p>
<p>In sqlobject it looks like you can do this by using the transactions object to control commits. You probably need to turn of the default AutoCommi... | 0 | 2009-06-19T01:31:10Z | [
"python",
"database",
"orm"
] |
Windows error and python | 1,013,311 | <p>I'm working on a bit of code that is supposed to run an exe file inside a folder on my system and getting an error saying... </p>
<p>WindowsError: [Error 3] The system cannot find the path specified.
Here's a bit of the code:</p>
<pre><code>exepath = os.path.join(EXE file localtion)
exepath = '"' + os.path.normpat... | 1 | 2009-06-18T15:20:11Z | 1,013,342 | <p>If I remember correctly, you don't need to quote your executuable file path, like you do in the second line.</p>
<p>EDIT: Well, just grabbed nearby Windows box and tested this. Popen works the same regardless the path is quoted or not. So this is not an issue.</p>
| 0 | 2009-06-18T15:23:54Z | [
"python",
"popen"
] |
Windows error and python | 1,013,311 | <p>I'm working on a bit of code that is supposed to run an exe file inside a folder on my system and getting an error saying... </p>
<p>WindowsError: [Error 3] The system cannot find the path specified.
Here's a bit of the code:</p>
<pre><code>exepath = os.path.join(EXE file localtion)
exepath = '"' + os.path.normpat... | 1 | 2009-06-18T15:20:11Z | 1,013,345 | <p>You need to properly escape the space in the executable path</p>
| 3 | 2009-06-18T15:24:27Z | [
"python",
"popen"
] |
Windows error and python | 1,013,311 | <p>I'm working on a bit of code that is supposed to run an exe file inside a folder on my system and getting an error saying... </p>
<p>WindowsError: [Error 3] The system cannot find the path specified.
Here's a bit of the code:</p>
<pre><code>exepath = os.path.join(EXE file localtion)
exepath = '"' + os.path.normpat... | 1 | 2009-06-18T15:20:11Z | 1,013,364 | <p>AFAIK, there is no need to surround the path in quotation marks unless <code>cmd.exe</code> is involved in running the program.</p>
<p>In addition, you might want to use the environment variable <code>ProgramFiles</code> to find out the actual location of 'Program Files' because that depends on regional settings an... | 0 | 2009-06-18T15:28:53Z | [
"python",
"popen"
] |
Windows error and python | 1,013,311 | <p>I'm working on a bit of code that is supposed to run an exe file inside a folder on my system and getting an error saying... </p>
<p>WindowsError: [Error 3] The system cannot find the path specified.
Here's a bit of the code:</p>
<pre><code>exepath = os.path.join(EXE file localtion)
exepath = '"' + os.path.normpat... | 1 | 2009-06-18T15:20:11Z | 1,013,379 | <p>Besides properly escaping spaces and other characters that could cause problems (such as /), you can also use the 8 character old DOS paths. </p>
<p>For example, Program Files would be:</p>
<p>Progra~1 , making sure to append ~1 for the last two characters.</p>
<p>EDIT: You could add an r to the front of the stri... | 1 | 2009-06-18T15:31:21Z | [
"python",
"popen"
] |
How to link C lib against python for embedding under Windows? | 1,013,441 | <p>I am working on an application written in C. One part of the application should embed python and there is my current problem. I try to link my source to the Python library but it does not work.</p>
<p>As I use MinGW I have created the python26.a file from python26.lib with dlltool and put the *.a file in <code>C:/P... | 1 | 2009-06-18T15:39:16Z | 1,013,523 | <p>Python (at least my distribution) comes with a "python-config" program that automatically creates the correct compiler and linker options for various situations. However, I have never used it on Windows. Perhaps this tool can help you though?</p>
| 1 | 2009-06-18T15:54:45Z | [
"python",
"c",
"windows",
"gcc",
"linker"
] |
How to link C lib against python for embedding under Windows? | 1,013,441 | <p>I am working on an application written in C. One part of the application should embed python and there is my current problem. I try to link my source to the Python library but it does not work.</p>
<p>As I use MinGW I have created the python26.a file from python26.lib with dlltool and put the *.a file in <code>C:/P... | 1 | 2009-06-18T15:39:16Z | 1,013,585 | <p>IIRC, dlltool does not always work. Having python 2.6 + Wow makes things even more less likely to work. For numpy, here is how I <a href="http://github.com/cournape/numpy/blob/a069480e25d79b76e6da96e951cd3ac66828d75d/numpy/distutils/mingw32ccompiler.py" rel="nofollow">did it</a>. Basically, I use obdump.exe to build... | 1 | 2009-06-18T16:05:02Z | [
"python",
"c",
"windows",
"gcc",
"linker"
] |
How to link C lib against python for embedding under Windows? | 1,013,441 | <p>I am working on an application written in C. One part of the application should embed python and there is my current problem. I try to link my source to the Python library but it does not work.</p>
<p>As I use MinGW I have created the python26.a file from python26.lib with dlltool and put the *.a file in <code>C:/P... | 1 | 2009-06-18T15:39:16Z | 1,017,194 | <p>Well on Windows the python distribution comes already with a <code>libpython26.a</code> in the libs subdir so there is no need to generate <code>.a</code> files using dll tools.</p>
<p>I did try a little example with a single C file toto.c:</p>
<pre><code>gcc -shared -o ./toto.dll ./toto.c -I/Python26/include/ -L/... | 2 | 2009-06-19T09:53:03Z | [
"python",
"c",
"windows",
"gcc",
"linker"
] |
Combining C and Python functions in a module | 1,013,449 | <p>I have a C extension module, to which I would like to add some Python utility functions. Is there a recommended way of doing this?</p>
<p>For example:</p>
<pre><code>import my_module
my_module.super_fast_written_in_C()
my_module.written_in_Python__easy_to_maintain()
</code></pre>
<p>I'm primarily interested in P... | 0 | 2009-06-18T15:41:00Z | 1,013,508 | <p>Prefix your native extension with an underscore.
Then, in Python, create a wrapper module that imports that native extension and adds some other non-native routines on top of that.</p>
| 5 | 2009-06-18T15:52:28Z | [
"python",
"cpython"
] |
Combining C and Python functions in a module | 1,013,449 | <p>I have a C extension module, to which I would like to add some Python utility functions. Is there a recommended way of doing this?</p>
<p>For example:</p>
<pre><code>import my_module
my_module.super_fast_written_in_C()
my_module.written_in_Python__easy_to_maintain()
</code></pre>
<p>I'm primarily interested in P... | 0 | 2009-06-18T15:41:00Z | 1,013,556 | <p>The usual way of doing this is: mymod.py contains the utility functions written in Python, and imports the goodies in the _mymod module which is written in C and is imported from _mymod.so or _mymod.pyd. For example, look at .../Lib/csv.py in your Python distribution.</p>
| 6 | 2009-06-18T16:00:29Z | [
"python",
"cpython"
] |
Combining C and Python functions in a module | 1,013,449 | <p>I have a C extension module, to which I would like to add some Python utility functions. Is there a recommended way of doing this?</p>
<p>For example:</p>
<pre><code>import my_module
my_module.super_fast_written_in_C()
my_module.written_in_Python__easy_to_maintain()
</code></pre>
<p>I'm primarily interested in P... | 0 | 2009-06-18T15:41:00Z | 1,015,935 | <p>The existing answers describe the method most often used: it has the potential advantage of allowing pure-Python (or other-language) implementations on platforms in which the compiled C extension is not available (including Jython and IronPython).</p>
<p>In a few cases, however, it may not be worth splitting the mo... | 1 | 2009-06-19T00:59:43Z | [
"python",
"cpython"
] |
Stealing wheelEvents from a QScrollArea | 1,013,670 | <p>I wanna put my custom widget in a QScrollArea, but in my custom widget, i reimplemented wheelEvent(e) and it never gets called. Im fine with the scroll area not having its mouse wheel scrolling functionality, I just need those wheelEvents to call my handler. I tried handling the events out at the level of the main w... | 1 | 2009-06-18T16:20:34Z | 1,014,898 | <p>I figured out that its got something to do with the installEventFilter method of QObject, but I couldn't get the example to work so I said to hell with this and changed my plan completely.</p>
<p>problem solved</p>
| 0 | 2009-06-18T20:06:22Z | [
"python",
"pyqt"
] |
Stealing wheelEvents from a QScrollArea | 1,013,670 | <p>I wanna put my custom widget in a QScrollArea, but in my custom widget, i reimplemented wheelEvent(e) and it never gets called. Im fine with the scroll area not having its mouse wheel scrolling functionality, I just need those wheelEvents to call my handler. I tried handling the events out at the level of the main w... | 1 | 2009-06-18T16:20:34Z | 19,917,798 | <p>You can install a eventFilter in your custom class</p>
<pre><code>class custom(QWidget):
def __init__(self, parent=None):
super(custom, self).__init__(parent)
self.parent = parent
self.installEventFilter(self)
def eventFilter(self, qobject, qevent):
qtype = qevent.type()
... | 0 | 2013-11-11T23:09:18Z | [
"python",
"pyqt"
] |
After writing to a file, why does os.path.getsize still return the previous size? | 1,013,778 | <p>I am trying to split up a large xml file into smaller chunks. I write to the output file and then check its size to see if its passed a threshold, but I dont think the getsize() method is working as expected.</p>
<p>What would be a good way to get the filesize of a file that is changing in size.</p>
<p>Ive done so... | 12 | 2009-06-18T16:38:24Z | 1,013,799 | <p>Yes, Python is buffering your output. You'd be better off tracking the size yourself, something like this:</p>
<pre><code>size = 0
for line in f1:
if str(line) == '</Service>\n':
break
else:
f2.write(line)
size += len(line)
print('size = ' + str(size))
</code></pre>
<p>(That might not be... | 9 | 2009-06-18T16:41:16Z | [
"python",
"filesize"
] |
After writing to a file, why does os.path.getsize still return the previous size? | 1,013,778 | <p>I am trying to split up a large xml file into smaller chunks. I write to the output file and then check its size to see if its passed a threshold, but I dont think the getsize() method is working as expected.</p>
<p>What would be a good way to get the filesize of a file that is changing in size.</p>
<p>Ive done so... | 12 | 2009-06-18T16:38:24Z | 1,014,653 | <p>Tracking the size yourself will be fine for your case. A different way would be to flush the file buffers just before you check the size:</p>
<pre><code>f2.write(line)
f2.flush() # <-- buffers are written to disk
size = os.path.getsize('split.xml')
</code></pre>
<p>Doing that too often will slow down file I/O,... | 3 | 2009-06-18T19:16:56Z | [
"python",
"filesize"
] |
After writing to a file, why does os.path.getsize still return the previous size? | 1,013,778 | <p>I am trying to split up a large xml file into smaller chunks. I write to the output file and then check its size to see if its passed a threshold, but I dont think the getsize() method is working as expected.</p>
<p>What would be a good way to get the filesize of a file that is changing in size.</p>
<p>Ive done so... | 12 | 2009-06-18T16:38:24Z | 1,239,240 | <p>Have you tried to replace os.path.getsize with os.tell, like this:</p>
<pre><code>f2.write(line)
size = f2.tell()
</code></pre>
| 5 | 2009-08-06T14:26:27Z | [
"python",
"filesize"
] |
After writing to a file, why does os.path.getsize still return the previous size? | 1,013,778 | <p>I am trying to split up a large xml file into smaller chunks. I write to the output file and then check its size to see if its passed a threshold, but I dont think the getsize() method is working as expected.</p>
<p>What would be a good way to get the filesize of a file that is changing in size.</p>
<p>Ive done so... | 12 | 2009-06-18T16:38:24Z | 5,821,833 | <p>File size is different from file position. For example,</p>
<pre><code>os.path.getsize('sample.txt')
</code></pre>
<p>It exactly returns file size in bytes. </p>
<p>But </p>
<pre><code>f = open('sample.txt')
print f.readline()
f.tell()
</code></pre>
<p>Here f.tell() returns the current position of the file ha... | 11 | 2011-04-28T16:22:11Z | [
"python",
"filesize"
] |
After writing to a file, why does os.path.getsize still return the previous size? | 1,013,778 | <p>I am trying to split up a large xml file into smaller chunks. I write to the output file and then check its size to see if its passed a threshold, but I dont think the getsize() method is working as expected.</p>
<p>What would be a good way to get the filesize of a file that is changing in size.</p>
<p>Ive done so... | 12 | 2009-06-18T16:38:24Z | 8,268,816 | <p>To find the offset to the end of a file:</p>
<pre><code>file.seek(0,2)
print file.tell()
</code></pre>
<p>Real world example - read updates to a file and print them as they happen:</p>
<pre><code>file = open('log.txt', 'r')
#find inital End Of File offset
file.seek(0,2)
eof = file.tell()
while True:
#set the ... | 1 | 2011-11-25T11:58:43Z | [
"python",
"filesize"
] |
How to write a Perl, Python, or Ruby program to change the memory of another process on Windows? | 1,013,828 | <p>I wonder if Perl, Python, or Ruby can be used to write a program so that it will look for 0x12345678 in the memory of another process (probably the heap, for both data and code data) and then if it is found, change it to 0x00000000? It is something similar to <a href="http://www.cheatengine.org/">Cheat Engine</a>, ... | 8 | 2009-06-18T16:45:46Z | 1,013,870 | <p>I initially thought this was not possible but after seeing Brian's comment, I searched CPAN and lo and behold, there is <a href="http://search.cpan.org/perldoc/Win32%3a%3aProcess%3a%3aMemory">Win32::Process::Memory</a>:</p>
<pre><code>C:\> ppm install Win32::Process::Info
C:\> ppm install Win32::Process::Memo... | 13 | 2009-06-18T16:52:57Z | [
"python",
"ruby",
"perl",
"winapi",
"readprocessmemory"
] |
How to write a Perl, Python, or Ruby program to change the memory of another process on Windows? | 1,013,828 | <p>I wonder if Perl, Python, or Ruby can be used to write a program so that it will look for 0x12345678 in the memory of another process (probably the heap, for both data and code data) and then if it is found, change it to 0x00000000? It is something similar to <a href="http://www.cheatengine.org/">Cheat Engine</a>, ... | 8 | 2009-06-18T16:45:46Z | 1,013,905 | <p>There are ways to do do this using Process injection, delay load library etc. </p>
<p>I don't see you doing it from the tools you have listed. This is C and assembler country and beginning to get you into virus writing territory. Once you get it to work, any anti-virus packages will veto it running and try and isol... | 4 | 2009-06-18T16:59:45Z | [
"python",
"ruby",
"perl",
"winapi",
"readprocessmemory"
] |
How to write a Perl, Python, or Ruby program to change the memory of another process on Windows? | 1,013,828 | <p>I wonder if Perl, Python, or Ruby can be used to write a program so that it will look for 0x12345678 in the memory of another process (probably the heap, for both data and code data) and then if it is found, change it to 0x00000000? It is something similar to <a href="http://www.cheatengine.org/">Cheat Engine</a>, ... | 8 | 2009-06-18T16:45:46Z | 1,013,941 | <p>Well, the fun part is getting access to the other process's memory. CheatEngine does it by running your entire OS under a virtual machine that allows memory protection to be defeated. There's also the 'running under a debugger' model, generally meaning start the target application as a child process of the modifyi... | 6 | 2009-06-18T17:07:15Z | [
"python",
"ruby",
"perl",
"winapi",
"readprocessmemory"
] |
How to write a Perl, Python, or Ruby program to change the memory of another process on Windows? | 1,013,828 | <p>I wonder if Perl, Python, or Ruby can be used to write a program so that it will look for 0x12345678 in the memory of another process (probably the heap, for both data and code data) and then if it is found, change it to 0x00000000? It is something similar to <a href="http://www.cheatengine.org/">Cheat Engine</a>, ... | 8 | 2009-06-18T16:45:46Z | 1,014,468 | <p>It is possible to do so if you have attached your program as a debugger to the process, which should be possible in those languages if wrappers around the appropriate APIs exist, or by directly accessing the windows functions through something like ctypes (for python). However, it may be easier to do in a more low-... | 8 | 2009-06-18T18:42:44Z | [
"python",
"ruby",
"perl",
"winapi",
"readprocessmemory"
] |
How to write a Perl, Python, or Ruby program to change the memory of another process on Windows? | 1,013,828 | <p>I wonder if Perl, Python, or Ruby can be used to write a program so that it will look for 0x12345678 in the memory of another process (probably the heap, for both data and code data) and then if it is found, change it to 0x00000000? It is something similar to <a href="http://www.cheatengine.org/">Cheat Engine</a>, ... | 8 | 2009-06-18T16:45:46Z | 1,216,456 | <p>It is possible to implement the entire process in one of the languages listed but a compiled language would be better for memory scanning (speed considerations if nothing else). There is a dll (with source) called SigScan available that, while tailored for a specific game, could probably be modified to suite your ne... | 0 | 2009-08-01T11:49:49Z | [
"python",
"ruby",
"perl",
"winapi",
"readprocessmemory"
] |
What Can A 'TreeDict' (Or Treemap) Be Used For In Practice? | 1,014,247 | <p>I'm developing a 'TreeDict' class in Python. This is a basically a dict that allows you to retrieve its key-value pairs in sorted order, just like the Treemap collection class in Java.</p>
<p>I've implemented some functionality based on the way unique indexes in relational databases can be used, e.g. functions to ... | 2 | 2009-06-18T17:59:25Z | 1,014,274 | <p>I often use <code>Dict<DateTime, someClassOrValue></code> when working with industrial process data--
Valve open/close, machinery start/stop, etc.</p>
<p>Having the keys sorted is especially useful when I need to compare time intervals between start/stop or open/close events in a decent amount of time.</p>
<... | 1 | 2009-06-18T18:06:45Z | [
"python",
"collections",
"dictionary",
"treemap",
"uses"
] |
What Can A 'TreeDict' (Or Treemap) Be Used For In Practice? | 1,014,247 | <p>I'm developing a 'TreeDict' class in Python. This is a basically a dict that allows you to retrieve its key-value pairs in sorted order, just like the Treemap collection class in Java.</p>
<p>I've implemented some functionality based on the way unique indexes in relational databases can be used, e.g. functions to ... | 2 | 2009-06-18T17:59:25Z | 1,014,281 | <p>The reason for keeping the elements in sorted order is for faster retrieval. Say I wanted all of the values in the dictionary in a sorted range. This is much faster with a TreeDict then with the regular hashmap. It basically allows you to keep everything in the dictionary in sorted order. I know in the applicati... | 2 | 2009-06-18T18:08:03Z | [
"python",
"collections",
"dictionary",
"treemap",
"uses"
] |
What Can A 'TreeDict' (Or Treemap) Be Used For In Practice? | 1,014,247 | <p>I'm developing a 'TreeDict' class in Python. This is a basically a dict that allows you to retrieve its key-value pairs in sorted order, just like the Treemap collection class in Java.</p>
<p>I've implemented some functionality based on the way unique indexes in relational databases can be used, e.g. functions to ... | 2 | 2009-06-18T17:59:25Z | 1,014,282 | <p>They can make various algorithms easier to implement.</p>
| 0 | 2009-06-18T18:08:11Z | [
"python",
"collections",
"dictionary",
"treemap",
"uses"
] |
What Can A 'TreeDict' (Or Treemap) Be Used For In Practice? | 1,014,247 | <p>I'm developing a 'TreeDict' class in Python. This is a basically a dict that allows you to retrieve its key-value pairs in sorted order, just like the Treemap collection class in Java.</p>
<p>I've implemented some functionality based on the way unique indexes in relational databases can be used, e.g. functions to ... | 2 | 2009-06-18T17:59:25Z | 1,014,401 | <p>Almost all "GROUP BY" reporting requires a sorted dictionary.</p>
<pre><code>summary = sortedDefaultDict()
for row in somePileOfData:
summary[row.group_by] += row.balance
for k in sorted(summary.keys()):
print k, summary[k]
</code></pre>
<p>This is done so often in data warehousing applications, that it's ... | 1 | 2009-06-18T18:31:13Z | [
"python",
"collections",
"dictionary",
"treemap",
"uses"
] |
What Can A 'TreeDict' (Or Treemap) Be Used For In Practice? | 1,014,247 | <p>I'm developing a 'TreeDict' class in Python. This is a basically a dict that allows you to retrieve its key-value pairs in sorted order, just like the Treemap collection class in Java.</p>
<p>I've implemented some functionality based on the way unique indexes in relational databases can be used, e.g. functions to ... | 2 | 2009-06-18T17:59:25Z | 1,014,601 | <p>It's useful when you need to go through a Dictionary in order of the keys; which comes up on occasion. I've actually found its infinitely more common in certain programming contests then anything else (think ACM, etc).</p>
<p>The most useful feature of a TreeMap is when you want to quickly find the min or max key; ... | 2 | 2009-06-18T19:04:30Z | [
"python",
"collections",
"dictionary",
"treemap",
"uses"
] |
What Can A 'TreeDict' (Or Treemap) Be Used For In Practice? | 1,014,247 | <p>I'm developing a 'TreeDict' class in Python. This is a basically a dict that allows you to retrieve its key-value pairs in sorted order, just like the Treemap collection class in Java.</p>
<p>I've implemented some functionality based on the way unique indexes in relational databases can be used, e.g. functions to ... | 2 | 2009-06-18T17:59:25Z | 1,015,901 | <p>I've seen several answers pointing to the "walk in ordered sequence" feature, which is indeed important, but none highlighting the other big feature, which is "find first entry with a key >= this". This has many uses even when there's no real need to "walk" from there.</p>
<p>For example (this came up in a recent S... | 5 | 2009-06-19T00:38:22Z | [
"python",
"collections",
"dictionary",
"treemap",
"uses"
] |
What Can A 'TreeDict' (Or Treemap) Be Used For In Practice? | 1,014,247 | <p>I'm developing a 'TreeDict' class in Python. This is a basically a dict that allows you to retrieve its key-value pairs in sorted order, just like the Treemap collection class in Java.</p>
<p>I've implemented some functionality based on the way unique indexes in relational databases can be used, e.g. functions to ... | 2 | 2009-06-18T17:59:25Z | 2,613,165 | <p>Have you seen that: <a href="http://code.activestate.com/recipes/576998/" rel="nofollow">http://code.activestate.com/recipes/576998/</a> ?</p>
<p>zuo</p>
| 1 | 2010-04-10T11:17:33Z | [
"python",
"collections",
"dictionary",
"treemap",
"uses"
] |
How do I convert a nested tuple of tuples and lists to lists of lists in Python? | 1,014,352 | <p>I have a tuple containing lists and more tuples. I need to convert it to nested lists with the same structure. For example, I want to convert <code>(1,2,[3,(4,5)])</code> to <code>[1,2,[3,[4,5]]]</code>.</p>
<p>How do I do this (in Python)?</p>
| 2 | 2009-06-18T18:20:54Z | 1,014,499 | <p>As a python newbie I would try this</p>
<pre><code>def f(t):
if type(t) == list or type(t) == tuple:
return [f(i) for i in t]
return t
t = (1,2,[3,(4,5)])
f(t)
>>> [1, 2, [3, [4, 5]]]
</code></pre>
<p>Or, if you like one liners:</p>
<pre><code>def f(t):
return [f(i) for i in t] if i... | 6 | 2009-06-18T18:48:36Z | [
"python",
"list",
"tuples"
] |
How do I convert a nested tuple of tuples and lists to lists of lists in Python? | 1,014,352 | <p>I have a tuple containing lists and more tuples. I need to convert it to nested lists with the same structure. For example, I want to convert <code>(1,2,[3,(4,5)])</code> to <code>[1,2,[3,[4,5]]]</code>.</p>
<p>How do I do this (in Python)?</p>
| 2 | 2009-06-18T18:20:54Z | 1,014,669 | <pre><code>def listit(t):
    return list(map(listit, t)) if isinstance(t, (list, tuple)) else t
</code></pre>
<p>The shortest solution I can imagine.</p>
| 12 | 2009-06-18T19:19:02Z | [
"python",
"list",
"tuples"
] |
How do I convert a nested tuple of tuples and lists to lists of lists in Python? | 1,014,352 | <p>I have a tuple containing lists and more tuples. I need to convert it to nested lists with the same structure. For example, I want to convert <code>(1,2,[3,(4,5)])</code> to <code>[1,2,[3,[4,5]]]</code>.</p>
<p>How do I do this (in Python)?</p>
| 2 | 2009-06-18T18:20:54Z | 1,210,288 | <p>This is what I had come up with, but I like the other's better.</p>
<pre><code>def deep_list(x):
"""fully copies trees of tuples or lists to a tree of lists.
deep_list( (1,2,(3,4)) ) returns [1,2,[3,4]]
deep_list( (1,2,[3,(4,5)]) ) returns [1,2,[3,[4,5]]]"""
if not ( type(x) == type( (... | 0 | 2009-07-31T01:50:40Z | [
"python",
"list",
"tuples"
] |
How do I convert a nested tuple of tuples and lists to lists of lists in Python? | 1,014,352 | <p>I have a tuple containing lists and more tuples. I need to convert it to nested lists with the same structure. For example, I want to convert <code>(1,2,[3,(4,5)])</code> to <code>[1,2,[3,[4,5]]]</code>.</p>
<p>How do I do this (in Python)?</p>
| 2 | 2009-06-18T18:20:54Z | 36,307,987 | <p>We can (ab)use the fact that <code>json.loads</code> always produces Python lists for JSON lists, while <code>json.dumps</code> turns any Python collection into a JSON list:</p>
<pre><code>import json
def nested_list(nested_collection):
return json.loads(json.dumps(nested_collection))
</code></pre>
| 0 | 2016-03-30T11:50:23Z | [
"python",
"list",
"tuples"
] |
What does : TypeError: cannot concatenate 'str' and 'list' objects mean? | 1,014,503 | <p>What does this error mean?</p>
<blockquote>
<p>TypeError: cannot concatenate 'str' and 'list' objects</p>
</blockquote>
<p>Here's part of the code:</p>
<pre><code>for j in ('90.','52.62263.','26.5651.','10.8123.'):
if j == '90.':
z = ('0.')
elif j == '52.62263.':
z = ('0.', '72.', '144.'... | 8 | 2009-06-18T18:49:36Z | 1,014,519 | <p>string objects can only be concatenated with other strings. Python is a strongly-typed language. It will not coerce types for you.</p>
<p>you can do: </p>
<pre><code>'a' + '1'
</code></pre>
<p>but not: </p>
<pre><code>'a' + 1
</code></pre>
<p>in your case, you are trying to concat a string and a list. this ... | 3 | 2009-06-18T18:52:10Z | [
"python",
"string"
] |
What does : TypeError: cannot concatenate 'str' and 'list' objects mean? | 1,014,503 | <p>What does this error mean?</p>
<blockquote>
<p>TypeError: cannot concatenate 'str' and 'list' objects</p>
</blockquote>
<p>Here's part of the code:</p>
<pre><code>for j in ('90.','52.62263.','26.5651.','10.8123.'):
if j == '90.':
z = ('0.')
elif j == '52.62263.':
z = ('0.', '72.', '144.'... | 8 | 2009-06-18T18:49:36Z | 1,014,596 | <p>I'm not sure you're aware that <code>cmd</code> is a one-element <code>list</code>, and not a string.</p>
<p>Changing that line to the below would construct a string, and the rest of your code will work:</p>
<pre><code># Just removing the square brackets
cmd = exepath + '-j' + str(j) + '-n' + str(z)
</code></pre>
... | 11 | 2009-06-18T19:03:32Z | [
"python",
"string"
] |
What does : TypeError: cannot concatenate 'str' and 'list' objects mean? | 1,014,503 | <p>What does this error mean?</p>
<blockquote>
<p>TypeError: cannot concatenate 'str' and 'list' objects</p>
</blockquote>
<p>Here's part of the code:</p>
<pre><code>for j in ('90.','52.62263.','26.5651.','10.8123.'):
if j == '90.':
z = ('0.')
elif j == '52.62263.':
z = ('0.', '72.', '144.'... | 8 | 2009-06-18T18:49:36Z | 1,015,817 | <p>There is ANOTHER problem in the OP's code:</p>
<p><code>z = ('0.')</code> then later <code>for k in z:</code></p>
<p>The parentheses in the first statement will be ignored, leading to the second statement binding <code>k</code> first to <code>'0'</code> and then <code>'.'</code> ... looks like <code>z = ('0.', )</... | 2 | 2009-06-19T00:02:54Z | [
"python",
"string"
] |
Simple syntax for bringing a list element to the front in python? | 1,014,523 | <p>I have an array with a set of elements. I'd like to bring a given element to the front but otherwise leave the order unchanged. Do folks have suggestions as to the cleanest syntax for this?</p>
<p>This is the best I've been able to come up with, but it seems like bad form to have an N log N operation when an N op... | 17 | 2009-06-18T18:52:58Z | 1,014,533 | <p>To bring (for example) the 5th element to the front, use:</p>
<pre><code>mylist.insert(0, mylist.pop(5))
</code></pre>
| 19 | 2009-06-18T18:55:17Z | [
"python"
] |
Simple syntax for bringing a list element to the front in python? | 1,014,523 | <p>I have an array with a set of elements. I'd like to bring a given element to the front but otherwise leave the order unchanged. Do folks have suggestions as to the cleanest syntax for this?</p>
<p>This is the best I've been able to come up with, but it seems like bad form to have an N log N operation when an N op... | 17 | 2009-06-18T18:52:58Z | 1,014,544 | <p>I would go with:</p>
<pre><code>mylist.insert(0, mylist.pop(mylist.index(targetvalue)))
</code></pre>
| 41 | 2009-06-18T18:57:35Z | [
"python"
] |
Simple syntax for bringing a list element to the front in python? | 1,014,523 | <p>I have an array with a set of elements. I'd like to bring a given element to the front but otherwise leave the order unchanged. Do folks have suggestions as to the cleanest syntax for this?</p>
<p>This is the best I've been able to come up with, but it seems like bad form to have an N log N operation when an N op... | 17 | 2009-06-18T18:52:58Z | 1,014,597 | <p>Note: the following code (and the sample code you offered) will put <em>all</em> matching elements at the front.</p>
<pre><code>x = targetvalue
for i in range(len(mylist)):
if(mylist[i] == x):
mylist = [mylist[i]] + mylist[:i] + mylist[i+1:]
</code></pre>
<p>For example, if mylist = [1, 2, 3, 4, 3] and... | 0 | 2009-06-18T19:03:40Z | [
"python"
] |
Simple syntax for bringing a list element to the front in python? | 1,014,523 | <p>I have an array with a set of elements. I'd like to bring a given element to the front but otherwise leave the order unchanged. Do folks have suggestions as to the cleanest syntax for this?</p>
<p>This is the best I've been able to come up with, but it seems like bad form to have an N log N operation when an N op... | 17 | 2009-06-18T18:52:58Z | 22,728,388 | <p>Using insertion design technique (which does exactly same as what Mike suggested):</p>
<pre><code>def move-to-front(key, mylist):
for i in range(len(mylist[:mylist.index(key)]), -1, -1):
mylist[i] = mylist[i - 1]
mylist[0] = key
</code></pre>
| 0 | 2014-03-29T07:38:54Z | [
"python"
] |
Simple syntax for bringing a list element to the front in python? | 1,014,523 | <p>I have an array with a set of elements. I'd like to bring a given element to the front but otherwise leave the order unchanged. Do folks have suggestions as to the cleanest syntax for this?</p>
<p>This is the best I've been able to come up with, but it seems like bad form to have an N log N operation when an N op... | 17 | 2009-06-18T18:52:58Z | 28,370,695 | <p>This requires just two list operations (no index):
<code>
mylist.remove(targetvalue)
mylist.insert(0, targetvalue)
</code></p>
| 4 | 2015-02-06T16:48:56Z | [
"python"
] |
Python Authentication with urllib2 | 1,014,570 | <p>So I'm trying to download a file from a site called vsearch.cisco.com with python</p>
<p>[python]</p>
<pre><code>#Connects to the Cisco Server and Downloads files at the URL specified
import urllib2
#Define Useful Variables
url = 'http://vsearch.cisco.com'
username = 'xxxxxxxx'
password = 'xxxxxxxx'
realm = 'CE... | 4 | 2009-06-18T19:00:28Z | 1,014,628 | <p>As for what I tried in my tests (<a href="http://devel.almad.net/trac/django-http-digest/browser/djangohttpdigest/tests/test_simple_digest.py" rel="nofollow">http://devel.almad.net/trac/django-http-digest/browser/djangohttpdigest/tests/test_simple_digest.py</a>), error is prabably in your url - To make it working, I... | 0 | 2009-06-18T19:09:54Z | [
"python"
] |
Python Authentication with urllib2 | 1,014,570 | <p>So I'm trying to download a file from a site called vsearch.cisco.com with python</p>
<p>[python]</p>
<pre><code>#Connects to the Cisco Server and Downloads files at the URL specified
import urllib2
#Define Useful Variables
url = 'http://vsearch.cisco.com'
username = 'xxxxxxxx'
password = 'xxxxxxxx'
realm = 'CE... | 4 | 2009-06-18T19:00:28Z | 1,014,646 | <p>A "password manager" might help:</p>
<pre><code> mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
mgr.add_password(None, url, user, password)
urllib2.build_opener(urllib2.HTTPBasicAuthHandler(mgr),
urllib2.HTTPDigestAuthHandler(mgr))
</code></pre>
| 7 | 2009-06-18T19:13:13Z | [
"python"
] |
Traversing foreign key related tables in django templates | 1,014,591 | <h2>View</h2>
<pre><code>categories = Category.objects.all()
t = loader.get_template('index.html')
v = Context({
'categories': categories
})
return HttpResponse(t.render(v))
</code></pre>
<h2>Template</h2>
<pre><code>{% for category in categories %}
<h1>{{ category.name }}</h1>
{% endfor %}
</code><... | 27 | 2009-06-18T19:02:45Z | 1,014,610 | <p>Just get rid of the parentheses:</p>
<pre><code>{% for company in category.company_set.all %}
</code></pre>
<p>Here's the <a href="http://docs.djangoproject.com/en/dev/topics/templates/#variables">appropriate documentation</a>. You can call methods that take 0 parameters this way.</p>
| 43 | 2009-06-18T19:06:31Z | [
"python",
"django",
"django-models",
"django-templates"
] |
Logging All Exceptions in a pyqt4 app | 1,015,047 | <p>What's the best way to log all of the exceptions in a pyqt4 application using the standard python logging api?</p>
<p>I've tried wrapping exec_() in a try, except block, and logging the exceptions from that, but it only logs exceptions from the initialization of the app.</p>
<p>As a temporary solution, I wrapped t... | 11 | 2009-06-18T20:34:23Z | 1,015,272 | <p>You need to override <a href="http://docs.python.org/library/sys.html"><code>sys.excepthook</code></a></p>
<pre><code>def my_excepthook(type, value, tback):
# log the exception here
# then call the default handler
sys.__excepthook__(type, value, tback)
sys.excepthook = my_excepthook
</code></pre>
| 15 | 2009-06-18T21:27:06Z | [
"python",
"logging",
"pyqt"
] |
Is it possible to override the method used to call Django's admin delete confirmation page? | 1,015,072 | <p>On Django's admin pages, I'd like to perform an action when the administrator clicks the Delete button for an object. In other words, I'd like to execute some code prior to arriving on the "Are you sure?" delete confirmation page.</p>
<p>I realize I could override the template page for this object, but I was hopin... | 4 | 2009-06-18T20:40:14Z | 1,015,332 | <p>You can override <code>ModelAdmin.delete_view()</code> method, like:</p>
<pre><code>class MyModelAdmin(ModelAdmin):
def delete_view(self, request, object_id, extra_context=None):
# if request.POST is set, the user already confirmed deletion
if not request.POST:
perform_my_action()
... | 7 | 2009-06-18T21:37:38Z | [
"python",
"django",
"django-admin"
] |
Is it possible to override the method used to call Django's admin delete confirmation page? | 1,015,072 | <p>On Django's admin pages, I'd like to perform an action when the administrator clicks the Delete button for an object. In other words, I'd like to execute some code prior to arriving on the "Are you sure?" delete confirmation page.</p>
<p>I realize I could override the template page for this object, but I was hopin... | 4 | 2009-06-18T20:40:14Z | 4,708,452 | <p>We can use django.shortcuts.redirect to interrupt deletion, like this:</p>
<pre><code>def check_del(self, object_id):
produkt = Produkt.objects.get(id = object_id)
if produkt.typsklepu_set.all():
return False
else:
return True
def delete_view(self, request, object_id, extra_context=None... | 1 | 2011-01-16T22:16:36Z | [
"python",
"django",
"django-admin"
] |
Running Python code contained in a string | 1,015,142 | <p>I'm writing a game engine using pygame and box2d, and in the character builder, I want to be able to write the code that will be executed on keydown events.</p>
<p>My plan was to have a text editor in the character builder that let you write code similar to:</p>
<pre><code>if key == K_a:
## Move left
pass
... | 7 | 2009-06-18T20:55:33Z | 1,015,147 | <p>You can use the <a href="http://docs.python.org/library/functions.html#eval"><code>eval(string)</code></a> method to do this. </p>
<h2>Definition</h2>
<p><code>eval(code, globals=None, locals=None)</code><br />
The code is just standard Python code - this means that it still needs to be properly indented. </p>
<... | 22 | 2009-06-18T20:57:11Z | [
"python",
"pygame",
"exec",
"eval"
] |
Running Python code contained in a string | 1,015,142 | <p>I'm writing a game engine using pygame and box2d, and in the character builder, I want to be able to write the code that will be executed on keydown events.</p>
<p>My plan was to have a text editor in the character builder that let you write code similar to:</p>
<pre><code>if key == K_a:
## Move left
pass
... | 7 | 2009-06-18T20:55:33Z | 1,015,154 | <p>You can use <a href="http://docs.python.org/library/functions.html#eval" rel="nofollow"><code>eval()</code></a></p>
| 0 | 2009-06-18T20:58:18Z | [
"python",
"pygame",
"exec",
"eval"
] |
Running Python code contained in a string | 1,015,142 | <p>I'm writing a game engine using pygame and box2d, and in the character builder, I want to be able to write the code that will be executed on keydown events.</p>
<p>My plan was to have a text editor in the character builder that let you write code similar to:</p>
<pre><code>if key == K_a:
## Move left
pass
... | 7 | 2009-06-18T20:55:33Z | 1,015,156 | <p>eval or exec. You should definitely read Python library reference before programming.</p>
| 0 | 2009-06-18T20:58:38Z | [
"python",
"pygame",
"exec",
"eval"
] |
Running Python code contained in a string | 1,015,142 | <p>I'm writing a game engine using pygame and box2d, and in the character builder, I want to be able to write the code that will be executed on keydown events.</p>
<p>My plan was to have a text editor in the character builder that let you write code similar to:</p>
<pre><code>if key == K_a:
## Move left
pass
... | 7 | 2009-06-18T20:55:33Z | 1,015,198 | <p>As others have pointed out, you can load the text into a string and use <code>exec "codestring"</code>. If contained in a file already, using <a href="http://docs.python.org/library/functions.html#execfile" rel="nofollow">execfile</a> will avoid having to load it.</p>
<p>One performance note: You should avoid exe... | 2 | 2009-06-18T21:12:28Z | [
"python",
"pygame",
"exec",
"eval"
] |
Python: Bind an Unbound Method? | 1,015,307 | <p>In Python, is there a way to bind an unbound method without calling it?</p>
<p>I am writing a wxPython program, and for a certain class I decided it'd be nice to group the data of all of my buttons together as a class-level list of tuples, like so:</p>
<pre><code>class MyWidget(wx.Window):
buttons = [("OK", On... | 82 | 2009-06-18T21:33:18Z | 1,015,355 | <p>This will bind <code>self</code> to <code>handler</code>:</p>
<pre><code>bound_handler = lambda *args, **kwargs: handler(self, *args, **kwargs)
</code></pre>
<p>This works by passing <code>self</code> as the first argument to the function. <code>object.function()</code> is just syntactic sugar for <code>function(o... | 2 | 2009-06-18T21:41:13Z | [
"python",
"class",
"methods",
"bind"
] |
Python: Bind an Unbound Method? | 1,015,307 | <p>In Python, is there a way to bind an unbound method without calling it?</p>
<p>I am writing a wxPython program, and for a certain class I decided it'd be nice to group the data of all of my buttons together as a class-level list of tuples, like so:</p>
<pre><code>class MyWidget(wx.Window):
buttons = [("OK", On... | 82 | 2009-06-18T21:33:18Z | 1,015,389 | <p>This can be done cleanly with <a href="http://docs.python.org/library/types.html#types.MethodType">types.MethodType</a>. Example:</p>
<pre><code>import types
def f(self): print self
class C(object): pass
meth = types.MethodType(f, C(), C) # Bind f to an instance of C
print meth # prints <bound method C.f of &... | 65 | 2009-06-18T21:50:36Z | [
"python",
"class",
"methods",
"bind"
] |
Python: Bind an Unbound Method? | 1,015,307 | <p>In Python, is there a way to bind an unbound method without calling it?</p>
<p>I am writing a wxPython program, and for a certain class I decided it'd be nice to group the data of all of my buttons together as a class-level list of tuples, like so:</p>
<pre><code>class MyWidget(wx.Window):
buttons = [("OK", On... | 82 | 2009-06-18T21:33:18Z | 1,015,405 | <p>All functions are also <em>descriptors</em>, so you can bind them by calling their <code>__get__</code> method:</p>
<pre><code>bound_handler = handler.__get__(self, MyWidget)
</code></pre>
<p>Here's R. Hettinger's excellent <a href="http://users.rcn.com/python/download/Descriptor.htm">guide</a> to descriptors.</p>... | 119 | 2009-06-18T21:54:29Z | [
"python",
"class",
"methods",
"bind"
] |
Python: Bind an Unbound Method? | 1,015,307 | <p>In Python, is there a way to bind an unbound method without calling it?</p>
<p>I am writing a wxPython program, and for a certain class I decided it'd be nice to group the data of all of my buttons together as a class-level list of tuples, like so:</p>
<pre><code>class MyWidget(wx.Window):
buttons = [("OK", On... | 82 | 2009-06-18T21:33:18Z | 7,312,062 | <p>Creating a closure with self in it will not technically bind the function, but it is an alternative way of solving the same (or very similar) underlying problem. Here's a trivial example:</p>
<pre><code>self.method = (lambda self: lambda args: self.do(args))(self)
</code></pre>
| 7 | 2011-09-05T19:31:03Z | [
"python",
"class",
"methods",
"bind"
] |
Continuous unit testing with Pydev (Python and Eclipse) | 1,015,581 | <p>Is there a way to integrate background unit tests with the Pydev Eclipse environment?</p>
<p>My unit tests run well, but I would like to integrate them to run in the background based on source file changes (e.g. with nose) and to integrate the result back to Eclipse (I'm thinking big red X when tests fail with a co... | 42 | 2009-06-18T22:46:50Z | 1,039,552 | <p>Pydev does have some unit-test integration, but that's only as a run configuration...so...</p>
<p>This is not a very elegant way, but if you:</p>
<ol>
<li>Enable Project->Build Automatically</li>
<li>In your project properties, add a new builder of type Program</li>
<li>Configure it to run your tests and select 'd... | 9 | 2009-06-24T16:44:23Z | [
"python",
"unit-testing",
"pydev"
] |
Continuous unit testing with Pydev (Python and Eclipse) | 1,015,581 | <p>Is there a way to integrate background unit tests with the Pydev Eclipse environment?</p>
<p>My unit tests run well, but I would like to integrate them to run in the background based on source file changes (e.g. with nose) and to integrate the result back to Eclipse (I'm thinking big red X when tests fail with a co... | 42 | 2009-06-18T22:46:50Z | 1,040,367 | <p>I just realized that PyDev has rather powerful scripting support. Unfortunately I don't have the time to do it all for you (but if you complete this, please post it here :)</p>
<p>If you create a file named <code>pyedit_nose.py</code> that looks like this in an otherwise empty folder :</p>
<pre><code>assert cmd is... | 5 | 2009-06-24T19:16:37Z | [
"python",
"unit-testing",
"pydev"
] |
Continuous unit testing with Pydev (Python and Eclipse) | 1,015,581 | <p>Is there a way to integrate background unit tests with the Pydev Eclipse environment?</p>
<p>My unit tests run well, but I would like to integrate them to run in the background based on source file changes (e.g. with nose) and to integrate the result back to Eclipse (I'm thinking big red X when tests fail with a co... | 42 | 2009-06-18T22:46:50Z | 2,597,280 | <p>I use <a href="http://pypi.python.org/pypi/nosy" rel="nofollow">Nosy</a> (available on pypi): </p>
<blockquote>
<p>Run the nose test discovery and execution tool whenever a source file
is changed.</p>
</blockquote>
| 0 | 2010-04-08T02:51:10Z | [
"python",
"unit-testing",
"pydev"
] |
Continuous unit testing with Pydev (Python and Eclipse) | 1,015,581 | <p>Is there a way to integrate background unit tests with the Pydev Eclipse environment?</p>
<p>My unit tests run well, but I would like to integrate them to run in the background based on source file changes (e.g. with nose) and to integrate the result back to Eclipse (I'm thinking big red X when tests fail with a co... | 42 | 2009-06-18T22:46:50Z | 4,338,466 | <p>I enhanced the "nosy" script to automatically build documentation and runs tests
continuously. Nothing stellar, but gets the job done. Posting it here because the original
link went down. Unlike the original nosy script, this one scans the directory recursively
and allows looking for multiple patterns.</p>
<pre><c... | 0 | 2010-12-02T18:29:34Z | [
"python",
"unit-testing",
"pydev"
] |
Continuous unit testing with Pydev (Python and Eclipse) | 1,015,581 | <p>Is there a way to integrate background unit tests with the Pydev Eclipse environment?</p>
<p>My unit tests run well, but I would like to integrate them to run in the background based on source file changes (e.g. with nose) and to integrate the result back to Eclipse (I'm thinking big red X when tests fail with a co... | 42 | 2009-06-18T22:46:50Z | 5,071,787 | <p>I run the test by hand the first time (<em>Run > Run As > Python unit test</em>). After that, I use
<code>Ctrl+Shift+F9</code> to have the files saved and the tests executed, instead of saving with <code>Ctrl+S</code> and expecting some magic to happen. </p>
<p>The <code>Ctrl+Shift+F9</code> key combination relaunc... | 0 | 2011-02-21T22:04:19Z | [
"python",
"unit-testing",
"pydev"
] |
Continuous unit testing with Pydev (Python and Eclipse) | 1,015,581 | <p>Is there a way to integrate background unit tests with the Pydev Eclipse environment?</p>
<p>My unit tests run well, but I would like to integrate them to run in the background based on source file changes (e.g. with nose) and to integrate the result back to Eclipse (I'm thinking big red X when tests fail with a co... | 42 | 2009-06-18T22:46:50Z | 5,650,640 | <p>This feature has been added to PyDev 2.0.1 with an option to relaunch the tests in the last test run whenever a python file change, with an additional option to rerun only the errors -- although it'll run the full test suite if no errors were found, as the idea is that you work through your errors and when all pass ... | 34 | 2011-04-13T14:09:41Z | [
"python",
"unit-testing",
"pydev"
] |
Why is `self` in Python objects immutable? | 1,015,592 | <p>Why can't I perform an action like the following:</p>
<pre><code>class Test(object):
def __init__(self):
self = 5
t = Test()
print t
</code></pre>
<p>I would expect it to print <code>5</code> since we're overwriting the instance with it, but instead it doesn't do anything at all. Doesn't even throw an... | 24 | 2009-06-18T22:51:21Z | 1,015,599 | <p>Dr. Egon Spengler: It would be bad.<br />
Dr. Peter Venkman: I'm fuzzy on the whole good/bad thing. What do you mean, "bad"?<br />
Dr. Egon Spengler: Try to imagine all life as you know it stopping instantaneously and every molecule in your body exploding at the speed of light.</p>
| 0 | 2009-06-18T22:54:10Z | [
"python",
"object"
] |
Why is `self` in Python objects immutable? | 1,015,592 | <p>Why can't I perform an action like the following:</p>
<pre><code>class Test(object):
def __init__(self):
self = 5
t = Test()
print t
</code></pre>
<p>I would expect it to print <code>5</code> since we're overwriting the instance with it, but instead it doesn't do anything at all. Doesn't even throw an... | 24 | 2009-06-18T22:51:21Z | 1,015,602 | <p><em>Any</em> simple assignment to <em>any</em> argument of <em>any</em> function behaves exactly the same way in Python: binds that name to a different value, and does nothing else whatsoever. "No special case is special enough to break the rules", as the Zen of Python says!-)</p>
<p>So, far from it being odd (that... | 58 | 2009-06-18T22:55:06Z | [
"python",
"object"
] |
Why is `self` in Python objects immutable? | 1,015,592 | <p>Why can't I perform an action like the following:</p>
<pre><code>class Test(object):
def __init__(self):
self = 5
t = Test()
print t
</code></pre>
<p>I would expect it to print <code>5</code> since we're overwriting the instance with it, but instead it doesn't do anything at all. Doesn't even throw an... | 24 | 2009-06-18T22:51:21Z | 1,015,604 | <p>It doesnt "ignore" the assignment. The assignment works just fine, you created a local name that points to the data 5.</p>
<p>If you <em>really</em> want to do what you are doing...</p>
<pre><code>class Test(object):
def __new__(*args):
return 5
</code></pre>
| 9 | 2009-06-18T22:55:28Z | [
"python",
"object"
] |
Why is `self` in Python objects immutable? | 1,015,592 | <p>Why can't I perform an action like the following:</p>
<pre><code>class Test(object):
def __init__(self):
self = 5
t = Test()
print t
</code></pre>
<p>I would expect it to print <code>5</code> since we're overwriting the instance with it, but instead it doesn't do anything at all. Doesn't even throw an... | 24 | 2009-06-18T22:51:21Z | 1,015,615 | <p>I just ran a quick test, and you can assign to self. Inside your <strong>init</strong>() method, print out the value of self. You'll see that it's 5.</p>
<p>What you're missing here is that parameters are passed by value in Python. So, changing the value of a variable in a function or method won't change it for ... | 3 | 2009-06-18T22:57:57Z | [
"python",
"object"
] |
Why is `self` in Python objects immutable? | 1,015,592 | <p>Why can't I perform an action like the following:</p>
<pre><code>class Test(object):
def __init__(self):
self = 5
t = Test()
print t
</code></pre>
<p>I would expect it to print <code>5</code> since we're overwriting the instance with it, but instead it doesn't do anything at all. Doesn't even throw an... | 24 | 2009-06-18T22:51:21Z | 1,015,645 | <p>Sometimes you want to do this, though not with immutable types like <code>int</code>:</p>
<pre><code>>>> class Test(list):
... def __init__(self):
... list.__init__(self, [1,2,3]) # self = [1,2,3] seems right, but isn't
>> t = Test()
>> print t
[1, 2, 3]
</code></pre>
| 1 | 2009-06-18T23:06:41Z | [
"python",
"object"
] |
Why is `self` in Python objects immutable? | 1,015,592 | <p>Why can't I perform an action like the following:</p>
<pre><code>class Test(object):
def __init__(self):
self = 5
t = Test()
print t
</code></pre>
<p>I would expect it to print <code>5</code> since we're overwriting the instance with it, but instead it doesn't do anything at all. Doesn't even throw an... | 24 | 2009-06-18T22:51:21Z | 1,015,670 | <pre><code>class Test(object):
def __init__(self):
self = 5
t = Test()
print t
</code></pre>
<p>is like having this PHP (only other lang i know, sorry)</p>
<pre><code>class Test {
function __construct() {
$this = 5;
}
}
</code></pre>
<p>I don't see how it makes sense. replacing t... | -3 | 2009-06-18T23:12:50Z | [
"python",
"object"
] |
How do I compile Python C extensions using MinGW inside a virtualenv? | 1,015,605 | <p>When using virtualenv in combination with the MinGW compiler on Windows, compiling a C extension results in the following error:</p>
<pre>
C:\MinGW\bin\..\lib\gcc\mingw32\3.4.5\..\..\..\..\mingw32\bin\ld.exe: cannot find -lpython25
collect2: ld returned 1 exit status
error: Setup script exited with error: command... | 2 | 2009-06-18T22:55:29Z | 1,015,628 | <p>Set the <code>LIBRARY_PATH</code> environment variable so MinGW knows where to find the system-wide Python <code>libpython25.a</code>.</p>
<p>Place a line in your virtualenv's <code>activate.bat</code>:</p>
<pre><code>set LIBRARY_PATH=c:\python25\libs
</code></pre>
<p>Or set a global environment variable in Windo... | 6 | 2009-06-18T23:01:38Z | [
"python",
"mingw",
"virtualenv"
] |
Passing Formatted Text Through XSLT | 1,015,816 | <p>I have formatted text (with newlines, tabs, etc.) coming in from a Telnet connection. I have a python script that manages the Telnet connection and embeds the Telnet response in XML that then gets passed through an XSLT transform. How do I pass that XML through the transform without losing the original formatting?... | 0 | 2009-06-19T00:02:53Z | 1,015,827 | <p>You could embed the text you want to be untouched in a <a href="http://www.w3schools.com/Xml/xml%5Fcdata.asp" rel="nofollow">CDATA section</a>.</p>
| 0 | 2009-06-19T00:07:37Z | [
"python",
"xslt"
] |
Passing Formatted Text Through XSLT | 1,015,816 | <p>I have formatted text (with newlines, tabs, etc.) coming in from a Telnet connection. I have a python script that manages the Telnet connection and embeds the Telnet response in XML that then gets passed through an XSLT transform. How do I pass that XML through the transform without losing the original formatting?... | 0 | 2009-06-19T00:02:53Z | 1,016,919 | <p>Data stored in XML comes out the same way it goes in. So if you store the text in an element, no whitespace and newlines are lost unless you tamper with the data in the XSLT. </p>
<p>Enclosing the text in CDATA is unnecessary <em>unless</em> there is some formatting that is invalid in XML (pointy brackets, ampersan... | 0 | 2009-06-19T08:33:52Z | [
"python",
"xslt"
] |
python importing relative modules | 1,016,105 | <p>I have the Python modules a.py and b.py in the same directory.
How can I reliably import b.py from a.py, given that a.py may have been imported from another directory or executed directly? This module will be distributed so I can't hardcode a single path.</p>
<p>I've been playing around with <code>__file__</code>, ... | 0 | 2009-06-19T02:29:29Z | 1,016,121 | <p>Actually, <code>__file__</code> is available for an imported module, but only if it was imported from a .py/.pyc file. It won't be available if the module is built in. For example:</p>
<pre><code>>>> import sys, os
>>> hasattr(os, '__file__')
True
>>> hasattr(sys, '__file__')
False
</co... | 6 | 2009-06-19T02:37:02Z | [
"python",
"path",
"module",
"relative",
"python-import"
] |
python importing relative modules | 1,016,105 | <p>I have the Python modules a.py and b.py in the same directory.
How can I reliably import b.py from a.py, given that a.py may have been imported from another directory or executed directly? This module will be distributed so I can't hardcode a single path.</p>
<p>I've been playing around with <code>__file__</code>, ... | 0 | 2009-06-19T02:29:29Z | 1,016,185 | <p>Using the <a href="http://docs.python.org/library/inspect.html" rel="nofollow">inspect</a> module will make the builtin modules more obvious:</p>
<pre><code>>>> import os
>>> import sys
>>> inspect.getfile(os)
'/usr/local/lib/python2.6/os.pyc'
>>> inspect.getfile(sys)
Traceback (... | 1 | 2009-06-19T03:05:03Z | [
"python",
"path",
"module",
"relative",
"python-import"
] |
python importing relative modules | 1,016,105 | <p>I have the Python modules a.py and b.py in the same directory.
How can I reliably import b.py from a.py, given that a.py may have been imported from another directory or executed directly? This module will be distributed so I can't hardcode a single path.</p>
<p>I've been playing around with <code>__file__</code>, ... | 0 | 2009-06-19T02:29:29Z | 1,036,276 | <p>Put the directory that contains both in your python path... or vice versa.</p>
| -1 | 2009-06-24T03:37:49Z | [
"python",
"path",
"module",
"relative",
"python-import"
] |
Cross-platform subprocess with hidden window | 1,016,384 | <p>I want to open a process in the background and interact with it, but this process should be invisible in both Linux and Windows. In Windows you have to do some stuff with STARTUPINFO, while this isn't valid in Linux:</p>
<blockquote>
<p>ValueError: startupinfo is only supported on Windows platforms</p>
</blockqu... | 25 | 2009-06-19T04:52:50Z | 1,016,400 | <p>I'm not sure you can get much simpler than what you've done. You're talking about optimising out maybe 5 lines of code. For the money I would just get on with my project and accept this as a consquence of cross-platform development. If you do it a lot then create a specialised class or function to encapsulate the lo... | 3 | 2009-06-19T05:00:22Z | [
"python",
"windows",
"linux",
"cross-platform",
"subprocess"
] |
Cross-platform subprocess with hidden window | 1,016,384 | <p>I want to open a process in the background and interact with it, but this process should be invisible in both Linux and Windows. In Windows you have to do some stuff with STARTUPINFO, while this isn't valid in Linux:</p>
<blockquote>
<p>ValueError: startupinfo is only supported on Windows platforms</p>
</blockqu... | 25 | 2009-06-19T04:52:50Z | 1,016,633 | <p>You can turn your code into:</p>
<pre><code>params = dict()
if os.name == 'nt':
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
params['startupinfo'] = startupinfo
proc = subprocess.Popen(command, **params)
</code></pre>
<p>but that's not much better.</p>... | 1 | 2009-06-19T06:38:02Z | [
"python",
"windows",
"linux",
"cross-platform",
"subprocess"
] |
Cross-platform subprocess with hidden window | 1,016,384 | <p>I want to open a process in the background and interact with it, but this process should be invisible in both Linux and Windows. In Windows you have to do some stuff with STARTUPINFO, while this isn't valid in Linux:</p>
<blockquote>
<p>ValueError: startupinfo is only supported on Windows platforms</p>
</blockqu... | 25 | 2009-06-19T04:52:50Z | 1,016,651 | <p>You can reduce one line :)</p>
<pre><code>startupinfo = None
if os.name == 'nt':
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
proc = subprocess.Popen(command, startupinfo=startupinfo)
</code></pre>
| 27 | 2009-06-19T06:48:07Z | [
"python",
"windows",
"linux",
"cross-platform",
"subprocess"
] |
Cross-platform subprocess with hidden window | 1,016,384 | <p>I want to open a process in the background and interact with it, but this process should be invisible in both Linux and Windows. In Windows you have to do some stuff with STARTUPINFO, while this isn't valid in Linux:</p>
<blockquote>
<p>ValueError: startupinfo is only supported on Windows platforms</p>
</blockqu... | 25 | 2009-06-19T04:52:50Z | 3,443,174 | <p>Just a note: for <strong>Python 2.7</strong> I have to use <code>subprocess._subprocess.STARTF_USESHOWWINDOW</code> instead of <code>subprocess.STARTF_USESHOWWINDOW</code>.</p>
| 12 | 2010-08-09T18:49:16Z | [
"python",
"windows",
"linux",
"cross-platform",
"subprocess"
] |
finding firefox version | 1,016,609 | <p>How to find Firefox version using python?</p>
| 1 | 2009-06-19T06:30:56Z | 1,016,637 | <p>Try the following code snippet:</p>
<pre><code>import os
firefox_version = os.popen("firefox --version").read()
</code></pre>
| 2 | 2009-06-19T06:39:53Z | [
"python",
"firefox"
] |
finding firefox version | 1,016,609 | <p>How to find Firefox version using python?</p>
| 1 | 2009-06-19T06:30:56Z | 1,024,846 | <p>I tried Alan's code snippet and it didn't work for me. One problem with it is that in order for the "-v or -version" flags to work, you must have a debug version firefox. See <a href="https://developer.mozilla.org/En/Command%5FLine%5FOptions" rel="nofollow">here</a> under "Miscellaneous" for details.</p>
<p>Try the... | 3 | 2009-06-21T22:05:49Z | [
"python",
"firefox"
] |
How to "keep-alive" with cookielib and httplib in python? | 1,016,765 | <p>In python, I'm using httplib because it "keep-alive" the http connection (as oppose to urllib(2)). Now, I want to use cookielib with httplib but they seem to hate each other!! (no way to interface them together). </p>
<p>Does anyone know of a solution to that problem?</p>
| 1 | 2009-06-19T07:32:11Z | 1,016,898 | <p><a href="http://urlgrabber.baseurl.org/help/urlgrabber.keepalive.html" rel="nofollow">HTTP handler for urllib2 that supports keep-alive</a></p>
| 2 | 2009-06-19T08:26:38Z | [
"python",
"cookies",
"urllib2",
"httplib"
] |
How to "keep-alive" with cookielib and httplib in python? | 1,016,765 | <p>In python, I'm using httplib because it "keep-alive" the http connection (as oppose to urllib(2)). Now, I want to use cookielib with httplib but they seem to hate each other!! (no way to interface them together). </p>
<p>Does anyone know of a solution to that problem?</p>
| 1 | 2009-06-19T07:32:11Z | 1,053,602 | <p>You should consider using the <a href="http://docs.python-requests.org/en/latest/" rel="nofollow"><code>Requests</code></a> library instead at the earliest chance you have to refactor your code. In the mean time;</p>
<p>HACK ALERT! :)</p>
<p>I'd go other suggested way, but I've done a hack (done for different reas... | 2 | 2009-06-27T20:51:39Z | [
"python",
"cookies",
"urllib2",
"httplib"
] |
What to do with "Unexpected indent" in python? | 1,016,814 | <p>How do I rectify the error "unexpected indent" in python?</p>
| 60 | 2009-06-19T07:53:20Z | 1,016,829 | <p>By using correct indentation. Python is whitespace aware, so you need to follow its indentation guidlines for blocks or you'll get indentation errors.</p>
| 8 | 2009-06-19T07:58:22Z | [
"python",
"syntax-error"
] |
What to do with "Unexpected indent" in python? | 1,016,814 | <p>How do I rectify the error "unexpected indent" in python?</p>
| 60 | 2009-06-19T07:53:20Z | 1,016,836 | <p>In Python, the spacing is very important, this gives the structure of your code blocks.
This error happens when you mess up your code structure, for example like this :</p>
<pre><code>def test_function() :
if 5 > 3 :
print "hello"
</code></pre>
<p>You may also have a mix of tabs and spaces in your file.</... | 21 | 2009-06-19T08:00:08Z | [
"python",
"syntax-error"
] |
What to do with "Unexpected indent" in python? | 1,016,814 | <p>How do I rectify the error "unexpected indent" in python?</p>
| 60 | 2009-06-19T07:53:20Z | 1,017,404 | <p>Python uses spacing at the start of the line to determine when code blocks start and end. Errors you can get are:</p>
<p><strong>Unexpected indent.</strong> This line of code has more spaces at the start than the one before, but the one before is not the start of a subblock (e.g. if/while/for statement). All lines ... | 85 | 2009-06-19T11:03:01Z | [
"python",
"syntax-error"
] |
What to do with "Unexpected indent" in python? | 1,016,814 | <p>How do I rectify the error "unexpected indent" in python?</p>
| 60 | 2009-06-19T07:53:20Z | 1,017,428 | <p>If the indentation looks ok then have a look to see if your editor has a "View Whitespace" option. Enabling this should allow to find where spaces and tabs are mixed.</p>
| 1 | 2009-06-19T11:15:26Z | [
"python",
"syntax-error"
] |
What to do with "Unexpected indent" in python? | 1,016,814 | <p>How do I rectify the error "unexpected indent" in python?</p>
| 60 | 2009-06-19T07:53:20Z | 1,017,449 | <p>There is a trick that always worked for me:</p>
<p>If you got and unexpected indent and you see that all the code is perfectly indented, try opening it with another editor and you will see what line of code is not indented.</p>
<p>It happened to me when used vim, gedit or editors like that.</p>
<p>Try to use only... | 2 | 2009-06-19T11:21:56Z | [
"python",
"syntax-error"
] |
What to do with "Unexpected indent" in python? | 1,016,814 | <p>How do I rectify the error "unexpected indent" in python?</p>
| 60 | 2009-06-19T07:53:20Z | 1,017,458 | <p><strong>Turn on visible whitespace in whatever editor you are using and turn on replace tabs with spaces.</strong></p>
<p>While you can use tabs with Python mixing tabs and space usually leads to the error you are experiencing. Replacing tabs with 4 spaces is the recommended approach for writing Python code.</p>
| 8 | 2009-06-19T11:25:47Z | [
"python",
"syntax-error"
] |
What to do with "Unexpected indent" in python? | 1,016,814 | <p>How do I rectify the error "unexpected indent" in python?</p>
| 60 | 2009-06-19T07:53:20Z | 7,499,004 | <p>Run your code with the -tt option to find out if you are using tabs and spaces inconsistently </p>
| 8 | 2011-09-21T11:31:51Z | [
"python",
"syntax-error"
] |
What to do with "Unexpected indent" in python? | 1,016,814 | <p>How do I rectify the error "unexpected indent" in python?</p>
| 60 | 2009-06-19T07:53:20Z | 18,830,607 | <p>Make sure you use the option "insert spaces instead of tabs" in your editor. Then you can choose you want a tab width of, for example 4. You can find those options in gedit under edit-->preferences-->editor.</p>
<p>bottom line: USE SPACES not tabs</p>
| 3 | 2013-09-16T14:33:24Z | [
"python",
"syntax-error"
] |
What to do with "Unexpected indent" in python? | 1,016,814 | <p>How do I rectify the error "unexpected indent" in python?</p>
| 60 | 2009-06-19T07:53:20Z | 25,902,014 | <p>Notepad++ was giving the tab space correct but the indentation problem was finally found in Sublime text editor.</p>
<p>Use Sublime text editor and go line by line</p>
| 1 | 2014-09-17T23:38:25Z | [
"python",
"syntax-error"
] |
What to do with "Unexpected indent" in python? | 1,016,814 | <p>How do I rectify the error "unexpected indent" in python?</p>
| 60 | 2009-06-19T07:53:20Z | 35,339,628 | <p>Simply copy your script and put under """ your entire code """ ...</p>
<p>specify this line in a variable.. like,</p>
<pre><code>a = """ your python script """
print a.replace('here please press tab button it will insert some space"," here simply press space bar four times")
# here we replacing tab space by four c... | 1 | 2016-02-11T12:40:59Z | [
"python",
"syntax-error"
] |
Generate from generators | 1,016,997 | <p>I have a generator that takes a number as an argument and yields other numbers.
I want to use the numbers yielded by this generator and pass them as arguments to the same generator, creating a chain of some length.</p>
<p>For example, mygenerator(2) yields 5, 4 and 6. Apply mygenerator to each of these numbers, ove... | 2 | 2009-06-19T09:00:33Z | 1,017,014 | <p>I have just started learning Python so bear with me if my answer seems a tad amateurish. What you could do is use a list of lists to populate the values returned from the myGenerator function.</p>
<p>So for eg. with 2 as the starting argument your data-structure would resemble something like </p>
<pre><code>resDat... | 0 | 2009-06-19T09:06:58Z | [
"python",
"generator"
] |
Generate from generators | 1,016,997 | <p>I have a generator that takes a number as an argument and yields other numbers.
I want to use the numbers yielded by this generator and pass them as arguments to the same generator, creating a chain of some length.</p>
<p>For example, mygenerator(2) yields 5, 4 and 6. Apply mygenerator to each of these numbers, ove... | 2 | 2009-06-19T09:00:33Z | 1,017,035 | <p>Suppose our generator yields square and cube of given number that way it will output unique
so if we want to get numbers at dist D in simplest case we can recursively get numbers at dist D-1 and then apply generator to them</p>
<pre><code>def mygen(N):
yield N**2
yield N**3
def getSet(N, dist):
if dist... | 3 | 2009-06-19T09:13:34Z | [
"python",
"generator"
] |
Generate from generators | 1,016,997 | <p>I have a generator that takes a number as an argument and yields other numbers.
I want to use the numbers yielded by this generator and pass them as arguments to the same generator, creating a chain of some length.</p>
<p>For example, mygenerator(2) yields 5, 4 and 6. Apply mygenerator to each of these numbers, ove... | 2 | 2009-06-19T09:00:33Z | 1,017,105 | <p>This solution does not require to keep all results in memory: (in case it doesn't fit in memory etc)</p>
<pre><code>def grandKids(generation, kidsFunc, val):
layer = [val]
for i in xrange(generation):
layer = itertools.chain.from_iterable(itertools.imap(kidsFunc, layer))
return layer
</code></pre>
<p>Exa... | 2 | 2009-06-19T09:29:45Z | [
"python",
"generator"
] |
Python cgi performance | 1,017,087 | <p>I own a legacy python application written as CGI. Until now this works OK, but the number of concurrent users will increment largely in the very near future.
Here on SO I read: "CGI is great for low-traffic websites, but it has some performance problems for anything else". I know it would have been better to start i... | 2 | 2009-06-19T09:26:02Z | 1,017,103 | <p>Use <a href="http://www.fastcgi.com/drupal/" rel="nofollow">FastCGI</a>. If I understand FastCGI correctly, you can do what you want by writing a very simple Python program that sits between the web server and your legacy code.</p>
| 3 | 2009-06-19T09:29:14Z | [
"python",
"performance",
"cgi"
] |
Python cgi performance | 1,017,087 | <p>I own a legacy python application written as CGI. Until now this works OK, but the number of concurrent users will increment largely in the very near future.
Here on SO I read: "CGI is great for low-traffic websites, but it has some performance problems for anything else". I know it would have been better to start i... | 2 | 2009-06-19T09:26:02Z | 1,017,354 | <p>CGI doesn't scale because each request forks a brand new server process. It's a lot of overhead. mod_wsgi avoid the overhead by forking one process and handing requests to that one running process.</p>
<p>Let's assume the application is the worst kind of cgi.</p>
<p>The worst case is that it has files like this.... | 6 | 2009-06-19T10:46:31Z | [
"python",
"performance",
"cgi"
] |
UnicodeDecodeError when reading dictionary words file with simple Python script | 1,017,334 | <p>First time doing Python in a while, and I'm having trouble doing a simple scan of a file when I run the following script with Python 3.0.1,</p>
<pre><code>with open("/usr/share/dict/words", 'r') as f:
for line in f:
pass
</code></pre>
<p>I get this exception:</p>
<pre><code>Traceback (most recent call l... | 0 | 2009-06-19T10:35:22Z | 1,017,346 | <p>Can you check to make sure it is valid UTF-8? A way to do that is given at <a href="http://stackoverflow.com/questions/115210/utf-8-validation">this SO question</a>:</p>
<pre><code>iconv -f UTF-8 /usr/share/dict/words -o /dev/null
</code></pre>
<p>There are other ways to do the same thing.</p>
| 1 | 2009-06-19T10:42:29Z | [
"python"
] |
UnicodeDecodeError when reading dictionary words file with simple Python script | 1,017,334 | <p>First time doing Python in a while, and I'm having trouble doing a simple scan of a file when I run the following script with Python 3.0.1,</p>
<pre><code>with open("/usr/share/dict/words", 'r') as f:
for line in f:
pass
</code></pre>
<p>I get this exception:</p>
<pre><code>Traceback (most recent call l... | 0 | 2009-06-19T10:35:22Z | 1,017,376 | <p>How have you determined from "position 1689-1692" what line in the file it has blown up on? Those numbers would be offsets in the chunk that it's trying to decode. You would have had to determine what chunk it was -- how?</p>
<p>Try this at the interactive prompt:</p>
<pre><code>buf = open('the_file', 'rb').read()... | 1 | 2009-06-19T10:55:12Z | [
"python"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.