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
Equivalent of Beautiful Soup's renderContents() method in lxml?
2,028,270
<p>Is there an equivalent of Beautiful Soup's <code>tag.renderContents()</code> method in lxml?</p> <p>I've tried using <code>element.text</code>, but that doesn't render child tags, as well as <code>''.join(etree.tostring(child) for child in element)</code>, but that doesn't render child text. The closest I've been a...
4
2010-01-08T14:45:03Z
2,062,262
<p>One hackish solution:</p> <pre><code>from lxml import etree def render_contents(element): """ Surely there is a safe lxml built-in for this... """ tagname = element.tag return re.sub('&lt;/%s&gt;\s*$' % tagname, '', re.sub(r'^&lt;%s(\s+\w+=".*?")*?&gt;' % tagname, ...
0
2010-01-14T04:59:54Z
[ "python", "xml", "rendering", "beautifulsoup", "lxml" ]
Equivalent of Beautiful Soup's renderContents() method in lxml?
2,028,270
<p>Is there an equivalent of Beautiful Soup's <code>tag.renderContents()</code> method in lxml?</p> <p>I've tried using <code>element.text</code>, but that doesn't render child tags, as well as <code>''.join(etree.tostring(child) for child in element)</code>, but that doesn't render child text. The closest I've been a...
4
2010-01-08T14:45:03Z
2,256,462
<p>You're most of the way there with your original idea. <code>element.text</code> gives you the first text child of the element, and your list comprehension gives you everything else. If you concatenate the two strings together, you get what you're looking for:</p> <pre><code>&gt;&gt;&gt; xmlstr = "&lt;sec&gt;header ...
1
2010-02-13T04:25:14Z
[ "python", "xml", "rendering", "beautifulsoup", "lxml" ]
Sorting a tuple of dicts
2,028,375
<p>I am new to Python and am curious if I am doing this correctly. I have a tuple of dicts (from a database call):</p> <pre><code>companies = ( { 'companyid': 1, 'companyname': 'Company C' }, { 'companyid': 2, 'companyname': 'Company A' }, { 'companyid': 3, 'companyname': 'Company B' } ) <...
3
2010-01-08T15:02:34Z
2,028,419
<p>That's fine, but you might want to consider <a href="http://wiki.python.org/moin/HowTo/Sorting#Sortingbykeys" rel="nofollow">sorting by keys</a>:</p> <pre><code>sortcompanies.sort(key=lambda x:x['companyname']) </code></pre> <p>instead. It's a little easier to read, and there will be fewer calls to <code>x['compan...
2
2010-01-08T15:07:27Z
[ "python", "sorting" ]
Sorting a tuple of dicts
2,028,375
<p>I am new to Python and am curious if I am doing this correctly. I have a tuple of dicts (from a database call):</p> <pre><code>companies = ( { 'companyid': 1, 'companyname': 'Company C' }, { 'companyid': 2, 'companyname': 'Company A' }, { 'companyid': 3, 'companyname': 'Company B' } ) <...
3
2010-01-08T15:02:34Z
2,028,422
<pre><code>&gt;&gt;&gt; companies = ( { 'companyid': 1, 'companyname': 'Company C' }, { 'companyid': 2, 'companyname': 'Company A' }, { 'companyid': 3, 'companyname': 'Company B' } ) &gt;&gt;&gt; sorted(companies, key=lambda x: x['companyname']) [{'companyname': 'Company A', 'companyid': 2}...
3
2010-01-08T15:07:54Z
[ "python", "sorting" ]
Sorting a tuple of dicts
2,028,375
<p>I am new to Python and am curious if I am doing this correctly. I have a tuple of dicts (from a database call):</p> <pre><code>companies = ( { 'companyid': 1, 'companyname': 'Company C' }, { 'companyid': 2, 'companyname': 'Company A' }, { 'companyid': 3, 'companyname': 'Company B' } ) <...
3
2010-01-08T15:02:34Z
2,028,441
<p>You could do something like:</p> <pre><code>import operator ... sortcompanies.sort(key=operator.itemgetter("companyname")) </code></pre> <p>I think that's a matter of taste.</p> <p><strong>EDIT</strong> I got <code>companyid</code> in stead of <code>companyname</code>. Corrected that error.</p>
7
2010-01-08T15:11:09Z
[ "python", "sorting" ]
Complex Django query over foreign keys
2,028,440
<p>I have two models in the same application. The application is called "News", and it has two classes in its model called "Article" and "Category".</p> <pre><code>class Category(models.Model): name = models.CharField(_("Name"), max_length=100) slug = models.SlugField(_("Slug"), max_length=100, unique=True) c...
2
2010-01-08T15:11:03Z
2,028,521
<pre><code>Article.objects.filter(archived=True).order_by('category') </code></pre> <p>i am editing this to get more info to try and help out. </p> <p>given:</p> <ul> <li>cat1 <ul> <li>art1</li> <li>art2-archived</li> <li>art3</li> </ul></li> <li>cat2 <ul> <li>art4</li> <li>art5</li> <li>art6-archived</li> </ul></li...
3
2010-01-08T15:23:47Z
[ "python", "django", "django-orm" ]
Complex Django query over foreign keys
2,028,440
<p>I have two models in the same application. The application is called "News", and it has two classes in its model called "Article" and "Category".</p> <pre><code>class Category(models.Model): name = models.CharField(_("Name"), max_length=100) slug = models.SlugField(_("Slug"), max_length=100, unique=True) c...
2
2010-01-08T15:11:03Z
2,028,921
<p>Isn't this what you want?</p> <pre><code>class Article(models.Model): category = models.ForeignKey(Category, related_name='articles') archived = models.BooleanField(default=False) categories = Category.objects.select_related("articles").filter(articles__archived=True) </code></pre>
2
2010-01-08T16:14:52Z
[ "python", "django", "django-orm" ]
Complex Django query over foreign keys
2,028,440
<p>I have two models in the same application. The application is called "News", and it has two classes in its model called "Article" and "Category".</p> <pre><code>class Category(models.Model): name = models.CharField(_("Name"), max_length=100) slug = models.SlugField(_("Slug"), max_length=100, unique=True) c...
2
2010-01-08T15:11:03Z
2,066,308
<blockquote> <blockquote> <blockquote> <p>c = Category.objects.filter(article__archived=True)</p> </blockquote> </blockquote> </blockquote>
3
2010-01-14T17:58:16Z
[ "python", "django", "django-orm" ]
Can not remove french letters in a string returned by Python glob
2,028,503
<p>I would like to rename files with french letters. I am using glob to browse the files and a function I've found on the Internet to remove the french letters. The <code>supprime_accent</code> seems to work ok. However, it doesn't rename files returned by the glob function. </p> <p>Does anybody knows what can be the ...
3
2010-01-08T15:19:48Z
2,028,523
<p>try this question and answers to it, in question I have given the final solution I am using <a href="http://stackoverflow.com/questions/1382998/latin-1-to-ascii">http://stackoverflow.com/questions/1382998/latin-1-to-ascii</a></p> <p>and pass a unicode string to glob, to get unicode file names back e.g.</p> <pre><c...
1
2010-01-08T15:23:58Z
[ "python" ]
Can not remove french letters in a string returned by Python glob
2,028,503
<p>I would like to rename files with french letters. I am using glob to browse the files and a function I've found on the Internet to remove the french letters. The <code>supprime_accent</code> seems to work ok. However, it doesn't rename files returned by the glob function. </p> <p>Does anybody knows what can be the ...
3
2010-01-08T15:19:48Z
2,028,912
<p>I've succeed to fix the problem by converting file_name to unicode with cp1252 enncoding.</p> <pre><code>for file_name in glob.glob("attachments/*.jpg"): file_name = file_name.decode(sys.getfilesystemencoding()) print unicodedata.normalize('NFKD', file_name).encode('ascii','ignore') </code></pre> <p>Edit: ...
1
2010-01-08T16:13:55Z
[ "python" ]
Can not remove french letters in a string returned by Python glob
2,028,503
<p>I would like to rename files with french letters. I am using glob to browse the files and a function I've found on the Internet to remove the french letters. The <code>supprime_accent</code> seems to work ok. However, it doesn't rename files returned by the glob function. </p> <p>Does anybody knows what can be the ...
3
2010-01-08T15:19:48Z
2,028,946
<p>I see two potential problems here.</p> <p>First, you need to use unicode strings in your source code, and you need to <a href="http://docs.python.org/tutorial/interpreter.html#source-code-encoding" rel="nofollow">tell Python what encoding the source code is in</a>. Unfortunately doing it right doubles the number of...
2
2010-01-08T16:18:44Z
[ "python" ]
Django - Allow duplicate usernames
2,028,515
<p>I'm working on a project in django which calls for having separate groups of users in their own <code>username</code> namespace. </p> <p>So for example, I might have multiple "organizations", and <code>username</code> should only have to be unique within that organization.</p> <p>I know I can do this by using ano...
8
2010-01-08T15:22:39Z
2,028,567
<p>I'm not sure if this is exactly what you're looking for, but I think you could use a hack similar to what is in <a href="http://stackoverflow.com/questions/927729/how-to-override-the-verbose-name-of-a-superclass-model-field-in-django">this answer</a>.</p> <p>The following code works, as long as it is in a place tha...
7
2010-01-08T15:29:43Z
[ "python", "django", "authentication" ]
Django - Allow duplicate usernames
2,028,515
<p>I'm working on a project in django which calls for having separate groups of users in their own <code>username</code> namespace. </p> <p>So for example, I might have multiple "organizations", and <code>username</code> should only have to be unique within that organization.</p> <p>I know I can do this by using ano...
8
2010-01-08T15:22:39Z
2,029,080
<p>I have not personally been required to find a solution to this, but one way to tackle this (from an SAAS perspective) would be to prefix the username with an organizational identifier (presuming unique organizations). For example: subdomain.yoursite.com would equate to a user with the username: subdomain_username. ...
1
2010-01-08T16:40:02Z
[ "python", "django", "authentication" ]
Django - Allow duplicate usernames
2,028,515
<p>I'm working on a project in django which calls for having separate groups of users in their own <code>username</code> namespace. </p> <p>So for example, I might have multiple "organizations", and <code>username</code> should only have to be unique within that organization.</p> <p>I know I can do this by using ano...
8
2010-01-08T15:22:39Z
2,030,103
<p>What you can do is extend the User model. For the User table, generate a username (e.g. A_123, A_345) that will not be displayed at all in the site.</p> <p>Then create a new model that extends User.</p> <pre><code>class AppUser(User): username = models.CharField... organization = models.CharField... </code...
4
2010-01-08T19:22:50Z
[ "python", "django", "authentication" ]
Django - Allow duplicate usernames
2,028,515
<p>I'm working on a project in django which calls for having separate groups of users in their own <code>username</code> namespace. </p> <p>So for example, I might have multiple "organizations", and <code>username</code> should only have to be unique within that organization.</p> <p>I know I can do this by using ano...
8
2010-01-08T15:22:39Z
17,344,403
<p>I'm facing the exact same problem and I've been reading a lot (about how to solve that problem in 1.5) and I just thought of a much simpler solution. What if you just add a fixed-length prefix with the organization id to store the username? </p> <p>I.e. Organization id = 115, chosen username = "john" and a fixed le...
0
2013-06-27T13:23:23Z
[ "python", "django", "authentication" ]
Python urllib2 Progress Hook
2,028,517
<p>I am trying to create a download progress bar in python using the urllib2 http client. I've looked through the API (and on google) and it seems that urllib2 does not allow you to register progress hooks. However the older deprecated urllib does have this functionality.</p> <p>Does anyone know how to create a progre...
26
2010-01-08T15:22:50Z
2,028,704
<p>Why not just read data in chunks and do whatever you want to do in between, e.g. run in a thread, hook into a UI, etc etc</p> <pre><code>import urllib2 urlfile = urllib2.urlopen("http://www.google.com") data_list = [] chunk = 4096 while 1: data = urlfile.read(chunk) if not data: print "done." ...
12
2010-01-08T15:48:04Z
[ "python", "http", "progress-bar", "urllib2", "httpclient" ]
Python urllib2 Progress Hook
2,028,517
<p>I am trying to create a download progress bar in python using the urllib2 http client. I've looked through the API (and on google) and it seems that urllib2 does not allow you to register progress hooks. However the older deprecated urllib does have this functionality.</p> <p>Does anyone know how to create a progre...
26
2010-01-08T15:22:50Z
2,028,745
<p><a href="http://urlgrabber.baseurl.org/">urlgrabber</a> has built-in support for progress notification.</p>
5
2010-01-08T15:53:02Z
[ "python", "http", "progress-bar", "urllib2", "httpclient" ]
Python urllib2 Progress Hook
2,028,517
<p>I am trying to create a download progress bar in python using the urllib2 http client. I've looked through the API (and on google) and it seems that urllib2 does not allow you to register progress hooks. However the older deprecated urllib does have this functionality.</p> <p>Does anyone know how to create a progre...
26
2010-01-08T15:22:50Z
2,030,027
<p>Here's a fully working example that builds on Anurag's approach of chunking in a response. My version allows you to set the the chunk size, and attach an arbitrary reporting function:</p> <pre><code>import urllib2, sys def chunk_report(bytes_so_far, chunk_size, total_size): percent = float(bytes_so_far) / total...
37
2010-01-08T19:11:23Z
[ "python", "http", "progress-bar", "urllib2", "httpclient" ]
Python urllib2 Progress Hook
2,028,517
<p>I am trying to create a download progress bar in python using the urllib2 http client. I've looked through the API (and on google) and it seems that urllib2 does not allow you to register progress hooks. However the older deprecated urllib does have this functionality.</p> <p>Does anyone know how to create a progre...
26
2010-01-08T15:22:50Z
27,971,337
<h2>Simplified version:</h2> <pre><code>temp_filename = "/tmp/" + file_url.split('/')[-1] f = open(temp_filename, 'wb') remote_file = urllib2.urlopen(file_url) try: total_size = remote_file.info().getheader('Content-Length').strip() header = True except AttributeError: header = False # a response doesn't ...
0
2015-01-15T19:22:18Z
[ "python", "http", "progress-bar", "urllib2", "httpclient" ]
Python data structures, dictionary?
2,028,723
<p>I hope somebody can help. I am using Python and I would like to be able to do the following.</p> <p>I have a set of objects (shapes for example) and a series of commands to act on these objects. The commands have the a format of a command string followed by a variable number of parameters which can be strings or in...
2
2010-01-08T15:50:56Z
2,028,774
<p>It seems to me that a command could be represented as a list <code>[]</code> or tuple <code>()</code>, and so could a series of commands. So one possibility is that you have a list of lists of strings. Generally you want to use a dictionary only when you want to look up a value by key. For example, if you knew th...
0
2010-01-08T15:56:26Z
[ "python", "dictionary" ]
Python data structures, dictionary?
2,028,723
<p>I hope somebody can help. I am using Python and I would like to be able to do the following.</p> <p>I have a set of objects (shapes for example) and a series of commands to act on these objects. The commands have the a format of a command string followed by a variable number of parameters which can be strings or in...
2
2010-01-08T15:50:56Z
2,028,783
<p><code>dicts</code> are for when the order isn't important but you want store values for different names.</p> <p><code>lists</code> are ordered sequences of objects, usually of the same type and the position doesn't mean anything particular.</p> <p><code>tuples</code> are ordered sequences of objects, possibly of d...
2
2010-01-08T15:57:34Z
[ "python", "dictionary" ]
Python data structures, dictionary?
2,028,723
<p>I hope somebody can help. I am using Python and I would like to be able to do the following.</p> <p>I have a set of objects (shapes for example) and a series of commands to act on these objects. The commands have the a format of a command string followed by a variable number of parameters which can be strings or in...
2
2010-01-08T15:50:56Z
2,028,795
<p>You might be better off creating your own class:</p> <pre><code>class Shape(object): def __init__(self): self.shape = "rectangle" self.color = "green" self.fillstyle = "hatch" # etc def ChangeColor(self, color): self.color = color # etc </code></pre>
3
2010-01-08T15:58:44Z
[ "python", "dictionary" ]
Python data structures, dictionary?
2,028,723
<p>I hope somebody can help. I am using Python and I would like to be able to do the following.</p> <p>I have a set of objects (shapes for example) and a series of commands to act on these objects. The commands have the a format of a command string followed by a variable number of parameters which can be strings or in...
2
2010-01-08T15:50:56Z
2,028,901
<p>I would suggest using an object class and storing all of the values/commands within that object so that you can pass it around easily. (Similar to what <a href="http://stackoverflow.com/users/44743/recursive">recursive</a> said). </p> <p>However; you could also use a dictionary with the key being the object name an...
1
2010-01-08T16:12:54Z
[ "python", "dictionary" ]
Python data structures, dictionary?
2,028,723
<p>I hope somebody can help. I am using Python and I would like to be able to do the following.</p> <p>I have a set of objects (shapes for example) and a series of commands to act on these objects. The commands have the a format of a command string followed by a variable number of parameters which can be strings or in...
2
2010-01-08T15:50:56Z
2,029,029
<p>What about this?</p> <h1>Example</h1> <pre><code>s = {'Rectangle': {'ChangeColor':'green','FillStyle':'hatch', 'Dimension1': 10, 'Dimension2':15}} s['Triangle'] = {'ChangeColor':'red','FillStyle':'hatch', 'Dimension1': 10, 'Dimension2':15, 'Dimension3':5} for k, v in s.iteritems(): p...
0
2010-01-08T16:31:21Z
[ "python", "dictionary" ]
Python data structures, dictionary?
2,028,723
<p>I hope somebody can help. I am using Python and I would like to be able to do the following.</p> <p>I have a set of objects (shapes for example) and a series of commands to act on these objects. The commands have the a format of a command string followed by a variable number of parameters which can be strings or in...
2
2010-01-08T15:50:56Z
2,029,742
<p>I would store the commands as a list of lists, or of tuples, depending on whether or not I thought I'd modify commands. Note that argument unpacking in Python makes for a very simple mechanism for executing these commands, e.g.:</p> <pre><code>class Shape(object): def background(self, color): print "ba...
0
2010-01-08T18:23:52Z
[ "python", "dictionary" ]
adding lighting effects to an image in python
2,028,809
<p>I want to specify a light source at a particular location in an image using Python. </p> <p>PIL's ImageEnhance module does provide a way to briten an image. but I want to have a control over light source placement to acheieve special effects. Does anyone know how to do this?</p> <p>thank you!</p>
1
2010-01-08T16:00:56Z
2,029,265
<p>So, the bad news is that PIL can't do that. I trhow a couple of ideas bellow, unfortunatelly none of which is straightforward.</p> <p>GIMP (GNU Image Manipulation Program) does have an awesome "ligthning effects" plug-in,</p> <p>GIMP is scriptable in Python, and it is possible to call teh plug-in paramtrically. T...
1
2010-01-08T17:13:05Z
[ "python", "image-processing", "python-imaging-library" ]
Django DateField default options
2,029,295
<p>I have a model which has a date time field:</p> <pre>date = models.DateField(_("Date"), default=datetime.now())</pre> <p>When I check the app in the built in django admin, the DateField also has the time appended to it, so that if you try to save it it returns an error. How do I make the default just the date? (da...
47
2010-01-08T17:18:42Z
2,029,339
<p>You mistake is using the datetime module instead of the date module. You meant to do this:</p> <pre><code>from datetime import date date = models.DateField(_("Date"), default=date.today) </code></pre> <p>If you only want to capture the current date the proper way to handle this is to use the auto_now_add paramete...
25
2010-01-08T17:23:53Z
[ "python", "django", "django-models" ]
Django DateField default options
2,029,295
<p>I have a model which has a date time field:</p> <pre>date = models.DateField(_("Date"), default=datetime.now())</pre> <p>When I check the app in the built in django admin, the DateField also has the time appended to it, so that if you try to save it it returns an error. How do I make the default just the date? (da...
47
2010-01-08T17:18:42Z
2,030,142
<p>This is why you should always import the base <code>datetime</code> module: <code>import datetime</code>, rather than the <code>datetime</code> class within that module: <code>from datetime import datetime</code>. </p> <p>The other mistake you have made is to actually call the function in the default, with the <cod...
82
2010-01-08T19:29:22Z
[ "python", "django", "django-models" ]
Django DateField default options
2,029,295
<p>I have a model which has a date time field:</p> <pre>date = models.DateField(_("Date"), default=datetime.now())</pre> <p>When I check the app in the built in django admin, the DateField also has the time appended to it, so that if you try to save it it returns an error. How do I make the default just the date? (da...
47
2010-01-08T17:18:42Z
8,365,510
<p>This should do the trick:</p> <pre><code>models.DateTimeField(_("Date"), auto_now_add = True) </code></pre>
3
2011-12-03T04:21:20Z
[ "python", "django", "django-models" ]
Django DateField default options
2,029,295
<p>I have a model which has a date time field:</p> <pre>date = models.DateField(_("Date"), default=datetime.now())</pre> <p>When I check the app in the built in django admin, the DateField also has the time appended to it, so that if you try to save it it returns an error. How do I make the default just the date? (da...
47
2010-01-08T17:18:42Z
9,089,179
<pre><code>date = models.DateTimeField(default=datetime.now, blank=True) </code></pre>
5
2012-02-01T00:36:01Z
[ "python", "django", "django-models" ]
Django DateField default options
2,029,295
<p>I have a model which has a date time field:</p> <pre>date = models.DateField(_("Date"), default=datetime.now())</pre> <p>When I check the app in the built in django admin, the DateField also has the time appended to it, so that if you try to save it it returns an error. How do I make the default just the date? (da...
47
2010-01-08T17:18:42Z
23,916,701
<p>You could also use <code>lambda</code>. Useful if you're using <a href="https://docs.djangoproject.com/en/1.6/ref/utils/#django.utils.timezone.now" rel="nofollow">django.utils.timezone.now</a></p> <pre><code>date = models.DateField(_("Date"), default=lambda: now().date()) </code></pre>
2
2014-05-28T16:07:50Z
[ "python", "django", "django-models" ]
How to prevent a module from being imported twice?
2,029,523
<p>When writing python modules, is there a way to prevent it being imported twice by the client codes? Just like the c/c++ header files do:</p> <pre><code>#ifndef XXX #define XXX ... #endif </code></pre> <p>Thanks very much!</p>
16
2010-01-08T17:49:45Z
2,029,528
<p>Imports are cached, and only run once. Additional imports only cost the lookup time in <code>sys.modules</code>.</p>
9
2010-01-08T17:50:41Z
[ "python", "import", "module" ]
How to prevent a module from being imported twice?
2,029,523
<p>When writing python modules, is there a way to prevent it being imported twice by the client codes? Just like the c/c++ header files do:</p> <pre><code>#ifndef XXX #define XXX ... #endif </code></pre> <p>Thanks very much!</p>
16
2010-01-08T17:49:45Z
2,029,546
<p>Python modules aren't imported multiple times. Just running import two times will not reload the module. If you want it to be reloaded, you have to use the <code>reload</code> statement. Here's a demo</p> <p><code>foo.py</code> is a module with the single line</p> <pre><code>print "I am being imported" </code></pr...
24
2010-01-08T17:53:34Z
[ "python", "import", "module" ]
How to prevent a module from being imported twice?
2,029,523
<p>When writing python modules, is there a way to prevent it being imported twice by the client codes? Just like the c/c++ header files do:</p> <pre><code>#ifndef XXX #define XXX ... #endif </code></pre> <p>Thanks very much!</p>
16
2010-01-08T17:49:45Z
35,917,320
<p>As specified in other answers, <em>Python</em> generally doesn't reload a module when encountering a second import statement for it. Instead, it returns its cached version from <code>sys.modules</code> without executing any of its code.</p> <p>However there are several pitfalls worth noting:</p> <ul> <li><p>Import...
3
2016-03-10T13:02:42Z
[ "python", "import", "module" ]
python - good places to check out example prog / code online?
2,029,606
<p>there is a year old, similar question - but in case there have been changes afoot:</p> <p>i'm an intermediate c++ programmer just starting out on python, post some online tuts etc i can do some basic pythoneering, but was wondering if there are good places i can look online for simple(ish) --pref console based-- co...
1
2010-01-08T18:03:23Z
2,029,622
<p>The standard library is an excellent place to the start. It's maintained by the core python team and is of high quality with a lot of interesting idioms. I'd recommend the newer modules since they don't have much backward compatibility cruft and are more representative of the language as it is now. The older ones we...
4
2010-01-08T18:06:33Z
[ "python" ]
python - good places to check out example prog / code online?
2,029,606
<p>there is a year old, similar question - but in case there have been changes afoot:</p> <p>i'm an intermediate c++ programmer just starting out on python, post some online tuts etc i can do some basic pythoneering, but was wondering if there are good places i can look online for simple(ish) --pref console based-- co...
1
2010-01-08T18:03:23Z
2,029,638
<p><a href="http://code.activestate.com/recipes/" rel="nofollow">ActiveState Recipes</a> is a good source for all kinds of Python scripts. But if you want to learn the basics of Python, you might just want to look at the standard library that ships with Python ("lib" directory").</p>
2
2010-01-08T18:08:08Z
[ "python" ]
python - good places to check out example prog / code online?
2,029,606
<p>there is a year old, similar question - but in case there have been changes afoot:</p> <p>i'm an intermediate c++ programmer just starting out on python, post some online tuts etc i can do some basic pythoneering, but was wondering if there are good places i can look online for simple(ish) --pref console based-- co...
1
2010-01-08T18:03:23Z
2,029,774
<p>i came across <a href="http://julielearnspython.wordpress.com/" rel="nofollow">This</a> The other day, Probably you can learn some python basics and have a laugh too! Anyways, look at the libs as they said above, they are very useful</p>
0
2010-01-08T18:30:09Z
[ "python" ]
python - good places to check out example prog / code online?
2,029,606
<p>there is a year old, similar question - but in case there have been changes afoot:</p> <p>i'm an intermediate c++ programmer just starting out on python, post some online tuts etc i can do some basic pythoneering, but was wondering if there are good places i can look online for simple(ish) --pref console based-- co...
1
2010-01-08T18:03:23Z
2,030,199
<p>If you enjoy riddles: <a href="http://www.pythonchallenge.com" rel="nofollow">www.pythonchallenge.com</a></p> <p>If you're an intermediate C++ programmer, you're already equipped to handle to programming concepts. I like it because it gives me a reason to learn each part of the language, without being mundane 'Hel...
0
2010-01-08T19:38:39Z
[ "python" ]
Comparing Python nested lists
2,029,795
<p>I have two nested lists, each nested list containing two strings e.g.:</p> <pre><code>list 1 [('EFG', '[3,4,5]'), ('DEF', '[2,3,4]')] and list 2 [('DEF', '[2,3,4]'), ('FGH', '[4,5,6]')] </code></pre> <p>I would like to compare the two lists and recover those nested lists which are identical with each other. In th...
2
2010-01-08T18:34:01Z
2,029,816
<p>If the lists only contain string tuples, then the easiest way to do it is using sets intersection (&amp;):</p> <pre><code>&gt;&gt;&gt; set([('EFG', '[3,4,5]'), ('DEF', '[2,3,4]')]) &amp; set([('DEF', '[2,3,4]'), ('FGH', '[4,5,6]')]) set([('DEF', '[2,3,4]')]) </code></pre>
8
2010-01-08T18:38:13Z
[ "python", "list", "nested", "intersection" ]
Comparing Python nested lists
2,029,795
<p>I have two nested lists, each nested list containing two strings e.g.:</p> <pre><code>list 1 [('EFG', '[3,4,5]'), ('DEF', '[2,3,4]')] and list 2 [('DEF', '[2,3,4]'), ('FGH', '[4,5,6]')] </code></pre> <p>I would like to compare the two lists and recover those nested lists which are identical with each other. In th...
2
2010-01-08T18:34:01Z
2,029,824
<p>Here's one approach. Convert your lists to sets and find their intersections.</p> <pre><code>&gt;&gt;&gt; a,b = set([('EFG', '[3,4,5]'), ('DEF', '[2,3,4]')]), set([('DEF', '[2,3,4]'), ('FGH', '[4,5,6]')]) &gt;&gt;&gt; print a.intersection(b) set([('DEF', '[2,3,4]')]) </code></pre> <p>I don't think it will degrade ...
0
2010-01-08T18:39:19Z
[ "python", "list", "nested", "intersection" ]
Comparing Python nested lists
2,029,795
<p>I have two nested lists, each nested list containing two strings e.g.:</p> <pre><code>list 1 [('EFG', '[3,4,5]'), ('DEF', '[2,3,4]')] and list 2 [('DEF', '[2,3,4]'), ('FGH', '[4,5,6]')] </code></pre> <p>I would like to compare the two lists and recover those nested lists which are identical with each other. In th...
2
2010-01-08T18:34:01Z
2,029,840
<p>Just use <strong>set</strong> the builtin support for sets</p> <pre><code>def get_set(list1,list2): s = set(list1) s &amp;= set(list2) return s </code></pre> <p>And <strong>Boom</strong> there's your union</p>
0
2010-01-08T18:41:43Z
[ "python", "list", "nested", "intersection" ]
Comparing Python nested lists
2,029,795
<p>I have two nested lists, each nested list containing two strings e.g.:</p> <pre><code>list 1 [('EFG', '[3,4,5]'), ('DEF', '[2,3,4]')] and list 2 [('DEF', '[2,3,4]'), ('FGH', '[4,5,6]')] </code></pre> <p>I would like to compare the two lists and recover those nested lists which are identical with each other. In th...
2
2010-01-08T18:34:01Z
2,030,394
<pre><code>intersection = [item for item in list1 if item in list2] </code></pre> <p>But only use it, if for some reason you have mutables in your lists and can’t convert to a set. Of course, it’s all depending on the size of your lists and the number of duplicates, but it could well be a factor of 10 times slower...
0
2010-01-08T20:07:42Z
[ "python", "list", "nested", "intersection" ]
Comparing Python nested lists
2,029,795
<p>I have two nested lists, each nested list containing two strings e.g.:</p> <pre><code>list 1 [('EFG', '[3,4,5]'), ('DEF', '[2,3,4]')] and list 2 [('DEF', '[2,3,4]'), ('FGH', '[4,5,6]')] </code></pre> <p>I would like to compare the two lists and recover those nested lists which are identical with each other. In th...
2
2010-01-08T18:34:01Z
2,030,515
<p>Using sets to do this is a very good implementation, but for optimal performance you should use only <em>one</em> set:</p> <pre><code>set1 = set([('EFG', '[3,4,5]'), ('DEF', '[2,3,4]')]) matches = [x for x in [('DEF', '[2,3,4]'), ('FGH', '[4,5,6]')] if x in set1] </code></pre>
3
2010-01-08T20:29:12Z
[ "python", "list", "nested", "intersection" ]
Comparing Python nested lists
2,029,795
<p>I have two nested lists, each nested list containing two strings e.g.:</p> <pre><code>list 1 [('EFG', '[3,4,5]'), ('DEF', '[2,3,4]')] and list 2 [('DEF', '[2,3,4]'), ('FGH', '[4,5,6]')] </code></pre> <p>I would like to compare the two lists and recover those nested lists which are identical with each other. In th...
2
2010-01-08T18:34:01Z
13,845,997
<pre><code> python 3.2 [i for i in list1 for v in list2 if i==v] </code></pre>
0
2012-12-12T18:11:45Z
[ "python", "list", "nested", "intersection" ]
Keeping track of changes since the last save in django models
2,029,814
<p>A couple of times I've run into a situation, when at save time I need to know which model fields are going to be updated and act accordingly.</p> <p>The most obvious solution to this is to take the primary key field and retrieve a copy of the model from the database:</p> <pre><code>class MyModel(models.Model): ...
9
2010-01-08T18:37:49Z
2,030,006
<p>I think your solution looks reasonable.</p> <p>Alternatively you could have a Manager method called <code>get_and_copy()</code> (or something) that hung a copy of the original object off of what is returned. You could then use another Manager method, <code>save_and_check()</code> which took advantage of the copied ...
2
2010-01-08T19:07:41Z
[ "python", "django", "django-models" ]
Keeping track of changes since the last save in django models
2,029,814
<p>A couple of times I've run into a situation, when at save time I need to know which model fields are going to be updated and act accordingly.</p> <p>The most obvious solution to this is to take the primary key field and retrieve a copy of the model from the database:</p> <pre><code>class MyModel(models.Model): ...
9
2010-01-08T18:37:49Z
5,380,027
<p>This will not work for fixtures. <code>loaddata</code> command uses <code>models.Model.base_save</code>. Probably the cleanest method would be to use descriptors for fields, but one has to figure out how to inset them properly.</p>
0
2011-03-21T15:42:36Z
[ "python", "django", "django-models" ]
Install Plone egg as a Python module on Windows
2,029,826
<p>I have a Plone site (Plone version 3.1.2) that I need to install a product called GrufSpaces on - (<a href="http://plone.org/products/grufspaces" rel="nofollow">http://plone.org/products/grufspaces</a>). However, it is a production site and so I can't easily take it down to upgrade Plone to 3.2+ in order to use buil...
0
2010-01-08T18:39:39Z
2,038,150
<p>Did you check GrufSpaces' INSTALL.TXT? From there:</p> <blockquote> <p>Unpack it into your Zope Products Folder</p> </blockquote> <p>For Plone, the easiest way is probably to unpack it the top level <code>products</code> folder.</p> <p>See also <a href="http://plone.org/documentation/kb/third-party-products/ins...
1
2010-01-10T18:58:32Z
[ "python", "plone", "zope", "plone-3.x" ]
Install Plone egg as a Python module on Windows
2,029,826
<p>I have a Plone site (Plone version 3.1.2) that I need to install a product called GrufSpaces on - (<a href="http://plone.org/products/grufspaces" rel="nofollow">http://plone.org/products/grufspaces</a>). However, it is a production site and so I can't easily take it down to upgrade Plone to 3.2+ in order to use buil...
0
2010-01-08T18:39:39Z
2,038,156
<p>If you are trying to install GrufSpaces 2.0 then you should consider upgrading to Plone 3.3 (see the <a href="https://svn.plone.org/svn/collective/GrufSpaces/tags/v2_0/INSTALL.txt" rel="nofollow">install requirements</a>)</p> <p>Placing the collective.* packages to <code>[plone directory]/Zope/lib/python</code> sho...
1
2010-01-10T18:59:07Z
[ "python", "plone", "zope", "plone-3.x" ]
Install Plone egg as a Python module on Windows
2,029,826
<p>I have a Plone site (Plone version 3.1.2) that I need to install a product called GrufSpaces on - (<a href="http://plone.org/products/grufspaces" rel="nofollow">http://plone.org/products/grufspaces</a>). However, it is a production site and so I can't easily take it down to upgrade Plone to 3.2+ in order to use buil...
0
2010-01-08T18:39:39Z
2,040,311
<p>No advice specific to GruffSpaces as I've never used it but it sounds like you may be under the mistaken impression that you need Plone 3.2+ for buildout. This is incorrect. Buildout works just fine with Plone 3.1.2. I've also done buildouts for Plone 2.5.5 and even one for Plone 2.1 (although this last one was a...
1
2010-01-11T06:36:20Z
[ "python", "plone", "zope", "plone-3.x" ]
Writing a LaTeX document with Python code snippets
2,029,957
<p>I am using LaTeX to write a document about Python. This document will contain code snippets (examples).</p> <p>I could use the <code>verbatim</code> environment, but before I embark onto it, I'd like to know if you are aware of any LaTeX style file which provides an environment for Python code. Syntax highlight wou...
8
2010-01-08T19:01:45Z
2,029,980
<p>Use Docutils and RST for this. It has Latex with Syntax highlighting.</p> <p><a href="http://docutils.sourceforge.net/docs/user/latex.html" rel="nofollow">http://docutils.sourceforge.net/docs/user/latex.html</a></p>
2
2010-01-08T19:04:24Z
[ "python", "latex" ]
Writing a LaTeX document with Python code snippets
2,029,957
<p>I am using LaTeX to write a document about Python. This document will contain code snippets (examples).</p> <p>I could use the <code>verbatim</code> environment, but before I embark onto it, I'd like to know if you are aware of any LaTeX style file which provides an environment for Python code. Syntax highlight wou...
8
2010-01-08T19:01:45Z
2,030,029
<p>The LaTeX Listings package seems to know about Python. Worth taking a look at.</p> <p>Mark</p>
2
2010-01-08T19:11:34Z
[ "python", "latex" ]
Writing a LaTeX document with Python code snippets
2,029,957
<p>I am using LaTeX to write a document about Python. This document will contain code snippets (examples).</p> <p>I could use the <code>verbatim</code> environment, but before I embark onto it, I'd like to know if you are aware of any LaTeX style file which provides an environment for Python code. Syntax highlight wou...
8
2010-01-08T19:01:45Z
2,030,051
<p>Take a look at this question <a href="http://stackoverflow.com/questions/1966425/source-code-highlighting-in-latex">http://stackoverflow.com/questions/1966425/source-code-highlighting-in-latex</a> for more information.</p> <p>You should also look at the <a href="http://pygments.org/">pygments</a> program for source...
5
2010-01-08T19:15:22Z
[ "python", "latex" ]
Random strings in Python
2,030,053
<p>How do you create a random string in Python?</p> <p>I needed it to be number then character repeat till you're done this is what I created</p> <pre><code>def random_id(length): number = '0123456789' alpha = 'abcdefghijklmnopqrstuvwxyz' id = '' for i in range(0,length,2): id += random.choice...
43
2010-01-08T19:15:47Z
2,030,072
<p>You can build random ascii characters like:</p> <pre><code>import random print chr(random.randint(0,255)) </code></pre> <p>And then build up a longer string like:</p> <pre><code>len = 50 print ''.join( [chr(random.randint(0,255)) for i in xrange(0,len)] ) </code></pre>
4
2010-01-08T19:18:33Z
[ "python" ]
Random strings in Python
2,030,053
<p>How do you create a random string in Python?</p> <p>I needed it to be number then character repeat till you're done this is what I created</p> <pre><code>def random_id(length): number = '0123456789' alpha = 'abcdefghijklmnopqrstuvwxyz' id = '' for i in range(0,length,2): id += random.choice...
43
2010-01-08T19:15:47Z
2,030,081
<p>Generating strings from (for example) lowercase characters:</p> <pre><code>import random, string def randomword(length): return ''.join(random.choice(string.lowercase) for i in range(length)) </code></pre> <p>Results:</p> <pre><code>&gt;&gt;&gt; randomword(10) 'vxnxikmhdc' &gt;&gt;&gt; randomword(10) 'ytqhdoh...
109
2010-01-08T19:19:40Z
[ "python" ]
Random strings in Python
2,030,053
<p>How do you create a random string in Python?</p> <p>I needed it to be number then character repeat till you're done this is what I created</p> <pre><code>def random_id(length): number = '0123456789' alpha = 'abcdefghijklmnopqrstuvwxyz' id = '' for i in range(0,length,2): id += random.choice...
43
2010-01-08T19:15:47Z
2,030,109
<p>You haven't really said much about what sort of random string you need. But in any case, you should look into the <code>random</code> module.</p> <p>A very simple solution is pasted below.</p> <pre><code>import random def randstring(length=10): valid_letters='ABCDEFGHIJKLMNOPQRSTUVWXYZ' return ''.join((ra...
2
2010-01-08T19:23:27Z
[ "python" ]
Random strings in Python
2,030,053
<p>How do you create a random string in Python?</p> <p>I needed it to be number then character repeat till you're done this is what I created</p> <pre><code>def random_id(length): number = '0123456789' alpha = 'abcdefghijklmnopqrstuvwxyz' id = '' for i in range(0,length,2): id += random.choice...
43
2010-01-08T19:15:47Z
2,030,156
<p>Since this question is fairly, uh, random, this may work for you: </p> <pre><code>&gt;&gt;&gt; import uuid &gt;&gt;&gt; print uuid.uuid4() 58fe9784-f60a-42bc-aa94-eb8f1a7e5c17 </code></pre>
25
2010-01-08T19:32:04Z
[ "python" ]
Random strings in Python
2,030,053
<p>How do you create a random string in Python?</p> <p>I needed it to be number then character repeat till you're done this is what I created</p> <pre><code>def random_id(length): number = '0123456789' alpha = 'abcdefghijklmnopqrstuvwxyz' id = '' for i in range(0,length,2): id += random.choice...
43
2010-01-08T19:15:47Z
2,030,293
<pre><code>&gt;&gt;&gt; import random &gt;&gt;&gt; import string &gt;&gt;&gt; s=string.lowercase+string.digits &gt;&gt;&gt; ''.join(random.sample(s,10)) 'jw72qidagk </code></pre>
20
2010-01-08T19:53:22Z
[ "python" ]
Random strings in Python
2,030,053
<p>How do you create a random string in Python?</p> <p>I needed it to be number then character repeat till you're done this is what I created</p> <pre><code>def random_id(length): number = '0123456789' alpha = 'abcdefghijklmnopqrstuvwxyz' id = '' for i in range(0,length,2): id += random.choice...
43
2010-01-08T19:15:47Z
18,172,468
<p>Answer to the original question:</p> <pre><code>os.urandom(n) </code></pre> <p>Quote from: <a href="http://docs.python.org/2/library/os.html">http://docs.python.org/2/library/os.html</a></p> <blockquote> <p>Return a string of n random bytes suitable for cryptographic use.</p> <p>This function returns rando...
8
2013-08-11T13:34:56Z
[ "python" ]
Random strings in Python
2,030,053
<p>How do you create a random string in Python?</p> <p>I needed it to be number then character repeat till you're done this is what I created</p> <pre><code>def random_id(length): number = '0123456789' alpha = 'abcdefghijklmnopqrstuvwxyz' id = '' for i in range(0,length,2): id += random.choice...
43
2010-01-08T19:15:47Z
30,380,814
<pre><code>random_name = lambda length: ''.join(random.sample(string.letters, length)) </code></pre> <p>length must be &lt;= len(string.letters) = 53. result example </p> <pre><code> &gt;&gt;&gt; [random_name(x) for x in range(1,20)] ['V', 'Rq', 'YtL', 'AmUF', 'loFdS', 'eNpRFy', 'iWFGtDz', 'ZTNgCvLA', 'fjUDXJvMP', ...
0
2015-05-21T17:42:36Z
[ "python" ]
How to get current_app for using with reverse in multi-deployable reusable Django application?
2,030,225
<p>I'm writing reusable app. And I want to deploy it several times.</p> <p>Here is urls.py:</p> <pre><code>urlpatterns = patterns('', (r'^carphotos/', include('webui.photos.urls', app_name='car-photos') ), (r'^userphotos/', include('webui.photos.urls', app_name='profile-photos') ),) </code></pre> <p>and photos/urls...
8
2010-01-08T19:44:14Z
2,030,245
<p>I believe that's what the <a href="http://docs.djangoproject.com/en/dev/ref/contrib/sites/" rel="nofollow"><code>sites</code></a> framework is for.</p>
-3
2010-01-08T19:46:22Z
[ "python", "django", "django-urls" ]
How to get current_app for using with reverse in multi-deployable reusable Django application?
2,030,225
<p>I'm writing reusable app. And I want to deploy it several times.</p> <p>Here is urls.py:</p> <pre><code>urlpatterns = patterns('', (r'^carphotos/', include('webui.photos.urls', app_name='car-photos') ), (r'^userphotos/', include('webui.photos.urls', app_name='profile-photos') ),) </code></pre> <p>and photos/urls...
8
2010-01-08T19:44:14Z
2,031,177
<p>In your urls, you have a different <code>app_name</code> even though it's the same app. Set the <code>app_name</code> to the same thing, and set <code>namespace</code> uniquely for each instance. eg.</p> <pre><code>urlpatterns = patterns('', (r'^carphotos/', include('webui.photos.urls', app_name="webui_photos", nam...
1
2010-01-08T22:21:30Z
[ "python", "django", "django-urls" ]
How to get current_app for using with reverse in multi-deployable reusable Django application?
2,030,225
<p>I'm writing reusable app. And I want to deploy it several times.</p> <p>Here is urls.py:</p> <pre><code>urlpatterns = patterns('', (r'^carphotos/', include('webui.photos.urls', app_name='car-photos') ), (r'^userphotos/', include('webui.photos.urls', app_name='profile-photos') ),) </code></pre> <p>and photos/urls...
8
2010-01-08T19:44:14Z
2,040,601
<p>After exploring this topic for several days, I found that it isn't natural to mount django app more than once. </p> <p>There is implementation of pluggable applications pattern: <a href="http://github.com/nowells/django-pluggables" rel="nofollow">http://github.com/nowells/django-pluggables</a>. It looks too tricky ...
-3
2010-01-11T08:19:46Z
[ "python", "django", "django-urls" ]
How to get current_app for using with reverse in multi-deployable reusable Django application?
2,030,225
<p>I'm writing reusable app. And I want to deploy it several times.</p> <p>Here is urls.py:</p> <pre><code>urlpatterns = patterns('', (r'^carphotos/', include('webui.photos.urls', app_name='car-photos') ), (r'^userphotos/', include('webui.photos.urls', app_name='profile-photos') ),) </code></pre> <p>and photos/urls...
8
2010-01-08T19:44:14Z
13,249,060
<p>I know this is a pretty old question... but I think I found a solution:</p> <p>As Will Hardy suggested you'll have to keep <code>app_name</code> the same for both instances (or not define it at all, it will default to the app the included urls reside in). Define a separate namespace for each app instance though:</p...
10
2012-11-06T10:28:52Z
[ "python", "django", "django-urls" ]
Project Euler #101 - how to work around numpy polynomial overflow?
2,030,422
<p><a href="http://projecteuler.net/index.php?section=problems&amp;id=101" rel="nofollow">Project Euler #101</a></p> <p>I just started learning Numpy and it so far looks pretty straightforward to me.</p> <p>One thing I ran into is that when I evaluate the polynomial, the result is a int32, so an overflow would occur....
2
2010-01-08T20:12:46Z
2,030,493
<p>It wasn't the scaling by 100 that helped, but the fact that the numbers given were floats instead of ints, and thus had a higher range. Due to the floating-point calculations, there are some inaccuracies introduced to the calculations as you have seen.</p> <p>You can specify the type manually like this:</p> <pre><...
4
2010-01-08T20:24:51Z
[ "python", "numpy" ]
Project Euler #101 - how to work around numpy polynomial overflow?
2,030,422
<p><a href="http://projecteuler.net/index.php?section=problems&amp;id=101" rel="nofollow">Project Euler #101</a></p> <p>I just started learning Numpy and it so far looks pretty straightforward to me.</p> <p>One thing I ran into is that when I evaluate the polynomial, the result is a int32, so an overflow would occur....
2
2010-01-08T20:12:46Z
2,030,642
<p>Interjay posted a better answer while I was writing this up, but I figured you might want an alternative anyway.</p> <p>Here's a simple implementation for the examples you showed:</p> <pre><code>class Poly(object): def __init__(self, coefficients): assert len(coefficients) &gt; 0 self.coefficie...
0
2010-01-08T20:51:09Z
[ "python", "numpy" ]
How do I ignore lines using difflib.ndiff?
2,030,551
<p>According to the documentation, you can provide a linejunk function to ignore certian lines. However, I can't get it to work. Here is some sample code for discussion:</p> <pre><code>from re import search from difflib import ndiff t1 = 'one 1\ntwo 2\nthree 3' t2 = 'one 1\ntwo 29\nthree 3' diff = ndiff(t1.splitlin...
1
2010-01-08T20:34:56Z
2,031,474
<p>Your example has a problem: the first two arguments to ndiff should each be a list of strings; you have a single string which is treated just like a list of characters. See <a href="http://docs.python.org/library/difflib.html#difflib.ndiff" rel="nofollow">the docs</a>. Use e.g. <code>t1 = 'one 1\ntwo 2\nthree 3'.spl...
0
2010-01-08T23:21:16Z
[ "python" ]
How do I ignore lines using difflib.ndiff?
2,030,551
<p>According to the documentation, you can provide a linejunk function to ignore certian lines. However, I can't get it to work. Here is some sample code for discussion:</p> <pre><code>from re import search from difflib import ndiff t1 = 'one 1\ntwo 2\nthree 3' t2 = 'one 1\ntwo 29\nthree 3' diff = ndiff(t1.splitlin...
1
2010-01-08T20:34:56Z
24,588,672
<p>I've recently met with the same problem.</p> <p>Here's what I've found out:</p> <p>cf. <a href="http://bugs.python.org/issue14332" rel="nofollow">http://bugs.python.org/issue14332</a></p> <blockquote> <p>The main intent of the *junk parameters is to speed up matching to find differences, not to mask differenc...
0
2014-07-05T16:59:45Z
[ "python" ]
Logging into facebook with python
2,030,652
<p>If I run the following code 10 times in a row, it will work about half the time and fail the rest. Anyone know why?</p> <pre><code>import urllib2, cookielib, re, os, sys class Facebook(): def __init__(self, email, password): self.email = email self.password = password cj = cookielib.Co...
4
2010-01-08T20:52:38Z
2,030,823
<p>Maybe Facebook limits the maximum number of login attempts per minute. It's just a guess. </p>
0
2010-01-08T21:21:02Z
[ "python" ]
Logging into facebook with python
2,030,652
<p>If I run the following code 10 times in a row, it will work about half the time and fail the rest. Anyone know why?</p> <pre><code>import urllib2, cookielib, re, os, sys class Facebook(): def __init__(self, email, password): self.email = email self.password = password cj = cookielib.Co...
4
2010-01-08T20:52:38Z
2,031,690
<p>Okay, I think I found the answer by basically looking at the response data.</p> <p>"Logout" does not exist - at least for me -, yet, "Log out" and "logout" does (the later appears as <code>logout.php</code>, which probably won't change on different locales). So, for your particular issue, just replace <code>"Log ou...
0
2010-01-09T00:15:44Z
[ "python" ]
Logging into facebook with python
2,030,652
<p>If I run the following code 10 times in a row, it will work about half the time and fail the rest. Anyone know why?</p> <pre><code>import urllib2, cookielib, re, os, sys class Facebook(): def __init__(self, email, password): self.email = email self.password = password cj = cookielib.Co...
4
2010-01-08T20:52:38Z
3,846,516
<p>I've run into the same problem. The only solution I found was... that facebook mobile is more stable.</p> <pre><code>class Acc: jar = cookielib.CookieJar() cookie = urllib2.HTTPCookieProcessor(jar) opener = urllib2.build_opener(cookie) headers = { "User-Agent" : "Mozilla/5.0 (X11; U;...
5
2010-10-02T16:08:39Z
[ "python" ]
Logging into facebook with python
2,030,652
<p>If I run the following code 10 times in a row, it will work about half the time and fail the rest. Anyone know why?</p> <pre><code>import urllib2, cookielib, re, os, sys class Facebook(): def __init__(self, email, password): self.email = email self.password = password cj = cookielib.Co...
4
2010-01-08T20:52:38Z
5,253,853
<p>The fix worked for me, every time. Then I wanted to actually read the content of the page after logging in. For this, I added a 'print usock.read()' right after 'print 'Logged in'', but that returned an empty string. I guessed it's because usock is getting called twice, so I just modified the first call to usock:</p...
1
2011-03-09T23:56:18Z
[ "python" ]
Logging into facebook with python
2,030,652
<p>If I run the following code 10 times in a row, it will work about half the time and fail the rest. Anyone know why?</p> <pre><code>import urllib2, cookielib, re, os, sys class Facebook(): def __init__(self, email, password): self.email = email self.password = password cj = cookielib.Co...
4
2010-01-08T20:52:38Z
11,026,989
<p>So I tried your code, and got it to log in once, then like you I had trouble logging in again. On a line before the 'if' statement, I added print usock.read() and ended up getting a bunch of html code. I then dropped that code into a notepad, saved it as an html file, and pulled it up. This is what's happening: Fac...
15
2012-06-14T05:11:01Z
[ "python" ]
Python Image Library produces a crappy quality jpeg when I resize a picture
2,030,871
<p>I use the Python Image Library (PIL) to resize an image and create a thumbnail. Why is it that my code produces an image that is so crappy and low-quality? Can someone tell me how to modify the code so that it's the highest quality JPEG?</p> <pre><code>def create_thumbnail(buffer, width=100, height=100): im = I...
4
2010-01-08T21:27:44Z
2,030,905
<p><a href="http://www.pythonware.com/library/pil/handbook/format-jpeg.htm">Documentation sayyyyys</a>:</p> <pre><code>im.save(thumbnail_file, 'JPEG', quality=90) </code></pre>
13
2010-01-08T21:32:20Z
[ "python", "image", "file", "encoding", "python-imaging-library" ]
Debugging Django Forms validation errors
2,030,896
<p>One of my forms fails on form.is_valid()</p> <p>First time I debug a Django form so I am not too sure where to look</p> <p>forms.py</p> <pre><code>class ImageForm(forms.ModelForm): def __init__(self,user,*args,**kwargs): super(ImageForm,self ).__init__(*args,**kwargs) # populates the form class Meta: mod...
2
2010-01-08T21:31:14Z
2,031,629
<p>You really should learn how to use debugger with Django and it's built in server- it has saved me lot's of print/dir expressions and endless edit-run-observe output-edit iterations.</p> <p>The most basic way to debug python applications is by using <a href="http://docs.python.org/library/pdb.html" rel="nofollow">pd...
4
2010-01-08T23:56:00Z
[ "python", "django", "django-forms" ]
Python Matplotlib rectangular binning
2,030,970
<p>I've got a series of (x,y) values that I want to plot a 2d histogram of using python's matplotlib. Using hexbin, I get something like this: <img src="http://img121.imageshack.us/img121/1339/hexbin.png" alt="alt text"> But I'm looking for something like this: <img src="http://img17.imageshack.us/img17/1927/recthist.p...
17
2010-01-08T21:44:26Z
2,031,844
<p>Is <code>matplotlib.pyplot.hist</code> what you're looking for? </p> <pre><code>&gt;&gt;&gt; help(matplotlib.pyplot.hist) Help on function hist in module matplotlib.pyplot: hist(x, bins=10, range=None, normed=False, weights=None, cumulative=False, botto m=None, histtype='bar', align='mid', orientation='vertical', ...
0
2010-01-09T00:54:15Z
[ "python", "matplotlib", "histogram" ]
Python Matplotlib rectangular binning
2,030,970
<p>I've got a series of (x,y) values that I want to plot a 2d histogram of using python's matplotlib. Using hexbin, I get something like this: <img src="http://img121.imageshack.us/img121/1339/hexbin.png" alt="alt text"> But I'm looking for something like this: <img src="http://img17.imageshack.us/img17/1927/recthist.p...
17
2010-01-08T21:44:26Z
2,072,868
<p>Numpy has a function called <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.histogram2d.html">histogram2d</a>, whose docstring also shows you how to visualize it using Matplotlib. Add <code>interpolation=nearest</code> to the imshow call to disable the interpolation.</p>
12
2010-01-15T15:57:15Z
[ "python", "matplotlib", "histogram" ]
Python Matplotlib rectangular binning
2,030,970
<p>I've got a series of (x,y) values that I want to plot a 2d histogram of using python's matplotlib. Using hexbin, I get something like this: <img src="http://img121.imageshack.us/img121/1339/hexbin.png" alt="alt text"> But I'm looking for something like this: <img src="http://img17.imageshack.us/img17/1927/recthist.p...
17
2010-01-08T21:44:26Z
4,221,667
<p>Use <code>xlim</code> and <code>ylim</code> to set the limits of the plot. <code>xlim(-3, 3)</code> and <code>ylim(-3, 3)</code> should do it.</p>
0
2010-11-19T02:44:42Z
[ "python", "matplotlib", "histogram" ]
Python Matplotlib rectangular binning
2,030,970
<p>I've got a series of (x,y) values that I want to plot a 2d histogram of using python's matplotlib. Using hexbin, I get something like this: <img src="http://img121.imageshack.us/img121/1339/hexbin.png" alt="alt text"> But I'm looking for something like this: <img src="http://img17.imageshack.us/img17/1927/recthist.p...
17
2010-01-08T21:44:26Z
9,915,927
<p>I just submitted a pull request for this <a href="https://github.com/matplotlib/matplotlib/pull/805" rel="nofollow">https://github.com/matplotlib/matplotlib/pull/805</a> . Hopefully, it will be accepted.</p>
1
2012-03-28T21:28:58Z
[ "python", "matplotlib", "histogram" ]
Python Matplotlib rectangular binning
2,030,970
<p>I've got a series of (x,y) values that I want to plot a 2d histogram of using python's matplotlib. Using hexbin, I get something like this: <img src="http://img121.imageshack.us/img121/1339/hexbin.png" alt="alt text"> But I'm looking for something like this: <img src="http://img17.imageshack.us/img17/1927/recthist.p...
17
2010-01-08T21:44:26Z
10,854,768
<p>I realize that there is a patch submitted to matplotlib, but I adopted the code from the other example to acommodate a few needs that I had.</p> <p>now the histogram is plotted from the lower left corner, as in conventional math (not computing)</p> <p>also, values outside the binning range are ignored and I use a ...
1
2012-06-01T17:22:58Z
[ "python", "matplotlib", "histogram" ]
In Python, how can I put a thread to sleep until a specific time?
2,031,111
<p>I know that I can cause a thread to sleep for a specific amount of time with:</p> <pre><code>time.sleep(NUM) </code></pre> <p>How can I make a thread sleep until 2AM? Do I have to do math to determine the number of seconds until 2AM? Or is there some library function?</p> <p>( Yes, I know about cron and equival...
21
2010-01-08T22:10:52Z
2,031,297
<p>Here's a half-ass solution that doesn't account for clock jitter or adjustment of the clock. See comments for ways to get rid of that.</p> <pre><code>import time import datetime # if for some reason this script is still running # after a year, we'll stop after 365 days for i in xrange(0,365): # sleep until 2A...
19
2010-01-08T22:42:03Z
[ "python" ]
In Python, how can I put a thread to sleep until a specific time?
2,031,111
<p>I know that I can cause a thread to sleep for a specific amount of time with:</p> <pre><code>time.sleep(NUM) </code></pre> <p>How can I make a thread sleep until 2AM? Do I have to do math to determine the number of seconds until 2AM? Or is there some library function?</p> <p>( Yes, I know about cron and equival...
21
2010-01-08T22:10:52Z
2,031,505
<p>One possible approach is to sleep for an hour. Every hour, check if the time is in the middle of the night. If so, proceed with your operation. If not, sleep for another hour and continue.</p> <p>If the user were to change their clock in the middle of the day, this approach would reflect that change. While it requi...
2
2010-01-08T23:27:55Z
[ "python" ]
In Python, how can I put a thread to sleep until a specific time?
2,031,111
<p>I know that I can cause a thread to sleep for a specific amount of time with:</p> <pre><code>time.sleep(NUM) </code></pre> <p>How can I make a thread sleep until 2AM? Do I have to do math to determine the number of seconds until 2AM? Or is there some library function?</p> <p>( Yes, I know about cron and equival...
21
2010-01-08T22:10:52Z
7,739,273
<p>Slightly beside the point of the original question:</p> <p>Even if you don't want to muck around with crontabs, if you can schedule python scripts to those hosts, you might be interested to schedule anacron tasks? anacron's major differentiator to cron is that it does not rely the computer to run continuously. Depe...
0
2011-10-12T11:22:07Z
[ "python" ]
In Python, how can I put a thread to sleep until a specific time?
2,031,111
<p>I know that I can cause a thread to sleep for a specific amount of time with:</p> <pre><code>time.sleep(NUM) </code></pre> <p>How can I make a thread sleep until 2AM? Do I have to do math to determine the number of seconds until 2AM? Or is there some library function?</p> <p>( Yes, I know about cron and equival...
21
2010-01-08T22:10:52Z
26,188,836
<pre><code>from datetime import datetime import time, operator time.sleep([i[0]*3600 + i[1]*60 for i in [[H, M]]][0] - [i[0]*3600 + i[1]*60 for i in [map(int, datetime.now().strftime("%H:%M").split(':'))]][0]) </code></pre>
-3
2014-10-04T01:46:15Z
[ "python" ]
In Python, how can I put a thread to sleep until a specific time?
2,031,111
<p>I know that I can cause a thread to sleep for a specific amount of time with:</p> <pre><code>time.sleep(NUM) </code></pre> <p>How can I make a thread sleep until 2AM? Do I have to do math to determine the number of seconds until 2AM? Or is there some library function?</p> <p>( Yes, I know about cron and equival...
21
2010-01-08T22:10:52Z
31,929,804
<pre><code>import pause from datetime import datetime pause.until(datetime(2015, 8, 12, 2)) </code></pre>
4
2015-08-10T21:51:46Z
[ "python" ]
In Python, how can I put a thread to sleep until a specific time?
2,031,111
<p>I know that I can cause a thread to sleep for a specific amount of time with:</p> <pre><code>time.sleep(NUM) </code></pre> <p>How can I make a thread sleep until 2AM? Do I have to do math to determine the number of seconds until 2AM? Or is there some library function?</p> <p>( Yes, I know about cron and equival...
21
2010-01-08T22:10:52Z
32,547,148
<p>I tried the "pause" pacakage. It does not work for Python 3.x. From the pause package I extracted the code required to wait until a specific datetime and made the following def.</p> <pre><code>def wait_until(execute_it_now): while True: diff = (execute_it_now - datetime.now()).total_seconds() if...
0
2015-09-13T07:02:01Z
[ "python" ]
Detect if a process is already running and collaborate with it
2,031,121
<p>I'm trying to create a program that starts a process pool of, say, 5 processes, performs some operation, and then quits, but leaves the 5 processes open. Later the user can run the program again, and instead of it starting new processes it uses the existing 5. Basically it's a producer-consumer model where:</p> <...
8
2010-01-08T22:12:53Z
2,031,615
<p>Take a look at these different Service Discovery mechanisms: <a href="http://en.wikipedia.org/wiki/Service_discovery" rel="nofollow">http://en.wikipedia.org/wiki/Service_discovery</a></p> <p>The basic idea is that the consumers would each register a service when they start. The producer would go through the discov...
1
2010-01-08T23:53:12Z
[ "python", "multiprocessing" ]
Detect if a process is already running and collaborate with it
2,031,121
<p>I'm trying to create a program that starts a process pool of, say, 5 processes, performs some operation, and then quits, but leaves the 5 processes open. Later the user can run the program again, and instead of it starting new processes it uses the existing 5. Basically it's a producer-consumer model where:</p> <...
8
2010-01-08T22:12:53Z
2,032,098
<p>There are a couple of common ways to do your item #1 (detecting running processes), but to use them would first require that you slightly tweak your mental picture of how these background processes are started by the first invocation of the program.</p> <p>Think of the first program not as starting the five process...
2
2010-01-09T02:16:40Z
[ "python", "multiprocessing" ]
Detect if a process is already running and collaborate with it
2,031,121
<p>I'm trying to create a program that starts a process pool of, say, 5 processes, performs some operation, and then quits, but leaves the 5 processes open. Later the user can run the program again, and instead of it starting new processes it uses the existing 5. Basically it's a producer-consumer model where:</p> <...
8
2010-01-08T22:12:53Z
2,032,284
<p>You need a client-server model on a local system. You could do this using TCP/IP sockets to communicate between your clients and servers, but it's faster to use local named pipes if you don't have the need to communicate over a network.</p> <p>The basic requirements for you if I understood correctly are these: <br/...
1
2010-01-09T03:50:15Z
[ "python", "multiprocessing" ]
Using python's map() with multiple args?
2,031,216
<p>Okay, so I've got a piece of Python code which really needs optimizing.</p> <p>I need to iterate over every single pixel of a small (80x60) image and extract the RGB values from it. The code in the loop itself isn't too slow, but I'm doing it using nested for loops, which I assume add quite a bit of overhead...</p>...
1
2010-01-08T22:27:39Z
2,031,266
<p>What's making your code slow is probably not the loops, they are incredibly fast.</p> <p>What slows done your code are the number of function calls. For example</p> <pre><code>pixelR = get_at((x,y))[0] pixelG = get_at((x,y))[1] pixelB = get_at((x,y))[2] </code></pre> <p>is <em>a lot</em> slower than (about 3 time...
3
2010-01-08T22:37:27Z
[ "python", "optimization", "map", "loops", "nested" ]
Using python's map() with multiple args?
2,031,216
<p>Okay, so I've got a piece of Python code which really needs optimizing.</p> <p>I need to iterate over every single pixel of a small (80x60) image and extract the RGB values from it. The code in the loop itself isn't too slow, but I'm doing it using nested for loops, which I assume add quite a bit of overhead...</p>...
1
2010-01-08T22:27:39Z
2,031,388
<pre><code>map(do_stuff, ((x, y) for x in xrange(80) for y in xrange(60))) </code></pre> <p>where <code>do_stuff</code> would presumably be defined like so:</p> <pre><code>def do_stuff(coords): r, g, b, a = get_at(coords) # ... whatever you need to do with those ... set_at(coords, (r, g, b)) </code></pre>...
2
2010-01-08T23:00:48Z
[ "python", "optimization", "map", "loops", "nested" ]
Using python's map() with multiple args?
2,031,216
<p>Okay, so I've got a piece of Python code which really needs optimizing.</p> <p>I need to iterate over every single pixel of a small (80x60) image and extract the RGB values from it. The code in the loop itself isn't too slow, but I'm doing it using nested for loops, which I assume add quite a bit of overhead...</p>...
1
2010-01-08T22:27:39Z
2,031,608
<p>Since you are reading and rewriting <em>every</em> pixel, I think you can get the best speed improvement by not using a <code>Surface</code>.</p> <p>I suggest first taking your 80x60 image and converting it to a plain bitmap file with 32-bit pixels. Then read the pixel data into a python <a href="http://docs.pytho...
1
2010-01-08T23:52:30Z
[ "python", "optimization", "map", "loops", "nested" ]
Python logging over multiple files
2,031,394
<p>I've read through the logging module documentation and whilst I may have missed something obvious, the code I've got doesn't appear to be working as intended. I'm using Python 2.6.4.</p> <p>My program consists of several different python files, from which I want to send logging messages to a text file and, potentia...
5
2010-01-08T23:01:32Z
2,031,557
<p>Are you sure no other logging setup is being done in anything you import.</p> <p>The incorrect output in your console logs look like the default configuration for a logger, so something else may be setting that up. </p> <p>Running this quick test script:</p> <pre><code>import logging from logging.handlers import ...
12
2010-01-08T23:41:58Z
[ "python", "logging", "error-logging" ]
Python - automating MySQL index: passing parameter
2,031,401
<p>I have a function with a new improved version of the code for automatic table indexing:</p> <pre><code>def update_tableIndex(self,tableName): getIndexMySQLQuery = """SELECT numberID FROM %s;""" % (tableName,) updateIndexMySQLQuery = """UPDATE %s SET numberID=%s WHERE numberID=%s;""" % (tableName,)...
1
2010-01-08T23:02:40Z
2,031,422
<p>Second one doesn't work, because you are using three placeholders inside the query string and provide only one variable for interpolation.</p> <pre><code>updateIndexMySQLQuery = """UPDATE %s SET numberID=%%s WHERE numberID=%%s;""" % (tableName,) </code></pre> <p>This way the string formatting mechanism doesn't ex...
2
2010-01-08T23:05:57Z
[ "python", "mysql", "parameters", "automation" ]
Python - automating MySQL index: passing parameter
2,031,401
<p>I have a function with a new improved version of the code for automatic table indexing:</p> <pre><code>def update_tableIndex(self,tableName): getIndexMySQLQuery = """SELECT numberID FROM %s;""" % (tableName,) updateIndexMySQLQuery = """UPDATE %s SET numberID=%s WHERE numberID=%s;""" % (tableName,)...
1
2010-01-08T23:02:40Z
2,031,433
<p>Use %s to replace the table name in the beginning, but use a question mark to create a parameter replacement.</p> <pre><code>updateIndexMySQLQuery = """UPDATE %s SET numberID=? WHERE numberID=?;""" % (tableName,) ... self.cursorMySQL.execute(updateIndexMySQLQuery,(updateIndex,indexID)) </code></pre>
0
2010-01-08T23:09:17Z
[ "python", "mysql", "parameters", "automation" ]
Python - automating MySQL index: passing parameter
2,031,401
<p>I have a function with a new improved version of the code for automatic table indexing:</p> <pre><code>def update_tableIndex(self,tableName): getIndexMySQLQuery = """SELECT numberID FROM %s;""" % (tableName,) updateIndexMySQLQuery = """UPDATE %s SET numberID=%s WHERE numberID=%s;""" % (tableName,)...
1
2010-01-08T23:02:40Z
2,031,490
<p>thanks for the input. I just re-did the whole function. Here is how it's working and looks now:</p> <pre><code>def update_tableIndex(self,tableName,indexName): getIndexMySQLQuery = """SELECT %s FROM %s;""" % (indexName,tableName,) updateIndex=1 self.cursorMySQL.execute(getIndexMySQLQuery) for ...
0
2010-01-08T23:24:27Z
[ "python", "mysql", "parameters", "automation" ]
Python: Very confused about decorators
2,031,559
<p>I thought I understood decorators but not anymore. Do decorators only work when the function is created?</p> <p>I wanted to create a series of functions that all have a required argument called 'ticket_params' that is a dictionary. and then decorate them with something like <code>@param_checker(['req_param_1', 'req...
2
2010-01-08T23:42:07Z
2,031,591
<p>Decorators are only called once on a function, that is, when the <code>def</code> statement is parsed like so:</p> <pre><code>@mydecorator def myfunction(): ... </code></pre> <p>I assume you mean something like that:</p> <pre><code>class param_checker: def __init__(self, l): self.l = l def __call__(self,...
5
2010-01-08T23:48:20Z
[ "python", "decorator" ]
Python: Very confused about decorators
2,031,559
<p>I thought I understood decorators but not anymore. Do decorators only work when the function is created?</p> <p>I wanted to create a series of functions that all have a required argument called 'ticket_params' that is a dictionary. and then decorate them with something like <code>@param_checker(['req_param_1', 'req...
2
2010-01-08T23:42:07Z
2,031,605
<p>A decorator is applied immediately after the <code>def</code> statement; the equivalence is:</p> <pre><code>@param_checker(['req_param_1', 'req_param_2']) def my_decorated_function(params): # do stuff </code></pre> <p>is <strong>exactly</strong> the same thing as:</p> <pre><code>def my_decorated_function(para...
11
2010-01-08T23:51:58Z
[ "python", "decorator" ]
Python: Very confused about decorators
2,031,559
<p>I thought I understood decorators but not anymore. Do decorators only work when the function is created?</p> <p>I wanted to create a series of functions that all have a required argument called 'ticket_params' that is a dictionary. and then decorate them with something like <code>@param_checker(['req_param_1', 'req...
2
2010-01-08T23:42:07Z
2,031,646
<p>Here's a full example based on @AndiDog's example. Remember any callable can be used as a decorator, it doesn't have to be a class.</p> <pre><code>class MyCustomException(Exception): pass # The decorator - instances of this class are callable as it implements __call__ class param_checker: # In this example...
3
2010-01-09T00:02:13Z
[ "python", "decorator" ]
Python: Very confused about decorators
2,031,559
<p>I thought I understood decorators but not anymore. Do decorators only work when the function is created?</p> <p>I wanted to create a series of functions that all have a required argument called 'ticket_params' that is a dictionary. and then decorate them with something like <code>@param_checker(['req_param_1', 'req...
2
2010-01-08T23:42:07Z
2,031,722
<p>Check Alex's answer in order to understand python decorators; by the way:</p> <p>1) what aren't you understanding of decorators? Don't you understand decorators as a general concept, or Python decorators? Beware, the "classical" decorator pattern, java annotations and python decorators are different things.</p> <p...
2
2010-01-09T00:21:55Z
[ "python", "decorator" ]
Python: Very confused about decorators
2,031,559
<p>I thought I understood decorators but not anymore. Do decorators only work when the function is created?</p> <p>I wanted to create a series of functions that all have a required argument called 'ticket_params' that is a dictionary. and then decorate them with something like <code>@param_checker(['req_param_1', 'req...
2
2010-01-08T23:42:07Z
2,034,646
<p>This is a good explanation for those asking the same question:</p> <pre><code># This does nothing. class donothing(object): def __init__(self, func): """ The 'func' argument is the function being decorated because in this case, we're not instantiating the decorator class. Instead we are...
0
2010-01-09T19:34:46Z
[ "python", "decorator" ]