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
displaying a large amount of formated text in Python
2,279,063
<p>I have two large identical-sized files. One is ASCII plain text, and the other is a colour-coded overlay, one byte per text character in the corresponding file.</p> <p>These files can be large - upto 2.5 MB; possibly substantially more, perhaps over 100MB later.</p> <p>I want to display the text is a scrollable t...
6
2010-02-17T07:46:29Z
2,289,232
<p>How about using a scrollable canvas instead, and only ever drawing the text/heatmap that is exposed by the user? That should give you a quick initial draw and a quick redraw when things move around, regardless of the size of the file.</p> <p>If you want more speed and more control, then you would need some sort of ...
3
2010-02-18T14:23:45Z
[ "python", "performance", "richtextbox", "tkinter" ]
How can I add consistent whitespace to existing HTML using Python?
2,279,404
<p>I just started working on a website that is full of pages with all their HTML on a single line, which is a real pain to read and work with. I'm looking for a tool (preferably a Python library) that will take HTML input and return the same HTML unchanged, except for adding linebreaks and appropriate indentation. (A...
3
2010-02-17T09:08:18Z
2,279,453
<p>If the html is indeed well formed xml, you can use DOM parser.</p> <pre><code>from xml.dom.minidom import parse, parseString #if you have html string in a variable html = parseString(theHtmlString) #or parse the html file html = parse(htmlFileName) print html.toprettyxml() </code></pre> <p>The <a href="http://d...
1
2010-02-17T09:16:42Z
[ "python", "html", "whitespace", "html5lib" ]
How can I add consistent whitespace to existing HTML using Python?
2,279,404
<p>I just started working on a website that is full of pages with all their HTML on a single line, which is a real pain to read and work with. I'm looking for a tool (preferably a Python library) that will take HTML input and return the same HTML unchanged, except for adding linebreaks and appropriate indentation. (A...
3
2010-02-17T09:08:18Z
2,280,800
<h3>Algorithm</h3> <ol> <li>Parse html into some representation</li> <li>Serialize the representation back to html</li> </ol> <h3>Example <a href="http://stackoverflow.com/questions/459552/beautifulsoup-3-1-parser-breaks-far-too-easily/638597#638597">html5lib parser with BeautifulSoup tree builder</a></h3> <pre><cod...
2
2010-02-17T13:05:33Z
[ "python", "html", "whitespace", "html5lib" ]
How can I add consistent whitespace to existing HTML using Python?
2,279,404
<p>I just started working on a website that is full of pages with all their HTML on a single line, which is a real pain to read and work with. I'm looking for a tool (preferably a Python library) that will take HTML input and return the same HTML unchanged, except for adding linebreaks and appropriate indentation. (A...
3
2010-02-17T09:08:18Z
2,284,971
<p>I chose J.F. Sebastian's answer because I think it's the simplest and thus the best, but I'm adding another solution for anyone who doesn't want to install Beautiful Soup. (Also, the Beautiful Soup tree builder is going to be <a href="http://code.google.com/p/html5lib/issues/detail?id=120&amp;can=1&amp;q=beautifuls...
2
2010-02-17T22:39:05Z
[ "python", "html", "whitespace", "html5lib" ]
Python function composition
2,279,423
<p>I've tried to implement function composition with nice syntax and here is what I've got:</p> <pre><code>from functools import partial class _compfunc(partial): def __lshift__(self, y): f = lambda *args, **kwargs: self.func(y(*args, **kwargs)) return _compfunc(f) def __rshift__(self, y): ...
9
2010-02-17T09:11:50Z
2,279,486
<p><code>append</code> does in-place addition, as Ignacio Vazquez-Abrams said (well, implied) -- so, while you could fix that by just adding a <code>return</code> to your function, it would have the side-effect of changing the argument it was passed, too:</p> <pre><code>@composable def f4(a): a.append(0) retur...
9
2010-02-17T09:22:02Z
[ "python", "function-composition" ]
Python reference external module in Netbeans
2,279,628
<p>I'm working with a Netbeans for Python development, I have a number of projects (which have a number of modules). What I basically want to know is, how do I import one of these modules into a new project? I have tried editing the python path in netbeans, but to no avail. Here's my setup:</p> <pre> Netbeans projects...
3
2010-02-17T09:52:27Z
2,688,688
<p>Hadji, you may want to discard Netbeans' default structures for Python development.</p> <p>First of all, Python code file (<code>.py</code>) is a module. A package contains a number of modules.</p> <p>What you should do is structure your files like the following:</p> <pre><code>Netbeans projects =================...
2
2010-04-22T06:38:37Z
[ "python", "netbeans", "module", "projects" ]
Bash alias to Python script -- is it possible?
2,279,749
<p>The particular alias I'm looking to "class up" into a Python script happens to be one that makes use of the cUrl -o (output to file) option. I suppose I could as easily turn it into a BASH function, but someone advised me that I could avoid the quirks and pitfalls of the different versions and "flavors" of BASH by t...
2
2010-02-17T10:11:46Z
2,279,883
<p>The <a href="http://www.gnu.org/software/bash/manual/bashref.html#Aliases" rel="nofollow">relevant section</a> from the Bash manual states:</p> <blockquote> <p>Aliases allow a string to be substituted for a word when it is used as the first word of a simple command.</p> </blockquote> <p>So, there should be n...
7
2010-02-17T10:33:17Z
[ "python", "bash", "curl", "scripting", "multiplatform" ]
Bash alias to Python script -- is it possible?
2,279,749
<p>The particular alias I'm looking to "class up" into a Python script happens to be one that makes use of the cUrl -o (output to file) option. I suppose I could as easily turn it into a BASH function, but someone advised me that I could avoid the quirks and pitfalls of the different versions and "flavors" of BASH by t...
2
2010-02-17T10:11:46Z
2,301,977
<p>I thought Pycurl might be the answer. Ahh Daniel Sternberg and his innocent presumptions that everybody knows what he does. I asked on the list whether or not pycurl had a "curl -o" analogue, and then asked 'If so: How would one go about coding it/them in a Python script?' His reply was the following:<br><br> <i>"cu...
0
2010-02-20T11:15:51Z
[ "python", "bash", "curl", "scripting", "multiplatform" ]
Unit testing functions that access files
2,279,835
<p>I have two functions—one that builds the path to a set of files and another that reads the files. Below are the two functions:</p> <pre><code>def pass_file_name(self): self.log_files= [] file_name = self.path+"\\access_"+self.appliacation+".log" if os.path.isfile(file_name): self.log_files.app...
8
2010-02-17T10:25:55Z
2,279,848
<p>Bind the <code>open</code> name in the module to a function that mocks the file opening.</p>
1
2010-02-17T10:28:14Z
[ "python", "unit-testing" ]
Unit testing functions that access files
2,279,835
<p>I have two functions—one that builds the path to a set of files and another that reads the files. Below are the two functions:</p> <pre><code>def pass_file_name(self): self.log_files= [] file_name = self.path+"\\access_"+self.appliacation+".log" if os.path.isfile(file_name): self.log_files.app...
8
2010-02-17T10:25:55Z
2,279,900
<p>Personally, I'd build a test harness that set up the required files before testing those two functions. </p> <p>For each test case (where you expect the file to be present - remember to test failure cases too!), write some known logs into the appropriately named files; then call the functions under test and check t...
2
2010-02-17T10:35:27Z
[ "python", "unit-testing" ]
Unit testing functions that access files
2,279,835
<p>I have two functions—one that builds the path to a set of files and another that reads the files. Below are the two functions:</p> <pre><code>def pass_file_name(self): self.log_files= [] file_name = self.path+"\\access_"+self.appliacation+".log" if os.path.isfile(file_name): self.log_files.app...
8
2010-02-17T10:25:55Z
2,279,931
<p>You have two <em>units</em> here:</p> <ul> <li>One that generate file paths</li> <li>Second that reads them</li> </ul> <p>Thus there should be two unit-test-cases (i.e. classes with tests). First would test only file paths generation. Second would test reading from predefined set of files you prepared in special s...
7
2010-02-17T10:41:03Z
[ "python", "unit-testing" ]
Unit testing functions that access files
2,279,835
<p>I have two functions—one that builds the path to a set of files and another that reads the files. Below are the two functions:</p> <pre><code>def pass_file_name(self): self.log_files= [] file_name = self.path+"\\access_"+self.appliacation+".log" if os.path.isfile(file_name): self.log_files.app...
8
2010-02-17T10:25:55Z
2,280,255
<p>I'm no expert but I'll give it a go. First a bit of refactoring: make them functional (remove all class stuff), remove unneeded things. This should make it much easier to test. You can always make the class call these functions if you really want it in a class. </p> <pre><code>def pass_file_name(base_filename, exis...
2
2010-02-17T11:43:12Z
[ "python", "unit-testing" ]
django test client trouble
2,279,917
<p>I've got a problem... we're writing project using django, and i'm trying to use django.test.client with nose test-framework for tests.</p> <p>Our code is like this:</p> <pre><code>from simplejson import loads from urlparse import urljoin from django.test.client import Client TEST_URL = "http://smakly.localhost:9...
2
2010-02-17T10:37:41Z
3,241,895
<p>Probably want django-nose if you want to use nose.</p> <p><a href="http://github.com/jbalogh/django-nose" rel="nofollow">http://github.com/jbalogh/django-nose</a></p> <p>I would recommend using the TestCase class</p> <p><a href="http://docs.djangoproject.com/en/dev/topics/testing/" rel="nofollow">http://docs.djan...
0
2010-07-13T21:59:38Z
[ "python", "django" ]
django test client trouble
2,279,917
<p>I've got a problem... we're writing project using django, and i'm trying to use django.test.client with nose test-framework for tests.</p> <p>Our code is like this:</p> <pre><code>from simplejson import loads from urlparse import urljoin from django.test.client import Client TEST_URL = "http://smakly.localhost:9...
2
2010-02-17T10:37:41Z
5,962,933
<p>Shameless self-promotion: exactly for those reasons I made test library that enables you to test application with urllib2.</p> <p>Docs are there: <a href="http://readthedocs.org/docs/django-sane-testing/en/latest/" rel="nofollow">http://readthedocs.org/docs/django-sane-testing/en/latest/</a></p> <p>Example of what...
0
2011-05-11T10:42:34Z
[ "python", "django" ]
Discovering referers to SQLAlchemy object
2,279,919
<p>I have a lot of model classes with ralations between them with a CRUD interface to edit. The problem is that some objects can't be deleted since there are other objects refering to them. Sometimes I can setup ON DELETE rule to handle this case, but in most cases I don't want automatic deletion of related objects til...
8
2010-02-17T10:37:59Z
2,279,998
<p>In general, there's no way to "discover" <em>all</em> of the references in a relational database.</p> <p>In some databases, they may use declarative referential integrity in the form of explicit Foreign Key or Check constraints.</p> <p>But there's no requirement to do this. It can be incomplete or inconsistent.</...
1
2010-02-17T10:53:37Z
[ "python", "orm", "sqlalchemy" ]
Discovering referers to SQLAlchemy object
2,279,919
<p>I have a lot of model classes with ralations between them with a CRUD interface to edit. The problem is that some objects can't be deleted since there are other objects refering to them. Sometimes I can setup ON DELETE rule to handle this case, but in most cases I don't want automatic deletion of related objects til...
8
2010-02-17T10:37:59Z
2,280,124
<p>For each model class, you can easily see if all its one-to-many relations are empty simply by asking for the list in each case and seeing how many entries it contains. (There is probably a more efficient way implemented in terms of COUNT, too.) If there are any foreign keys relating to the object, and you have your ...
0
2010-02-17T11:20:12Z
[ "python", "orm", "sqlalchemy" ]
Discovering referers to SQLAlchemy object
2,279,919
<p>I have a lot of model classes with ralations between them with a CRUD interface to edit. The problem is that some objects can't be deleted since there are other objects refering to them. Sometimes I can setup ON DELETE rule to handle this case, but in most cases I don't want automatic deletion of related objects til...
8
2010-02-17T10:37:59Z
2,280,671
<p><strong>SQL:</strong> I have to absolutely disagree with S.Lott' <a href="http://stackoverflow.com/questions/2279919/discovering-referers-to-sqlalchemy-object/2279998#2279998">answer</a>. I am not aware of out-of-the-box solution, but it is <strong>definitely possible</strong> to discover all the tables that have Fo...
6
2010-02-17T12:50:24Z
[ "python", "orm", "sqlalchemy" ]
Formatting data from a python array
2,280,190
<p>I'm learning python for the first time. I have an aim which is to take data from an API and output it as xml.</p> <p>The output is stored in an array ("projectData"), here is an example of the output:</p> <pre><code>[{'code': 'demo', 'created_at': datetime.datetime(2008, 6, 11, 7, 35, 19, tzinfo=&lt;api.LocalTime...
0
2010-02-17T11:30:44Z
2,280,219
<p>Consider using something like <a href="http://genshi.edgewall.org/" rel="nofollow"><code>genshi</code></a> or <a href="http://docs.python.org/library/xml.etree.elementtree.html" rel="nofollow"><code>etree</code></a> instead of building the XML by hand.</p>
2
2010-02-17T11:37:30Z
[ "python" ]
Formatting data from a python array
2,280,190
<p>I'm learning python for the first time. I have an aim which is to take data from an API and output it as xml.</p> <p>The output is stored in an array ("projectData"), here is an example of the output:</p> <pre><code>[{'code': 'demo', 'created_at': datetime.datetime(2008, 6, 11, 7, 35, 19, tzinfo=&lt;api.LocalTime...
0
2010-02-17T11:30:44Z
2,280,323
<p>Consider using some kind of template tool (even <code>string.Template</code>) instead of lots of string manipulation.</p> <p>For example, a generic dictionary-to-tag is pretty simple with the silly little built-in Template class.</p> <pre><code>import string tag= string.Template( "&lt;$tag&gt;$value&lt;/$tag&gt;" ...
0
2010-02-17T11:54:58Z
[ "python" ]
Formatting data from a python array
2,280,190
<p>I'm learning python for the first time. I have an aim which is to take data from an API and output it as xml.</p> <p>The output is stored in an array ("projectData"), here is an example of the output:</p> <pre><code>[{'code': 'demo', 'created_at': datetime.datetime(2008, 6, 11, 7, 35, 19, tzinfo=&lt;api.LocalTime...
0
2010-02-17T11:30:44Z
2,280,456
<p>Here's an example using <code>lxml.etree</code>, incomplete.. and probably a bit naive. Really you should define a schema and make sure your output is consistent with it.</p> <p><em>Edit, said it was incomplete, added None type and assumed a created_by is like an updated_by when populated</em></p> <pre><code>impor...
2
2010-02-17T12:18:56Z
[ "python" ]
Shortest way of creating an object with arbitrary attributes in Python?
2,280,334
<p>Hey, I just started wondering about this as I came upon a code that expected an object with a certain set of attributes (but with no specification of what type this object should be).</p> <p>One solution would be to create a new class that has the attributes the code expects, but as I call other code that also need...
14
2010-02-17T11:56:18Z
2,280,351
<p>Use <code>collections.namedtuple</code>.</p> <p>It works well.</p> <pre><code>from collections import namedtuple Data = namedtuple( 'Data', [ 'do_good_stuff', 'do_bad_stuff' ] ) options = Data( True, False ) </code></pre>
14
2010-02-17T11:58:34Z
[ "python" ]
Shortest way of creating an object with arbitrary attributes in Python?
2,280,334
<p>Hey, I just started wondering about this as I came upon a code that expected an object with a certain set of attributes (but with no specification of what type this object should be).</p> <p>One solution would be to create a new class that has the attributes the code expects, but as I call other code that also need...
14
2010-02-17T11:56:18Z
2,280,458
<p>If I understand your question correctly, you need records. Python classes may be used this way, which is what you do. </p> <p>I believe the most pythonic way of dealing with "records" is simply... <strong>dictionaries</strong>! A class is a sort of dictionary on steroids.</p> <p>Your class example <code>data</code...
0
2010-02-17T12:19:20Z
[ "python" ]
Shortest way of creating an object with arbitrary attributes in Python?
2,280,334
<p>Hey, I just started wondering about this as I came upon a code that expected an object with a certain set of attributes (but with no specification of what type this object should be).</p> <p>One solution would be to create a new class that has the attributes the code expects, but as I call other code that also need...
14
2010-02-17T11:56:18Z
2,280,537
<p>This is the shortest way I know</p> <pre><code>&gt;&gt;&gt; obj = type("myobj",(object,),dict(foo=1,bar=2)) &gt;&gt;&gt; obj.foo 1 &gt;&gt;&gt; obj.bar 2 &gt;&gt;&gt; </code></pre> <p>using dict instead of {} insures your attribute names are valid</p> <pre><code>&gt;&gt;&gt; obj = type("myobj",(object,),{"foo-at...
6
2010-02-17T12:30:37Z
[ "python" ]
Shortest way of creating an object with arbitrary attributes in Python?
2,280,334
<p>Hey, I just started wondering about this as I came upon a code that expected an object with a certain set of attributes (but with no specification of what type this object should be).</p> <p>One solution would be to create a new class that has the attributes the code expects, but as I call other code that also need...
14
2010-02-17T11:56:18Z
2,281,697
<p>You might be interested in the "Struct", which is part of the IPython package. It does what you want to do, with lots of useful methods.</p> <p><a href="http://ipython.org/ipython-doc/rel-0.13/api/generated/IPython.utils.ipstruct.html" rel="nofollow">http://ipython.org/ipython-doc/rel-0.13/api/generated/IPython.uti...
0
2010-02-17T15:01:02Z
[ "python" ]
Shortest way of creating an object with arbitrary attributes in Python?
2,280,334
<p>Hey, I just started wondering about this as I came upon a code that expected an object with a certain set of attributes (but with no specification of what type this object should be).</p> <p>One solution would be to create a new class that has the attributes the code expects, but as I call other code that also need...
14
2010-02-17T11:56:18Z
2,282,942
<p>This is typically something you would use a dict for, not making a class at all.</p>
-1
2010-02-17T17:31:17Z
[ "python" ]
Shortest way of creating an object with arbitrary attributes in Python?
2,280,334
<p>Hey, I just started wondering about this as I came upon a code that expected an object with a certain set of attributes (but with no specification of what type this object should be).</p> <p>One solution would be to create a new class that has the attributes the code expects, but as I call other code that also need...
14
2010-02-17T11:56:18Z
2,283,725
<p>This works in 2.5, 2.6, and 3.1:</p> <pre><code>class Struct(object): pass something = Struct() something.awesome = abs result = something.awesome(-42) </code></pre> <p>EDIT: I thought maybe giving the source would help out as well. <a href="http://docs.python.org/tutorial/classes.html#odds-and-ends">http://...
8
2010-02-17T19:22:45Z
[ "python" ]
Shortest way of creating an object with arbitrary attributes in Python?
2,280,334
<p>Hey, I just started wondering about this as I came upon a code that expected an object with a certain set of attributes (but with no specification of what type this object should be).</p> <p>One solution would be to create a new class that has the attributes the code expects, but as I call other code that also need...
14
2010-02-17T11:56:18Z
2,284,238
<p>The original code can be streamlined a little by using <code>__dict__</code>:</p> <pre><code>In [1]: class data: ...: def __init__(self, **kwargs): ...: self.__dict__.update(kwargs) ...: In [2]: d = data(foo=1, bar=2) In [3]: d.foo Out[3]: 1 In [4]: d.bar Out[4]: 2 </code></pre>
17
2010-02-17T20:42:58Z
[ "python" ]
Shortest way of creating an object with arbitrary attributes in Python?
2,280,334
<p>Hey, I just started wondering about this as I came upon a code that expected an object with a certain set of attributes (but with no specification of what type this object should be).</p> <p>One solution would be to create a new class that has the attributes the code expects, but as I call other code that also need...
14
2010-02-17T11:56:18Z
12,692,127
<p>Use a combination between lambda and type build-in, I think is the smallest way to do that:</p> <pre><code>obj = lambda **kwargs: type('obj', (object,), kwargs)() options = obj(do_good_stuff=True, do_bad_stuff=False) print options.do_good_stuff print options.do_bad_stuff </code></pre>
4
2012-10-02T14:21:07Z
[ "python" ]
Shortest way of creating an object with arbitrary attributes in Python?
2,280,334
<p>Hey, I just started wondering about this as I came upon a code that expected an object with a certain set of attributes (but with no specification of what type this object should be).</p> <p>One solution would be to create a new class that has the attributes the code expects, but as I call other code that also need...
14
2010-02-17T11:56:18Z
19,016,603
<p>If you don't need to pass values in the constructor, you can do this:</p> <pre><code>class data: pass data.foo = 1 data.bar = 2 </code></pre> <p>You use the class static member variables to hold your data.</p>
2
2013-09-25T23:03:04Z
[ "python" ]
Shortest way of creating an object with arbitrary attributes in Python?
2,280,334
<p>Hey, I just started wondering about this as I came upon a code that expected an object with a certain set of attributes (but with no specification of what type this object should be).</p> <p>One solution would be to create a new class that has the attributes the code expects, but as I call other code that also need...
14
2010-02-17T11:56:18Z
24,448,351
<p><code>type('', (), {})()</code> will create an object that can have arbitrary attributes.</p> <p>Example:</p> <pre><code>obj = type('', (), {})() obj.hello = "hello" obj.world = "world" print obj.hello, obj.world #will print "hello world" </code></pre> <p><code>type()</code> with three arguments creates a new typ...
5
2014-06-27T09:25:54Z
[ "python" ]
Shortest way of creating an object with arbitrary attributes in Python?
2,280,334
<p>Hey, I just started wondering about this as I came upon a code that expected an object with a certain set of attributes (but with no specification of what type this object should be).</p> <p>One solution would be to create a new class that has the attributes the code expects, but as I call other code that also need...
14
2010-02-17T11:56:18Z
34,378,560
<p>A function is an object. So you could assign attributes to a function. Or make one. This is the simplest way in terms of lines of code, I think.</p> <pre><code>def hello(): pass hello.chook = 123 </code></pre> <p>but the easiest &amp; most elegant way (but python >3.3) is to use Standard Libary's simpleName...
0
2015-12-20T06:33:33Z
[ "python" ]
How to start using Beaker in Django
2,280,603
<p>Question: Could people show or point me toward a complete example or tutorial to start using Beaker in Django?</p> <p>Information: Since I've read about problems in database connection with django ORM <a href="http://adam.gomaa.us/blog/2007/aug/26/the-django-orm-problem/" rel="nofollow">here</a> I've decided to re...
0
2010-02-17T12:39:39Z
16,757,470
<p>This question is old so I'm not sure if this is still needed, but here is one link: <a href="http://seeknuance.com/2010/09/16/multiple-cache-backends-in-django/" rel="nofollow">http://seeknuance.com/2010/09/16/multiple-cache-backends-in-django/</a></p>
0
2013-05-26T08:28:12Z
[ "python", "django", "beaker" ]
Python imports with different directory structures
2,280,761
<p>I'm working on a <a href="http://cdsware.cern.ch/invenio/" rel="nofollow">project</a> where all the code in the source tree is separated into module directories, e.g.:</p> <pre><code>modules/check/lib/check.py modules/edit/lib/edit.py </code></pre> <p>During installation, the Python files are put in the same direc...
3
2010-02-17T13:00:37Z
2,280,783
<p>Why don't you install symlinks underneath <code>prog_name</code> on your dev machine?</p>
0
2010-02-17T13:04:01Z
[ "python", "import", "directory-structure" ]
Python imports with different directory structures
2,280,761
<p>I'm working on a <a href="http://cdsware.cern.ch/invenio/" rel="nofollow">project</a> where all the code in the source tree is separated into module directories, e.g.:</p> <pre><code>modules/check/lib/check.py modules/edit/lib/edit.py </code></pre> <p>During installation, the Python files are put in the same direc...
3
2010-02-17T13:00:37Z
2,280,910
<p>You can just add the <code>/modules/</code> directories to your PYTHONPATH in your dev environment. Once installed in site-packages, calling <code>import edit</code> inside check.py will import the correct module since they are in the same directory. Calling <code>import edit</code> from your dev environ will impor...
2
2010-02-17T13:21:22Z
[ "python", "import", "directory-structure" ]
Django ORM and Unicode data
2,280,855
<p>I'm using following model to store info about pages:</p> <pre><code>class Page(models.Model): title = models.TextField(blank = False, null = False) </code></pre> <p>New data saves correctly, I'm saving Unicode data there (lots of non-ASCII titles). But when I'm performing query:</p> <pre><code>page = Page.obj...
2
2010-02-17T13:13:27Z
2,280,886
<p>Might just be your shell not being able to display unicode characters maybe?</p> <p>What happens if you do <code>print page.title</code>?</p>
1
2010-02-17T13:18:05Z
[ "python", "django", "orm", "unicode", "django-models" ]
Django ORM and Unicode data
2,280,855
<p>I'm using following model to store info about pages:</p> <pre><code>class Page(models.Model): title = models.TextField(blank = False, null = False) </code></pre> <p>New data saves correctly, I'm saving Unicode data there (lots of non-ASCII titles). But when I'm performing query:</p> <pre><code>page = Page.obj...
2
2010-02-17T13:13:27Z
2,280,887
<p>That's perfectly fine. It's "Ющенко" unicode-escaped.</p>
2
2010-02-17T13:18:17Z
[ "python", "django", "orm", "unicode", "django-models" ]
Django ORM and Unicode data
2,280,855
<p>I'm using following model to store info about pages:</p> <pre><code>class Page(models.Model): title = models.TextField(blank = False, null = False) </code></pre> <p>New data saves correctly, I'm saving Unicode data there (lots of non-ASCII titles). But when I'm performing query:</p> <pre><code>page = Page.obj...
2
2010-02-17T13:13:27Z
2,280,890
<p>You're doing nothing wrong. Have you tried printing it (or outputting it in a web page)?</p> <pre><code>In [1]: l = u'\u042e\u0449\u0435\u043d\u043a\u043e' In [2]: print l Ющенко </code></pre>
3
2010-02-17T13:18:32Z
[ "python", "django", "orm", "unicode", "django-models" ]
Django ORM and Unicode data
2,280,855
<p>I'm using following model to store info about pages:</p> <pre><code>class Page(models.Model): title = models.TextField(blank = False, null = False) </code></pre> <p>New data saves correctly, I'm saving Unicode data there (lots of non-ASCII titles). But when I'm performing query:</p> <pre><code>page = Page.obj...
2
2010-02-17T13:13:27Z
2,281,191
<p>There is no problem with what you have posted so far.</p> <pre><code>&gt;&gt;&gt; print json.dumps(u'\u042e\u0449\u0435\u043d\u043a\u043e') "\u042e\u0449\u0435\u043d\u043a\u043e" </code></pre> <p>Which is a correct JavaScript string literal. Assign that to a variable and you'll get <code>Ющенко</code> in a J...
1
2010-02-17T13:55:45Z
[ "python", "django", "orm", "unicode", "django-models" ]
Django ORM and Unicode data
2,280,855
<p>I'm using following model to store info about pages:</p> <pre><code>class Page(models.Model): title = models.TextField(blank = False, null = False) </code></pre> <p>New data saves correctly, I'm saving Unicode data there (lots of non-ASCII titles). But when I'm performing query:</p> <pre><code>page = Page.obj...
2
2010-02-17T13:13:27Z
2,281,194
<p>That's correct behaviour: <code>dumps</code> encodes the json for you. It looks ugly now, but that's just for transmission. To see your unicode string again have to decode it (usually on the other end):</p> <pre><code>&gt;&gt;&gt; from django.utils.simplejson import dumps, loads &gt;&gt;&gt; original = u'\u042e\u04...
1
2010-02-17T13:55:55Z
[ "python", "django", "orm", "unicode", "django-models" ]
A list vs. tuple situation in Python
2,280,881
<p>Is there a situation where the use of a list leads to an error, and you must use a tuple instead?</p> <p>I know something about the properties of both tuples and lists, but not enough to find out the answer to this question. If the question would be the other way around, it would be that lists can be adjusted but t...
8
2010-02-17T13:17:34Z
2,280,923
<p>You can use tuples as dictionary keys, because they are immutable, but you can't use lists. Eg:</p> <pre><code>d = {(1, 2): 'a', (3, 8, 1): 'b'} # Valid. d = {[1, 2]: 'a', [3, 8, 1]: 'b'} # Error. </code></pre>
14
2010-02-17T13:23:17Z
[ "python", "list", "tuples" ]
A list vs. tuple situation in Python
2,280,881
<p>Is there a situation where the use of a list leads to an error, and you must use a tuple instead?</p> <p>I know something about the properties of both tuples and lists, but not enough to find out the answer to this question. If the question would be the other way around, it would be that lists can be adjusted but t...
8
2010-02-17T13:17:34Z
2,287,849
<p>Because of their immutable nature, tuples (unlike lists) are <a href="http://docs.python.org/glossary.html">hashable</a>. This is what allows tuples to be keys in dictionaries and also members of sets. Strictly speaking it is their hashability, not their immutability that counts.</p> <p>So in addition to the dictio...
9
2010-02-18T10:30:05Z
[ "python", "list", "tuples" ]
A list vs. tuple situation in Python
2,280,881
<p>Is there a situation where the use of a list leads to an error, and you must use a tuple instead?</p> <p>I know something about the properties of both tuples and lists, but not enough to find out the answer to this question. If the question would be the other way around, it would be that lists can be adjusted but t...
8
2010-02-17T13:17:34Z
2,431,117
<p>In <strong>string formatting</strong> tuples are mandatory:</p> <pre><code>"You have %s new %s" % ('5', 'mails') # must be a tuple, not a list! </code></pre> <p>Using a list in that example produces the error "not enough arguments for format string", because a list is considered as one argument. Weird but true.</p...
3
2010-03-12T07:25:20Z
[ "python", "list", "tuples" ]
Using SQLite3 in Python
2,280,882
<p>I am trying to store some parsed feed contents values in Sqlite database table in python.But facing error.Could anybody help me out of this issue.Infact it is so trivial question to ask!I am newbie!..Anyway thanks in advance! </p> <pre><code>from sqlite3 import * import feedparser data = feedparser.parse("some url...
0
2010-02-17T13:17:47Z
2,280,920
<p>the error should be this line</p> <pre><code> curs.execute("insert into location_tr values\ (NULL, data.entries[i].title,data.feed.updated)") </code></pre> <p><code>data.entries[i].title</code> comes from Python. So if you enclose it in double quotes, it becomes a literal string, not a value. It shoul...
0
2010-02-17T13:22:52Z
[ "python", "sqlite3" ]
Using SQLite3 in Python
2,280,882
<p>I am trying to store some parsed feed contents values in Sqlite database table in python.But facing error.Could anybody help me out of this issue.Infact it is so trivial question to ask!I am newbie!..Anyway thanks in advance! </p> <pre><code>from sqlite3 import * import feedparser data = feedparser.parse("some url...
0
2010-02-17T13:17:47Z
2,280,936
<p>Try</p> <pre><code>curs.execute("insert into location_tr values\ (NULL, '%s', '%s')" % (data.entries[i].title, data.feed.updated)) </code></pre>
1
2010-02-17T13:24:46Z
[ "python", "sqlite3" ]
How to iterate over a the attributes of a class, in the order they were defined?
2,280,961
<p>Python comes with the handy <code>dir()</code> function that would list the content of a class for you. For example, for this class:</p> <pre><code>class C: i = 1 a = 'b' </code></pre> <p><code>dir(C)</code> would return</p> <pre><code>['__doc__', '__module__', 'a', 'i'] </code></pre> <p>This is great, but...
8
2010-02-17T13:28:48Z
2,281,001
<p>I don't think this is possible in Python 2.x. When the class members are provided to the <code>__new__</code> method they are given as a dictionary, so the order has already been lost at that point. Therefore even metaclasses can't help you here (unless there are additional features that I missed).</p> <p>In Python...
7
2010-02-17T13:34:28Z
[ "python", "reflection" ]
How to iterate over a the attributes of a class, in the order they were defined?
2,280,961
<p>Python comes with the handy <code>dir()</code> function that would list the content of a class for you. For example, for this class:</p> <pre><code>class C: i = 1 a = 'b' </code></pre> <p><code>dir(C)</code> would return</p> <pre><code>['__doc__', '__module__', 'a', 'i'] </code></pre> <p>This is great, but...
8
2010-02-17T13:28:48Z
2,282,910
<p>This information is not accessible, since attributes are stored in a dict, which is inherently unordered. Python does not store this information about order anywhere.</p> <p>If you want your serialization format to store things in a certain order you would <em>specify <strong>that</strong> order explicitly</em>. Yo...
1
2010-02-17T17:26:14Z
[ "python", "reflection" ]
How to iterate over a the attributes of a class, in the order they were defined?
2,280,961
<p>Python comes with the handy <code>dir()</code> function that would list the content of a class for you. For example, for this class:</p> <pre><code>class C: i = 1 a = 'b' </code></pre> <p><code>dir(C)</code> would return</p> <pre><code>['__doc__', '__module__', 'a', 'i'] </code></pre> <p>This is great, but...
8
2010-02-17T13:28:48Z
8,243,486
<p>I'm new in python, so my solution may be not effective</p> <pre><code>class Q: def __init__(self): self.a = 5 self.b = 10 if __name__ == "__main__": w = Q() keys = w.__dict__.keys() for k in keys: print "Q.%s = %d"%(k,w.__dict__[k]) </code></pre> <p>Output is:</p> <pre><code>Q.a = 5 ...
3
2011-11-23T14:02:53Z
[ "python", "reflection" ]
How to iterate over a the attributes of a class, in the order they were defined?
2,280,961
<p>Python comes with the handy <code>dir()</code> function that would list the content of a class for you. For example, for this class:</p> <pre><code>class C: i = 1 a = 'b' </code></pre> <p><code>dir(C)</code> would return</p> <pre><code>['__doc__', '__module__', 'a', 'i'] </code></pre> <p>This is great, but...
8
2010-02-17T13:28:48Z
9,188,236
<p>put this method in your class</p> <pre><code>def __setattr__(self, attr, value): if attr not in dir(self): if attr == "__ordered_fields__": super.__setattr__(self, attr, value) else: if not hasattr(self, "__ordered_fields__"): setattr(self, "__ordered_fiel...
1
2012-02-08T05:24:34Z
[ "python", "reflection" ]
Python: Do (explicit) string parameters hurt performance?
2,281,019
<p>Suppose some function that always gets some parameter s that it does not use.</p> <pre><code>def someFunc(s): # do something _not_ using s, for example a=1 </code></pre> <p>now consider this call</p> <pre><code>someFunc("the unused string") </code></pre> <p>which gives a string as a parameter that is not bui...
1
2010-02-17T13:37:00Z
2,281,066
<p>The string is passed (by reference) each time, but the overhead is way too tiny to really affect performance unless it's in a super-tight loop.</p>
2
2010-02-17T13:42:50Z
[ "python", "performance", "function", "parameters", "compile-time" ]
Python: Do (explicit) string parameters hurt performance?
2,281,019
<p>Suppose some function that always gets some parameter s that it does not use.</p> <pre><code>def someFunc(s): # do something _not_ using s, for example a=1 </code></pre> <p>now consider this call</p> <pre><code>someFunc("the unused string") </code></pre> <p>which gives a string as a parameter that is not bui...
1
2010-02-17T13:37:00Z
2,281,203
<p>this is an implementation detail of CPython, and may not apply to other pythons but yes, in many cases in a compiled module, a constant string will reference the same object, minimizing the overhead.</p> <p>In general, even if it didn't, you really shouldn't worry about it, as it's probably imperceptibly tiny compa...
1
2010-02-17T13:57:45Z
[ "python", "performance", "function", "parameters", "compile-time" ]
Why/When in Python does `x==y` call `y.__eq__(x)`?
2,281,222
<p>The Python docs clearly state that <code>x==y</code> calls <code>x.__eq__(y)</code>. However it seems that under many circumstances, the opposite is true. Where is it documented when or why this happens, and how can I work out for sure whether my object's <code>__cmp__</code> or <code>__eq__</code> methods are goi...
31
2010-02-17T14:00:16Z
2,281,271
<p>Is this not documented in the <a href="http://docs.python.org/reference/datamodel.html#special-method-names" rel="nofollow">Language Reference</a>? Just from a quick look there, it looks like <code>__cmp__</code> is ignored when <code>__eq__</code>, <code>__lt__</code>, etc are defined. I'm understanding that to inc...
1
2010-02-17T14:09:07Z
[ "python", "comparison", "operator-overloading" ]
Why/When in Python does `x==y` call `y.__eq__(x)`?
2,281,222
<p>The Python docs clearly state that <code>x==y</code> calls <code>x.__eq__(y)</code>. However it seems that under many circumstances, the opposite is true. Where is it documented when or why this happens, and how can I work out for sure whether my object's <code>__cmp__</code> or <code>__eq__</code> methods are goi...
31
2010-02-17T14:00:16Z
2,281,309
<p>As I know, <code>__eq__()</code> is a so-called “rich comparison” method, and is called for comparison operators in preference to <code>__cmp__()</code> below. <code>__cmp__()</code> is called if "rich comparison" is not defined.</p> <p>So in A == B:<br> If <code>__eq__()</code> is defined in A it will be c...
1
2010-02-17T14:13:32Z
[ "python", "comparison", "operator-overloading" ]
Why/When in Python does `x==y` call `y.__eq__(x)`?
2,281,222
<p>The Python docs clearly state that <code>x==y</code> calls <code>x.__eq__(y)</code>. However it seems that under many circumstances, the opposite is true. Where is it documented when or why this happens, and how can I work out for sure whether my object's <code>__cmp__</code> or <code>__eq__</code> methods are goi...
31
2010-02-17T14:00:16Z
2,281,339
<p>Actually, in the <a href="http://docs.python.org/reference/datamodel.html#basic-customization" rel="nofollow">docs</a>, it states:</p> <blockquote> <p>[<code>__cmp__</code> is c]alled by comparison operations if rich comparison (see above) is not defined.</p> </blockquote> <p><code>__eq__</code> is a rich compar...
6
2010-02-17T14:18:09Z
[ "python", "comparison", "operator-overloading" ]
Why/When in Python does `x==y` call `y.__eq__(x)`?
2,281,222
<p>The Python docs clearly state that <code>x==y</code> calls <code>x.__eq__(y)</code>. However it seems that under many circumstances, the opposite is true. Where is it documented when or why this happens, and how can I work out for sure whether my object's <code>__cmp__</code> or <code>__eq__</code> methods are goi...
31
2010-02-17T14:00:16Z
2,282,795
<p>You're missing a key exception to the usual behaviour: when the right-hand operand is an instance of a subclass of the class of the left-hand operand, the special method for the right-hand operand is called first.</p> <p>See the documentation at:</p> <p><a href="http://docs.python.org/reference/datamodel.html#coe...
27
2010-02-17T17:10:34Z
[ "python", "comparison", "operator-overloading" ]
Removing empty items from a list (Python)
2,281,263
<p>I'm reading a file in Python that isn't well formatted, values are separated by multiple spaces and some tabs too so the lists returned has a lot of empty items, how do I remove/avoid those?</p> <p>This is my current code:</p> <pre><code>import re f = open('myfile.txt','r') for line in f.readlines(): if re...
2
2010-02-17T14:07:46Z
2,281,299
<p>Why not do <code>line.strip()</code> before handling it? Also, you could use <code>re.split</code> to use a regex like '\s+' as your delimiter.</p>
0
2010-02-17T14:12:16Z
[ "python", "regex", "list", "split" ]
Removing empty items from a list (Python)
2,281,263
<p>I'm reading a file in Python that isn't well formatted, values are separated by multiple spaces and some tabs too so the lists returned has a lot of empty items, how do I remove/avoid those?</p> <p>This is my current code:</p> <pre><code>import re f = open('myfile.txt','r') for line in f.readlines(): if re...
2
2010-02-17T14:07:46Z
2,281,308
<p>Don't explicitly specify <code>' '</code> as the delimiter. <code>line.split()</code> will split on all whitespace. It's equivalent to using <code>re.split</code>:</p> <pre><code>&gt;&gt;&gt; line = ' a b c \n\tg ' &gt;&gt;&gt; line.split() ['a', 'b', 'c', 'g'] &gt;&gt;&gt; import re &gt;&gt;&gt; re.split('\s+'...
11
2010-02-17T14:13:28Z
[ "python", "regex", "list", "split" ]
Removing empty items from a list (Python)
2,281,263
<p>I'm reading a file in Python that isn't well formatted, values are separated by multiple spaces and some tabs too so the lists returned has a lot of empty items, how do I remove/avoid those?</p> <p>This is my current code:</p> <pre><code>import re f = open('myfile.txt','r') for line in f.readlines(): if re...
2
2010-02-17T14:07:46Z
2,281,439
<pre><code>for line in open("file"): if " Deposit" in line: line=line.rstrip() print line.split() </code></pre> <p>Update: </p> <pre><code>for line in open("file"): if "Deposit" in line: line=line.rstrip() print line[line.index("Deposit"):].split() </code></pre>
2
2010-02-17T14:31:05Z
[ "python", "regex", "list", "split" ]
Removing empty items from a list (Python)
2,281,263
<p>I'm reading a file in Python that isn't well formatted, values are separated by multiple spaces and some tabs too so the lists returned has a lot of empty items, how do I remove/avoid those?</p> <p>This is my current code:</p> <pre><code>import re f = open('myfile.txt','r') for line in f.readlines(): if re...
2
2010-02-17T14:07:46Z
2,281,495
<pre><code>linesAsLists = [line.split() for line in open('myfile.txt', 'r') if 'Deposit' in line)] </code></pre>
1
2010-02-17T14:38:38Z
[ "python", "regex", "list", "split" ]
Django ModelForm Template?
2,281,295
<p>I want to learn how can I add to template to my ModelForm i'm newbie. Below you can see my models.py, url.py and views.py:</p> <p>My model.py looks like that:</p> <pre><code>from django.db import models from django.forms import ModelForm from django.contrib.auth.models import User class Yazilar(models.Model): ...
2
2010-02-17T14:11:54Z
2,811,613
<p>You could in fact use <code>&lt;form action=""&gt;</code> since the url you want to post to is the same as the page you are on.</p> <p>If you don't like that then as long as you have 'django.core.context_processors.request' in your TEMPLATE_CONTEXT_PROCESSORS in settings.py I think you could also do:</p> <pre><cod...
1
2010-05-11T14:39:03Z
[ "python", "django", "templates", "django-forms" ]
Django ModelForm Template?
2,281,295
<p>I want to learn how can I add to template to my ModelForm i'm newbie. Below you can see my models.py, url.py and views.py:</p> <p>My model.py looks like that:</p> <pre><code>from django.db import models from django.forms import ModelForm from django.contrib.auth.models import User class Yazilar(models.Model): ...
2
2010-02-17T14:11:54Z
4,942,627
<p>It seems to me that your problem is in the view, you should be doing something like this:</p> <pre><code>@login_required def yazi_ekle(request): yazim = YaziForm() # Look at the (), they are needed for instantiation return render_to_response('yazi/save.html', {'YaziForm': yazim}) # Sending the form ...
5
2011-02-09T08:18:29Z
[ "python", "django", "templates", "django-forms" ]
Enable or disable gtk.Button in PyGTK
2,281,373
<p>How can I set a <code>gtk.Button</code> enabled or disabled in PyGTK?</p>
6
2010-02-17T14:23:07Z
2,281,422
<pre><code>my_button.set_sensitive(False) </code></pre> <p>True is enabled, False disabled. See the <a href="http://www.pygtk.org/docs/pygtk/class-gtkwidget.html#method-gtkwidget--set-sensitive">gtk.Widget documentation</a>.</p>
12
2010-02-17T14:29:18Z
[ "python", "pygtk" ]
Are there more ways to define a tuple with only one item?
2,281,409
<p>I know this is one way, by placing a comma:</p> <pre><code>&gt;&gt;&gt; empty = () &gt;&gt;&gt; singleton = 'hello', # &lt;-- note trailing comma &gt;&gt;&gt; len(empty) 0 &gt;&gt;&gt; len(singleton) 1 &gt;&gt;&gt; singleton ('hello',) </code></pre> <p>Source: <a href="http://docs.python.org/tutorial/datastruct...
5
2010-02-17T14:27:54Z
2,281,466
<pre><code>&gt;&gt;&gt; tuple(['hello']) ('hello',) </code></pre> <p>But the built-in syntax is there for a reason.</p>
8
2010-02-17T14:33:57Z
[ "python", "singleton", "tuples" ]
Are there more ways to define a tuple with only one item?
2,281,409
<p>I know this is one way, by placing a comma:</p> <pre><code>&gt;&gt;&gt; empty = () &gt;&gt;&gt; singleton = 'hello', # &lt;-- note trailing comma &gt;&gt;&gt; len(empty) 0 &gt;&gt;&gt; len(singleton) 1 &gt;&gt;&gt; singleton ('hello',) </code></pre> <p>Source: <a href="http://docs.python.org/tutorial/datastruct...
5
2010-02-17T14:27:54Z
2,281,484
<p><code>singleton = ('hello',)</code></p> <p>This is more clear I guess, and @jleedev even more clear. But I like the method you used the best:</p> <p><code>singleton = 'hello',</code></p>
1
2010-02-17T14:36:56Z
[ "python", "singleton", "tuples" ]
Are there more ways to define a tuple with only one item?
2,281,409
<p>I know this is one way, by placing a comma:</p> <pre><code>&gt;&gt;&gt; empty = () &gt;&gt;&gt; singleton = 'hello', # &lt;-- note trailing comma &gt;&gt;&gt; len(empty) 0 &gt;&gt;&gt; len(singleton) 1 &gt;&gt;&gt; singleton ('hello',) </code></pre> <p>Source: <a href="http://docs.python.org/tutorial/datastruct...
5
2010-02-17T14:27:54Z
2,281,509
<p>Another one is</p> <pre><code>&gt;&gt;&gt; (1, 2)[0:1] (1,) </code></pre> <p>A very obfuscated way, but it <em>is</em> an alternative...</p>
2
2010-02-17T14:40:11Z
[ "python", "singleton", "tuples" ]
Are there more ways to define a tuple with only one item?
2,281,409
<p>I know this is one way, by placing a comma:</p> <pre><code>&gt;&gt;&gt; empty = () &gt;&gt;&gt; singleton = 'hello', # &lt;-- note trailing comma &gt;&gt;&gt; len(empty) 0 &gt;&gt;&gt; len(singleton) 1 &gt;&gt;&gt; singleton ('hello',) </code></pre> <p>Source: <a href="http://docs.python.org/tutorial/datastruct...
5
2010-02-17T14:27:54Z
2,281,525
<p>Even though you can define a tuple as <code>'hello',</code> I think it would be easy for someone to possibly miss the trailing comma if they were reading your code. I definitely prefer <code>('hello',)</code> from a readability stand-point.</p>
4
2010-02-17T14:41:28Z
[ "python", "singleton", "tuples" ]
Is it a good idea to have a syntax sugar to function composition in Python?
2,281,693
<p>Some time ago I looked over Haskell docs and found it's functional composition operator really nice. So I've implemented this tiny decorator:</p> <pre><code>from functools import partial class _compfunc(partial): def __lshift__(self, y): f = lambda *args, **kwargs: self.func(y(*args, **kwargs)) ...
17
2010-02-17T15:00:19Z
2,281,838
<p>IMHO: no, it's not. While I like Haskell, this just doesn't seem to fit in Python. Instead of <code>(f1 &gt;&gt; f2 &gt;&gt; f3)</code> you can do <code>compose(f1, f2, f3)</code> and that solves your problem -- you can use it with any callable without any overloading, decorating or changing the core (IIRC somebody ...
8
2010-02-17T15:20:30Z
[ "python", "function-composition" ]
Is it a good idea to have a syntax sugar to function composition in Python?
2,281,693
<p>Some time ago I looked over Haskell docs and found it's functional composition operator really nice. So I've implemented this tiny decorator:</p> <pre><code>from functools import partial class _compfunc(partial): def __lshift__(self, y): f = lambda *args, **kwargs: self.func(y(*args, **kwargs)) ...
17
2010-02-17T15:00:19Z
2,283,106
<p>Function composition isn't a super-common operation in Python, especially not in a way that a composition operator is clearly needed. If something was added, I am not certain I like the choice of <code>&lt;&lt;</code> and <code>&gt;&gt;</code> for Python, which are not as obvious to me as they seem to be to you. </p...
6
2010-02-17T17:54:59Z
[ "python", "function-composition" ]
Is it a good idea to have a syntax sugar to function composition in Python?
2,281,693
<p>Some time ago I looked over Haskell docs and found it's functional composition operator really nice. So I've implemented this tiny decorator:</p> <pre><code>from functools import partial class _compfunc(partial): def __lshift__(self, y): f = lambda *args, **kwargs: self.func(y(*args, **kwargs)) ...
17
2010-02-17T15:00:19Z
7,688,723
<p>You can do it with <code>reduce</code>, although the order of calls is left-to-right only:</p> <pre class="lang-py prettyprint-override"><code>def f1(a): return a+1 def f2(a): return a+10 def f3(a): return a+100 def call(a,f): return f(a) reduce(call, (f1, f2, f3), 5) # 5 -&gt; f1 -&gt; f2 -&gt...
6
2011-10-07T14:31:46Z
[ "python", "function-composition" ]
Is it a good idea to have a syntax sugar to function composition in Python?
2,281,693
<p>Some time ago I looked over Haskell docs and found it's functional composition operator really nice. So I've implemented this tiny decorator:</p> <pre><code>from functools import partial class _compfunc(partial): def __lshift__(self, y): f = lambda *args, **kwargs: self.func(y(*args, **kwargs)) ...
17
2010-02-17T15:00:19Z
13,728,218
<p>I don't have enough experience with Python to have a view on whether a language change would be worthwhile. But I wanted to describe the options available with the current language.</p> <p>To avoid creating unexpected behavior, functional composition should ideally follow the standard math (or Haskell) order of ope...
1
2012-12-05T16:48:40Z
[ "python", "function-composition" ]
How to set django upload_handler in admin?
2,281,881
<p>I'm trying to make a django upload progress bar within the django admin. The application is only a small part of the project, therefor I do not want to set the custom upload handler in the settings.py.</p> <p>The upload_handler can be set with <code>request.upload_handlers.insert(0, UploadProgressHandler(request))<...
6
2010-02-17T15:24:34Z
11,866,619
<p>Have a look at the source for the decorator that comes with the admin app:</p> <pre><code>def staff_member_required(view_func): """ Decorator for views that checks that the user is logged in and is a staff member, displaying the login page if necessary. """ @wraps(view_func) def _checklogin(...
1
2012-08-08T14:23:17Z
[ "python", "django", "file-upload", "django-admin" ]
Reload Method or Object in IDLE
2,281,955
<p>when using idle, I know you can reload a module if it's changed like this:</p> <pre><code>import foo reload(foo) </code></pre> <p>if I only import part of a module, is there a way to reload it in a similar matter?</p> <pre><code>from foo import bar </code></pre>
1
2010-02-17T15:32:18Z
2,282,106
<p>No. You'll have to import foo, then reload(foo), after all.</p>
1
2010-02-17T15:50:05Z
[ "python", "python-idle" ]
Reload Method or Object in IDLE
2,281,955
<p>when using idle, I know you can reload a module if it's changed like this:</p> <pre><code>import foo reload(foo) </code></pre> <p>if I only import part of a module, is there a way to reload it in a similar matter?</p> <pre><code>from foo import bar </code></pre>
1
2010-02-17T15:32:18Z
2,282,858
<p>No, <code>reload</code> has to re-run the whole module.</p> <p>Note that <code>reload</code> is confusing and does not have the ability to be consistent. It's much better to restart the interpreter.</p>
2
2010-02-17T17:18:35Z
[ "python", "python-idle" ]
Reload Method or Object in IDLE
2,281,955
<p>when using idle, I know you can reload a module if it's changed like this:</p> <pre><code>import foo reload(foo) </code></pre> <p>if I only import part of a module, is there a way to reload it in a similar matter?</p> <pre><code>from foo import bar </code></pre>
1
2010-02-17T15:32:18Z
13,220,419
<p><a href="http://docs.python.org/2/library/functions.html#reload" rel="nofollow">http://docs.python.org/2/library/functions.html#reload</a></p> <p>It says: </p> <blockquote> <p>"If a module imports objects from another module using from ... import ..., calling reload() for the other module does not redefine the...
1
2012-11-04T16:25:41Z
[ "python", "python-idle" ]
Setting up authentication in Trac
2,282,123
<p>I am in the works of setting up a Trac server for my (small) company and need a bit of help/guidance with the authentication mechanism.</p> <p>We have for some time developed our own web application which our users access in their day to day work. It is build in php5.3 and includes a users database stored in a mysq...
1
2010-02-17T15:52:51Z
2,282,173
<p>First off, don't use mod_python, use mod_wsgi.</p> <p>Second, you have several options for how to do authentication. One option might be to just use mod_authn_dbd with a MySQL backend, keeping your authn in the apache2 config.</p> <p>Third, look into Trac's AccountManager. It's one of the most useful Trac plugins ...
2
2010-02-17T15:59:43Z
[ "php", "python", "apache", "trac" ]
Setting up authentication in Trac
2,282,123
<p>I am in the works of setting up a Trac server for my (small) company and need a bit of help/guidance with the authentication mechanism.</p> <p>We have for some time developed our own web application which our users access in their day to day work. It is build in php5.3 and includes a users database stored in a mysq...
1
2010-02-17T15:52:51Z
2,282,204
<p>What you are looking for is called Single Sign On.</p> <p>Are you running Trac on Apache? In that case, it seems to be possible to make use of what user authentication interfaces (LDAP...) Apache can interface with. Check out <a href="http://www.mail-archive.com/trac-users@googlegroups.com/msg07553.html" rel="nofol...
0
2010-02-17T16:03:02Z
[ "php", "python", "apache", "trac" ]
Setting up authentication in Trac
2,282,123
<p>I am in the works of setting up a Trac server for my (small) company and need a bit of help/guidance with the authentication mechanism.</p> <p>We have for some time developed our own web application which our users access in their day to day work. It is build in php5.3 and includes a users database stored in a mysq...
1
2010-02-17T15:52:51Z
2,317,227
<p>Just a quick follow up: I ended up using Carsten Fuchs ScriptAuthPlugin (modifying it to md5-hash the password). Similar to TracCoSign, all you have to provide, is an address to which ScriptAuthPlugin can validate user credentials. Works nicely :-)</p> <p><a href="http://trac-hacks.org/wiki/ScriptAuthPlugin" rel="n...
0
2010-02-23T10:12:14Z
[ "php", "python", "apache", "trac" ]
Trouble importing modules in Python IDEs
2,282,239
<p>Right I'm getting a bit tired of this so hopefully you can help me sort it out once and for all.</p> <p>I'm really confused about what's going on with Python on my MacBook. I'm running OS X 10.6.2 and have installed python from the website (the package that includes IDLE). This works absolutely fine, and in fact ID...
4
2010-02-17T16:07:27Z
2,282,318
<p>I deal with this by sticking to the macports Python installation. For compatibility reasons, I'm very wary of mixing modules for different python versions. </p> <p>Using <code>python_select</code>, <code>port</code> installed modules and the macports version of <code>easy_install</code> should ensure that everythi...
0
2010-02-17T16:17:03Z
[ "python", "osx", "matplotlib" ]
Adding an entry to a python tuple
2,282,300
<p>I have a list of tuples representing x,y points. I also have a list of values for each of these points. How do I combine them into a list of lists (i.e one entry for each point [x,y,val]) or a list of tuples?</p> <p>Thanks</p>
3
2010-02-17T16:14:48Z
2,282,328
<p>Tuples are immutable, they can't be modified. Convert it to a list, then convert it back if you want to (list((a, b))).</p>
1
2010-02-17T16:17:35Z
[ "python", "list", "tuples" ]
Adding an entry to a python tuple
2,282,300
<p>I have a list of tuples representing x,y points. I also have a list of values for each of these points. How do I combine them into a list of lists (i.e one entry for each point [x,y,val]) or a list of tuples?</p> <p>Thanks</p>
3
2010-02-17T16:14:48Z
2,282,335
<p>You can't add entries to tuples, since tuples are immutable. But you can create a new list of lists:</p> <pre><code>new = [[x, y, val] for (x, y), val in zip(points, vals)] </code></pre>
10
2010-02-17T16:18:07Z
[ "python", "list", "tuples" ]
Help for novice choosing between Java and Python for app with sql db
2,282,360
<p>I'm going to write my first non-Access project, and I need advice on choosing the platform. I will be installing it on multiple friends' and family's computers, so (since I'm sure many, many platforms would suffice just fine for my app), my highest priority has two parts: 1) ease of install for the non-technical use...
0
2010-02-17T16:20:52Z
2,282,470
<p>The largest issue I can think of is the need to install an interpreter.</p> <p>With Java, a lot of people will already have that interpreter installed, although you won't necessarily know which version. It may be wise to include the installer for Java with the program.</p> <p>With Python, you're going to have to ...
1
2010-02-17T16:35:52Z
[ "java", "python" ]
Help for novice choosing between Java and Python for app with sql db
2,282,360
<p>I'm going to write my first non-Access project, and I need advice on choosing the platform. I will be installing it on multiple friends' and family's computers, so (since I'm sure many, many platforms would suffice just fine for my app), my highest priority has two parts: 1) ease of install for the non-technical use...
0
2010-02-17T16:20:52Z
2,282,474
<p>My personal choice would be to use Java. You shouldn't run into any problems with different OSs' because of the JVM. However, GUI programmign in Java can be cumbersome but there are plenty of good tutorials on how to create good GUIs' using swing. </p> <p><a href="http://java.sun.com/developer/technicalArticles/J2S...
1
2010-02-17T16:36:03Z
[ "java", "python" ]
Help for novice choosing between Java and Python for app with sql db
2,282,360
<p>I'm going to write my first non-Access project, and I need advice on choosing the platform. I will be installing it on multiple friends' and family's computers, so (since I'm sure many, many platforms would suffice just fine for my app), my highest priority has two parts: 1) ease of install for the non-technical use...
0
2010-02-17T16:20:52Z
2,282,484
<p>Then use <a href="http://www.jython.org" rel="nofollow">Jython</a> and you get the best of both worlds :-)</p> <p>Plus, you can write performance critical parts in pure Java and integrate it easily (more or less).</p>
1
2010-02-17T16:37:05Z
[ "java", "python" ]
Help for novice choosing between Java and Python for app with sql db
2,282,360
<p>I'm going to write my first non-Access project, and I need advice on choosing the platform. I will be installing it on multiple friends' and family's computers, so (since I'm sure many, many platforms would suffice just fine for my app), my highest priority has two parts: 1) ease of install for the non-technical use...
0
2010-02-17T16:20:52Z
2,282,498
<p>You can get a program up and running pretty quickly with <a href="http://www.python.org/download/releases/2.6.4/" rel="nofollow">Python 2.6</a>, the <a href="http://code.google.com/p/pyodbc/" rel="nofollow">pyodbc</a> module for SQL integration, <a href="http://www.riverbankcomputing.co.uk/software/pyqt/intro" rel="...
0
2010-02-17T16:38:23Z
[ "java", "python" ]
Help for novice choosing between Java and Python for app with sql db
2,282,360
<p>I'm going to write my first non-Access project, and I need advice on choosing the platform. I will be installing it on multiple friends' and family's computers, so (since I'm sure many, many platforms would suffice just fine for my app), my highest priority has two parts: 1) ease of install for the non-technical use...
0
2010-02-17T16:20:52Z
2,283,347
<p>If you're going to install only (or mostly) on Windows, I'd go with .Net. </p> <p>If you have experience with C++, then C# would be natural to you, but if you're comfortable with VBA, you can try VB.NET, but if you prefer Python, then there is IronPython or can give a try to IronRuby, but the best of all is you can...
1
2010-02-17T18:25:39Z
[ "java", "python" ]
How Do I Get the Module Name of an Object's Class Definition Rather Than the Module Name of the Object's Instantiation?
2,282,369
<p>In python 2.5, I have the following code in a module called modtest.py:</p> <pre><code>def print_method_module(method): def printer(self): print self.__module__ return method(self) return printer class ModTest(): @print_method_module def testmethod(self): pass if __name__ ...
11
2010-02-17T16:22:02Z
2,282,399
<p>I'm guessing you could use sys._getframe() hackery to get at what you want.</p>
0
2010-02-17T16:25:23Z
[ "python" ]
How Do I Get the Module Name of an Object's Class Definition Rather Than the Module Name of the Object's Instantiation?
2,282,369
<p>In python 2.5, I have the following code in a module called modtest.py:</p> <pre><code>def print_method_module(method): def printer(self): print self.__module__ return method(self) return printer class ModTest(): @print_method_module def testmethod(self): pass if __name__ ...
11
2010-02-17T16:22:02Z
2,282,648
<p>When you execute a python source file directly, the module name of that file is <code>__main__</code>, even if it is known by another name when you execute some other file and import it. </p> <p>You probably want to do like you did in modtest2, and import the module containing the class definition instead of execut...
7
2010-02-17T16:55:18Z
[ "python" ]
Is there a cleaner or more efficient to do this Python assignment?
2,282,526
<p>Here's the code I have now:</p> <pre><code>lang = window.get_active_document().get_language() if lang != None: lang = lang.get_name() </code></pre> <p>Is there a better way to do that? I'm new to Pythonic and was wondering if there's a more Python way to say "something equals this if x is true, else it equals ...
0
2010-02-17T16:41:42Z
2,282,568
<p>You could do <code>lang = lang and lang.get_name()</code> instead of the 'if' statement.</p> <p>If lang is None it will stay None. If not, it will be set to lang.get_name().</p> <p>I'm not sure if that syntax makes things much clearer, though.</p> <p>P.S. Instead of <code>lang != None</code> you should use <code>...
7
2010-02-17T16:46:32Z
[ "python", "variable-assignment" ]
Is there a cleaner or more efficient to do this Python assignment?
2,282,526
<p>Here's the code I have now:</p> <pre><code>lang = window.get_active_document().get_language() if lang != None: lang = lang.get_name() </code></pre> <p>Is there a better way to do that? I'm new to Pythonic and was wondering if there's a more Python way to say "something equals this if x is true, else it equals ...
0
2010-02-17T16:41:42Z
2,282,572
<p>Try</p> <pre><code>lang = lang.get_name() if lang else None </code></pre>
2
2010-02-17T16:46:49Z
[ "python", "variable-assignment" ]
Is there a cleaner or more efficient to do this Python assignment?
2,282,526
<p>Here's the code I have now:</p> <pre><code>lang = window.get_active_document().get_language() if lang != None: lang = lang.get_name() </code></pre> <p>Is there a better way to do that? I'm new to Pythonic and was wondering if there's a more Python way to say "something equals this if x is true, else it equals ...
0
2010-02-17T16:41:42Z
2,283,249
<pre><code>try: lang = window.get_active_document().get_language().get_name() except AttributeError: lang = None </code></pre> <p>The advantage here is that window itself and all three nested methods become guarded in one statement.</p>
2
2010-02-17T18:12:11Z
[ "python", "variable-assignment" ]
Is there a cleaner or more efficient to do this Python assignment?
2,282,526
<p>Here's the code I have now:</p> <pre><code>lang = window.get_active_document().get_language() if lang != None: lang = lang.get_name() </code></pre> <p>Is there a better way to do that? I'm new to Pythonic and was wondering if there's a more Python way to say "something equals this if x is true, else it equals ...
0
2010-02-17T16:41:42Z
2,283,323
<p>Your solution is fine and clearer most solutions offered so far. Slightly more pythonic would be:</p> <pre><code>lang = window.get_active_document().get_language() if lang: lang = lang.get_name() </code></pre> <p>or</p> <pre><code>lang = window.get_active_document().get_language() if lang is not None: la...
1
2010-02-17T18:22:22Z
[ "python", "variable-assignment" ]
Python, trying to run a program from the command prompt
2,282,544
<p>I am trying to run a program from the command prompt in windows. I am having some issues. The code is below: </p> <pre><code>commandString = "'C:\Program Files\WebShot\webshotcmd.exe' //url '" + columns[3] + "' //out '"+columns[1]+"~"+columns[2]+".jpg'" os.system(commandString) time.sleep(10) </code></pre> <p>So w...
-1
2010-02-17T16:43:50Z
2,282,577
<p>Use the <a href="http://docs.python.org/library/subprocess.html" rel="nofollow">subprocess</a> module for calling system commands. Also ,try removing the single quotes and use double quotes.</p>
1
2010-02-17T16:47:02Z
[ "python", "windows", "command-line", "command-prompt", "os.system" ]
Python, trying to run a program from the command prompt
2,282,544
<p>I am trying to run a program from the command prompt in windows. I am having some issues. The code is below: </p> <pre><code>commandString = "'C:\Program Files\WebShot\webshotcmd.exe' //url '" + columns[3] + "' //out '"+columns[1]+"~"+columns[2]+".jpg'" os.system(commandString) time.sleep(10) </code></pre> <p>So w...
-1
2010-02-17T16:43:50Z
2,282,813
<ul> <li>Windows requires double quotes in this situation, and you used single quotes.</li> <li>Use the <code>subprocess</code> module rather than <code>os.system</code>, which is more robust and avoids calling the shell directly, making you not have to worry about confusing escaping issues.</li> <li>Dont use <code>+</...
1
2010-02-17T17:12:42Z
[ "python", "windows", "command-line", "command-prompt", "os.system" ]
strcmp for python or how to sort substrings efficiently (without copy) when building a suffix array
2,282,579
<p>Here's a very simple way to build an <a href="http://en.wikipedia.org/wiki/Suffix_array">suffix array</a> from a string in python:</p> <pre><code>def sort_offsets(a, b): return cmp(content[a:], content[b:]) content = "foobar baz foo" suffix_array.sort(cmp=sort_offsets) print suffix_array [6, 10, 4, 8, 3, 7, 11...
10
2010-02-17T16:47:11Z
2,282,624
<p>I don't know if there's a fast way to compare substrings, but you can make your code much faster (and simpler) by using <code>key</code> instead of <code>cmp</code>:</p> <pre><code>suffix_array.sort(key=lambda a: content[a:]) </code></pre> <p>This will create the substring just once for each value of a.</p> <p>Ed...
5
2010-02-17T16:52:49Z
[ "python", "string", "sorting", "suffix-array" ]
strcmp for python or how to sort substrings efficiently (without copy) when building a suffix array
2,282,579
<p>Here's a very simple way to build an <a href="http://en.wikipedia.org/wiki/Suffix_array">suffix array</a> from a string in python:</p> <pre><code>def sort_offsets(a, b): return cmp(content[a:], content[b:]) content = "foobar baz foo" suffix_array.sort(cmp=sort_offsets) print suffix_array [6, 10, 4, 8, 3, 7, 11...
10
2010-02-17T16:47:11Z
2,282,674
<p>The <a href="http://docs.python.org/library/functions.html#buffer">buffer</a> function does not copy the whole string, but creates an object that only references the source string. Using interjay's suggestion, that would be:</p> <pre><code>suffix_array.sort(key=lambda a: buffer(content, a)) </code></pre>
6
2010-02-17T16:59:20Z
[ "python", "string", "sorting", "suffix-array" ]
strcmp for python or how to sort substrings efficiently (without copy) when building a suffix array
2,282,579
<p>Here's a very simple way to build an <a href="http://en.wikipedia.org/wiki/Suffix_array">suffix array</a> from a string in python:</p> <pre><code>def sort_offsets(a, b): return cmp(content[a:], content[b:]) content = "foobar baz foo" suffix_array.sort(cmp=sort_offsets) print suffix_array [6, 10, 4, 8, 3, 7, 11...
10
2010-02-17T16:47:11Z
2,283,415
<p>+1 for a very interesting problem! I can't see any obvious way to do this directly, but I was able to get a significant speedup (an order of magnitude for 100000 character strings) by using the following comparison function in place of yours:</p> <pre><code>def compare_offsets2(a, b): return (cmp(content[a:a+1...
3
2010-02-17T18:38:19Z
[ "python", "string", "sorting", "suffix-array" ]
strcmp for python or how to sort substrings efficiently (without copy) when building a suffix array
2,282,579
<p>Here's a very simple way to build an <a href="http://en.wikipedia.org/wiki/Suffix_array">suffix array</a> from a string in python:</p> <pre><code>def sort_offsets(a, b): return cmp(content[a:], content[b:]) content = "foobar baz foo" suffix_array.sort(cmp=sort_offsets) print suffix_array [6, 10, 4, 8, 3, 7, 11...
10
2010-02-17T16:47:11Z
2,383,650
<p>You could use the <a href="http://pypi.python.org/pypi/blist/" rel="nofollow" title="blist extension type">blist extension type</a> that I wrote. A <code>blist</code> works like the built-in <code>list</code>, but (among other things) uses copy-on-write so that taking a slice takes O(log n) time and memory.</p> <p...
0
2010-03-05T00:04:36Z
[ "python", "string", "sorting", "suffix-array" ]
Suggestions wanted: learning material for Django
2,282,619
<p>I am looking for advice on best resources to learn how to develop webapps with Django [the python framework]. Here's a few information to help responders to narrow-down the gazillion options "out there".</p> <h3>Where I stand</h3> <ul> <li><strong>I know python</strong> (2.x series) and I have developed a few appl...
6
2010-02-17T16:52:29Z
2,282,645
<p>Well, I have a trivial solution - get used to reading the manual and the django book they host.</p> <p>Django manual is organized well, and once you have a mental picture of it, you'll really be able to make a good use of it.</p> <p>Two things I wish Django docs were better at - tell clearly where to import stuff ...
2
2010-02-17T16:54:51Z
[ "python", "django", "model-view-controller", "frameworks" ]
Suggestions wanted: learning material for Django
2,282,619
<p>I am looking for advice on best resources to learn how to develop webapps with Django [the python framework]. Here's a few information to help responders to narrow-down the gazillion options "out there".</p> <h3>Where I stand</h3> <ul> <li><strong>I know python</strong> (2.x series) and I have developed a few appl...
6
2010-02-17T16:52:29Z
2,282,792
<p>Check out <a href="http://blogs.jetbrains.com/pycharm/" rel="nofollow">PyCharm</a> from JetBrains - I am just starting to dabble with Django, and this IDE has built-in Django support.</p>
0
2010-02-17T17:10:27Z
[ "python", "django", "model-view-controller", "frameworks" ]
Suggestions wanted: learning material for Django
2,282,619
<p>I am looking for advice on best resources to learn how to develop webapps with Django [the python framework]. Here's a few information to help responders to narrow-down the gazillion options "out there".</p> <h3>Where I stand</h3> <ul> <li><strong>I know python</strong> (2.x series) and I have developed a few appl...
6
2010-02-17T16:52:29Z
2,282,872
<p>My opinion has been <a href="http://stackoverflow.com/questions/1145414/what-are-the-best-books-and-resources-for-learning-to-develop-deploy-and-or-host/1145440#1145440">expressed in this answer</a></p> <p>I have read the djangobook, practical django projects, pro django and some portions of "Web development with d...
4
2010-02-17T17:20:31Z
[ "python", "django", "model-view-controller", "frameworks" ]
Suggestions wanted: learning material for Django
2,282,619
<p>I am looking for advice on best resources to learn how to develop webapps with Django [the python framework]. Here's a few information to help responders to narrow-down the gazillion options "out there".</p> <h3>Where I stand</h3> <ul> <li><strong>I know python</strong> (2.x series) and I have developed a few appl...
6
2010-02-17T16:52:29Z
2,284,201
<p><a href="http://djangobook.com" rel="nofollow">Djangobook</a> has been the best asset to my learning so far. They structure it in a way that lets you suffer doing things the hard way <strong>first</strong> so that you get an understanding of what is really going on behind the scenes when you take the "shortcuts." I'...
1
2010-02-17T20:35:45Z
[ "python", "django", "model-view-controller", "frameworks" ]