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
list
In Django - Model Inheritance - Does it allow you to override a parent model's attribute?
2,344,751
<p>I'm looking to do this:</p> <pre><code>class Place(models.Model): name = models.CharField(max_length=20) rating = models.DecimalField() class LongNamedRestaurant(Place): # Subclassing `Place`. name = models.CharField(max_length=255) # Notice, I'm overriding `Place.name` to give it a longer length. food_type ...
45
2010-02-26T20:50:54Z
24,581,514
<p>See <a href="http://stackoverflow.com/a/6379556/15690">http://stackoverflow.com/a/6379556/15690</a>:</p> <pre><code>class BaseMessage(models.Model): is_public = models.BooleanField(default=False) # some more fields... class Meta: abstract = True class Message(BaseMessage): # some fields......
13
2014-07-04T23:04:06Z
[ "python", "django", "django-inheritance" ]
In Django - Model Inheritance - Does it allow you to override a parent model's attribute?
2,344,751
<p>I'm looking to do this:</p> <pre><code>class Place(models.Model): name = models.CharField(max_length=20) rating = models.DecimalField() class LongNamedRestaurant(Place): # Subclassing `Place`. name = models.CharField(max_length=255) # Notice, I'm overriding `Place.name` to give it a longer length. food_type ...
45
2010-02-26T20:50:54Z
31,014,448
<p>You can not override Model fields, but its easily achieved by overriding/specifying clean() method. I had the issue with email field and wanted to make it unique on Model level and did it like this:</p> <pre><code>def clean(self): """ Make sure that email field is unique """ if MyUser.objects.filter...
0
2015-06-23T22:13:29Z
[ "python", "django", "django-inheritance" ]
In Django - Model Inheritance - Does it allow you to override a parent model's attribute?
2,344,751
<p>I'm looking to do this:</p> <pre><code>class Place(models.Model): name = models.CharField(max_length=20) rating = models.DecimalField() class LongNamedRestaurant(Place): # Subclassing `Place`. name = models.CharField(max_length=255) # Notice, I'm overriding `Place.name` to give it a longer length. food_type ...
45
2010-02-26T20:50:54Z
32,720,559
<p>This supercool piece of code allows you to 'override' fields in abstract parent classes.</p> <pre><code>def AbstractClassWithoutFieldsNamed(cls, *excl): """ Removes unwanted fields from abstract base classes. Usage:: &gt;&gt;&gt; from oscar.apps.address.abstract_models import AbstractBillingAddress...
5
2015-09-22T15:11:47Z
[ "python", "django", "django-inheritance" ]
In Django - Model Inheritance - Does it allow you to override a parent model's attribute?
2,344,751
<p>I'm looking to do this:</p> <pre><code>class Place(models.Model): name = models.CharField(max_length=20) rating = models.DecimalField() class LongNamedRestaurant(Place): # Subclassing `Place`. name = models.CharField(max_length=255) # Notice, I'm overriding `Place.name` to give it a longer length. food_type ...
45
2010-02-26T20:50:54Z
39,278,537
<p>Since Django 1.10 <a href="https://docs.djangoproject.com/en/dev/topics/db/models/#field-name-hiding-is-not-permitted" rel="nofollow">it's possible</a>! You just have to do what you asked for:</p> <pre><code>class Place(models.Model): name = models.CharField(max_length=20) rating = models.DecimalField() ...
1
2016-09-01T18:26:56Z
[ "python", "django", "django-inheritance" ]
PyUnit tearDown and setUp vs __init__ and __del__
2,344,772
<p>Is there a difference between using tearDown and setUp versus <code>__init__</code> and <code>__del__</code> when using the pyUnit testing framework? If so, what is it exactly and what is the preferred method of use?</p>
8
2010-02-26T20:53:52Z
2,344,828
<p><code>setUp</code> is called before every test, and <code>tearDown</code> is called after every test. <code>__init__</code> is called only once when the class is instantiated. You generally do not need to define <code>__init__</code> or <code>__del__</code> when writing unit tests, though you could use <code>__init_...
13
2010-02-26T21:03:43Z
[ "python", "unit-testing" ]
Extra parameter for Django models
2,344,994
<p>With Django models, I want to achieve this:</p> <pre><code>class Foo(models.Model): name = models.CharField(max_length=50) #wrapping the save function, including extra tasks def save(self, *args, **kwargs): super(Foo, self).save(*args, **kwargs) if extra_param: ...do ta...
1
2010-02-26T21:38:17Z
2,345,041
<p>You can define non-persistent fields in your model.</p> <pre><code>class Foo(models.Model): name = models.CharField(max_length=50) extra_param = False def save(self, *args, **kwargs): ... print self.extra_param </code></pre> <p>Alternatively, you can do:</p> <pre><code>Foo(name="Bill Gates").sav...
9
2010-02-26T21:44:12Z
[ "python", "django", "wrapper", "django-forms" ]
Python: Why is comparison between lists and tuples not supported?
2,345,092
<p>When comparing a tuple with a list like ...</p> <pre><code>&gt;&gt;&gt; [1,2,3] == (1,2,3) False &gt;&gt;&gt; [1,2,3].__eq__((1,2,3)) NotImplemented &gt;&gt;&gt; (1,2,3).__eq__([1,2,3]) NotImplemented </code></pre> <p>... Python does not deep-compare them as done with <code>(1,2,3) == (1,2,3)</code>.</p> <p>So wh...
12
2010-02-26T21:53:52Z
2,345,112
<p>You can always "cast" it</p> <pre><code>&gt;&gt;&gt; tuple([1, 2]) == (1, 2) True </code></pre> <p>Keep in mind that Python, unlike for example Javascript, <a href="http://en.wikipedia.org/wiki/Strongly_typed_programming_language">is strongly</a> <a href="http://wiki.python.org/moin/Why%20is%20Python%20a%20dynamic...
16
2010-02-26T21:56:49Z
[ "python", "list", "comparison", "tuples" ]
Python: Why is comparison between lists and tuples not supported?
2,345,092
<p>When comparing a tuple with a list like ...</p> <pre><code>&gt;&gt;&gt; [1,2,3] == (1,2,3) False &gt;&gt;&gt; [1,2,3].__eq__((1,2,3)) NotImplemented &gt;&gt;&gt; (1,2,3).__eq__([1,2,3]) NotImplemented </code></pre> <p>... Python does not deep-compare them as done with <code>(1,2,3) == (1,2,3)</code>.</p> <p>So wh...
12
2010-02-26T21:53:52Z
2,345,235
<p>There's no technical reason for lists not being able to compare to tuples; it's entirely a design decision driven by semantics. For proof that it's not related to thread-safety, you can compare lists to other lists:</p> <pre><code>&gt;&gt;&gt; l1 = [1, 2, 3] &gt;&gt;&gt; l2 = [1, 2, 3] &gt;&gt;&gt; l1 == l2 True &...
6
2010-02-26T22:19:19Z
[ "python", "list", "comparison", "tuples" ]
how to save/read class wholly in Python
2,345,151
<pre><code>som = SOM_CLASS() # includes many big difficult data structures som.hard_work() som.save_to_disk(filename) #then later or another program som = SOM_CLASS() som.read_from_file(filename) som.do_anythink_else() </code></pre> <p>or</p> <pre><code>som = SOM_CLASS() save(som) #... load(som) som.work() </code></p...
5
2010-02-26T22:04:49Z
2,345,158
<p>Take a look at Python's <a href="http://docs.python.org/library/pickle.html" rel="nofollow"><code>pickle</code></a> library.</p>
3
2010-02-26T22:05:52Z
[ "python", "class", "autosave" ]
how to save/read class wholly in Python
2,345,151
<pre><code>som = SOM_CLASS() # includes many big difficult data structures som.hard_work() som.save_to_disk(filename) #then later or another program som = SOM_CLASS() som.read_from_file(filename) som.do_anythink_else() </code></pre> <p>or</p> <pre><code>som = SOM_CLASS() save(som) #... load(som) som.work() </code></p...
5
2010-02-26T22:04:49Z
2,345,201
<p>You can (de)serialize with <a href="http://docs.python.org/library/pickle.html">pickle</a>. It is backward-compatible, i.e. it will support all old protocols in future versions.</p> <pre><code>import pickle som = SOM_CLASS() fileObject = &lt;any file-like object&gt; pickle.dump(som, fileObject) #... som = pickle.l...
5
2010-02-26T22:12:51Z
[ "python", "class", "autosave" ]
how to save/read class wholly in Python
2,345,151
<pre><code>som = SOM_CLASS() # includes many big difficult data structures som.hard_work() som.save_to_disk(filename) #then later or another program som = SOM_CLASS() som.read_from_file(filename) som.do_anythink_else() </code></pre> <p>or</p> <pre><code>som = SOM_CLASS() save(som) #... load(som) som.work() </code></p...
5
2010-02-26T22:04:49Z
9,201,726
<p>I use this code:</p> <pre><code>import cPickle import traceback class someClass(): def __init__(self): #set name from variable name. http://stackoverflow.com/questions/1690400/getting-an-instance-name-inside-class-init (filename,line_number,function_name,text)=traceback.extract_stack()[-2] ...
0
2012-02-08T21:29:30Z
[ "python", "class", "autosave" ]
How can I capture and print packets from the internet on Windows?
2,345,217
<p>How can I capture them? Is there any module/lib to do it?</p> <p>Please if it do, post an example</p>
1
2010-02-26T22:16:08Z
2,345,238
<p>If you can install <a href="http://www.wireshark.org/" rel="nofollow">Wireshark</a>, you can <a href="http://wiki.wireshark.org/Python" rel="nofollow">use it programaticaly from Python</a>. (This isn't <em>yet</em> supported on Windows, as per <a href="https://bugs.wireshark.org/bugzilla/show_bug.cgi?id=3500" rel="n...
1
2010-02-26T22:19:32Z
[ "python", "windows", "packets" ]
Creating a Persistent Data Object In Django
2,345,257
<p>I have a Python-based maximum entropy classifier. It's large, stored as a Pickle, and takes about a minute to unserialize. It's also not thread safe. However, it runs fast and can classify a sample (a simple Python dictionary) in a few milliseconds.</p> <p>I'd like to create a basic Django web app, so users can sub...
4
2010-02-26T22:24:27Z
2,345,334
<p>Consider running it in another process. You could have your Django application submit samples via a socket that the classifier process listens on, or you could run a queue and have Django submit requests to the queue.</p>
2
2010-02-26T22:41:20Z
[ "python", "django", "persistence" ]
Creating a Persistent Data Object In Django
2,345,257
<p>I have a Python-based maximum entropy classifier. It's large, stored as a Pickle, and takes about a minute to unserialize. It's also not thread safe. However, it runs fast and can classify a sample (a simple Python dictionary) in a few milliseconds.</p> <p>I'd like to create a basic Django web app, so users can sub...
4
2010-02-26T22:24:27Z
2,348,841
<p>you could use djangos <a href="http://docs.djangoproject.com/en/dev/topics/cache/" rel="nofollow">cache-framework</a> and set the timeout to a extreme value</p>
4
2010-02-27T20:27:33Z
[ "python", "django", "persistence" ]
Pyunit: "Import Site"
2,345,331
<p>Using pyUnit to do what is currently a very small and simple unit test I am getting the message:</p> <pre><code>'import site' failed; use -v for traceback ... ____________________________________________ Ran 3 tests in 0.094S </code></pre> <p>When I rerun the unit test with the -v parameter, it returns verbose inf...
0
2010-02-26T22:40:40Z
2,345,511
<p>The first thing to know is that the message you're seeing is from the Python interpreter, and has nothing to do with pyUnit. The -v in the message refers to "python -v".</p> <p>As to why you can't import site, and why running pyUnit with -v makes the error go away, I don't know. Do you have your own site.py?</p>
1
2010-02-26T23:25:35Z
[ "python", "unit-testing", "pyunit" ]
Accessing void pointers in Python (using SWIG or something else)
2,345,354
<p>I've been trying to use SWIG to wrap around a simple library that uses ioctl() to populate a structure like the following:</p> <pre><code>struct data { header* hdr; void* data; size_t len; }; </code></pre> <p><strong>data</strong> is a pointer to a buffer, <strong>len</strong> is the length of that buffer.</...
1
2010-02-26T22:45:44Z
2,346,012
<p>Since you say "or something else" in the Q's title -- if you choose to use <a href="http://docs.python.org/library/ctypes.html?highlight=ctypes#module-ctypes" rel="nofollow">ctypes</a>, you can represent a <code>void*</code> with <code>c_void_p</code> (one of ctypes' <a href="http://docs.python.org/library/ctypes.ht...
1
2010-02-27T02:28:31Z
[ "python", "pointers", "swig", "void" ]
Accessing void pointers in Python (using SWIG or something else)
2,345,354
<p>I've been trying to use SWIG to wrap around a simple library that uses ioctl() to populate a structure like the following:</p> <pre><code>struct data { header* hdr; void* data; size_t len; }; </code></pre> <p><strong>data</strong> is a pointer to a buffer, <strong>len</strong> is the length of that buffer.</...
1
2010-02-26T22:45:44Z
10,634,684
<p>swig provides a module named 'cdata.i'. You should include this in the interface definition file.</p> <p>Once you include this, it gives two functions cdata() and memmove(). Given a void * and the length of the binary data, cdata() converts it into a string type of the target language. memmove() is the reverse. giv...
1
2012-05-17T11:16:16Z
[ "python", "pointers", "swig", "void" ]
Why is post_save being raised twice during the save of a Django model?
2,345,400
<p>I am attaching a method to the post_save signal of my Django model. This way I can clear some cached items whenever the model is modified. </p> <p>The problem I am having is that the signal is being triggered twice when the model is saved. It doesn't necessarily hurt anything (the code will just gracefully error ou...
15
2010-02-26T22:55:25Z
2,345,948
<p>While looking for the root of this problem, you can use quick workaround to prevent registering signal twice:</p> <pre><code>signals.post_save.connect(my_handler, MyModel, dispatch_uid="path.to.this.module") </code></pre> <p><a href="http://code.djangoproject.com/wiki/Signals#Helppost_saveseemstobeemittedtwicefore...
7
2010-02-27T01:57:51Z
[ "python", "django", "django-models", "signals" ]
Why is post_save being raised twice during the save of a Django model?
2,345,400
<p>I am attaching a method to the post_save signal of my Django model. This way I can clear some cached items whenever the model is modified. </p> <p>The problem I am having is that the signal is being triggered twice when the model is saved. It doesn't necessarily hurt anything (the code will just gracefully error ou...
15
2010-02-26T22:55:25Z
2,345,962
<p>Here is the ticket about this issue: <a href="http://code.djangoproject.com/ticket/3951" rel="nofollow">Django's signal framework may register listeners more than once #3951</a>. It is now fixed in SVN version of Django.</p> <p>The problem is exactly as You said: Your module which registers signal, is loaded couple...
0
2010-02-27T02:04:35Z
[ "python", "django", "django-models", "signals" ]
Why is post_save being raised twice during the save of a Django model?
2,345,400
<p>I am attaching a method to the post_save signal of my Django model. This way I can clear some cached items whenever the model is modified. </p> <p>The problem I am having is that the signal is being triggered twice when the model is saved. It doesn't necessarily hurt anything (the code will just gracefully error ou...
15
2010-02-26T22:55:25Z
2,345,967
<p>Apparently, <a href="http://stackoverflow.com/questions/1801249/import-twice-when-run-test">Python is sensitive to the way you import modules</a>. In my case, it wasn't an issue with any of import code inside my blog application but an issue with the INSTALLED_APPS configuration, which I assume is used by Django to ...
12
2010-02-27T02:06:07Z
[ "python", "django", "django-models", "signals" ]
Numpy array memory issue
2,345,518
<p>I believe I am having a memory issue using numpy arrays. The following code is being run for hours on end:</p> <pre><code> new_data = npy.array([new_x, new_y1, new_y2, new_y3]) private.data = npy.row_stack([private.data, new_data]) </code></pre> <p>where new_x, new_y1, new_y2, new_y3 are floats.</p> <p>Aft...
5
2010-02-26T23:29:28Z
2,345,662
<p><strong>Update</strong>: I incorporated @EOL's excellent indexing suggestion into the answer.</p> <p>The problem might be the way <code>row_stack</code> grows the destination. You might be better off handling the reallocation yourself. The following code allocates a big empty array, fills it, and grows it as it f...
2
2010-02-27T00:12:55Z
[ "python", "arrays", "numpy" ]
Numpy array memory issue
2,345,518
<p>I believe I am having a memory issue using numpy arrays. The following code is being run for hours on end:</p> <pre><code> new_data = npy.array([new_x, new_y1, new_y2, new_y3]) private.data = npy.row_stack([private.data, new_data]) </code></pre> <p>where new_x, new_y1, new_y2, new_y3 are floats.</p> <p>Aft...
5
2010-02-26T23:29:28Z
2,352,857
<p>Use Python lists. Seriously, they grow far more efficiently. This is what they are designed for. They are remarkably efficient in this setting.</p> <p>If you need to create an array out of them at the end (or even occasionally in the midst of this computation), it will be far more efficient to accumulate in a list ...
3
2010-02-28T22:00:36Z
[ "python", "arrays", "numpy" ]
starting Python IDLE from command line to edit scripts
2,345,607
<p>I've tried many variations of this command: <code>idle.py -e filepath</code>, but it simply starts IDLE like normal, not opening any extra windows for editing, and not throwing any errors.</p> <p>So how can I do the equivalent of opening IDLE, file>open>filepath via the command line (or perhaps even a Python module...
5
2010-02-26T23:57:23Z
2,345,680
<p>Make a new text file, and put something like this in it:</p> <pre><code>C:\Python26\Lib\idlelib\idle.pyw "C:\file1.py" "C:\file2.py" </code></pre> <p>In your actual script, you'll replace "C:\file1.py" and "C:\file2.py" with your files' paths, save as a .bat, and then launch it. That should do what you want.</p>
6
2010-02-27T00:19:12Z
[ "python", "windows", "python-idle", "time-saving" ]
starting Python IDLE from command line to edit scripts
2,345,607
<p>I've tried many variations of this command: <code>idle.py -e filepath</code>, but it simply starts IDLE like normal, not opening any extra windows for editing, and not throwing any errors.</p> <p>So how can I do the equivalent of opening IDLE, file>open>filepath via the command line (or perhaps even a Python module...
5
2010-02-26T23:57:23Z
2,345,690
<p>you can just program in Python to edit your Python files. A simple example. say you want to search for a word and then replace it with something else.</p> <pre><code>import fileinput import os os.chdir( os.path.join("c:\\","path") ) for file in os.listdir("."): for line in fileinput.input(file,inplace=0): ...
0
2010-02-27T00:22:10Z
[ "python", "windows", "python-idle", "time-saving" ]
starting Python IDLE from command line to edit scripts
2,345,607
<p>I've tried many variations of this command: <code>idle.py -e filepath</code>, but it simply starts IDLE like normal, not opening any extra windows for editing, and not throwing any errors.</p> <p>So how can I do the equivalent of opening IDLE, file>open>filepath via the command line (or perhaps even a Python module...
5
2010-02-26T23:57:23Z
5,522,920
<p>Rarely the native os is useful. I created a 'win batch file, in the folder with my .py files:</p> <pre><code>start /MIN cmd /C c:\Python27\lib\idlelib\idle.py -e %1 %2 %3 %4 %5 %6 </code></pre> <p>This can open up to six files from cmd line in one shot. Just type the name of the batch file, followed by from zero t...
2
2011-04-02T11:39:54Z
[ "python", "windows", "python-idle", "time-saving" ]
starting Python IDLE from command line to edit scripts
2,345,607
<p>I've tried many variations of this command: <code>idle.py -e filepath</code>, but it simply starts IDLE like normal, not opening any extra windows for editing, and not throwing any errors.</p> <p>So how can I do the equivalent of opening IDLE, file>open>filepath via the command line (or perhaps even a Python module...
5
2010-02-26T23:57:23Z
13,481,033
<p>Please forgive me for bumping such an old thread, but I've been teaching myself linux and python with the help of the community, and was trying to figure out how to invoke IDLE2 and IDLE3 from the command line. I came across this post some of the solutions seemed a bit complicated for my application. Then it occur...
4
2012-11-20T19:53:51Z
[ "python", "windows", "python-idle", "time-saving" ]
starting Python IDLE from command line to edit scripts
2,345,607
<p>I've tried many variations of this command: <code>idle.py -e filepath</code>, but it simply starts IDLE like normal, not opening any extra windows for editing, and not throwing any errors.</p> <p>So how can I do the equivalent of opening IDLE, file>open>filepath via the command line (or perhaps even a Python module...
5
2010-02-26T23:57:23Z
24,127,604
<p>You need to do as stated in the main.py file of the idelib folder (C:\Python33\Lib\idlelib), at least on the python 3.3 version explains that:</p> <pre><code>IDLE main entry point Run IDLE as python -m idlelib </code></pre> <p>So with <code>python -m idlelib &lt;script_to_edit&gt;</code> you will be able to open ...
3
2014-06-09T19:35:38Z
[ "python", "windows", "python-idle", "time-saving" ]
starting Python IDLE from command line to edit scripts
2,345,607
<p>I've tried many variations of this command: <code>idle.py -e filepath</code>, but it simply starts IDLE like normal, not opening any extra windows for editing, and not throwing any errors.</p> <p>So how can I do the equivalent of opening IDLE, file>open>filepath via the command line (or perhaps even a Python module...
5
2010-02-26T23:57:23Z
29,289,580
<p>Just add IDLE's path to your <code>PATH</code> environment variable.</p> <p>For example I created an environment variable called <code>IDLE_PATH</code> and set the value to <code>C:\Python27\Lib\idlelib</code></p> <p>Then in my <code>PATH</code> variable I added <code>;%IDLE_PATH%;</code> and open a new cmd prompt...
0
2015-03-26T21:52:33Z
[ "python", "windows", "python-idle", "time-saving" ]
starting Python IDLE from command line to edit scripts
2,345,607
<p>I've tried many variations of this command: <code>idle.py -e filepath</code>, but it simply starts IDLE like normal, not opening any extra windows for editing, and not throwing any errors.</p> <p>So how can I do the equivalent of opening IDLE, file>open>filepath via the command line (or perhaps even a Python module...
5
2010-02-26T23:57:23Z
39,559,184
<p>first make sure you have location of idle in path<br> I am using "python3.5".So mine looks like this: <b><code>C:\Program Files\Python35\Lib\idlelib</code></b>.Yours may differ.<br> use this following command:<b><code>idle -r file_name.py</code></b> to run the file or just <b><code>idle file_name.py</code></b> to...
0
2016-09-18T15:11:42Z
[ "python", "windows", "python-idle", "time-saving" ]
wxPython: Threading GUI --> Using Custom Event Handler
2,345,608
<p>I am trying to learn how to run a thread off the main GUI app to do my serial port sending/receiving while keeping my GUI alive. My best Googling attempts have landed me at the wxpython wiki on: <a href="http://wiki.wxpython.org/LongRunningTasks" rel="nofollow">http://wiki.wxpython.org/LongRunningTasks</a> which pro...
1
2010-02-26T23:57:50Z
2,345,732
<p>That's the old style of defining custom events. See <a href="http://www.wxpython.org/migrationguide.php" rel="nofollow">the migration guide</a> for more information.</p> <p>Taken from the migration guide:</p> <blockquote> <p>If you create your own custom event types and EVT_* functions, and you want to be a...
3
2010-02-27T00:39:22Z
[ "python", "multithreading", "wxpython", "custom-events" ]
wxPython: Threading GUI --> Using Custom Event Handler
2,345,608
<p>I am trying to learn how to run a thread off the main GUI app to do my serial port sending/receiving while keeping my GUI alive. My best Googling attempts have landed me at the wxpython wiki on: <a href="http://wiki.wxpython.org/LongRunningTasks" rel="nofollow">http://wiki.wxpython.org/LongRunningTasks</a> which pro...
1
2010-02-26T23:57:50Z
2,346,858
<p>You can define events like this:</p> <pre><code>from wx.lib.newevent import NewEvent ResultEvent, EVT_RESULT = NewEvent() </code></pre> <p>You post the event like this:</p> <pre><code>wx.PostEvent(handler, ResultEvent(data=data)) </code></pre> <p>Bind it like this:</p> <pre><code>def OnResult(event): event...
2
2010-02-27T09:41:54Z
[ "python", "multithreading", "wxpython", "custom-events" ]
wxPython: Threading GUI --> Using Custom Event Handler
2,345,608
<p>I am trying to learn how to run a thread off the main GUI app to do my serial port sending/receiving while keeping my GUI alive. My best Googling attempts have landed me at the wxpython wiki on: <a href="http://wiki.wxpython.org/LongRunningTasks" rel="nofollow">http://wiki.wxpython.org/LongRunningTasks</a> which pro...
1
2010-02-26T23:57:50Z
2,359,229
<p>You may want to use Python threads and queues and not custom events. I have a wxPython program (<a href="http://openstv.org" rel="nofollow">OpenSTV</a>) that loads large files that caused the gui to freeze during the loading. To prevent the freezing, I dispatch a thread to load the file and use a queue to communic...
0
2010-03-01T21:33:30Z
[ "python", "multithreading", "wxpython", "custom-events" ]
using a key to rearrange string
2,345,628
<p>Using Python I want to <em>randomly</em> rearrange sections of a string based on a given key. I also want to restore the original string with the same key:</p> <pre><code>def rearrange(key, data): pass def restore(key, rearranged_data): pass </code></pre> <p>Efficiency is not important. Any ideas?</p> <p...
4
2010-02-27T00:03:19Z
2,345,659
<p>Use <code>random.shuffle</code> with the key as a seed:</p> <pre><code>import random def rearrange(key, data): random.seed(key) d = list(data) random.shuffle(d) return ''.join(d) def restore(key, rearranged_data): l = len(rearranged_data) random.seed(key) d = range(l) random.shuffl...
4
2010-02-27T00:11:32Z
[ "python", "algorithm", "string", "encryption" ]
using a key to rearrange string
2,345,628
<p>Using Python I want to <em>randomly</em> rearrange sections of a string based on a given key. I also want to restore the original string with the same key:</p> <pre><code>def rearrange(key, data): pass def restore(key, rearranged_data): pass </code></pre> <p>Efficiency is not important. Any ideas?</p> <p...
4
2010-02-27T00:03:19Z
2,345,709
<p>you can reinvent the wheel, but why not try an <a href="http://www.pycrypto.org/" rel="nofollow">encryption library</a> first, if possible.</p>
3
2010-02-27T00:29:23Z
[ "python", "algorithm", "string", "encryption" ]
using a key to rearrange string
2,345,628
<p>Using Python I want to <em>randomly</em> rearrange sections of a string based on a given key. I also want to restore the original string with the same key:</p> <pre><code>def rearrange(key, data): pass def restore(key, rearranged_data): pass </code></pre> <p>Efficiency is not important. Any ideas?</p> <p...
4
2010-02-27T00:03:19Z
2,345,716
<p>An implementation that reverses the shuffling with <code>sort()</code>:</p> <pre><code>import random def reorder_list(ls, key): random.seed(key) random.shuffle(ls) def reorder(s, key): data = list(s) reorder_list(data, key) return ''.join(data) def restore(s, key): indexes = range(len(s)) re...
1
2010-02-27T00:32:59Z
[ "python", "algorithm", "string", "encryption" ]
Does turning a list into a set, then back again, cause problems in Python?
2,345,862
<p>I'm turning a list into a set in Python, like so:</p> <pre><code>request.session['vote_set'] = set(request.session['vote_set']) </code></pre> <p>So I can easily do a <code>if x in set</code> lookup and eliminate duplicates. Then, when I'm done, I reconvert it:</p> <pre><code>request.session['vote_set'] = list(req...
5
2010-02-27T01:21:57Z
2,345,889
<p>You'll lose ordering, if that's important to you. </p>
1
2010-02-27T01:31:08Z
[ "python" ]
Does turning a list into a set, then back again, cause problems in Python?
2,345,862
<p>I'm turning a list into a set in Python, like so:</p> <pre><code>request.session['vote_set'] = set(request.session['vote_set']) </code></pre> <p>So I can easily do a <code>if x in set</code> lookup and eliminate duplicates. Then, when I'm done, I reconvert it:</p> <pre><code>request.session['vote_set'] = list(req...
5
2010-02-27T01:21:57Z
2,345,901
<p>You'll lose duplicates if you actually wanted them. If this is actually a list of "votes" as your naming suggests, you'd 'lose' some :)</p> <p>why not just:</p> <pre><code>if x in set(request.session['vote_set']) </code></pre> <p>if you're worried.</p> <p>Although I have to wonder if that would be slower than ju...
5
2010-02-27T01:37:08Z
[ "python" ]
Does turning a list into a set, then back again, cause problems in Python?
2,345,862
<p>I'm turning a list into a set in Python, like so:</p> <pre><code>request.session['vote_set'] = set(request.session['vote_set']) </code></pre> <p>So I can easily do a <code>if x in set</code> lookup and eliminate duplicates. Then, when I'm done, I reconvert it:</p> <pre><code>request.session['vote_set'] = list(req...
5
2010-02-27T01:21:57Z
2,345,907
<p>This is how you remove duplicates AND maintain the order (if you care): <a href="http://stackoverflow.com/questions/1801459/algorithm-how-to-delete-duplicate-elements-in-a-list-efficiently">http://stackoverflow.com/questions/1801459/algorithm-how-to-delete-duplicate-elements-in-a-list-efficiently</a></p> <p>The oth...
0
2010-02-27T01:38:31Z
[ "python" ]
Exclude object's field from pickling in python
2,345,944
<p>I would like to avoid pickling of certain fields in an instance of a class. Currently, before pickling I just set those fields to None, but I wonder whether there's more elegant solution?</p>
5
2010-02-27T01:56:55Z
2,345,953
<p>There is an example <a href="http://docs.python.org/library/pickle.html#example" rel="nofollow">here</a> which solves your problem with <code>__getstate__</code> and <code>__setstate__</code>.</p>
3
2010-02-27T02:00:01Z
[ "python", "pickle" ]
Exclude object's field from pickling in python
2,345,944
<p>I would like to avoid pickling of certain fields in an instance of a class. Currently, before pickling I just set those fields to None, but I wonder whether there's more elegant solution?</p>
5
2010-02-27T01:56:55Z
2,345,985
<p>One way to handle instance attributes that are not picklable objects is to use the special methods available for modifying a class instance's state: <em>getstate</em>() and <em>setstate</em>(). Here is an example</p> <pre><code>class Foo(object): def __init__(self, value, filename): self.value = value ...
14
2010-02-27T02:14:46Z
[ "python", "pickle" ]
How can you draw a bezier curve given four points with wxPython?
2,346,054
<p>It appears to me that the <a href="http://www.wxpython.org/docs/api/wx.DC-class.html" rel="nofollow">DC</a>'s only support for curves of any sort is with splines. Are there any libraries that add bezier functionality, or is there a way to convert a bezier curve into a spline?</p>
0
2010-02-27T02:53:20Z
2,346,147
<p>Given 4 control points, the formula for the associated cubic Bezier curve is <a href="http://en.wikipedia.org/wiki/B%C3%A9zier_curve" rel="nofollow">not hard to compute</a>. Once you calculate a set of points on the curve, you could use <a href="http://www.wxpython.org/docs/api/wx.DC-class.html#DrawLines" rel="nofol...
2
2010-02-27T03:48:48Z
[ "python", "wxpython", "bezier-curve", "spline" ]
How can you draw a bezier curve given four points with wxPython?
2,346,054
<p>It appears to me that the <a href="http://www.wxpython.org/docs/api/wx.DC-class.html" rel="nofollow">DC</a>'s only support for curves of any sort is with splines. Are there any libraries that add bezier functionality, or is there a way to convert a bezier curve into a spline?</p>
0
2010-02-27T02:53:20Z
2,346,393
<p>After a little googling, I think I'll go with <a href="http://www.wxpython.org/docs/api/wx.GraphicsContext-class.html" rel="nofollow">wx.GraphicsContext</a>, which supports <a href="http://www.wxpython.org/docs/api/wx.GraphicsPath-class.html" rel="nofollow">wx.GraphicsPath</a>. It appears to have exactly what I need...
1
2010-02-27T05:54:28Z
[ "python", "wxpython", "bezier-curve", "spline" ]
Execute sqlite3 "dot" commands from Python or register collation in command line utility
2,346,074
<p>My sqlite3 database contains a "collate" column-constraint. I've placed it in the schema for the table, to prevent accidentally neglecting to use the necessary collation. However this means when running <code>sqlite3</code> from the command line, and not from my Python code, the collation referenced in the schema is...
14
2010-02-27T03:05:15Z
2,346,075
<p>The dot commands are only available to the <code>sqlite3</code> executable. You will have to replace them with the equivalent combination of Python code and DB-API calls in order to mimic their behavior.</p>
7
2010-02-27T03:07:53Z
[ "python", "sqlite", "collation", "dot-command" ]
Execute sqlite3 "dot" commands from Python or register collation in command line utility
2,346,074
<p>My sqlite3 database contains a "collate" column-constraint. I've placed it in the schema for the table, to prevent accidentally neglecting to use the necessary collation. However this means when running <code>sqlite3</code> from the command line, and not from my Python code, the collation referenced in the schema is...
14
2010-02-27T03:05:15Z
2,776,816
<p>You can load new collating sequences and functions using <a href="http://sqlite.org/lang_corefunc.html#load_extension">load_extension()</a> built-in SQLite function or <a href="http://sqlite.org/sqlite.html">.load</a> command in command line shell for SQLite. Obviously, extensions shold be written in C.</p> <p>And ...
5
2010-05-05T21:12:28Z
[ "python", "sqlite", "collation", "dot-command" ]
Execute sqlite3 "dot" commands from Python or register collation in command line utility
2,346,074
<p>My sqlite3 database contains a "collate" column-constraint. I've placed it in the schema for the table, to prevent accidentally neglecting to use the necessary collation. However this means when running <code>sqlite3</code> from the command line, and not from my Python code, the collation referenced in the schema is...
14
2010-02-27T03:05:15Z
2,777,902
<p>The <code>.import</code> command in the sqlite shell is a builtin command. It's processed by the shell program, not the SQL engine, so you can't execute it like an SQL statement.</p> <p>Reading code for SQLite's <a href="http://www.sqlite.org/src/finfo?name=src/shell.c">shell.c</a>, it seems that <code>.import</co...
6
2010-05-06T01:38:28Z
[ "python", "sqlite", "collation", "dot-command" ]
In python, I need to store one element of the source of an html page as a string. How can I do this?
2,346,154
<p>So far I have managed to write some code that should print the source of the page. The problem is, it doesn't. I tried it with another web site, and it printed it out fine, so I used wget on the page "http://www.whitepages.com/carrier_lookup?carrier=other&amp;number_0=2165138899&amp;response=1" which should download...
1
2010-02-27T03:51:18Z
2,346,162
<p>For an explanation of what a 403 result from HTTP means, and how to deal with it, see <a href="http://www.checkupdown.com/status/E403.html" rel="nofollow">here</a>.</p> <p>I have no idea what "I need to save as a different string the carrier that the search found" can possibly mean -- I can't even parse it as an En...
1
2010-02-27T03:55:43Z
[ "python", "html", "parsing" ]
PyGame Set Mouse Cursor from Bitmap
2,346,205
<p>I'm making an image editor using pyGame and I was wondering if it was possible to change the mouse cursor to something more suitable (for instance a circle or rectangle) for brushes. PyGame has a really weird way of doing it that I'm not sure would work very well. Is there a way I can write to a bitmap and then use ...
8
2010-02-27T04:11:53Z
2,346,233
<p>You can load cursors in PyGame with <a href="http://www.pygame.org/docs/ref/cursors.html#pygame.cursors.load_xbm" rel="nofollow">pygame.cursors.load_xbm</a> -- that's black and white cursors only, of course, a well-documented limitation of PyGame, per <a href="http://www.pygame.org/docs/ref/cursors.html" rel="nofoll...
4
2010-02-27T04:25:38Z
[ "python", "pygame", "mouse-cursor" ]
PyGame Set Mouse Cursor from Bitmap
2,346,205
<p>I'm making an image editor using pyGame and I was wondering if it was possible to change the mouse cursor to something more suitable (for instance a circle or rectangle) for brushes. PyGame has a really weird way of doing it that I'm not sure would work very well. Is there a way I can write to a bitmap and then use ...
8
2010-02-27T04:11:53Z
2,354,944
<p>Another option is to simply <a href="http://www.pygame.org/docs/ref/mouse.html#pygame.mouse.set_visible">hide</a> the cursor, <a href="http://www.pygame.org/docs/ref/image.html#pygame.image.load">load</a> any arbitrary bitmap that you like and <a href="http://www.pygame.org/docs/ref/surface.html#Surface.blit">draw</...
11
2010-03-01T09:53:29Z
[ "python", "pygame", "mouse-cursor" ]
How can I remove part of an string on the re.search result?
2,346,215
<pre><code>text = urllib.urlopen('www.text.com').read() frase = re.search("your text here(.*)", text).group() </code></pre> <p>With these code, I get the result as "your text here mister"...</p> <p>How can I remove the your text here from the result, staying only with the "mister" part?</p>
1
2010-02-27T04:16:16Z
2,346,220
<p>Specify the number of the group (= thing between parenthesis in the regex) you want to receive in the call to <a href="http://docs.python.org/library/re.html#re.MatchObject.group" rel="nofollow"><code>group()</code></a>:</p> <pre><code>frase = re.search(...).group(1) </code></pre>
4
2010-02-27T04:18:34Z
[ "python" ]
How can I remove part of an string on the re.search result?
2,346,215
<pre><code>text = urllib.urlopen('www.text.com').read() frase = re.search("your text here(.*)", text).group() </code></pre> <p>With these code, I get the result as "your text here mister"...</p> <p>How can I remove the your text here from the result, staying only with the "mister" part?</p>
1
2010-02-27T04:16:16Z
2,346,237
<p>don't need regex</p> <pre><code>text = urllib.urlopen('www.text.com').read() print ''.join( text.split("your text here")[1:] ) </code></pre>
1
2010-02-27T04:27:40Z
[ "python" ]
Trying to write to binary plist format from Python (w/PyObjC) to be fetch and read in by Cocoa Touch
2,346,463
<p>I'm trying to serve a property list of search results to my iPhone app. The server is a prototype, written in Python.</p> <p>First I found Python's built-in plistlib, which is awesome. I want to give search-as-you-type a shot, so I need it to be as small as possible, and xml was too big. The binary plist format see...
3
2010-02-27T06:34:47Z
2,346,507
<p>I believe the correct function name is</p> <pre><code>NSPropertyListSerialization.dataWithPropertyList_format_options_error_ </code></pre> <p>because of the ending <code>:</code>. </p> <p>(BTW, if the object is always an array or dictionary, <code>-writeToFile:atomically:</code> will write the plist (as XML forma...
4
2010-02-27T06:58:08Z
[ "python", "cocoa-touch", "search", "pyobjc" ]
Trying to write to binary plist format from Python (w/PyObjC) to be fetch and read in by Cocoa Touch
2,346,463
<p>I'm trying to serve a property list of search results to my iPhone app. The server is a prototype, written in Python.</p> <p>First I found Python's built-in plistlib, which is awesome. I want to give search-as-you-type a shot, so I need it to be as small as possible, and xml was too big. The binary plist format see...
3
2010-02-27T06:34:47Z
2,433,890
<p>As KennyTM said, you're missing the trailing underscore in the method name. In PyObjC you need to take the Objective-C selector name (<code>dataWithPropertyList:format:options:error:</code>) and replace all of the colons with underscores (don't forget the last colon, too!). That gives you <code>dataWithPropertyLis...
2
2010-03-12T15:53:01Z
[ "python", "cocoa-touch", "search", "pyobjc" ]
Regular expression to ignore a certain number of character repetitions
2,346,917
<p>I'm trying to write a parser that uses two characters as token boundaries, but I can't figure out the regular expression that will allow me to ignore them when I'm regex-escaping the whole string.</p> <p>Given a string like:</p> <pre><code>This | is || token || some ||| text </code></pre> <p>I would like to end u...
2
2010-02-27T10:01:53Z
2,346,986
<p>No need regex. You are using Python after all. :)</p> <pre><code>&gt;&gt;&gt; s="This | is || token || some ||| text" &gt;&gt;&gt; items=s.split() &gt;&gt;&gt; items ['This', '|', 'is', '||', 'token', '||', 'some', '|||', 'text'] &gt;&gt;&gt; for n,i in enumerate(items): ... if "|" in i and i.count("|")!=2: ......
2
2010-02-27T10:27:30Z
[ "python", "regex", "regex-negation" ]
Regular expression to ignore a certain number of character repetitions
2,346,917
<p>I'm trying to write a parser that uses two characters as token boundaries, but I can't figure out the regular expression that will allow me to ignore them when I'm regex-escaping the whole string.</p> <p>Given a string like:</p> <pre><code>This | is || token || some ||| text </code></pre> <p>I would like to end u...
2
2010-02-27T10:01:53Z
2,347,079
<p>Here's a way to do it with regular expressions in perl, if anyone's interested. I used two separate regular expressions, one for the single match and one for the 3 or more match. I'm sure it's possible to combine them, but regular expressions are already difficult enough to read without adding needless complexity.</...
0
2010-02-27T11:05:28Z
[ "python", "regex", "regex-negation" ]
Regular expression to ignore a certain number of character repetitions
2,346,917
<p>I'm trying to write a parser that uses two characters as token boundaries, but I can't figure out the regular expression that will allow me to ignore them when I'm regex-escaping the whole string.</p> <p>Given a string like:</p> <pre><code>This | is || token || some ||| text </code></pre> <p>I would like to end u...
2
2010-02-27T10:01:53Z
2,347,305
<p>I don't see why you would need to regex-escape the tokens, but why not split up the string first and <em>then</em> escape them? This regex splits on two pipes that aren't preceded or followed by more pipes:</p> <pre><code>re.split('(?&lt;!\|)\|\|(?!\|)', 'This | is || token || some ||| text') &gt;&gt;&gt; ['This |...
1
2010-02-27T12:31:43Z
[ "python", "regex", "regex-negation" ]
Passing multiple arguments from IronPython to .NET method
2,347,003
<p>I have a class in .NET (C#):</p> <pre><code>public class MyHelper { public object exec( string script, params object[] arguments ) { // execute script with passed arguments in some external enviroment } } </code></pre> <p>I'm using IronPython runtime in my code to run python scripts, which should i...
4
2010-02-27T10:35:22Z
2,347,805
<p>According to <a href="http://blogs.msdn.com/csharpfaq/archive/2004/05/13/131493.aspx" rel="nofollow">this FAQ</a>, the <code>MyHelper.exec</code> you've defined should accept both an <code>array</code> as the second argument, or any number of <code>objects</code> following the first <code>string</code>.</p> <p>If y...
1
2010-02-27T15:18:45Z
[ "c#", "python", "interop", "ironpython" ]
Passing multiple arguments from IronPython to .NET method
2,347,003
<p>I have a class in .NET (C#):</p> <pre><code>public class MyHelper { public object exec( string script, params object[] arguments ) { // execute script with passed arguments in some external enviroment } } </code></pre> <p>I'm using IronPython runtime in my code to run python scripts, which should i...
4
2010-02-27T10:35:22Z
2,349,755
<p>The problem here is that "exec" is a keyword in Python so you can't use that as your function name. You could use "exec_" or execute or something like that instead. Alternately you could write:</p> <p>getattr(helper, 'exec')(...)</p>
3
2010-02-28T01:52:24Z
[ "c#", "python", "interop", "ironpython" ]
How to run a python script without specifying the file extension (cross platform solution)?
2,347,042
<p>Let's say that we have a Python script <code>do.py</code> and we want to be able to call it without extension, like <code>do</code> or <code>./do</code>. </p> <p>If we rename the file from <code>do.py</code> to <code>do</code> and assure we have a valid shebang line it will work for all platforms but Windows. On Wi...
8
2010-02-27T10:49:54Z
2,347,059
<p>you can always call your script with the Python interpreter. You get the same consistency in *nix, when you use the interpreter.</p> <p>Windows</p> <pre><code>c:\&gt; python c:\path\to\myscript </code></pre> <p>*nix</p> <pre><code>$ python /path/to/myscript </code></pre> <p>If its not what you want, then i am ...
0
2010-02-27T10:56:14Z
[ "python", "batch-file", "shell", "cmd", "wrapper" ]
How to run a python script without specifying the file extension (cross platform solution)?
2,347,042
<p>Let's say that we have a Python script <code>do.py</code> and we want to be able to call it without extension, like <code>do</code> or <code>./do</code>. </p> <p>If we rename the file from <code>do.py</code> to <code>do</code> and assure we have a valid shebang line it will work for all platforms but Windows. On Wi...
8
2010-02-27T10:49:54Z
2,347,084
<p>You can use distutils to install scripts into the Python installation (the easy_install tool is installed like that, for example).</p> <p>For Windows, you can use <a href="http://sourceforge.net/projects/py2exe/" rel="nofollow">py2exe</a> to create a script that can be executed without file extension. On Linux you ...
1
2010-02-27T11:06:32Z
[ "python", "batch-file", "shell", "cmd", "wrapper" ]
How to run a python script without specifying the file extension (cross platform solution)?
2,347,042
<p>Let's say that we have a Python script <code>do.py</code> and we want to be able to call it without extension, like <code>do</code> or <code>./do</code>. </p> <p>If we rename the file from <code>do.py</code> to <code>do</code> and assure we have a valid shebang line it will work for all platforms but Windows. On Wi...
8
2010-02-27T10:49:54Z
2,347,825
<p>So far I came up with this solution that seams to work. Create a file <code>yourname.py</code> with this content:</p> <pre><code>import os, sys filename = os.path.splitext(os.path.basename(sys.argv[0]))[0] if not os.path.exists(filename): # filename does not exists, we will emulate cmd behaviour sys.stderr....
2
2010-02-27T15:24:13Z
[ "python", "batch-file", "shell", "cmd", "wrapper" ]
How to run a python script without specifying the file extension (cross platform solution)?
2,347,042
<p>Let's say that we have a Python script <code>do.py</code> and we want to be able to call it without extension, like <code>do</code> or <code>./do</code>. </p> <p>If we rename the file from <code>do.py</code> to <code>do</code> and assure we have a valid shebang line it will work for all platforms but Windows. On Wi...
8
2010-02-27T10:49:54Z
2,348,017
<p>On windows i added the '.py' extension to the 'PATHEXT' environment variable and that works for me - if the .py file is stored in an directory that is part of the 'PATH' environment variable.</p> <pre><code>C:\&gt;echo %PATHEXT% .COM;.EXE;.BAT;.CMD;.PY;.JS;.JSE </code></pre>
5
2010-02-27T16:22:02Z
[ "python", "batch-file", "shell", "cmd", "wrapper" ]
How to run a python script without specifying the file extension (cross platform solution)?
2,347,042
<p>Let's say that we have a Python script <code>do.py</code> and we want to be able to call it without extension, like <code>do</code> or <code>./do</code>. </p> <p>If we rename the file from <code>do.py</code> to <code>do</code> and assure we have a valid shebang line it will work for all platforms but Windows. On Wi...
8
2010-02-27T10:49:54Z
3,592,208
<p>Write your main Python module with a <code>.py</code> extension. Set up <code>PATHEXT</code> correctly, and it will run on Windows without having to type the extension.</p> <p>On Unix, write a second Python program that simply imports the first, using she-bang syntax. No extension on this file - it's a shell scri...
4
2010-08-28T19:55:23Z
[ "python", "batch-file", "shell", "cmd", "wrapper" ]
How to run a python script without specifying the file extension (cross platform solution)?
2,347,042
<p>Let's say that we have a Python script <code>do.py</code> and we want to be able to call it without extension, like <code>do</code> or <code>./do</code>. </p> <p>If we rename the file from <code>do.py</code> to <code>do</code> and assure we have a valid shebang line it will work for all platforms but Windows. On Wi...
8
2010-02-27T10:49:54Z
22,009,832
<p><a href="http://stackoverflow.com/a/3592208/724176">Jason's answer</a> is clearer and simpler, but a generic version gets the module name from the filename:</p> <pre><code>#!/usr/bin/env python import importlib, os, sys importlib.import_module(os.path.basename(sys.argv[0])) </code></pre> <p>Having said that, I pre...
0
2014-02-25T09:28:37Z
[ "python", "batch-file", "shell", "cmd", "wrapper" ]
Is it OK to do 302s for architecture in my web applciation?
2,347,074
<p>For example, in my index(request):</p> <pre><code>def index(request): if logged_in: return HttpResponseRedirect("/home_profile") else: return HttpResponseRedirect("/login") </code></pre> <p>This way, when the user hits my home page...he is redirected appropriately. Is this a good architectu...
3
2010-02-27T11:03:56Z
2,347,165
<p>Redirection is ok(302 shouldn't cause any caching problem, as 302's are temporary), but why you need to have redirection in both if and else. Better way is to redirect to login page if not logged-in, view should otherwise return the response, instead of unnecessarily redirecting e.g.</p> <pre><code>def home(request...
3
2010-02-27T11:39:45Z
[ "python", "django", "redirect" ]
Why does += behave unexpectedly on lists?
2,347,265
<p>The <code>+=</code> operator in python seems to be operating unexpectedly on lists. Can anyone tell me what is going on here?</p> <pre><code>class foo: bar = [] def __init__(self,x): self.bar += [x] class foo2: bar = [] def __init__(self,x): self.bar = self.bar + [x] f =...
61
2010-02-27T12:15:59Z
2,347,272
<p>For the general case, see <a href="http://stackoverflow.com/a/2347423/1709587">Scott Griffith's answer</a>. When dealing with lists like you are, though, the <code>+=</code> operator is a shorthand for <code>someListObject.extend(iterableObject)</code>. See the <a href="http://docs.python.org/tutorial/datastructures...
75
2010-02-27T12:19:23Z
[ "python", "augmented-assignment" ]
Why does += behave unexpectedly on lists?
2,347,265
<p>The <code>+=</code> operator in python seems to be operating unexpectedly on lists. Can anyone tell me what is going on here?</p> <pre><code>class foo: bar = [] def __init__(self,x): self.bar += [x] class foo2: bar = [] def __init__(self,x): self.bar = self.bar + [x] f =...
61
2010-02-27T12:15:59Z
2,347,278
<p>The problem here is, <code>bar</code> is defined as a class attribute, not an instance variable.</p> <p>In <code>foo</code>, the class attribute is modified in the <code>init</code> method, that's why all instances are affected.</p> <p>In <code>foo2</code>, an instance variable is defined using the (empty) class a...
17
2010-02-27T12:23:17Z
[ "python", "augmented-assignment" ]
Why does += behave unexpectedly on lists?
2,347,265
<p>The <code>+=</code> operator in python seems to be operating unexpectedly on lists. Can anyone tell me what is going on here?</p> <pre><code>class foo: bar = [] def __init__(self,x): self.bar += [x] class foo2: bar = [] def __init__(self,x): self.bar = self.bar + [x] f =...
61
2010-02-27T12:15:59Z
2,347,423
<p>The general answer is that <code>+=</code> tries to call the <code>__iadd__</code> special method, and if that isn't available it tries to use <code>__add__</code> instead. So the issue is with the difference between these special methods.</p> <p>The <code>__iadd__</code> special method is for an in-place addition,...
65
2010-02-27T13:14:11Z
[ "python", "augmented-assignment" ]
Why does += behave unexpectedly on lists?
2,347,265
<p>The <code>+=</code> operator in python seems to be operating unexpectedly on lists. Can anyone tell me what is going on here?</p> <pre><code>class foo: bar = [] def __init__(self,x): self.bar += [x] class foo2: bar = [] def __init__(self,x): self.bar = self.bar + [x] f =...
61
2010-02-27T12:15:59Z
9,679,688
<pre><code>&gt;&gt;&gt; elements=[[1],[2],[3]] &gt;&gt;&gt; subset=[] &gt;&gt;&gt; subset+=elements[0:1] &gt;&gt;&gt; subset [[1]] &gt;&gt;&gt; elements [[1], [2], [3]] &gt;&gt;&gt; subset[0][0]='change' &gt;&gt;&gt; elements [['change'], [2], [3]] &gt;&gt;&gt; a=[1,2,3,4] &gt;&gt;&gt; b=a &gt;&gt;&gt; a+=[5] &gt;&gt;...
1
2012-03-13T07:08:09Z
[ "python", "augmented-assignment" ]
Why does += behave unexpectedly on lists?
2,347,265
<p>The <code>+=</code> operator in python seems to be operating unexpectedly on lists. Can anyone tell me what is going on here?</p> <pre><code>class foo: bar = [] def __init__(self,x): self.bar += [x] class foo2: bar = [] def __init__(self,x): self.bar = self.bar + [x] f =...
61
2010-02-27T12:15:59Z
13,331,298
<p>Although much time has passed and many correct things were said, there is no answer which bundles both effects.</p> <p>You have 2 effects:</p> <ol> <li>a "special", maybe unnoticed behaviour of lists with <code>+=</code> (as stated by <a href="http://stackoverflow.com/a/2347423/296974">Scott Griffiths</a>)</li> <l...
4
2012-11-11T12:56:02Z
[ "python", "augmented-assignment" ]
Why does += behave unexpectedly on lists?
2,347,265
<p>The <code>+=</code> operator in python seems to be operating unexpectedly on lists. Can anyone tell me what is going on here?</p> <pre><code>class foo: bar = [] def __init__(self,x): self.bar += [x] class foo2: bar = [] def __init__(self,x): self.bar = self.bar + [x] f =...
61
2010-02-27T12:15:59Z
17,066,710
<p>The other answers would seem to pretty much have it covered, though it seems worth quoting and referring to the <a href="http://www.python.org/dev/peps/pep-0203/" rel="nofollow">Augmented Assignments PEP 203</a>:</p> <blockquote> <p>They <em>[the augmented assignment operators]</em> implement the same operator ...
2
2013-06-12T13:23:05Z
[ "python", "augmented-assignment" ]
Why does += behave unexpectedly on lists?
2,347,265
<p>The <code>+=</code> operator in python seems to be operating unexpectedly on lists. Can anyone tell me what is going on here?</p> <pre><code>class foo: bar = [] def __init__(self,x): self.bar += [x] class foo2: bar = [] def __init__(self,x): self.bar = self.bar + [x] f =...
61
2010-02-27T12:15:59Z
19,589,775
<p>There are two things involved here:</p> <pre><code>1. class attributes and instance attributes 2. difference between the operators + and += for lists </code></pre> <p><code>+</code> operator calls the <code>__add__</code> method on a list. It takes all the elements from its operands and makes a new list containing...
0
2013-10-25T12:22:43Z
[ "python", "augmented-assignment" ]
Parameters not getting passed properly
2,347,266
<p>Here's an excerpt of my code:</p> <pre><code>def listFrom(here): print "[DBG] here: " + here def book(here, there, amount): print "[DBG] here: " + here + "; there: " + there + "; amount: " + str(amount) # Code that takes input and stores it into the string input # Yes, I know this is dangerous, but it's ...
0
2010-02-27T12:17:23Z
2,347,354
<p>This code works without problems in Python 2.6 on Linux/x86-32:</p> <pre><code>&gt;&gt;&gt; def listFrom(here): ... print "[DBG] here: " + here ... &gt;&gt;&gt; def book(here, there, amount): ... print "[DBG] here: " + here + "; there: " + there + "; amount: " + str(amount) ... &gt;&gt;&gt; book('LON', 'M...
0
2010-02-27T12:50:17Z
[ "python", "eval" ]
Python: passing a function with parameters as parameter
2,347,388
<pre><code>def lite(a,b,c): #... def big(func): # func = callable() #... #main big(lite(1,2,3)) </code></pre> <p>how to do this?<br> in what way to pass function with parameters to another function?</p>
11
2010-02-27T13:04:31Z
2,347,401
<p>Why not do:</p> <pre><code>big(lite, (1, 2, 3)) </code></pre> <p>?</p> <p>Then you can do:</p> <pre><code>def big(func, args): func(*args) </code></pre>
20
2010-02-27T13:08:17Z
[ "python", "function" ]
Python: passing a function with parameters as parameter
2,347,388
<pre><code>def lite(a,b,c): #... def big(func): # func = callable() #... #main big(lite(1,2,3)) </code></pre> <p>how to do this?<br> in what way to pass function with parameters to another function?</p>
11
2010-02-27T13:04:31Z
2,347,404
<pre><code>import functools #main big(functools.partial(lite, 1,2,3)) </code></pre>
2
2010-02-27T13:08:32Z
[ "python", "function" ]
Python: passing a function with parameters as parameter
2,347,388
<pre><code>def lite(a,b,c): #... def big(func): # func = callable() #... #main big(lite(1,2,3)) </code></pre> <p>how to do this?<br> in what way to pass function with parameters to another function?</p>
11
2010-02-27T13:04:31Z
2,347,415
<p>Not this way, you're passing to big the return value of lite() function.</p> <p>You should do something like:</p> <pre><code>def lite(a, b, c): return a + b + c def big(func, arg): print func(arg[0], arg[1], arg[2]) big(lite, (1, 2, 3)) </code></pre>
0
2010-02-27T13:12:20Z
[ "python", "function" ]
Python: passing a function with parameters as parameter
2,347,388
<pre><code>def lite(a,b,c): #... def big(func): # func = callable() #... #main big(lite(1,2,3)) </code></pre> <p>how to do this?<br> in what way to pass function with parameters to another function?</p>
11
2010-02-27T13:04:31Z
2,347,420
<p>Similar problem is usually solved in two ways:</p> <ol> <li>With lambda… but then the passed function will expect one argument, so big() needs to be changed</li> <li>With named functions calling the original functions with arguments. Please note, that such function can be declared inside other function and the ar...
3
2010-02-27T13:13:59Z
[ "python", "function" ]
How do I temporarily disable AppStats in my Google App Engine application?
2,347,567
<p>I recently configured my app to use the new AppStats feature of GAE. However, while debugging it, the extremely verbose logging from AppStats is annoying &amp; I'd like to disable it while I'm debugging and then turn it back on later. Surely there is a single line I can add to or modify in a config file that will le...
2
2010-02-27T14:00:13Z
2,353,251
<p>See the <a href="http://code.google.com/appengine/docs/python/tools/appstats.html#Configuring_Appstats" rel="nofollow">configuring appstats</a> docs: configuration is performed by creating your own <code>appengine_config.py</code> in your app's root directory. Best documentation of what you can do in that config fi...
4
2010-03-01T00:15:14Z
[ "python", "google-app-engine" ]
How do I temporarily disable AppStats in my Google App Engine application?
2,347,567
<p>I recently configured my app to use the new AppStats feature of GAE. However, while debugging it, the extremely verbose logging from AppStats is annoying &amp; I'd like to disable it while I'm debugging and then turn it back on later. Surely there is a single line I can add to or modify in a config file that will le...
2
2010-02-27T14:00:13Z
6,384,502
<p>I know this is old, but how about this:</p> <p>Add a config.py where you define the DEBUG flag (or if you have it defined elsewhere, even better). And then:</p> <pre><code>from config import DEBUG def webapp_add_wsgi_middleware(app): if not DEBUG: from google.appengine.ext.appstats import recor...
0
2011-06-17T10:34:55Z
[ "python", "google-app-engine" ]
Coping dictionary within a dictionary(Nested dictionary)
2,347,854
<p>I am having a dictionary like as <code>dict1 = { 0 : 0, 1 : 1, 2 : { 0: 0, 1 : 1}}</code> (which is also having a dictionary as value). I want to keep store these value same for some modification checking purpose. So now I am copy this dictionary content into another dictionary as <code>dict2 = dict1.copy()</code>....
3
2010-02-27T15:31:58Z
2,347,871
<p>Use <a href="http://docs.python.org/library/copy.html" rel="nofollow"><code>copy.deepcopy</code></a> to perform a deep copy.</p>
11
2010-02-27T15:35:05Z
[ "python", "dictionary" ]
What's wrong with this string normilizer Python snippet?
2,347,953
<p>It seems that every time I think I mastered encoding, I find something new to puzzle me :-)</p> <p>I'm trying to get rid of French accents from an UTF-8 string:</p> <pre><code>&gt;&gt;&gt; import unicodedata &gt;&gt;&gt; s = u"éèêàùçÇ" &gt;&gt;&gt; print(unicodedata.normalize('NFKD', s).encode('ascii','ig...
1
2010-02-27T15:59:20Z
2,348,158
<p>Afters further tests, it works if you use Python 3 or Python 2.6 interpreters instead of iPython.</p> <p>Maybe a wrong user setting or a bug.</p>
1
2010-02-27T16:56:48Z
[ "python", "string", "encoding", "normalize" ]
What's wrong with this string normilizer Python snippet?
2,347,953
<p>It seems that every time I think I mastered encoding, I find something new to puzzle me :-)</p> <p>I'm trying to get rid of French accents from an UTF-8 string:</p> <pre><code>&gt;&gt;&gt; import unicodedata &gt;&gt;&gt; s = u"éèêàùçÇ" &gt;&gt;&gt; print(unicodedata.normalize('NFKD', s).encode('ascii','ig...
1
2010-02-27T15:59:20Z
2,348,683
<p><code>python</code> works as it should:</p> <pre><code>$ python Python 2.6.4 (r264:75706, Dec 7 2009, 18:43:55) [GCC 4.4.1] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; s = u"éèêàùçÇ" &gt;&gt;&gt; s u'\xe9\xe8\xea\xe0\xf9\xe7\xc7' &gt;&gt;&gt; ord(s[0]) 233 ...
0
2010-02-27T19:42:47Z
[ "python", "string", "encoding", "normalize" ]
Dynamic Event Conditions
2,347,958
<p>Consider that we've a class named Foo that fires "ready" event when it's ready.</p> <pre><code>from observer import SubjectSet class Foo: def __init__(self): self.events = SubjectSet() self.events.create('ready') def do_sth(self): self.events.fire('ready') </code></pre> <p>As you see, do_sth meth...
1
2010-02-27T16:00:56Z
2,348,047
<p>I think you do not actually define very exactly what is the problem you try to solve. However, there's nothing wrong with the solution. It's clearly asynchronous and event-driven. But I think in general the solution should also arrow for error conditions, i.e. what happens if task1 or task2 fails due to any reason--...
1
2010-02-27T16:31:43Z
[ "python", "algorithm", "events", "asynchronous" ]
webcam motion tracking with Python
2,348,151
<p>Is there a simple way to track the motions of a single entity in a webcam feed? For example, I imagine a "hello world" app with an index finger used as mouse pointer.</p> <p>I realize there's still a lot of basic research in this area, so it might be too early to expect an easy to use, generic abstraction.</p> <p>...
1
2010-02-27T16:55:16Z
2,348,233
<p>You might want to take a look at <a href="http://opencv.willowgarage.com/wiki/PythonInterface" rel="nofollow">http://opencv.willowgarage.com/wiki/PythonInterface</a>. I'm not sure how hard it would be to do arbitrary motion tracking, but it was fairly simple to implement face tracking.</p>
4
2010-02-27T17:19:19Z
[ "python", "motion-detection" ]
GraphicsPath doesn't always refresh itself
2,348,183
<p>The simple curve in this application only appears when it's dragged off the screen, or the window is resized. When the application just starts up it doesn't appear, and when the window is maximized or minimized it also disappears. However, all of these times, "Path Drawn" is printed, so all of the painting functions...
1
2010-02-27T17:02:02Z
2,350,673
<p>Comment out the <code>self.SetDoubleBuffered(True)</code> part and it will work, because due to bug <a href="http://trac.wxwidgets.org/ticket/11138" rel="nofollow">http://trac.wxwidgets.org/ticket/11138</a> window isn't refreshed correctly if SetDoubleBuffered and GraphicsContext are used together.</p> <p>If you MU...
2
2010-02-28T09:47:02Z
[ "python", "wxpython", "graphicscontext", "graphicspath" ]
Share data between mod_python processes
2,348,202
<p>I'm running mod_python under Apache. If I've understood correctly, each Apache process runs its own Python interpreter.</p> <p>What would be the best way to share a tiny amount of data across all the processes? I'm talking about just a few hundred bytes here, making something database based completely overkill.</p>...
1
2010-02-27T17:08:50Z
2,348,270
<p>Put it in <a href="http://semanchuk.com/philip/sysv_ipc/" rel="nofollow">shared memory</a>.</p>
1
2010-02-27T17:28:22Z
[ "python", "apache", "mod-python", "share" ]
Share data between mod_python processes
2,348,202
<p>I'm running mod_python under Apache. If I've understood correctly, each Apache process runs its own Python interpreter.</p> <p>What would be the best way to share a tiny amount of data across all the processes? I'm talking about just a few hundred bytes here, making something database based completely overkill.</p>...
1
2010-02-27T17:08:50Z
2,348,297
<p>The quickest way is to use file IO. One process writes the file and the other reads it. You can use the <a href="http://docs.python.org/library/mmap.html#module-mmap" rel="nofollow"><code>mmap</code></a> module to make this a little more seamless. One interesting alternative that I haven't tried (yet) is to use s...
1
2010-02-27T17:35:06Z
[ "python", "apache", "mod-python", "share" ]
what is the pysvn command equvilent to "svn info file:///path/to/svn/repo"?
2,348,282
<p>I'm looking for a good python library to manipulate subversion repositories. I'm trying out <a href="http://pysvn.tigris.org/" rel="nofollow">PySvn</a>, but finding that it can't handle something like</p> <pre><code>pysvn.Client().info("/path/to/svn/repo") </code></pre> <p>because it's not a working copy. Anyone k...
1
2010-02-27T17:30:14Z
2,348,914
<p>Do you try info2 instead of info? Documentation says it can access URL of repository.</p>
5
2010-02-27T20:48:39Z
[ "python", "svn" ]
How to write a pager for Python iterators?
2,348,317
<p>I'm looking for a way to "page through" a Python iterator. That is, I would like to wrap a given iterator <b>iter</b> and <b>page_size</b> with another iterator that would would return the items from iter as a series of "pages". Each page would itself be an iterator with up to <b>page_size</b> iterations. </p> <p...
9
2010-02-27T17:41:26Z
2,348,326
<p>Look at <code>grouper()</code> in the <a href="http://docs.python.org/library/itertools.html#recipes"><code>itertools</code> recipes</a>.</p>
6
2010-02-27T17:43:37Z
[ "python", "iterator", "itertools" ]
How to write a pager for Python iterators?
2,348,317
<p>I'm looking for a way to "page through" a Python iterator. That is, I would like to wrap a given iterator <b>iter</b> and <b>page_size</b> with another iterator that would would return the items from iter as a series of "pages". Each page would itself be an iterator with up to <b>page_size</b> iterations. </p> <p...
9
2010-02-27T17:41:26Z
2,349,266
<p>Based on the pointer to the itertools recipe for grouper(), I came up with the following adaption of grouper() to mimic Pager. I wanted to filter out any None results and wanted to return an iterator rather than a tuple (though I suspect that there might be little advantage in doing this conversion)</p> <pre><code...
0
2010-02-27T22:55:00Z
[ "python", "iterator", "itertools" ]
How to write a pager for Python iterators?
2,348,317
<p>I'm looking for a way to "page through" a Python iterator. That is, I would like to wrap a given iterator <b>iter</b> and <b>page_size</b> with another iterator that would would return the items from iter as a series of "pages". Each page would itself be an iterator with up to <b>page_size</b> iterations. </p> <p...
9
2010-02-27T17:41:26Z
2,349,497
<p>I'd do it like this:</p> <pre><code>def pager(iterable, page_size): args = [iter(iterable)] * page_size fillvalue = object() for group in izip_longest(fillvalue=fillvalue, *args): yield (elem for elem in group if elem is not fillvalue) </code></pre> <p>That way, <code>None</code> can be a legit...
2
2010-02-28T00:15:53Z
[ "python", "iterator", "itertools" ]
How to write a pager for Python iterators?
2,348,317
<p>I'm looking for a way to "page through" a Python iterator. That is, I would like to wrap a given iterator <b>iter</b> and <b>page_size</b> with another iterator that would would return the items from iter as a series of "pages". Each page would itself be an iterator with up to <b>page_size</b> iterations. </p> <p...
9
2010-02-27T17:41:26Z
2,350,904
<p>Why aren't you using this?</p> <pre><code>def grouper( page_size, iterable ): page= [] for item in iterable: page.append( item ) if len(page) == page_size: yield page page= [] yield page </code></pre> <p>"Each page would itself be an iterator with up to page_size...
4
2010-02-28T11:34:13Z
[ "python", "iterator", "itertools" ]
How to write a pager for Python iterators?
2,348,317
<p>I'm looking for a way to "page through" a Python iterator. That is, I would like to wrap a given iterator <b>iter</b> and <b>page_size</b> with another iterator that would would return the items from iter as a series of "pages". Each page would itself be an iterator with up to <b>page_size</b> iterations. </p> <p...
9
2010-02-27T17:41:26Z
21,906,506
<pre><code>def group_by(iterable, size): """Group an iterable into lists that don't exceed the size given. &gt;&gt;&gt; group_by([1,2,3,4,5], 2) [[1, 2], [3, 4], [5]] """ sublist = [] for index, item in enumerate(iterable): if index &gt; 0 and index % size == 0: yield subl...
0
2014-02-20T11:32:46Z
[ "python", "iterator", "itertools" ]
Scraping for a "preview" of a webpage - Python
2,348,401
<p>I'm indexing a list of links, these links update quite often so I'm automating thumbnails for the sites.</p> <p>For most sites it's easy, as I just grab the biggest image on the page hoping it describes the content.</p> <p>But other times there are videos as main content of the page.</p> <hr> <p>Does somebody ha...
5
2010-02-27T18:09:00Z
2,348,433
<p><a href="http://code.google.com/p/wkhtmltopdf/" rel="nofollow">wkhtmltopdf</a> uses an embedded copy of the WebKit render engine (used in Safari, Chrome etc.) to save a webpage to PDF, including all images (no Flash video though I guess). That could be a starting point for a much more accurate thumbnail.</p>
3
2010-02-27T18:18:41Z
[ "python", "html", "django", "screen-scraping" ]
Scraping for a "preview" of a webpage - Python
2,348,401
<p>I'm indexing a list of links, these links update quite often so I'm automating thumbnails for the sites.</p> <p>For most sites it's easy, as I just grab the biggest image on the page hoping it describes the content.</p> <p>But other times there are videos as main content of the page.</p> <hr> <p>Does somebody ha...
5
2010-02-27T18:09:00Z
2,348,483
<p>There exists (free and paid) services that do exactly what you need. I use <a href="http://www.shrinktheweb.com" rel="nofollow">shrink the web</a>: </p>
3
2010-02-27T18:41:48Z
[ "python", "html", "django", "screen-scraping" ]
Python PIL and StringIO
2,348,443
<p>I'm trying to download images from URLs and pass them to PIL.</p> <p>I would like to use as few resources as possible, especially RAM. What would the best way of dealing with this? I've had suggestions to use cStringIO.</p>
2
2010-02-27T18:22:15Z
2,348,473
<p>Unfortunately file-likes from network functions such as <code>urllib2.urlopen()</code> don't support all the necessary methods, so you'll need to read the data into a <code>StringIO</code> or <code>cStringIO</code> in order to be able to pass them to <code>Image.open()</code>.</p>
4
2010-02-27T18:36:21Z
[ "python", "django", "python-imaging-library" ]
Why doesn't import prevent NameError in a python script run with execfile()?
2,348,630
<p>I looked at a number of existing questions about NameError exceptions when scripts are run with exec statements or execfile() in Python, but haven't found a good explanation yet of the following behavior. </p> <p>I want to make a simple game that creates script objects at runtime with execfile(). Below are 4 module...
4
2010-02-27T19:25:44Z
2,348,684
<p>From the <a href="http://docs.python.org/library/functions.html#execfile" rel="nofollow">Python documentation</a> for execfile:</p> <p><em>execfile(filename[, globals[, locals]])</em></p> <p><em>If the locals dictionary is omitted it defaults to the globals dictionary. If both dictionaries are omitted, the express...
3
2010-02-27T19:42:57Z
[ "python", "import", "exec", "nameerror", "execfile" ]
Why doesn't import prevent NameError in a python script run with execfile()?
2,348,630
<p>I looked at a number of existing questions about NameError exceptions when scripts are run with exec statements or execfile() in Python, but haven't found a good explanation yet of the following behavior. </p> <p>I want to make a simple game that creates script objects at runtime with execfile(). Below are 4 module...
4
2010-02-27T19:25:44Z
2,351,667
<p>The reason the 'import gamelib' in script.py has no effect is because it imports into the local scope of game.py main(), because this is the scope in which the import is executed. This scope is not a visible scope for ScriptObject.action() when it executes. </p> <p>Adding debug code to print out the changes in the ...
0
2010-02-28T16:21:22Z
[ "python", "import", "exec", "nameerror", "execfile" ]
Mocking imported modules in Python
2,348,712
<p>I'm trying to implement unit tests for function that uses imported external objects.</p> <p>For example <strong>helpers.py</strong> is:</p> <pre><code>import os import pylons def some_func(arg): ... var1 = os.path.exist(...) var2 = os.path.getmtime(...) var3 = pylons.request.environ['HTTP_HOST'] .....
4
2010-02-27T19:49:24Z
2,381,802
<p>Use voidspace's mocking library and it's patching/wrapping ability.</p> <p><a href="http://www.voidspace.org.uk/python/mock/patch.html" rel="nofollow">http://www.voidspace.org.uk/python/mock/patch.html</a></p>
2
2010-03-04T18:39:09Z
[ "python", "unit-testing", "mocking" ]
Mocking imported modules in Python
2,348,712
<p>I'm trying to implement unit tests for function that uses imported external objects.</p> <p>For example <strong>helpers.py</strong> is:</p> <pre><code>import os import pylons def some_func(arg): ... var1 = os.path.exist(...) var2 = os.path.getmtime(...) var3 = pylons.request.environ['HTTP_HOST'] .....
4
2010-02-27T19:49:24Z
2,430,483
<p>Well, in minimock there is an easier paradigm for this than what you are using above:</p> <pre><code>&gt;&gt;&gt; from minimock import mock &gt;&gt;&gt; import os.path &gt;&gt;&gt; mock('os.path.isfile', returns=True) </code></pre> <p>See <a href="http://pypi.python.org/pypi/MiniMock#creating-mocks" rel="nofollow"...
1
2010-03-12T04:17:45Z
[ "python", "unit-testing", "mocking" ]
Display value in Charfield for foreign key in django on error
2,348,829
<p>Let's say I've got a model and it has a foreign key to another one.</p> <pre><code>class ModelA(models.Model): field = models.CharField(max_length=100) class ModelB(models.Model): model_a = models.ForeignKey(ModelA) </code></pre> <p>Than I've got this form:</p> <pre><code>class FormB(models.ModelForm): ...
0
2010-02-27T20:24:47Z
2,348,888
<p>I can think of two options:</p> <ol> <li><p>Make <code>model_a</code> field on <code>ModelB</code> hidden with <code>editable=false</code>, and add a <code>CharField</code> to <code>ModelB</code> to store the text the user entered. Then show this field in the form, but use its value to populate <code>model_a</code>...
0
2010-02-27T20:39:02Z
[ "python", "django", "forms", "foreign-keys" ]