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
How to implement Symfony Partials or Components in Django?
1,691,400
<p>I've been developing in the Symfony framework for quite a time, but now I have to work with Django and I'm having problems with doing something like a "component" or "partial" in Symfony. </p> <p>That said, here is my goal:</p> <p>I have a webpage with lots of small widgets, all these need their logic - located in...
1
2009-11-07T00:21:37Z
1,691,415
<p>It sounds like what you're looking for is something like <a href="http://docs.djangoproject.com/en/dev/howto/custom-template-tags/" rel="nofollow">custom template tags</a>...</p> <p>You can write your own set of tags that process custom logic and return template chunks that are reusable in a very widget-like way.</...
3
2009-11-07T00:25:18Z
[ "python", "django", "symfony1" ]
How to implement Symfony Partials or Components in Django?
1,691,400
<p>I've been developing in the Symfony framework for quite a time, but now I have to work with Django and I'm having problems with doing something like a "component" or "partial" in Symfony. </p> <p>That said, here is my goal:</p> <p>I have a webpage with lots of small widgets, all these need their logic - located in...
1
2009-11-07T00:21:37Z
1,691,549
<p>Assuming you are going to be using the components in different places on different pages I would suggest trying {% include "foo.html" %}. One of the (several) downsides of the Django templating language is that there is no concept of macros, so you need to be very consistent in the names of values in the context you...
1
2009-11-07T01:17:20Z
[ "python", "django", "symfony1" ]
Organizing Python projects with shared packages
1,691,495
<p>What is the best way to organize and develop a project composed of many small scripts sharing one (or more) larger Python libraries?</p> <p>We have a bunch of programs in our repository that all use the same libraries stored in the same repository. So in other words, a layout like</p> <pre><code>trunk libs ...
3
2009-11-07T00:52:44Z
1,691,523
<p>The much better solution involves not storing all your projects and their shared dependencies in the same repository.</p> <p>Use one repository for each project, and <a href="http://svnbook.red-bean.com/en/1.0/ch07s03.html" rel="nofollow">externals</a> for the shared libraries.</p> <p>Make use of tags in the share...
2
2009-11-07T01:04:00Z
[ "python", "svn", "version-control", "code-organization" ]
Organizing Python projects with shared packages
1,691,495
<p>What is the best way to organize and develop a project composed of many small scripts sharing one (or more) larger Python libraries?</p> <p>We have a bunch of programs in our repository that all use the same libraries stored in the same repository. So in other words, a layout like</p> <pre><code>trunk libs ...
3
2009-11-07T00:52:44Z
1,691,565
<p>If I'm understanding your question properly, then you definitely want virtualenv. Add in some virtualenvwrapper goodness to make it that much better.</p>
1
2009-11-07T01:25:17Z
[ "python", "svn", "version-control", "code-organization" ]
Parsing output of apt-get install for progress bar
1,692,082
<p>I'm working on a simple GUI Python script to do some simple tasks on a system. Some of that work involves <code>apt-get install</code> to install some packages.</p> <p>While this is going on, I want to display a progress bar that should update with the progress of the download, using the little percentage shown in ...
5
2009-11-07T05:18:21Z
1,692,137
<p>As I've often said, use <a href="http://pexpect.sourceforge.net/pexpect.html" rel="nofollow">pexpect</a>, <strong>not</strong> subprocess etc, to run sub-processes when you need to get their continuous output. pexpect fools the subprocess into believing it's running on a terminal, so the subprocess will provide jus...
3
2009-11-07T05:53:22Z
[ "python", "progress-bar", "subprocess", "popen", "apt-get" ]
Parsing output of apt-get install for progress bar
1,692,082
<p>I'm working on a simple GUI Python script to do some simple tasks on a system. Some of that work involves <code>apt-get install</code> to install some packages.</p> <p>While this is going on, I want to display a progress bar that should update with the progress of the download, using the little percentage shown in ...
5
2009-11-07T05:18:21Z
1,692,347
<p>Instead of parsing the output of the apt-get, you can use python-apt to install packages. AFAIK it also has modules for reporting the progress.</p>
5
2009-11-07T07:42:22Z
[ "python", "progress-bar", "subprocess", "popen", "apt-get" ]
Performance difference in alternative switches in Python
1,692,107
<p>I have read a few articles around alternatives to the switch statement in Python. Mainly using dicts instead of lots of if's and elif's. However none really answer the question: is there one with better performance or efficiency? I have read a few arguments that if's and elifs would have to check each statement and ...
3
2009-11-07T05:29:10Z
1,692,118
<p>With all performance/profiling questions, the right answer is "test each case yourself for your specific needs."</p> <p>One great tool for this is <code>timeit</code> which you can learn about <a href="http://docs.python.org/library/timeit.html" rel="nofollow">in the python docs</a>.</p> <p>In general I have seen ...
3
2009-11-07T05:39:24Z
[ "python", "performance", "switch-statement" ]
Performance difference in alternative switches in Python
1,692,107
<p>I have read a few articles around alternatives to the switch statement in Python. Mainly using dicts instead of lots of if's and elif's. However none really answer the question: is there one with better performance or efficiency? I have read a few arguments that if's and elifs would have to check each statement and ...
3
2009-11-07T05:29:10Z
1,692,119
<p>Your concern should be about the readability and maintainability of the code, rather than its efficiency. This applies in most scenarios, and particularly in the one you describe now. The efficiency difference is likely to be negligible (you can easily check it with a small amount of benchmarking code), but 30-40 el...
6
2009-11-07T05:39:44Z
[ "python", "performance", "switch-statement" ]
Performance difference in alternative switches in Python
1,692,107
<p>I have read a few articles around alternatives to the switch statement in Python. Mainly using dicts instead of lots of if's and elif's. However none really answer the question: is there one with better performance or efficiency? I have read a few arguments that if's and elifs would have to check each statement and ...
3
2009-11-07T05:29:10Z
1,692,132
<p>I think a dict will gain advantage over the alternative sequence of <code>if</code> statements as the number of cases goes up, since the key lookup only requires one hash operation. Otherwise if you only have a few cases, a few <code>if</code> statements are better. A dict is probably a more elegant solution for wha...
0
2009-11-07T05:46:59Z
[ "python", "performance", "switch-statement" ]
Performance difference in alternative switches in Python
1,692,107
<p>I have read a few articles around alternatives to the switch statement in Python. Mainly using dicts instead of lots of if's and elif's. However none really answer the question: is there one with better performance or efficiency? I have read a few arguments that if's and elifs would have to check each statement and ...
3
2009-11-07T05:29:10Z
1,692,135
<p><code>dict</code>'s perfomance is typically going to be unbeatable, because a lookup into a <code>dict</code> is going to be O(1) except in rare and practically never-observed cases (where they key involves user-coded types with lousy hashing;-). You don't have to "create new modules" as you say, just arbitrary cal...
8
2009-11-07T05:50:45Z
[ "python", "performance", "switch-statement" ]
Performance difference in alternative switches in Python
1,692,107
<p>I have read a few articles around alternatives to the switch statement in Python. Mainly using dicts instead of lots of if's and elif's. However none really answer the question: is there one with better performance or efficiency? I have read a few arguments that if's and elifs would have to check each statement and ...
3
2009-11-07T05:29:10Z
1,692,248
<p>Times when you'd use a switch in many languages you would use a dict in Python. A switch statement, if added to Python (it's been considered), would not be able to give any real performance gain anyways.</p> <p>dicts are used ubiquitously in Python. CPython dicts are an insanely-efficient, robust hashtable implemen...
1
2009-11-07T06:44:28Z
[ "python", "performance", "switch-statement" ]
Performance difference in alternative switches in Python
1,692,107
<p>I have read a few articles around alternatives to the switch statement in Python. Mainly using dicts instead of lots of if's and elif's. However none really answer the question: is there one with better performance or efficiency? I have read a few arguments that if's and elifs would have to check each statement and ...
3
2009-11-07T05:29:10Z
4,401,589
<p>I ran a few benchmarks (see <a href="https://gist.github.com/729134" rel="nofollow">here</a>). Using lists of function pointers is fastest,if your keys are sequential integers. For the general case: Alex Martelli is right, dictionary are fastest.</p>
0
2010-12-09T18:10:14Z
[ "python", "performance", "switch-statement" ]
Django: Ordering objects by their children's attributes
1,692,322
<p>Consider the models:</p> <pre><code>class Author(models.Model): name = models.CharField(max_length=200, unique=True) class Book(models.Model): pub_date = models.DateTimeField() author = models.ForeignKey(Author) </code></pre> <p>Now suppose I want to order all the books by, say, their pub_date. I would use <co...
1
2009-11-07T07:32:21Z
1,692,353
<pre><code> def remove_duplicates(seq): seen = {} result = [] for item in seq: if item in seen: continue seen[item] = 1 result.append(item) return result # Get the authors of the most recent books query_result = Books.objects.order_by('pub_date').values('author') # Strip the k...
0
2009-11-07T07:50:12Z
[ "python", "sql", "database", "django", "django-models" ]
Django: Ordering objects by their children's attributes
1,692,322
<p>Consider the models:</p> <pre><code>class Author(models.Model): name = models.CharField(max_length=200, unique=True) class Book(models.Model): pub_date = models.DateTimeField() author = models.ForeignKey(Author) </code></pre> <p>Now suppose I want to order all the books by, say, their pub_date. I would use <co...
1
2009-11-07T07:32:21Z
1,692,414
<p>Or, you could play around with something like this:</p> <p><code>Author.objects.filter(book__pub_date__isnull=False).order_by('-book__pub_date')</code></p>
0
2009-11-07T08:21:35Z
[ "python", "sql", "database", "django", "django-models" ]
Django: Ordering objects by their children's attributes
1,692,322
<p>Consider the models:</p> <pre><code>class Author(models.Model): name = models.CharField(max_length=200, unique=True) class Book(models.Model): pub_date = models.DateTimeField() author = models.ForeignKey(Author) </code></pre> <p>Now suppose I want to order all the books by, say, their pub_date. I would use <co...
1
2009-11-07T07:32:21Z
1,692,582
<p>from django.db.models import Max Author.objects.annotate(max_pub_date=Max('books__pub_date')).order_by('-max_pub_date')</p> <p>this requires that you use django 1.1</p> <p>and i assumed you will add a 'related_name' to your author field in Book model, so it will be called by Author.books instead of Author.book...
1
2009-11-07T09:48:14Z
[ "python", "sql", "database", "django", "django-models" ]
Django: Ordering objects by their children's attributes
1,692,322
<p>Consider the models:</p> <pre><code>class Author(models.Model): name = models.CharField(max_length=200, unique=True) class Book(models.Model): pub_date = models.DateTimeField() author = models.ForeignKey(Author) </code></pre> <p>Now suppose I want to order all the books by, say, their pub_date. I would use <co...
1
2009-11-07T07:32:21Z
1,693,749
<p>Building on ayaz's solution, what about: Author.objects.filter(book__pub_date__isnull=False).distinct().order_by('-book__pub_date')</p>
0
2009-11-07T17:16:15Z
[ "python", "sql", "database", "django", "django-models" ]
Django: Ordering objects by their children's attributes
1,692,322
<p>Consider the models:</p> <pre><code>class Author(models.Model): name = models.CharField(max_length=200, unique=True) class Book(models.Model): pub_date = models.DateTimeField() author = models.ForeignKey(Author) </code></pre> <p>Now suppose I want to order all the books by, say, their pub_date. I would use <co...
1
2009-11-07T07:32:21Z
1,694,105
<blockquote> <p>Lastly, would the option of just adding a new field to each one to show the date of the last book and just updating that the whole time be better?</p> </blockquote> <p>Actually it would! This is a normal denormalization practice and can be done like this:</p> <pre><code>class Author(models.Model): ...
1
2009-11-07T19:18:11Z
[ "python", "sql", "database", "django", "django-models" ]
Adding authentication to beanstalkd from Python (or any UNIX) client
1,692,346
<p>So what I like about beanstalkd: small, lightweight, has priorities for messages, has a great set of clients, easy to use. </p> <p>What I dislike about beanstalkd: the lack of authentication menaing if you can connect to the port you can insert messages into it. </p> <p>So my thoughts are to either firewall it to ...
0
2009-11-07T07:42:11Z
1,692,516
<p>This question really belongs on the <a href="http://groups.google.com/group/beanstalk-talk/" rel="nofollow">beanstalkd talk list</a>.</p> <p>I added SASL support to memcached recently for a similar reason. The overhead is almost irrelevant in practice since you only authenticate at connect time (and you hold conne...
1
2009-11-07T09:15:05Z
[ "python", "beanstalkd" ]
Adding authentication to beanstalkd from Python (or any UNIX) client
1,692,346
<p>So what I like about beanstalkd: small, lightweight, has priorities for messages, has a great set of clients, easy to use. </p> <p>What I dislike about beanstalkd: the lack of authentication menaing if you can connect to the port you can insert messages into it. </p> <p>So my thoughts are to either firewall it to ...
0
2009-11-07T07:42:11Z
1,692,834
<p>I have to disagree about the practice of just having connections being held open indefinitely, since I use BeanstalkD from a web-scripting language (php) for various events. The overhead of opening a secure connection would be something I would have to think very carefully over.</p> <p>Like Memcached, beanstalkd i...
4
2009-11-07T12:11:25Z
[ "python", "beanstalkd" ]
Adding authentication to beanstalkd from Python (or any UNIX) client
1,692,346
<p>So what I like about beanstalkd: small, lightweight, has priorities for messages, has a great set of clients, easy to use. </p> <p>What I dislike about beanstalkd: the lack of authentication menaing if you can connect to the port you can insert messages into it. </p> <p>So my thoughts are to either firewall it to ...
0
2009-11-07T07:42:11Z
1,956,849
<p>I do two things that reduce the issue you are refererring to:</p> <p>First I always run beanstalkd on 127.0.0.1</p> <p>Second, I normally serialize the job structure, and load a "secret key" encrypted base64 digest as the job string. Only workers that can decrypt the job string correctly can parse jobs.</p> <p>I ...
0
2009-12-24T05:32:53Z
[ "python", "beanstalkd" ]
Python : List of dict, if exists increment a dict value, if not append a new dict
1,692,388
<p>I would like do something like that.</p> <pre><code>list_of_urls = ['http://www.google.fr/', 'http://www.google.fr/', 'http://www.google.cn/', 'http://www.google.com/', 'http://www.google.fr/', 'http://www.google.fr/', 'http://www.google.fr/', 'http://www.google.co...
41
2009-11-07T08:07:05Z
1,692,419
<p>To do it exactly your way? You could use the for...else structure</p> <pre><code>for url in list_of_urls: for url_dict in urls: if url_dict['url'] == url: url_dict['nbr'] += 1 break else: urls.append(dict(url=url, nbr=1)) </code></pre> <p>But it is quite inelegant. D...
2
2009-11-07T08:26:21Z
[ "python", "loops", "list", "tuples" ]
Python : List of dict, if exists increment a dict value, if not append a new dict
1,692,388
<p>I would like do something like that.</p> <pre><code>list_of_urls = ['http://www.google.fr/', 'http://www.google.fr/', 'http://www.google.cn/', 'http://www.google.com/', 'http://www.google.fr/', 'http://www.google.fr/', 'http://www.google.fr/', 'http://www.google.co...
41
2009-11-07T08:07:05Z
1,692,428
<p>That is a very strange way to organize things. If you stored in a dictionary, this is easy:</p> <pre><code># This example should work in any version of Python. # urls_d will contain URL keys, with counts as values, like: {'http://www.google.fr/' : 1 } urls_d = {} for url in list_of_urls: if not url in urls_d: ...
80
2009-11-07T08:28:18Z
[ "python", "loops", "list", "tuples" ]
Python : List of dict, if exists increment a dict value, if not append a new dict
1,692,388
<p>I would like do something like that.</p> <pre><code>list_of_urls = ['http://www.google.fr/', 'http://www.google.fr/', 'http://www.google.cn/', 'http://www.google.com/', 'http://www.google.fr/', 'http://www.google.fr/', 'http://www.google.fr/', 'http://www.google.co...
41
2009-11-07T08:07:05Z
1,692,429
<p>Use <a href="http://docs.python.org/library/collections.html#collections.defaultdict">defaultdict</a>:</p> <pre><code>from collections import defaultdict urls = defaultdict(int) for url in list_of_urls: urls[url] += 1 </code></pre>
11
2009-11-07T08:28:28Z
[ "python", "loops", "list", "tuples" ]
Python : List of dict, if exists increment a dict value, if not append a new dict
1,692,388
<p>I would like do something like that.</p> <pre><code>list_of_urls = ['http://www.google.fr/', 'http://www.google.fr/', 'http://www.google.cn/', 'http://www.google.com/', 'http://www.google.fr/', 'http://www.google.fr/', 'http://www.google.fr/', 'http://www.google.co...
41
2009-11-07T08:07:05Z
1,692,435
<p>Using the default works, but so does:</p> <pre><code>urls[url] = urls.get(url, 0) + 1 </code></pre> <p>using <code>.get</code>, you can get a default return if it doesn't exist. By default it's None, but in the case I sent you, it would be 0.</p>
43
2009-11-07T08:31:00Z
[ "python", "loops", "list", "tuples" ]
Python : List of dict, if exists increment a dict value, if not append a new dict
1,692,388
<p>I would like do something like that.</p> <pre><code>list_of_urls = ['http://www.google.fr/', 'http://www.google.fr/', 'http://www.google.cn/', 'http://www.google.com/', 'http://www.google.fr/', 'http://www.google.fr/', 'http://www.google.fr/', 'http://www.google.co...
41
2009-11-07T08:07:05Z
4,096,511
<p>this always works fine for me...</p> <pre> <code> for url in list_of_urls: urls.setdefault(url,0) urls[url]+=1 </code> </pre>
2
2010-11-04T12:14:30Z
[ "python", "loops", "list", "tuples" ]
Python : List of dict, if exists increment a dict value, if not append a new dict
1,692,388
<p>I would like do something like that.</p> <pre><code>list_of_urls = ['http://www.google.fr/', 'http://www.google.fr/', 'http://www.google.cn/', 'http://www.google.com/', 'http://www.google.fr/', 'http://www.google.fr/', 'http://www.google.fr/', 'http://www.google.co...
41
2009-11-07T08:07:05Z
38,064,879
<p>Except for the first time, each time a word is seen the if statement's test fails. If you are counting a large number of words, many will probably occur multiple times. In a situation where the initialization of a value is only going to occur once and the augmentation of that value will occur many times it is cheape...
1
2016-06-27T23:42:35Z
[ "python", "loops", "list", "tuples" ]
Open web page with custom cookies in Python
1,692,396
<p>For example, I have cookies</p> <pre><code>my_cookies = {'name': 'Albert', 'uid': '654897897564'} </code></pre> <p>and I want to open page <a href="http://website.com">http://website.com</a></p> <pre><code>opener = urllib2.build_opener(urllib2.HTTPCookieProcessor()) opener.addheaders.append(('User-agent', 'Mozill...
5
2009-11-07T08:11:30Z
1,692,484
<p>You just need a few more steps:</p> <pre><code>import urllib2 import cookielib cp = urllib2.HTTPCookieProcessor() cj = cp.cookiejar # see cookielib.Cookie documentation for options description cj.set_cookie(cookielib.Cookie(0, 'a_cookie', 'a_value', '80', False, 'domain', True, Fals...
7
2009-11-07T08:57:45Z
[ "python", "cookies", "urllib2" ]
What cool hacks can be done using sys.settrace?
1,692,866
<p>I love being able to modify the arguments the get sent to a function, using <code>settrace</code>, like :</p> <pre><code>import sys def trace_func(frame,event,arg): value = frame.f_locals["a"] if value % 2 == 0: value += 1 frame.f_locals["a"] = value def f(a): print a if __name__ == "...
18
2009-11-07T12:25:47Z
1,692,945
<p>I don't have an exhaustively comprehensive answer but one thing I did with it, with the help of another user on SO, was <a href="http://stackoverflow.com/questions/1645028/trace-table-for-python-programs">create a program that generates the trace tables of other Python programs</a>.</p>
1
2009-11-07T12:53:44Z
[ "python" ]
What cool hacks can be done using sys.settrace?
1,692,866
<p>I love being able to modify the arguments the get sent to a function, using <code>settrace</code>, like :</p> <pre><code>import sys def trace_func(frame,event,arg): value = frame.f_locals["a"] if value % 2 == 0: value += 1 frame.f_locals["a"] = value def f(a): print a if __name__ == "...
18
2009-11-07T12:25:47Z
1,693,056
<p>Of course, code coverage is accomplished with the trace function. One cool thing we haven't had before is branch coverage measurement, and that's coming along nicely, about to be released in an alpha version of <a href="http://bitbucket.org/ned/coveragepy">coverage.py</a>.</p> <p>So for example, consider this func...
8
2009-11-07T13:39:33Z
[ "python" ]
What cool hacks can be done using sys.settrace?
1,692,866
<p>I love being able to modify the arguments the get sent to a function, using <code>settrace</code>, like :</p> <pre><code>import sys def trace_func(frame,event,arg): value = frame.f_locals["a"] if value % 2 == 0: value += 1 frame.f_locals["a"] = value def f(a): print a if __name__ == "...
18
2009-11-07T12:25:47Z
1,693,108
<p>I would strongly recommend against abusing settrace. I'm assuming you understand this stuff, but others coming along later may not. There are a few reasons:</p> <ol> <li><p>Settrace is a very blunt tool. The OP's example is a simple one, but there's practically no way to extend it for use in a real system. </p>...
22
2009-11-07T14:00:59Z
[ "python" ]
What cool hacks can be done using sys.settrace?
1,692,866
<p>I love being able to modify the arguments the get sent to a function, using <code>settrace</code>, like :</p> <pre><code>import sys def trace_func(frame,event,arg): value = frame.f_locals["a"] if value % 2 == 0: value += 1 frame.f_locals["a"] = value def f(a): print a if __name__ == "...
18
2009-11-07T12:25:47Z
11,757,847
<p>For example, get the memory consumption of Python code line-by-line: <a href="http://pypi.python.org/pypi/memory_profiler" rel="nofollow">http://pypi.python.org/pypi/memory_profiler</a></p>
3
2012-08-01T11:00:51Z
[ "python" ]
What cool hacks can be done using sys.settrace?
1,692,866
<p>I love being able to modify the arguments the get sent to a function, using <code>settrace</code>, like :</p> <pre><code>import sys def trace_func(frame,event,arg): value = frame.f_locals["a"] if value % 2 == 0: value += 1 frame.f_locals["a"] = value def f(a): print a if __name__ == "...
18
2009-11-07T12:25:47Z
17,568,951
<p>I made a module called <a href="http://pycallgraph.slowchop.com/"><code>pycallgraph</code></a> which generates call graphs using <code>sys.settrace()</code>.</p> <p><img src="http://i.stack.imgur.com/aiNEA.png" alt=""></p>
13
2013-07-10T11:01:11Z
[ "python" ]
What cool hacks can be done using sys.settrace?
1,692,866
<p>I love being able to modify the arguments the get sent to a function, using <code>settrace</code>, like :</p> <pre><code>import sys def trace_func(frame,event,arg): value = frame.f_locals["a"] if value % 2 == 0: value += 1 frame.f_locals["a"] = value def f(a): print a if __name__ == "...
18
2009-11-07T12:25:47Z
22,212,891
<p>The python debugger Pdb uses sys.settrace to analyse lines to debug.</p> <p>Here's an c optimization/extension for pdb that also uses sys.settrace </p> <p><a href="https://bitbucket.org/jagguli/cpdb" rel="nofollow">https://bitbucket.org/jagguli/cpdb</a> </p>
1
2014-03-06T01:16:48Z
[ "python" ]
What is the use of Python's basic optimizations mode? (python -O)
1,693,088
<p>Python has a flag <code>-O</code> that you can execute the interpreter with. The option will generate "optimized" bytecode (written to .pyo files), and given twice, it will discard docstrings. From Python's man page:</p> <blockquote> <p>-O Turn on basic optimizations. This changes the filename extension for...
36
2009-11-07T13:51:35Z
1,693,127
<p>On stripping assert statements: this is a standard option in the C world, where many people believe part of the definition of ASSERT is that it doesn't run in production code. Whether stripping them out or not makes a difference depends less on how many asserts there are than on how much work those asserts do:</p> ...
24
2009-11-07T14:07:25Z
[ "python", "optimization", "assert", "bytecode" ]
What is the use of Python's basic optimizations mode? (python -O)
1,693,088
<p>Python has a flag <code>-O</code> that you can execute the interpreter with. The option will generate "optimized" bytecode (written to .pyo files), and given twice, it will discard docstrings. From Python's man page:</p> <blockquote> <p>-O Turn on basic optimizations. This changes the filename extension for...
36
2009-11-07T13:51:35Z
1,693,128
<p>You've pretty much figured it out: It does practically nothing at all. You're almost never going to see speed or memory gains, unless you're severely hurting for RAM.</p>
4
2009-11-07T14:08:15Z
[ "python", "optimization", "assert", "bytecode" ]
What is the use of Python's basic optimizations mode? (python -O)
1,693,088
<p>Python has a flag <code>-O</code> that you can execute the interpreter with. The option will generate "optimized" bytecode (written to .pyo files), and given twice, it will discard docstrings. From Python's man page:</p> <blockquote> <p>-O Turn on basic optimizations. This changes the filename extension for...
36
2009-11-07T13:51:35Z
1,693,130
<p>I imagine that the heaviest users of <code>-O</code> are <a href="http://www.py2exe.org/" rel="nofollow">py2exe</a> <a href="http://pypi.python.org/pypi/py2app/" rel="nofollow">py2app</a> and similar.</p> <p>I've personally never found a use for <code>-O</code> directly.</p>
4
2009-11-07T14:08:28Z
[ "python", "optimization", "assert", "bytecode" ]
What is the use of Python's basic optimizations mode? (python -O)
1,693,088
<p>Python has a flag <code>-O</code> that you can execute the interpreter with. The option will generate "optimized" bytecode (written to .pyo files), and given twice, it will discard docstrings. From Python's man page:</p> <blockquote> <p>-O Turn on basic optimizations. This changes the filename extension for...
36
2009-11-07T13:51:35Z
1,693,140
<p>If you have assertions in frequently called code (e.g. in an inner loop), stripping them can certainly make a difference. Extreme example:</p> <pre><code>$ python -c 'import timeit;print timeit.repeat("assert True")' [0.088717937469482422, 0.088625192642211914, 0.088654994964599609] $ python -O -c 'import timeit...
5
2009-11-07T14:11:28Z
[ "python", "optimization", "assert", "bytecode" ]
What is the use of Python's basic optimizations mode? (python -O)
1,693,088
<p>Python has a flag <code>-O</code> that you can execute the interpreter with. The option will generate "optimized" bytecode (written to .pyo files), and given twice, it will discard docstrings. From Python's man page:</p> <blockquote> <p>-O Turn on basic optimizations. This changes the filename extension for...
36
2009-11-07T13:51:35Z
1,693,940
<p>I have never encountered a good reason to use <code>-O</code>. I have always assumed its main purpose is in case at some point in the future some meaningful optimization is added.</p>
6
2009-11-07T18:18:41Z
[ "python", "optimization", "assert", "bytecode" ]
What is the use of Python's basic optimizations mode? (python -O)
1,693,088
<p>Python has a flag <code>-O</code> that you can execute the interpreter with. The option will generate "optimized" bytecode (written to .pyo files), and given twice, it will discard docstrings. From Python's man page:</p> <blockquote> <p>-O Turn on basic optimizations. This changes the filename extension for...
36
2009-11-07T13:51:35Z
1,698,167
<p>Another use for the <code>-O</code> flag is that the value of the <code>__debug__</code> builtin variable is set to <code>False</code>.</p> <p>So, basically, your code can have a lot of "debugging" paths like:</p> <pre><code>if __debug__: # output all your favourite debugging information # and then more ...
30
2009-11-08T22:35:40Z
[ "python", "optimization", "assert", "bytecode" ]
How does ironpython speed compare to other .net languages?
1,693,205
<p>I would like to give sources for what I'm saying but I just dont have them, it's something I heard.</p> <p>Once a programming professor told me that some software benchmarking done to .net vs Python in some particular items it gave a relation of 5:8 in favor of .NET . That was his argument in favor of Python not be...
11
2009-11-07T14:27:18Z
1,693,388
<p>Here are two interesting links with comparisons between IronPython, CPython, and C# (among others):</p> <ul> <li>CPython vs C# (Mono) <a href="http://shootout.alioth.debian.org/u32/benchmark.php?test=all&amp;lang=python&amp;lang2=csharp&amp;box=1">benchmarks</a>, based on several programs detailed on the site.</li>...
9
2009-11-07T15:21:50Z
[ ".net", "python", "performance", "ironpython" ]
How does ironpython speed compare to other .net languages?
1,693,205
<p>I would like to give sources for what I'm saying but I just dont have them, it's something I heard.</p> <p>Once a programming professor told me that some software benchmarking done to .net vs Python in some particular items it gave a relation of 5:8 in favor of .NET . That was his argument in favor of Python not be...
11
2009-11-07T14:27:18Z
1,694,288
<p>You could enable .net tracing, which outputs timing information at the bottom of the page. Make an app in C#/.Net and an app using Python and look at the differences in timing. That will give you a definitive answer.</p> <p>In all honesty I think you're better off just using C#, it's "faster" to develop since the V...
1
2009-11-07T20:24:16Z
[ ".net", "python", "performance", "ironpython" ]
How does ironpython speed compare to other .net languages?
1,693,205
<p>I would like to give sources for what I'm saying but I just dont have them, it's something I heard.</p> <p>Once a programming professor told me that some software benchmarking done to .net vs Python in some particular items it gave a relation of 5:8 in favor of .NET . That was his argument in favor of Python not be...
11
2009-11-07T14:27:18Z
2,617,858
<p>IronPython will be considerably slower than C#. You could think of the comparison as very roughly between CPython and C, but with the gap somewhat smaller.</p>
0
2010-04-11T17:02:56Z
[ ".net", "python", "performance", "ironpython" ]
X-Sendfile and VERY big files on Apache2
1,693,564
<p>Any filesize over about 4GB is not going to work with the mod_xsendfile for Apache2 (as it sets the content length to a long).</p> <p>I am willing to rewrite it to support this; however, I can find no documentation on how to set content length from the apache api to something larger than a long and thus serve large...
3
2009-11-07T16:24:50Z
1,693,668
<p>I have discovered the answer. Use the BETA version provided. It seems to fix this issue.</p>
1
2009-11-07T16:51:42Z
[ "python", "apache2", "wsgi", "x-sendfile" ]
X-Sendfile and VERY big files on Apache2
1,693,564
<p>Any filesize over about 4GB is not going to work with the mod_xsendfile for Apache2 (as it sets the content length to a long).</p> <p>I am willing to rewrite it to support this; however, I can find no documentation on how to set content length from the apache api to something larger than a long and thus serve large...
3
2009-11-07T16:24:50Z
2,011,279
<p>Location of the Beta for <a href="https://tn123.org/mod_xsendfile/beta/" rel="nofollow">mod_xsendfile</a> on Apache2</p>
4
2010-01-06T06:25:39Z
[ "python", "apache2", "wsgi", "x-sendfile" ]
Move or copy an entity to another kind
1,693,815
<p>Is there a way to move an entity to another kind in appengine.</p> <p>Say you have a kind defines, and you want to keep a record of deleted entities of that kind. But you want to separate the storage of live object and archived objects. Kinds are basically just serialized dicts in the bigtable anyway. And maybe you...
0
2009-11-07T17:39:19Z
1,693,856
<p>Unless someone's written utilities for this kind of thing, the way to go is to read from one and write to the other kind!</p>
1
2009-11-07T17:49:24Z
[ "python", "google-app-engine", "indexing", "archive", "bigtable" ]
Move or copy an entity to another kind
1,693,815
<p>Is there a way to move an entity to another kind in appengine.</p> <p>Say you have a kind defines, and you want to keep a record of deleted entities of that kind. But you want to separate the storage of live object and archived objects. Kinds are basically just serialized dicts in the bigtable anyway. And maybe you...
0
2009-11-07T17:39:19Z
1,693,979
<p>No - once created, the kind is a part of the entity's immutable key. You need to create a new entity and copy everything across. One way to do this would be to use the low-level google.appengine.api.datastore interface, which treats entities as dicts.</p>
1
2009-11-07T18:35:24Z
[ "python", "google-app-engine", "indexing", "archive", "bigtable" ]
Finding a logic bug in converting Python code to PHP
1,693,945
<p>The input <code>7|12|1|14|2|13|8|11|16|3|10|5|9|6|15|4</code> returns 0 by the PHP -code, while 1 by Python code: 1 means that the sums of the 4x4 magic square are the same, while 0 means the reverse. Python code is correct. </p> <p>The problem of the PHP code seems to be in the function <em>divide</em>'s for -loop...
2
2009-11-07T18:20:13Z
1,694,027
<p>In your Python code, you have:</p> <pre><code> summat += [sum(lista[0::5]) for i in range(0, len(lista), 16)] </code></pre> <p>I'm pretty sure this isn't doing what you intend it to do. <code>len(lista)</code> is 16, so this range is <code>range(0, 16, 16)</code> which is <code>[0]</code>. Then, you're not even...
1
2009-11-07T18:52:03Z
[ "php", "python" ]
Finding a logic bug in converting Python code to PHP
1,693,945
<p>The input <code>7|12|1|14|2|13|8|11|16|3|10|5|9|6|15|4</code> returns 0 by the PHP -code, while 1 by Python code: 1 means that the sums of the 4x4 magic square are the same, while 0 means the reverse. Python code is correct. </p> <p>The problem of the PHP code seems to be in the function <em>divide</em>'s for -loop...
2
2009-11-07T18:20:13Z
1,694,031
<p>The problem is in your PHP line:</p> <pre><code>for ( $i = 0; $i &lt; count( $sum ); $i++ ) { </code></pre> <p>you wanted:</p> <pre><code>for ( $i = 0; $i &lt; count( $array ); $i++ ) { </code></pre> <p>Fix it in both places, and you get the right answer.</p> <p>BTW: You are only checking the main diagonals, bu...
2
2009-11-07T18:52:22Z
[ "php", "python" ]
Finding a logic bug in converting Python code to PHP
1,693,945
<p>The input <code>7|12|1|14|2|13|8|11|16|3|10|5|9|6|15|4</code> returns 0 by the PHP -code, while 1 by Python code: 1 means that the sums of the 4x4 magic square are the same, while 0 means the reverse. Python code is correct. </p> <p>The problem of the PHP code seems to be in the function <em>divide</em>'s for -loop...
2
2009-11-07T18:20:13Z
1,694,087
<p>Look to Ned for your answer; this is just to note PHP improvements:</p> <pre><code> $s = 0; for ( $i = 0; $i &lt; count( $array ); $i += 5 ) { $s += $array[$i]; } $sum[]=$s; $s=0; for ( $i = 3; $i &lt; 15; $i+=3 ) { $s += $array[$i]; } $sum[]=$s; </code></pre>
1
2009-11-07T19:10:06Z
[ "php", "python" ]
Getting the Current Table in Numbers (Python/Appscript)
1,694,060
<p>How do I access the current table in Numbers using <code>py-appscript</code>? </p> <p><hr></p> <p>For posterity, the program I created using this information clears all the cells of the current table and returns the selection to cell <code>A1</code>. I turned it into a Service using a python Run Shell Script in Au...
1
2009-11-07T19:01:52Z
1,694,122
<pre><code>&gt;&gt;&gt; d = app('Numbers').documents.first() # reference to current top document </code></pre> <p>EDIT: There doesn't seem to be a straight-forward single reference to the current table but it looks like you can find it by searching the current first document's sheets for a table with a non-null selec...
2
2009-11-07T19:23:32Z
[ "python", "iwork", "appscript" ]
Using md5 on BeautifulSoup result
1,694,061
<p>Im trying to use the md5 algorithm on web pages to avoid seeing duplicates. Is there an easy way to convert the result from beautifulsoup into a string which is digestible by md5?</p> <p>Many thanks</p>
1
2009-11-07T19:01:52Z
1,694,068
<p>Just turn it into a string with <code>str</code>:</p> <pre><code>from BeautifulSoup import BeautifulSoup doc = "&lt;html&gt;&lt;h1&gt;Heading&lt;/h1&gt;&lt;p&gt;Text" soup = BeautifulSoup(doc) str(soup) </code></pre> <p>(from <a href="http://www.crummy.com/software/BeautifulSoup/documentation.html#Printing%20a%20...
4
2009-11-07T19:03:45Z
[ "python", "md5", "beautifulsoup" ]
Joomla and XMLRPC
1,694,205
<p>How do I get started with getting going with XML-RPC with joomla? I've been looking around for documentation and finding nothing...</p> <p>I'd like to connect to a joomla server, (after enabling the Core Joomla XML-RPC plugin), and be able to do things like login and add an article, and tweak all the parameters of ...
3
2009-11-07T19:53:53Z
1,696,183
<p>the book "Mastering Joomla 1.5 Extension and Framework Development" has a nice explanation of that.</p> <p>Joomla has a fex XML-RPC plugins that let you do a few things, like the blogger API interface. (plugins/xmlrpc/blogger.php)</p> <p>You should create your own XML-RPC plugin to do the custom things you want.</...
3
2009-11-08T12:04:05Z
[ "python", "joomla", "xml-rpc" ]
MapReduce, Python and NetworkX
1,694,237
<p>I have implemented an unweighted random walk function for a graph that I built in Python using NetworkX. Below is a snippet of my program that deals with the random walk. Elsewhere in my program, I have a method that creates the graph, and I have a method that simulates various custom graph testing methods that I've...
2
2009-11-07T20:05:16Z
1,694,286
<p>I don't see how map-reduce can help you. It's used where you have a two-part operation: the first part is a calculation that can be performed independently on many different data elements, and the second part is somehow combining all those results. Perhaps there's a clever way to use map-reduce to help with this r...
4
2009-11-07T20:22:27Z
[ "python", "hadoop", "mapreduce", "networkx" ]
MapReduce, Python and NetworkX
1,694,237
<p>I have implemented an unweighted random walk function for a graph that I built in Python using NetworkX. Below is a snippet of my program that deals with the random walk. Elsewhere in my program, I have a method that creates the graph, and I have a method that simulates various custom graph testing methods that I've...
2
2009-11-07T20:05:16Z
1,694,551
<p>To address your question:</p> <ol> <li><p>You need to address Ned's comment. He beat me to saying it. Explain your code; more on that later.</p></li> <li><p>I can not fathom a walking algorithm that could be run in parallel. By their very nature, they are each a linear process; each step depends on the previous. Yo...
1
2009-11-07T21:53:14Z
[ "python", "hadoop", "mapreduce", "networkx" ]
MapReduce, Python and NetworkX
1,694,237
<p>I have implemented an unweighted random walk function for a graph that I built in Python using NetworkX. Below is a snippet of my program that deals with the random walk. Elsewhere in my program, I have a method that creates the graph, and I have a method that simulates various custom graph testing methods that I've...
2
2009-11-07T20:05:16Z
19,932,697
<p>You don't have to actually perform the random walk if you use the formula detailed in <a href="http://www.computer.org/csdl/trans/tp/2007/11/i1873-abs.html" rel="nofollow">this paper</a>.</p>
0
2013-11-12T15:07:17Z
[ "python", "hadoop", "mapreduce", "networkx" ]
Reasons to prefer zope 3 over grok
1,694,309
<p>I am familiar with zope 2 and think that zope 3 is superior in many ways, as far as I've used it (i.e. primarily with Five).</p> <p>Now I'm considering to dive deeper into zope 3. Would you recommend going even one step further and use grok instead, and if so, why? (and if not, why not? :)</p>
3
2009-11-07T20:31:56Z
1,694,374
<p>A good resource is <a href="http://plone.org/products/dexterity/documentation/manual/five.grok/referencemanual-all-pages">http://plone.org/products/dexterity/documentation/manual/five.grok/referencemanual-all-pages</a> . Plone is probably the biggest piece of software that uses zope3, so the fact that plone uses gro...
6
2009-11-07T20:50:47Z
[ "python", "zope", "grok" ]
Python XPath Result displaying only []
1,694,427
<p>Hey I have just started to use Python recently and I want to use it with a bit of xPath, the thing is when I print the result of the query I only get [] and I don't know why =S</p> <pre><code> import libxml2, urllib doc = libxml2.parseDoc(urllib.urlopen("http://www.domain.com/").read()) result = doc.xpathEval(...
1
2009-11-07T21:10:36Z
1,694,459
<p>It could be that your XPath doesn't select any elements. For example, you are looking for td's inside th's, but those elements are peers, and shouldn't nest.</p> <p>Why do you say <code>(count(preceding-sibling::*) + 1) = 2</code> instead of <code>count(preceding-sibling::*) = 1</code>?</p> <p>If you use a simple...
1
2009-11-07T21:21:55Z
[ "python", "xpath", "libxml2" ]
Python XPath Result displaying only []
1,694,427
<p>Hey I have just started to use Python recently and I want to use it with a bit of xPath, the thing is when I print the result of the query I only get [] and I don't know why =S</p> <pre><code> import libxml2, urllib doc = libxml2.parseDoc(urllib.urlopen("http://www.domain.com/").read()) result = doc.xpathEval(...
1
2009-11-07T21:10:36Z
1,696,831
<p>Are you confusing th and tr? Change your th to tr.</p>
0
2009-11-08T15:15:02Z
[ "python", "xpath", "libxml2" ]
Python XPath Result displaying only []
1,694,427
<p>Hey I have just started to use Python recently and I want to use it with a bit of xPath, the thing is when I print the result of the query I only get [] and I don't know why =S</p> <pre><code> import libxml2, urllib doc = libxml2.parseDoc(urllib.urlopen("http://www.domain.com/").read()) result = doc.xpathEval(...
1
2009-11-07T21:10:36Z
1,700,233
<p>Side note: Where does all that unnecessary complexity in your XPath come from? This:</p> <pre> //th//td[(((count(preceding-sibling::*) + 1) = 2) and parent::*)]//a </pre> <p>is equivalent to:</p> <pre> //th//td[count(preceding-sibling::*) = 1)]//a </pre> <p>and very probably even to:</p> <pre> //th/td[2]//a </p...
0
2009-11-09T10:33:24Z
[ "python", "xpath", "libxml2" ]
Set Selection in Numbers (Python/Appscript)
1,694,478
<p>How do you set the selection for a table in Numbers using <code>py-appscript</code>?</p> <p>This seems like it should be really simple to do but the solution is frustratingly evasive. I can get the current selection:</p> <pre><code> current_table.selection_range </code></pre> <p>and I can get its cells:</p> <pre...
0
2009-11-07T21:28:17Z
1,694,653
<p>Looks like something like this works:</p> <pre><code>&gt;&gt;&gt; current_table.selection_range.set(to=current_table.ranges[u'B3:C10']) </code></pre> <p>Note, looking at <code>Number's</code> script dictionary in <code>AppleScript Editor</code> or with <code>ASDictionary</code>, the property <code>selection_range<...
3
2009-11-07T22:25:00Z
[ "python", "iwork", "appscript" ]
Difference between ^ Operator in JS and Python
1,694,507
<p>I need to port some JS code which involves <code>Math.random()*2147483648)^(new Date).getTime()</code>. While it looks like for smaller numbers, the python function and the JS function are equivalent in function, but with large numbers like this, the values end up entirely different.</p> <p>Python:</p> <pre><code>...
2
2009-11-07T21:34:45Z
1,694,524
<p>Python has unlimited-precision integers, while Javascript is using a 32-bit integer. You can manually apply a 32-bit limit to get the result you want:</p> <pre><code>def xor32bit(a, b): m = (a ^ b) % (2**32) if m &gt; (2**16): m -= 2**32 return m </code></pre>
7
2009-11-07T21:41:17Z
[ "javascript", "python", "bit-manipulation", "xor" ]
Difference between ^ Operator in JS and Python
1,694,507
<p>I need to port some JS code which involves <code>Math.random()*2147483648)^(new Date).getTime()</code>. While it looks like for smaller numbers, the python function and the JS function are equivalent in function, but with large numbers like this, the values end up entirely different.</p> <p>Python:</p> <pre><code>...
2
2009-11-07T21:34:45Z
1,694,532
<p>Easiest way would be to use ctypes to get the same overflow behavior as Javascript:</p> <pre><code>&gt;&gt;&gt; import ctypes &gt;&gt;&gt; ctypes.c_int(1257075044427) c_long(-1350373301) </code></pre> <p>To get the value:</p> <pre><code>&gt;&gt;&gt; ctypes.c_int(1257075044427).value -1350373301 </code></pre>
4
2009-11-07T21:44:42Z
[ "javascript", "python", "bit-manipulation", "xor" ]
generating javascript string in python
1,694,939
<p>i have string stored in python variables, and i am outputting a html that contains javascript, and the i need to create javascript variables.</p> <p>for ex, in python</p> <pre><code>title = "What's your name?" </code></pre> <p>i use Cheetah to generate the html. Cheetah code:</p> <pre><code>var title = '$title';...
1
2009-11-08T00:39:20Z
1,694,950
<p>You probably want JSON:</p> <pre><code>import simplejson as sj print sj.dumps('What\'s your name?') # =&gt; '"What\'s your name?"' </code></pre> <p>Don't generate js with cheetah, there are libraries.</p>
3
2009-11-08T00:45:53Z
[ "javascript", "python", "cheetah" ]
generating javascript string in python
1,694,939
<p>i have string stored in python variables, and i am outputting a html that contains javascript, and the i need to create javascript variables.</p> <p>for ex, in python</p> <pre><code>title = "What's your name?" </code></pre> <p>i use Cheetah to generate the html. Cheetah code:</p> <pre><code>var title = '$title';...
1
2009-11-08T00:39:20Z
1,694,952
<p>Either just do <code>title = title.replace("'", "\\'")</code> in Python before the <code>title</code> value gets to Cheetah, or add a custom filter to Cheetah for the purpose and invoke it in the template. Doing it on the Python side of things seems simpler, though.</p>
-2
2009-11-08T00:46:26Z
[ "javascript", "python", "cheetah" ]
Secure Python intepreter?
1,695,014
<p>Is there a secure Python intepreter?</p> <p>Imagine a Python VM you can run on your machine, that restricts the operations. No files can be opened, no system calls, etc. It just transforms stdin to stdout, maybe with text processing + math etc.</p> <p>Does such a secure Python VM exist?</p>
6
2009-11-08T01:20:04Z
1,695,034
<p>I know of no such "secure interpreter" that is openly distributed (obviously Google has one that it uses in App Engine, though with somewhat different restrictions from those you desire, e.g., certain files <em>can</em> be opened, in a read-only way). There are some claims for it, though, e.g. <a href="http://wiki....
7
2009-11-08T01:28:05Z
[ "python", "security", "virtual-machine", "interpreter" ]
Secure Python intepreter?
1,695,014
<p>Is there a secure Python intepreter?</p> <p>Imagine a Python VM you can run on your machine, that restricts the operations. No files can be opened, no system calls, etc. It just transforms stdin to stdout, maybe with text processing + math etc.</p> <p>Does such a secure Python VM exist?</p>
6
2009-11-08T01:20:04Z
1,695,109
<p>You could run IronPython inside a .NET appdomain that has restricted privileges.</p> <p>This would definitely work in Windows, and possibly/probably in Mono (I couldn't really say).</p> <p>You would need to write a little program that embeds the IronPython interpreter and passes the script to it.</p> <p>The first...
1
2009-11-08T02:08:27Z
[ "python", "security", "virtual-machine", "interpreter" ]
Secure Python intepreter?
1,695,014
<p>Is there a secure Python intepreter?</p> <p>Imagine a Python VM you can run on your machine, that restricts the operations. No files can be opened, no system calls, etc. It just transforms stdin to stdout, maybe with text processing + math etc.</p> <p>Does such a secure Python VM exist?</p>
6
2009-11-08T01:20:04Z
1,695,169
<p>You could run Jython on the JVM with a SecurityManager that allows you to specify permitted / disallowed operations.</p>
2
2009-11-08T02:38:31Z
[ "python", "security", "virtual-machine", "interpreter" ]
Secure Python intepreter?
1,695,014
<p>Is there a secure Python intepreter?</p> <p>Imagine a Python VM you can run on your machine, that restricts the operations. No files can be opened, no system calls, etc. It just transforms stdin to stdout, maybe with text processing + math etc.</p> <p>Does such a secure Python VM exist?</p>
6
2009-11-08T01:20:04Z
1,695,267
<p>I've been toying with this lately. My requirements include Python 3.x which immediately takes solutions like Jython and IronPython off the table. I'd be hesitant to take that route anyway, as I've never trusted user-mode language VMs.</p> <p>That being the case, for my purposes the best solution so far is to take i...
-1
2009-11-08T03:23:27Z
[ "python", "security", "virtual-machine", "interpreter" ]
Secure Python intepreter?
1,695,014
<p>Is there a secure Python intepreter?</p> <p>Imagine a Python VM you can run on your machine, that restricts the operations. No files can be opened, no system calls, etc. It just transforms stdin to stdout, maybe with text processing + math etc.</p> <p>Does such a secure Python VM exist?</p>
6
2009-11-08T01:20:04Z
1,695,275
<p>I am an undergrad and in my first year, we were taught python. We had these things called "CodeLabs" that had to be submitted periodically. It works by asking a question and asking the student to input their answer into a text box and running that code on some test cases and checking their return values</p> <p>One ...
1
2009-11-08T03:25:31Z
[ "python", "security", "virtual-machine", "interpreter" ]
Secure Python intepreter?
1,695,014
<p>Is there a secure Python intepreter?</p> <p>Imagine a Python VM you can run on your machine, that restricts the operations. No files can be opened, no system calls, etc. It just transforms stdin to stdout, maybe with text processing + math etc.</p> <p>Does such a secure Python VM exist?</p>
6
2009-11-08T01:20:04Z
1,695,905
<p>You don't need a modified Python to restrict execution in a certain sense. Just look at <a href="http://codepad.org/" rel="nofollow">codepad.org</a>, a pastebin where you can paste code (in Python and other languages) and have it run and the output shown. The code runs in a very restricted environment, but that's ju...
2
2009-11-08T09:52:40Z
[ "python", "security", "virtual-machine", "interpreter" ]
Secure Python intepreter?
1,695,014
<p>Is there a secure Python intepreter?</p> <p>Imagine a Python VM you can run on your machine, that restricts the operations. No files can be opened, no system calls, etc. It just transforms stdin to stdout, maybe with text processing + math etc.</p> <p>Does such a secure Python VM exist?</p>
6
2009-11-08T01:20:04Z
1,697,077
<p>You could always go to the source code and make your own flavor of Python. If enough people need it, it will be no time before it's up and running.</p>
0
2009-11-08T16:38:31Z
[ "python", "security", "virtual-machine", "interpreter" ]
Secure Python intepreter?
1,695,014
<p>Is there a secure Python intepreter?</p> <p>Imagine a Python VM you can run on your machine, that restricts the operations. No files can be opened, no system calls, etc. It just transforms stdin to stdout, maybe with text processing + math etc.</p> <p>Does such a secure Python VM exist?</p>
6
2009-11-08T01:20:04Z
2,215,015
<p>Isn't security more a job for the operating system ?</p> <p>I mean, create a user with restricted access to files and such. Then let the vm be ran only with these rights.</p> <p>Or maybe I'm speaking nonsense. I'm no sysadmin or security expert, but I tend to do things with the tools that are made for it.</p>
-1
2010-02-06T22:38:33Z
[ "python", "security", "virtual-machine", "interpreter" ]
How to percent-encode URL parameters in Python?
1,695,183
<p>If I do </p> <pre><code>url = "http://example.com?p=" + urllib.quote(query) </code></pre> <ol> <li>It doesn't encode <code>/</code> to <code>%2F</code> (breaks OAuth normalization)</li> <li>It doesn't handle Unicode (it throws an exception)</li> </ol> <p>Is there a better library?</p>
153
2009-11-08T02:43:45Z
1,695,199
<p>From the <a href="http://docs.python.org/library/urllib.html#urllib.quote">docs</a>:</p> <pre><code>urllib.quote(string[, safe]) </code></pre> <blockquote> <p>Replace special characters in string using the %xx escape. Letters, digits, and the characters '_.-' are never quoted. By default, this function is ...
219
2009-11-08T02:52:22Z
[ "python", "url", "encoding", "urllib", "urlencode" ]
How to percent-encode URL parameters in Python?
1,695,183
<p>If I do </p> <pre><code>url = "http://example.com?p=" + urllib.quote(query) </code></pre> <ol> <li>It doesn't encode <code>/</code> to <code>%2F</code> (breaks OAuth normalization)</li> <li>It doesn't handle Unicode (it throws an exception)</li> </ol> <p>Is there a better library?</p>
153
2009-11-08T02:43:45Z
13,625,238
<p>In Python 3, <a href="http://docs.python.org/2/library/urllib.html#urllib.quote"><code>urllib.quote</code></a> has been moved to <a href="http://docs.python.org/3/library/urllib.parse.html#urllib.parse.quote"><code>urllib.parse.quote</code></a> and it does handle unicode by default.</p> <pre><code>&gt;&gt;&gt; from...
60
2012-11-29T11:52:51Z
[ "python", "url", "encoding", "urllib", "urlencode" ]
How to percent-encode URL parameters in Python?
1,695,183
<p>If I do </p> <pre><code>url = "http://example.com?p=" + urllib.quote(query) </code></pre> <ol> <li>It doesn't encode <code>/</code> to <code>%2F</code> (breaks OAuth normalization)</li> <li>It doesn't handle Unicode (it throws an exception)</li> </ol> <p>Is there a better library?</p>
153
2009-11-08T02:43:45Z
31,401,601
<p>My answer is similar to Paolo's answer.</p> <p>I think module <code>requests</code> is much better. It's based on <code>urllib3</code>. You can try this:</p> <pre><code>&gt;&gt;&gt; from requests.utils import quote &gt;&gt;&gt; quote('/test') '/test' &gt;&gt;&gt; quote('/test', safe='') '%2Ftest' </code></pre>
15
2015-07-14T08:30:58Z
[ "python", "url", "encoding", "urllib", "urlencode" ]
How to percent-encode URL parameters in Python?
1,695,183
<p>If I do </p> <pre><code>url = "http://example.com?p=" + urllib.quote(query) </code></pre> <ol> <li>It doesn't encode <code>/</code> to <code>%2F</code> (breaks OAuth normalization)</li> <li>It doesn't handle Unicode (it throws an exception)</li> </ol> <p>Is there a better library?</p>
153
2009-11-08T02:43:45Z
33,377,041
<p>If you're using django, you can use urlquote:</p> <pre><code>&gt;&gt;&gt; from django.utils.http import urlquote &gt;&gt;&gt; urlquote(u"Müller") u'M%C3%BCller' </code></pre>
2
2015-10-27T19:40:21Z
[ "python", "url", "encoding", "urllib", "urlencode" ]
"".join(reversed(val)) vs val[::-1]...which is pythonic?
1,695,385
<p>So according to the <em>Zen of Python</em> ... <em>Explicit is better than implicit</em>...<em>Sparse is better than dense</em>...<em>Readability counts</em>...but then again <em>Flat is better than nested</em>...so then which is <em>pythonic</em>?</p> <pre><code>val = "which is pythonic?" print("".join(reversed(va...
14
2009-11-08T04:42:34Z
1,695,386
<p>The second one (in my opinion) is more Pythonic as it is simpler, shorter, and clearer.</p> <p>For more info on what is <em>Pythonic</em> I would recommend <a href="http://www.python.org/dev/peps/pep-0020/" rel="nofollow">The Zen of Python</a>:</p> <blockquote> <p>Beautiful is better than ugly.<br> Explici...
4
2009-11-08T04:44:01Z
[ "python" ]
"".join(reversed(val)) vs val[::-1]...which is pythonic?
1,695,385
<p>So according to the <em>Zen of Python</em> ... <em>Explicit is better than implicit</em>...<em>Sparse is better than dense</em>...<em>Readability counts</em>...but then again <em>Flat is better than nested</em>...so then which is <em>pythonic</em>?</p> <pre><code>val = "which is pythonic?" print("".join(reversed(va...
14
2009-11-08T04:42:34Z
1,695,400
<p>With a string, as you have, I would go with the first option, since it makes it clear that the result you want is a string. For a list or other iterable/slicable, I'd go with the second.</p> <p>An added benefit of the first form is it will work if <code>val</code> is not actually a string, but some other iterable ...
0
2009-11-08T04:51:26Z
[ "python" ]
"".join(reversed(val)) vs val[::-1]...which is pythonic?
1,695,385
<p>So according to the <em>Zen of Python</em> ... <em>Explicit is better than implicit</em>...<em>Sparse is better than dense</em>...<em>Readability counts</em>...but then again <em>Flat is better than nested</em>...so then which is <em>pythonic</em>?</p> <pre><code>val = "which is pythonic?" print("".join(reversed(va...
14
2009-11-08T04:42:34Z
1,695,416
<p>My wife Anna has nicknamed <code>x[::-1]</code> "the Martian Smiley" -- I mostly bow to her (and her long experience in training &amp;c, and studies in human psychology &amp;c), when it comes to judging what's easy and natural for most people, and she absolutely <em>loves</em> the martial smiley. "Just walk it back...
45
2009-11-08T04:59:12Z
[ "python" ]
"".join(reversed(val)) vs val[::-1]...which is pythonic?
1,695,385
<p>So according to the <em>Zen of Python</em> ... <em>Explicit is better than implicit</em>...<em>Sparse is better than dense</em>...<em>Readability counts</em>...but then again <em>Flat is better than nested</em>...so then which is <em>pythonic</em>?</p> <pre><code>val = "which is pythonic?" print("".join(reversed(va...
14
2009-11-08T04:42:34Z
1,695,430
<p>First, if you are a beginner, don't worry what is more pythonic or not. This smell language wars, and you will eventually find your own opinion anyway. Just use the way you think is more readable/simpler for you and you will find the light, I think.</p> <p>That said, I agree with Alex's excellent answer (as he is a...
0
2009-11-08T05:08:16Z
[ "python" ]
Searching values of a list in another List using Python
1,695,452
<p>I'm a trying to find a sublist of a list. Meaning if list1 say [1,5] is in list2 say [1,4,3,5,6] than it should return True. What I have so far is this:</p> <pre><code>for nums in l1: if nums in l2: return True else: return False </code></pre> <p>This would be true but I'm trying to return ...
3
2009-11-08T05:20:21Z
1,695,464
<p>This question looks a bit like homework and for this reason I'd like to take the time and discuss what may be going wrong with the snippet shown in the question.</p> <p>Although you are using a word in its plural form, for the nums variable, you need to understand that Python will use this variable to store ONE ite...
2
2009-11-08T05:26:20Z
[ "python", "list" ]
Searching values of a list in another List using Python
1,695,452
<p>I'm a trying to find a sublist of a list. Meaning if list1 say [1,5] is in list2 say [1,4,3,5,6] than it should return True. What I have so far is this:</p> <pre><code>for nums in l1: if nums in l2: return True else: return False </code></pre> <p>This would be true but I'm trying to return ...
3
2009-11-08T05:20:21Z
1,695,470
<pre><code>try: last_found = -1 for num in L1: last_found = L2.index(num, last_found + 1) return True except ValueError: return False </code></pre> <p>The <code>index</code> method of list L2 returns the position at which the first argument (<code>num</code>) is found in the list; called, like here, with ...
7
2009-11-08T05:27:51Z
[ "python", "list" ]
Searching values of a list in another List using Python
1,695,452
<p>I'm a trying to find a sublist of a list. Meaning if list1 say [1,5] is in list2 say [1,4,3,5,6] than it should return True. What I have so far is this:</p> <pre><code>for nums in l1: if nums in l2: return True else: return False </code></pre> <p>This would be true but I'm trying to return ...
3
2009-11-08T05:20:21Z
1,695,482
<p>I have a feeling this is more intensive than Alex's answer, but here was my first thought:</p> <pre><code>def test(list1, list2): try: for num in list1: list2 = list2[list2.index(num):] except: return False else: return True </code></pre> <p><strong>Edit:</strong> Just tried it. His...
0
2009-11-08T05:35:28Z
[ "python", "list" ]
Searching values of a list in another List using Python
1,695,452
<p>I'm a trying to find a sublist of a list. Meaning if list1 say [1,5] is in list2 say [1,4,3,5,6] than it should return True. What I have so far is this:</p> <pre><code>for nums in l1: if nums in l2: return True else: return False </code></pre> <p>This would be true but I'm trying to return ...
3
2009-11-08T05:20:21Z
1,695,552
<p>I think this solution is the fastest, since it iterates only once, albeit on the longer list and exits before finishing the iteration if a match is found. (Edit: However, it is not as succinct or as fast as Alex's latest solution)</p> <pre><code>def ck(l1,l2): i,j = 0,len(l1) for e in l2: if e == l1...
2
2009-11-08T06:16:27Z
[ "python", "list" ]
Searching values of a list in another List using Python
1,695,452
<p>I'm a trying to find a sublist of a list. Meaning if list1 say [1,5] is in list2 say [1,4,3,5,6] than it should return True. What I have so far is this:</p> <pre><code>for nums in l1: if nums in l2: return True else: return False </code></pre> <p>This would be true but I'm trying to return ...
3
2009-11-08T05:20:21Z
1,695,626
<p>I have a hard time seeing questions like this and not wishing that Python's list handling was more like Haskell's. This seems a much more straightforward solution than anything I could come up with in Python:</p> <pre><code>contains_inorder :: Eq a =&gt; [a] -&gt; [a] -&gt; Bool contains_inorder [] _ = True contai...
0
2009-11-08T07:05:23Z
[ "python", "list" ]
Searching values of a list in another List using Python
1,695,452
<p>I'm a trying to find a sublist of a list. Meaning if list1 say [1,5] is in list2 say [1,4,3,5,6] than it should return True. What I have so far is this:</p> <pre><code>for nums in l1: if nums in l2: return True else: return False </code></pre> <p>This would be true but I'm trying to return ...
3
2009-11-08T05:20:21Z
1,696,287
<p>This should be easy to understand and avoid corner case nicely as you don't need to work with indexes:</p> <pre><code>def compare(l1, l2): it = iter(l2) for e in l1: try: while it.next() != e: pass except StopIteration: return False return True </code></pre> <p>it tries to c...
1
2009-11-08T12:44:37Z
[ "python", "list" ]
Searching values of a list in another List using Python
1,695,452
<p>I'm a trying to find a sublist of a list. Meaning if list1 say [1,5] is in list2 say [1,4,3,5,6] than it should return True. What I have so far is this:</p> <pre><code>for nums in l1: if nums in l2: return True else: return False </code></pre> <p>This would be true but I'm trying to return ...
3
2009-11-08T05:20:21Z
1,696,950
<p>The ultra-optimized version of Andrea's solution:</p> <pre><code>from itertools import dropwhile from operator import ne from functools import partial def compare(l1, l2): it = iter(l2) try: for e in l1: dropwhile(partial(ne, e), it).next() return True except StopIteration: ...
0
2009-11-08T15:58:55Z
[ "python", "list" ]
How do I mark an item as read with google reader api (using python)
1,695,556
<p>I use the following python function to mark an item as read in google reader, but it always returns error HTTPErrors: HTTP 401: Unauthorized:</p> <pre>def mark_as_read(SID, entryid): token = get_token(SID) mark_as_read_url = 'http://www.google.com/reader/api/0/edit-tag' header = {'Content-type': '...
7
2009-11-08T06:23:31Z
5,171,262
<p>When i compare this to the request I'm making in Firefox (inspected with liveheaders), it looks ok. I only have the extra parameters</p> <pre><code>async=true sync=true s=feed/http://feeds.feedburner.com/37signals/beM </code></pre> <p>And in the user, on the place of <code>-</code> there is a long id.</p> <p>So y...
0
2011-03-02T17:39:59Z
[ "python", "google-reader" ]
How do I mark an item as read with google reader api (using python)
1,695,556
<p>I use the following python function to mark an item as read in google reader, but it always returns error HTTPErrors: HTTP 401: Unauthorized:</p> <pre>def mark_as_read(SID, entryid): token = get_token(SID) mark_as_read_url = 'http://www.google.com/reader/api/0/edit-tag' header = {'Content-type': '...
7
2009-11-08T06:23:31Z
5,955,243
<p>It seems you are missing the authentication header:</p> <pre><code>header = { 'Content-type': 'application/x-www-form-urlencoded', 'Authorization': 'GoogleLogin auth=YOUR_AUTH_TOKEN' } </code></pre>
2
2011-05-10T19:17:29Z
[ "python", "google-reader" ]
How to make words into a category. (NLP)
1,695,841
<pre><code>I love to eat chicken. Today I went running, swimming and played basketball. </code></pre> <p>My objective is to return <strong>FOOD</strong> and <strong>SPORTS</strong> just by analyzing these two sentences. How can you do that?</p> <p>I am familiar with NLP and Wordnet. But is there something more high-...
1
2009-11-08T09:22:19Z
1,695,866
<p><a href="http://labs.google.com/sets" rel="nofollow">Google Sets</a> does some of this, and there is some <a href="http://www.googlelabs.com/show%5Fdetails?app%5Fkey=agtnbGFiczIwLXd3d3ITCxIMTGFic0FwcE1vZGVsGIYxDA" rel="nofollow">discussion</a> that mentions supersets. However, I have not really seen any technical d...
2
2009-11-08T09:33:49Z
[ "python", "text", "nlp", "nltk" ]
How to make words into a category. (NLP)
1,695,841
<pre><code>I love to eat chicken. Today I went running, swimming and played basketball. </code></pre> <p>My objective is to return <strong>FOOD</strong> and <strong>SPORTS</strong> just by analyzing these two sentences. How can you do that?</p> <p>I am familiar with NLP and Wordnet. But is there something more high-...
1
2009-11-08T09:22:19Z
1,697,002
<p>That problem is difficult to solve procedurally, but much progress has been made in the area lately.</p> <p>Most natural language processing begins with a grammar (which may or may not be context free.) Its a set of construction rules stating how more general things are made out of more specific ones.</p> <p>examp...
4
2009-11-08T16:11:20Z
[ "python", "text", "nlp", "nltk" ]
How to make words into a category. (NLP)
1,695,841
<pre><code>I love to eat chicken. Today I went running, swimming and played basketball. </code></pre> <p>My objective is to return <strong>FOOD</strong> and <strong>SPORTS</strong> just by analyzing these two sentences. How can you do that?</p> <p>I am familiar with NLP and Wordnet. But is there something more high-...
1
2009-11-08T09:22:19Z
1,725,401
<p>The question you ask is a whole area of research called topical text categorization. A great overview of techniques is <a href="http://portal.acm.org/citation.cfm?id=505283" rel="nofollow">"Machine learning in automated text categorization" in ACM Computing Surveys, by Fabrizio Sebastiani.</a>. One of the simplest t...
2
2009-11-12T21:04:55Z
[ "python", "text", "nlp", "nltk" ]
How to make words into a category. (NLP)
1,695,841
<pre><code>I love to eat chicken. Today I went running, swimming and played basketball. </code></pre> <p>My objective is to return <strong>FOOD</strong> and <strong>SPORTS</strong> just by analyzing these two sentences. How can you do that?</p> <p>I am familiar with NLP and Wordnet. But is there something more high-...
1
2009-11-08T09:22:19Z
1,734,159
<p>You might take a look at <strong>WordNet Domains</strong> resource by people from FBK. It is an extension of WordNet which is designed to be used for text categorization and word sense disambiguation. It allows varying degrees of granularity.</p> <p><a href="http://wndomains.fbk.eu/" rel="nofollow">http://wndomains...
0
2009-11-14T12:53:21Z
[ "python", "text", "nlp", "nltk" ]
Does WordNet have "levels"? (NLP)
1,695,971
<p>For example...</p> <p>Chicken is an <strong>animal</strong>.<br> Burrito is a <strong>food</strong>.</p> <p>WordNet allows you to do "is-a"...the hiearchy feature.</p> <p>However, how do I know when to stop travelling up the tree? I want a LEVEL.<br> That is consistent.</p> <p>For example, if presented with a bu...
4
2009-11-08T10:29:19Z
1,695,983
<p>WordNet is a lexicon rather than an ontology, so 'levels' don't really apply.</p> <p>There is <a href="http://www.ontologyportal.org/">SUMO</a>, which is an upper ontology which relates to WordNet if you want a directed lattice instead of a network. </p> <p>For some domains, SUMO's mid-level ontology is probably ...
11
2009-11-08T10:34:12Z
[ "python", "text", "nlp", "words", "wordnet" ]
Does WordNet have "levels"? (NLP)
1,695,971
<p>For example...</p> <p>Chicken is an <strong>animal</strong>.<br> Burrito is a <strong>food</strong>.</p> <p>WordNet allows you to do "is-a"...the hiearchy feature.</p> <p>However, how do I know when to stop travelling up the tree? I want a LEVEL.<br> That is consistent.</p> <p>For example, if presented with a bu...
4
2009-11-08T10:29:19Z
1,696,133
<p>In order to get levels, you need to predefine the content of each level. An ontology often defines these as the immediate IS_A children of a specific concept, but if that is absent, you need to develop a method of that yourself.</p> <p>The next step is to put a priority on each concept, in case you want to present ...
2
2009-11-08T11:46:47Z
[ "python", "text", "nlp", "words", "wordnet" ]
Does WordNet have "levels"? (NLP)
1,695,971
<p>For example...</p> <p>Chicken is an <strong>animal</strong>.<br> Burrito is a <strong>food</strong>.</p> <p>WordNet allows you to do "is-a"...the hiearchy feature.</p> <p>However, how do I know when to stop travelling up the tree? I want a LEVEL.<br> That is consistent.</p> <p>For example, if presented with a bu...
4
2009-11-08T10:29:19Z
1,698,380
<p>[<strong>Please credit Pete Kirkham</strong>, he first came with the reference to SUMO which may well answer the question asked by Alex, the OP]</p> <p>(I'm just providing a complement of information here; I started in a comment field but soon ran out of space and layout capabilites...)</p> <p><strong>Alex</strong...
5
2009-11-08T23:46:42Z
[ "python", "text", "nlp", "words", "wordnet" ]
Does WordNet have "levels"? (NLP)
1,695,971
<p>For example...</p> <p>Chicken is an <strong>animal</strong>.<br> Burrito is a <strong>food</strong>.</p> <p>WordNet allows you to do "is-a"...the hiearchy feature.</p> <p>However, how do I know when to stop travelling up the tree? I want a LEVEL.<br> That is consistent.</p> <p>For example, if presented with a bu...
4
2009-11-08T10:29:19Z
1,717,952
<p>WordNet's hypernym tree ends with a single root synset for the word "entity". If you are using WordNet's C library, then you can get a while recursive structure for a synset's ancestors using <code>traceptrs_ds</code>, and you can get the whole synset tree by recursively following <code>nextss</code> and <code>ptrls...
0
2009-11-11T20:46:53Z
[ "python", "text", "nlp", "words", "wordnet" ]
How to create 3 dimensions matrix in numpy , like matlab a(:,:,:)
1,696,135
<p>How to create 3 dimensions matrix in numpy , like matlab a(:,:,:) . I try to convert matlab code that create 3d matrix to python by use numpy.array and i don't know how to create 3d matrix/array in numpy </p>
17
2009-11-08T11:47:19Z
1,696,206
<pre><code>a=np.empty((2,3,5)) </code></pre> <p>creates a 2x3x5 array. (There is also np.zeros if you want the values initialized.)</p> <p>You can also reshape existing arrays:</p> <pre><code>a=np.arange(30).reshape(2,3,5) </code></pre> <p>np.arange(30) creates a 1-d array with values from 0..29. The reshape() meth...
51
2009-11-08T12:12:25Z
[ "python", "matlab", "numpy" ]
Easy Python ASync. Precompiler?
1,696,152
<p>imagine you have an io heavy function like this:</p> <pre><code>def getMd5Sum(path): with open(path) as f: return md5(f.read()).hexdigest() </code></pre> <p>Do you think Python is flexible enough to allow code like this (notice the $):</p> <pre><code>def someGuiCallback(filebutton): ... path =...
2
2009-11-08T11:53:35Z
1,696,269
<p>You can use import hooks to achieve this goal...</p> <ul> <li><a href="http://www.python.org/dev/peps/pep-0302/" rel="nofollow">PEP 302 - New Import Hooks</a></li> <li><a href="http://www.python.org/dev/peps/pep-0369/" rel="nofollow">PEP 369 - Post Import Hooks</a></li> </ul> <p>... but I'd personally view it as a...
2
2009-11-08T12:36:00Z
[ "python", "compiler-construction", "syntax", "asynchronous" ]
Easy Python ASync. Precompiler?
1,696,152
<p>imagine you have an io heavy function like this:</p> <pre><code>def getMd5Sum(path): with open(path) as f: return md5(f.read()).hexdigest() </code></pre> <p>Do you think Python is flexible enough to allow code like this (notice the $):</p> <pre><code>def someGuiCallback(filebutton): ... path =...
2
2009-11-08T11:53:35Z
1,696,288
<p>How about something like this:</p> <pre><code>def performAsync(asyncFunc, notifyFunc): def threadProc(): retValue = asyncFunc() glib.idle_add(notifyFunc, retValue) Thread(target=threadProc).start() def someGuiCallback(filebutton): path = filebutton.getPath() performAsync( la...
1
2009-11-08T12:44:39Z
[ "python", "compiler-construction", "syntax", "asynchronous" ]