title stringlengths 12 150 | question_id int64 469 40.1M | question_score int64 2 5.52k | question_date stringdate 2008-08-02 15:11:16 2016-10-18 06:16:31 | answer_id int64 536 40.1M | answer_score int64 7 8.38k | answer_date stringdate 2008-08-02 18:49:07 2016-10-18 06:19:33 | tags listlengths 1 5 | question_body_md stringlengths 15 30.2k | answer_body_md stringlengths 11 27.8k |
|---|---|---|---|---|---|---|---|---|---|
How to Query model where name contains any word in python list? | 7,088,173 | 22 | 2011-08-17T05:01:19Z | 7,088,229 | 33 | 2011-08-17T05:12:04Z | [
"python",
"django",
"list"
] | Aim to Achieve:
I want all objects where name attribute contains any word from the list.
I have:
```
list = ['word1','word2','word3']
ob_list = data.objects.filter( // What to write here ? )
// or any other way to get the objects where any word in list is contained, in
// the na-me attribute of data.
```
For exam... | You could use [`Q` objects](https://docs.djangoproject.com/en/dev/topics/db/queries/#complex-lookups-with-q-objects) to constuct a query like this:
```
from django.db.models import Q
ob_list = data.objects.filter(reduce(lambda x, y: x | y, [Q(name__contains=word) for word in list]))
```
Edit:
```
reduce(lambda x, y... |
how to show a django ModelForm field as uneditable | 7,088,321 | 3 | 2011-08-17T05:28:29Z | 7,089,528 | 12 | 2011-08-17T08:00:39Z | [
"python",
"django",
"forms",
"model",
"edit"
] | taking my initial lessons with `django ModelForm` ,I wanted to give the user ,ability to edit an entry in a blog.The `BlogEntry` has a `date,postedTime, title and content`.I want to show the user an editform which shows all these fields,but with only `title and content as editable`. The `date and postedTime should be s... | In the form object, declare the attribute of the field as `readonly`:
```
form.fields['field'].widget.attrs['readonly'] = True
``` |
What is the most efficient way to check if a value exists in a NumPy array? | 7,088,625 | 16 | 2011-08-17T06:13:55Z | 7,088,668 | 17 | 2011-08-17T06:18:51Z | [
"python",
"performance",
"numpy"
] | I have a very large NumPy array
```
1 40 3
4 50 4
5 60 7
5 49 6
6 70 8
8 80 9
8 72 1
9 90 7
....
```
I want to check to see if a value exists in the 1st column of the array. I've got a bunch of homegrown ways (e.g. iterating through each row and checking), but given the size of the array I'd like to find the most eff... | Competition time! The most obvious to me would be:
```
np.any(my_array[:, 0] == value)
``` |
What is the most efficient way to check if a value exists in a NumPy array? | 7,088,625 | 16 | 2011-08-17T06:13:55Z | 7,088,674 | 26 | 2011-08-17T06:19:55Z | [
"python",
"performance",
"numpy"
] | I have a very large NumPy array
```
1 40 3
4 50 4
5 60 7
5 49 6
6 70 8
8 80 9
8 72 1
9 90 7
....
```
I want to check to see if a value exists in the 1st column of the array. I've got a bunch of homegrown ways (e.g. iterating through each row and checking), but given the size of the array I'd like to find the most eff... | How about
```
if value in my_array[:, col_num]:
do_whatever
```
Edit: I think `__contains__` is implemented in such a way that this is the same as @detly's version |
What is the most efficient way to check if a value exists in a NumPy array? | 7,088,625 | 16 | 2011-08-17T06:13:55Z | 7,089,483 | 10 | 2011-08-17T07:55:59Z | [
"python",
"performance",
"numpy"
] | I have a very large NumPy array
```
1 40 3
4 50 4
5 60 7
5 49 6
6 70 8
8 80 9
8 72 1
9 90 7
....
```
I want to check to see if a value exists in the 1st column of the array. I've got a bunch of homegrown ways (e.g. iterating through each row and checking), but given the size of the array I'd like to find the most eff... | To check multiple values, you can use numpy.in1d(), which is an element-wise function version of the python keyword in. If your data is sorted, you can use numpy.searchsorted():
```
import numpy as np
data = np.array([1,4,5,5,6,8,8,9])
values = [2,3,4,6,7]
print np.in1d(values, data)
index = np.searchsorted(data, val... |
PyAudio working, but spits out error messages each time | 7,088,672 | 14 | 2011-08-17T06:19:42Z | 13,453,192 | 15 | 2012-11-19T11:50:15Z | [
"python",
"alsa",
"pyaudio"
] | I'm using PyAudio to record input from the microphone.
Since the audio is recording fine for me, should I try to simply suppress its error messages? Or would there be a way of resolving them?
```
ALSA lib pcm.c:2212:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.rear
ALSA lib pcm.c:2212:(snd_pcm_open_noupdate) Unknown... | You can try to clean up your ALSA configuration, for example,
```
ALSA lib pcm.c:2212:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.rear
ALSA lib pcm.c:2212:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.center_lfe
ALSA lib pcm.c:2212:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.side
```
are caused by `/usr/share/als... |
PyAudio working, but spits out error messages each time | 7,088,672 | 14 | 2011-08-17T06:19:42Z | 17,673,011 | 9 | 2013-07-16T09:37:09Z | [
"python",
"alsa",
"pyaudio"
] | I'm using PyAudio to record input from the microphone.
Since the audio is recording fine for me, should I try to simply suppress its error messages? Or would there be a way of resolving them?
```
ALSA lib pcm.c:2212:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.rear
ALSA lib pcm.c:2212:(snd_pcm_open_noupdate) Unknown... | All of the above is true and a good solution. I just came here to suggest a nicer way of re-using the error handler code:
```
from ctypes import *
from contextlib import contextmanager
import pyaudio
ERROR_HANDLER_FUNC = CFUNCTYPE(None, c_char_p, c_int, c_char_p, c_int, c_char_p)
def py_error_handler(filename, line,... |
Most efficient way to sum huge 2D NumPy array, grouped by ID column? | 7,089,379 | 5 | 2011-08-17T07:45:28Z | 7,089,540 | 10 | 2011-08-17T08:01:28Z | [
"python",
"numpy"
] | I have a massive data array (500k rows) that looks like:
```
id value score
1 20 20
1 10 30
1 15 0
2 12 4
2 3 8
2 56 9
3 6 18
...
```
As you can see, there is a non-unique ID column to the left, and various scores in the 3rd column.
I'm looking to quickly add up all of t... | you can use bincount():
```
import numpy as np
ids = [1,1,1,2,2,2,3]
data = [20,30,0,4,8,9,18]
print np.bincount(ids, weights=data)
```
the output is [ 0. 50. 21. 18.], which means the sum of id==0 is 0, the sum of id==1 is 50. |
VTK / Python / compile | 7,089,620 | 5 | 2011-08-17T08:09:25Z | 7,090,656 | 7 | 2011-08-17T09:32:51Z | [
"python",
"compilation",
"cmake",
"vtk"
] | I want to use VTK together with Python on a Windows system.
It seems that I cannot use the windows installer but "have to compile VTK from source code using CMake and a native build system". So far I have installed CMake.
But now I wonder how to proceed? It seems that I need MS Visual Studio to create the project fil... | There is a VTK installer here:
<http://www.lfd.uci.edu/~gohlke/pythonlibs/>
It appears to work fine for me and it beats compiling it. |
Regular expression to match 3 capital letters followed by a small letter followed by 3 capital letters? | 7,090,717 | 2 | 2011-08-17T09:37:37Z | 7,090,731 | 15 | 2011-08-17T09:39:22Z | [
"python",
"regex"
] | I need a regular expression in python which matches exactly 3 capital letters followed by a small letter followed by exactly 3 capital letters.
For example, it should match ASDfGHJ and not ASDFgHJK. | ```
r'\b[A-Z]{3}[a-z][A-Z]{3}\b'
```
This will match what you posted if it is a complete word.
```
r'(?<![^A-Z])[A-Z]{3}[a-z][A-Z]{3}(?![A-Z])'
```
This will match what you posted so long as it's not preceded or followed by another capital letter. |
How do you read from stdin in python from a pipe which has no ending | 7,091,413 | 11 | 2011-08-17T10:36:54Z | 7,091,512 | 15 | 2011-08-17T10:45:12Z | [
"python",
"pipe",
"stdin"
] | I've problem to read from Standard input or pipe in python when the pipe is from a "open" (do not know right name)
file.
I have as example
**pipetest.py:**
```
import sys
import time
k = 0
try:
for line in sys.stdin:
k = k + 1
print line
except KeyboardInterrupt:
sys.stdout.flush()
pass
print k
`... | Try the next:
```
import sys
import time
k = 0
try:
buff = ''
while True:
buff += sys.stdin.read(1)
if buff.endswith('\n'):
print buff[:-1]
buff = ''
k = k + 1
except KeyboardInterrupt:
sys.stdout.flush()
pass
print k
``` |
python timedelta behaviour on subtraction | 7,091,616 | 8 | 2011-08-17T10:54:15Z | 7,091,759 | 7 | 2011-08-17T11:04:04Z | [
"python",
"datetime",
"timedelta"
] | This question originated when I came upon ([another thread](http://stackoverflow.com/questions/7065761/how-to-substract-two-datetime-time-values-in-django-template-and-how-to-format-a)) about python's datetime and timedelta instances
I followed the update by `jimgardener` and read the comments by `eyquem` ,and tried o... | The `timedelta`s don't represent time from a midnight, just an **amount of time**.
If it took me **three hours** minus **four hours** to do something, it would take me **negative one hour**.
The difference between the two `timedelta`s is **negative one day** plus **45 minutes**.
This is the same as **negative 23 hou... |
how to use Python SaveAs dialog | 7,094,324 | 6 | 2011-08-17T14:13:29Z | 7,094,628 | 7 | 2011-08-17T14:35:01Z | [
"python",
"tkinter"
] | I'm trying to find a python function for presenting a 'save file as' dialog that returns a filename as a string.
I quickly found the `tkFileDialog` module, only to realize that its `asksaveasfilename` function throws an exception if the file entered doesn't already exist, which is not the behavior I'm looking for.
I ... | Here is a small example for the `asksaveasfilename()` function. I hope you can use it:
```
import Tkinter, Tkconstants, tkFileDialog
class TkFileDialogExample(Tkinter.Frame):
def __init__(self, root):
Tkinter.Frame.__init__(self, root)
button_opt = {'fill': Tkconstants.BOTH, 'padx': 5, 'pady': 5... |
Python PIL: best scaling method that preserves lines | 7,096,323 | 8 | 2011-08-17T16:32:51Z | 7,098,736 | 12 | 2011-08-17T20:04:35Z | [
"python",
"thumbnails",
"python-imaging-library"
] | I have a 2D drawing with a black background and white lines (exported from Autocad) and I want to create a thumbnail preserving lines, using [Python PIL library](http://effbot.org/imagingbook/image.htm).
But what I obtain using the 'thumbnail' method is just a black picture scattered with white dots.
Note that if I p... | The default resizing method used by `thumbnail` is NEAREST, which is a really bad choice. If you're resizing to 1/5 of the original size for example, it will output one pixel and throw out the next 4 - a one-pixel wide line has only a 1 out of 5 chance of showing up *at all* in the result!
The surprising thing is that... |
Able to run Python code with Unicode string in Eclipse, but getting UnicodeEncodeError when running via command line or Idle. | 7,096,857 | 3 | 2011-08-17T17:19:21Z | 7,098,605 | 8 | 2011-08-17T19:53:11Z | [
"python",
"eclipse",
"unicode",
"pydev"
] | I've experienced this a lot, where I'll decode/encode some string of Unicode in Eclipse (PyDev), and it runs fine and how I expected, but then when I launch the same script from the command line (for example) instead, I'll get encoding errors.
Is there any simple explanation for this? Is Eclipse doing something to the... | ```
value = u'\u2019'.decode( 'utf-8', 'ignore' )
```
Byte strings are DECODED into Unicode strings.
Unicode strings are ENCODED into byte strings.
So if you say `someunicodestring.decode`, it tries to coerce the Unicode string to a byte string, in order to be able to decode it (back to Unicode!). Being an implicit ... |
Able to run Python code with Unicode string in Eclipse, but getting UnicodeEncodeError when running via command line or Idle. | 7,096,857 | 3 | 2011-08-17T17:19:21Z | 7,100,707 | 9 | 2011-08-17T23:22:39Z | [
"python",
"eclipse",
"unicode",
"pydev"
] | I've experienced this a lot, where I'll decode/encode some string of Unicode in Eclipse (PyDev), and it runs fine and how I expected, but then when I launch the same script from the command line (for example) instead, I'll get encoding errors.
Is there any simple explanation for this? Is Eclipse doing something to the... | Just wanted to add why it worked on PyDev: it has a special sitecustomize that'll customize python through sys.setdefaultencoding to use the encoding of the PyDev console.
Note that the response from bobince is correct, if you have a unicode string, you have to use the encode() method to transform it into a proper str... |
pygame dual monitors and fullscreen | 7,097,163 | 4 | 2011-08-17T17:48:11Z | 8,107,070 | 7 | 2011-11-12T19:46:05Z | [
"python",
"pygame"
] | I am using pygame to program a simple behavioral test. I'm running it on my macbook pro and have almost all the functionality working. However, during testing I'll have a second, external monitor that the subject sees and the laptop monitor. I'd like to have the game so up fullscreen on the external monitor and not on ... | Pygame doesn't support two displays in a single pygame process(yet). See the question [here](http://www.gamedev.net/topic/503946-pygame-181-released/page__view__findpost__p__4287142) and developer answer [immediately after](http://www.gamedev.net/topic/503946-pygame-181-released/page__view__findpost__p__4287718), where... |
Vim Python completion | 7,097,299 | 26 | 2011-08-17T18:00:22Z | 12,885,410 | 28 | 2012-10-14T18:51:00Z | [
"python",
"vim",
"omnicomplete"
] | I'm having trouble with Vim and Python completion.
In fact I'm totally confused how does this work.
I have generic gvim 7.3, on windows 7 (with python/dyn)
I'm using SuperTab plugin, amongst many others, some of which
are python-specific, with following settings in vimrc:
```
au FileType python set omnifunc=pythoncom... | pythoncomplete is rather old and unmaintained.
Try to use Jedi: <https://github.com/davidhalter/jedi-vim>
It was originally an improved pythoncomplete, but is now much much more powerful!
It works for complex code:
And has additional features:
![enter image descriptio... |
Django - get_or_create not working | 7,097,475 | 6 | 2011-08-17T18:13:26Z | 7,099,051 | 7 | 2011-08-17T20:27:49Z | [
"python",
"django",
"django-models"
] | can you help me understand why this code causes a duplicate entry (IntegrityError)?
I'm on Django 1.2.
```
(row, is_new) = MyModel.objects.get_or_create(field1=1)
row.other_field = 2
row.save()
```
I do have a unique constraint on field1. If there is a row where field1=1, everything works fine, Django does a "get".
... | Assuming that's a reasonably faithful representation of your real code, not surprisingly it's not Django that's busted, it's your model.
You've overridden the automatic primary key field with your own `id` field, but neglected to make it an autoincrement. So the database is not using a new value for the PK, hence the ... |
What is an attracting component subgraph? | 7,097,627 | 3 | 2011-08-17T18:27:09Z | 7,098,068 | 7 | 2011-08-17T19:04:40Z | [
"python",
"networkx"
] | What is a attracting component subgraph of a graph?
[Networkx has an algorithm for this.](http://networkx.lanl.gov/reference/generated/networkx.algorithms.components.attracting.attracting_component_subgraphs.html?highlight=subgraph#networkx.algorithms.components.attracting.attracting_component_subgraphs) But I am un... | The definition of an attracting component is provided in the documentation for `nx.algorithms.components.attracting_components`.
> An attracting component in a directed graph is a strongly connected
> component with the property that a random walker on the graph will
> never leave the component, once it enters the com... |
Using PIL to fill empty image space with nearby colors (aka inpainting) | 7,098,410 | 9 | 2011-08-17T19:35:58Z | 7,103,508 | 8 | 2011-08-18T06:55:04Z | [
"python",
"image-processing",
"numpy",
"python-imaging-library"
] | I create an image with PIL:

I need to fill in the empty space (depicted as black). I could easily fill it with a static color, but what I'd like to do is fill the pixels in with nearby colors. For example, the first pixel after the border might be a Gaussian blur o... | A method with nice results is the [**Navier-Stokes Image Restoration**.](http://www.dtic.upf.edu/~mbertalmio/final-cvpr.pdf) I know OpenCV has it, don't know about PIL.
Your example:
 ... |
Repeatedly extract a line between two delimiters in a text file, Python | 7,098,530 | 8 | 2011-08-17T19:47:03Z | 7,098,678 | 15 | 2011-08-17T19:59:42Z | [
"python",
"regex"
] | I have a text file in the following format:
```
DELIMITER1
extract me
extract me
extract me
DELIMITER2
```
I'd like to extract every block of `extract me`s between DELIMITER1 and DELIMITER2 in the .txt file
This is my current, non-performing code:
```
import re
def GetTheSentences(file):
fileContents = open(f... | You can simplify this to one regular expression using `re.S`, the [DOTALL flag](http://docs.python.org/library/re.html#re.DOTALL).
```
import re
def GetTheSentences(infile):
with open(infile) as fp:
for result in re.findall('DELIMITER1(.*?)DELIMITER2', fp.read(), re.S):
print result
# extrac... |
How to ignore hidden files using os.listdir()? | 7,099,290 | 32 | 2011-08-17T20:48:50Z | 7,099,316 | 8 | 2011-08-17T20:51:19Z | [
"python",
"hidden-files"
] | My python script executes an `os.listdir(path)` where the path is a queue containing archives that I need to treat one by one.
The problem is that I'm getting the list in an array and then I just do a simple `array.pop(0)`. It was working fine until I put the project in subversion. Now I get the `.svn` folder in my ar... | [glob](http://docs.python.org/3/library/glob.html):
```
>>> import glob
>>> glob.glob('*')
```
(`glob` claims to use `listdir` and `fnmatch` under the hood, but it also checks for a leading `'.'`, not by using `fnmatch`.) |
How to ignore hidden files using os.listdir()? | 7,099,290 | 32 | 2011-08-17T20:48:50Z | 7,099,342 | 37 | 2011-08-17T20:53:33Z | [
"python",
"hidden-files"
] | My python script executes an `os.listdir(path)` where the path is a queue containing archives that I need to treat one by one.
The problem is that I'm getting the list in an array and then I just do a simple `array.pop(0)`. It was working fine until I put the project in subversion. Now I get the `.svn` folder in my ar... | You can write one yourself:
```
def listdir_nohidden(path):
for f in os.listdir(path):
if not f.startswith('.'):
yield f
```
Or you can use a [glob](http://docs.python.org/library/glob.html):
```
def listdir_nohidden(path):
return glob.glob(os.path.join(path, '*'))
```
Either of these wi... |
How to ignore hidden files using os.listdir()? | 7,099,290 | 32 | 2011-08-17T20:48:50Z | 14,063,074 | 9 | 2012-12-28T00:26:46Z | [
"python",
"hidden-files"
] | My python script executes an `os.listdir(path)` where the path is a queue containing archives that I need to treat one by one.
The problem is that I'm getting the list in an array and then I just do a simple `array.pop(0)`. It was working fine until I put the project in subversion. Now I get the `.svn` folder in my ar... | On Windows, Linux and OS X:
```
if os.name == 'nt':
import win32api, win32con
def folder_is_hidden(p):
if os.name== 'nt':
attribute = win32api.GetFileAttributes(p)
return attribute & (win32con.FILE_ATTRIBUTE_HIDDEN | win32con.FILE_ATTRIBUTE_SYSTEM)
else:
return p.startswith('.') #... |
How to ignore hidden files using os.listdir()? | 7,099,290 | 32 | 2011-08-17T20:48:50Z | 16,289,300 | 8 | 2013-04-29T22:29:51Z | [
"python",
"hidden-files"
] | My python script executes an `os.listdir(path)` where the path is a queue containing archives that I need to treat one by one.
The problem is that I'm getting the list in an array and then I just do a simple `array.pop(0)`. It was working fine until I put the project in subversion. Now I get the `.svn` folder in my ar... | ```
filter( lambda f: not f.startswith('.'), os.listdir('.'))
``` |
Storing Python dictionaries | 7,100,125 | 39 | 2011-08-17T22:06:47Z | 7,100,163 | 18 | 2011-08-17T22:10:15Z | [
"python",
"json",
"dictionary",
"save",
"pickle"
] | I'm used to bringing data in and out of Python using .csv files, but there are obvious challenges to this. Any advice on simple ways to store a dictionary (or sets of dictionaries) in a json or pck file? For example:
```
data = {}
data ['key1'] = "keyinfo"
data ['key2'] = "keyinfo2"
```
I would like to know both how ... | Minimal example, writing directly to a file:
```
import json
json.dump(data, open(filename, 'wb'))
data = json.load(open(filename))
```
or safely opening / closing:
```
import json
with open(filename, 'wb') as outfile:
json.dump(data, outfile)
with open(filename) as infile:
data = json.load(infile)
```
If y... |
Storing Python dictionaries | 7,100,125 | 39 | 2011-08-17T22:06:47Z | 7,100,202 | 107 | 2011-08-17T22:14:53Z | [
"python",
"json",
"dictionary",
"save",
"pickle"
] | I'm used to bringing data in and out of Python using .csv files, but there are obvious challenges to this. Any advice on simple ways to store a dictionary (or sets of dictionaries) in a json or pck file? For example:
```
data = {}
data ['key1'] = "keyinfo"
data ['key2'] = "keyinfo2"
```
I would like to know both how ... | **[Pickle](http://docs.python.org/library/pickle.html) save:**
```
import cPickle as pickle
with open('data.p', 'wb') as fp:
pickle.dump(data, fp)
```
**[Pickle](http://docs.python.org/library/pickle.html) load:**
```
with open('data.p', 'rb') as fp:
data = pickle.load(fp)
```
---
**[JSON](http://docs.pyth... |
Python/NumPy first occurrence of subarray | 7,100,242 | 7 | 2011-08-17T22:20:24Z | 7,100,681 | 8 | 2011-08-17T23:17:45Z | [
"python",
"numpy",
"arrays"
] | In Python or NumPy, what is the best way to find out the first occurrence of a subarray?
For example, I have
```
a = [1, 2, 3, 4, 5, 6]
b = [2, 3, 4]
```
What is the fastest way (run-time-wise) to find out where b occurs in a? I understand for strings this is extremely easy, but what about for a list or numpy ndarra... | I'm assuming you're looking for a numpy-specific solution, rather than a simple list comprehension or for loop. One approach might be to use the [rolling window](http://stackoverflow.com/questions/6811183/rolling-window-for-1d-arrays-in-numpy) technique to search for windows of the appropriate size. Here's the rolling\... |
Finding in elements in a tuple and filtering them | 7,100,243 | 3 | 2011-08-17T22:20:36Z | 7,100,256 | 7 | 2011-08-17T22:22:57Z | [
"python"
] | Assuming I have a tuple like:
```
[('text-1','xxx'), ('img-1','iii'), ('img-2','jjj'), ('text-2','xxx')]
```
I want to filter out the list and produce a new one with elements that begin with 'img'. So my new list will look like:
```
[('img-1','iii'), ('img-2','jjj')]
```
Thanks! | One way:
```
>>> l = [('text-1','xxx'), ('img-1','iii'), ('img-2','jjj'), ('text-2','xxx')]
>>> [t for t in l if t[0].startswith('img')]
[('img-1', 'iii'), ('img-2', 'jjj')]
```
Another way:
```
>>> filter(lambda x: x[0].startswith('img'), l)
[('img-1', 'iii'), ('img-2', 'jjj')]
```
The first is called a list compr... |
Flask session member not persisting across requests | 7,100,315 | 3 | 2011-08-17T22:30:16Z | 7,114,057 | 8 | 2011-08-18T20:57:27Z | [
"python",
"flask"
] | I'm writing a quick app to view a giant XML file with some AJAX style calls to `viewgroup`. My problem is `session['groups']` not persisting. I have some old array with only 4 members that is stuck somewhere (cookie?..). That value is present when `view` is called. I then overwrite that session member with info from th... | The data was simply too big to serialize into the session. Now I generate a key into a global dict and store that key in the session.
```
gXmlData[path] = groups
```
There's the problem that the global dict will stay around forever with more and more keys but the process isn't meant to live long. |
Flask route with URI encoded component | 7,100,573 | 17 | 2011-08-17T23:03:00Z | 7,101,089 | 23 | 2011-08-18T00:27:35Z | [
"python",
"flask"
] | It seems Flask doesn't support routes with a URI encoded component. I'm curious if I'm doing something wrong, or if there is a special flag I need to include.
My route looks something like this:
```
@app.route('/foo/<encoded>/bar/')
def foo(encoded):
# ...
pass
```
The URL that this should match can look like th... | Add `path` to your url rule:
`@app.route('/foo/<path:encoded>/bar/')`
Update per comment: The route API docs are here: <http://flask.pocoo.org/docs/api/#flask.Flask.route>. The underlying classes that implement the `path` style route converter are here: <http://werkzeug.pocoo.org/docs/routing/#custom-converters> (thi... |
How do I stop having carriage returns added to my file output in Python? | 7,100,698 | 3 | 2011-08-17T23:21:04Z | 7,100,716 | 7 | 2011-08-17T23:24:01Z | [
"python",
"file-io"
] | I'm trying to parse a BMP file, do some changes and then reassemble a new BMP using Python.
The carriage return seems to be a huge problem. When I open the bitmap file using Notepad++ and search for `"\r'`, the character does not exist. I read the file in Python (readData = fileIn.read()) and try searching using `read... | You're probably opening the file as text (the default) when you want to open it as binary.
```
open("example.bmp", "rb") # to [r]ead as [b]inary
open("example.bmp", "wb") # to [w]rite as [b]inary
```
From [the documentation](http://docs.python.org/library/functions.html#open):
> The default is to use text mode, whic... |
Testing if all values in a numpy array are equal | 7,100,995 | 9 | 2011-08-18T00:09:06Z | 7,101,026 | 43 | 2011-08-18T00:16:25Z | [
"python",
"numpy"
] | I have an numpy one dimensional array c that is supposed to be filled with the contents of
`a + b`. I'm first executing `a + b` on a device using `PyOpenCL`
I want to quickly determine the correctness of the result array `c` in python using numpy slicing.
This is what I currently have
```
def python_kernel(a, b, c):... | Why not just use [`numpy.array_equal(a1, a2)`*[docs]*](http://docs.scipy.org/doc/numpy/reference/generated/numpy.array_equal.html) from NumPy's functions? |
Testing if all values in a numpy array are equal | 7,100,995 | 9 | 2011-08-18T00:09:06Z | 7,101,240 | 7 | 2011-08-18T00:57:13Z | [
"python",
"numpy"
] | I have an numpy one dimensional array c that is supposed to be filled with the contents of
`a + b`. I'm first executing `a + b` on a device using `PyOpenCL`
I want to quickly determine the correctness of the result array `c` in python using numpy slicing.
This is what I currently have
```
def python_kernel(a, b, c):... | You would call `any` on the result of the comparison: `if np.any(a+b != c):` or equivalently `if np.all(a+b == c):`. `a+b != c` creates an array of `dtype=bool`, and then `any` looks at that array to see if any member is `True`.
```
>>> import numpy as np
>>> a = np.array([1,2,3])
>>> b = np.array([4,5,2])
>>> c = a+b... |
get_or_create() takes exactly 1 argument (2 given) | 7,101,077 | 4 | 2011-08-18T00:23:59Z | 7,101,101 | 12 | 2011-08-18T00:30:10Z | [
"python",
"django",
"django-models"
] | Last time I checked, (h) one argument:
```
for entry in f['entries']:
h = {'feed':self, 'link': entry['link'],'title':entry['title'],
'summary':entry['summary'],
'updated_at':datetime.fromtimestamp(mktime(entry['updated_parsed']))}
en = Entry.objects.get_or_create(h)
```
This code is failin... | `get_or_create` takes keyword arguments only. If the arguments are in a dict, you can call it with:
```
en = Entry.objects.get_or_create(**h)
```
Or you can put the keyword arguments directly:
```
en = Entry.objects.get_or_create(name=value, ....)
```
The reason the error message told you that you supplied two argu... |
How can I get a Python generator to return None rather than StopIteration? | 7,102,050 | 18 | 2011-08-18T03:29:35Z | 7,102,204 | 41 | 2011-08-18T04:00:11Z | [
"python",
"exception",
"generator",
"stopiteration"
] | I am using generators to perform searches in lists like this simple example:
```
>>> a = [1,2,3,4]
>>> (i for i, v in enumerate(a) if v == 4).next()
3
```
(Just to frame the example a bit, I am using very much longer lists compared to the one above, and the entries are a little bit more complicated than `int`. I do i... | If you are using Python 2.6+ you should use the [`next`](http://docs.python.org/library/functions.html#next) built-in function, not the `next` method (which was replaced with `__next__` in 3.x). The `next` built-in takes an optional default argument to return if the iterator is exhausted, instead of raising `StopIterat... |
What gui library is used by sublime text editor? | 7,102,378 | 50 | 2011-08-18T04:28:21Z | 7,102,527 | 16 | 2011-08-18T04:49:52Z | [
"python",
"user-interface",
"sublimetext"
] | I've downloaded an editor of [sublimetext](http://www.sublimetext.com/) and found that it's written in python.
I want to know what GUI library is used in there, but I'm not good at python.
The filenames of files that are in the editor executables directory are:
```
bz2.pyd
Microsoft.VC90.CRT.manifest
msvcp90.dll
... | a little Googling suggested it is using the Sublime GUI, which judging by the Debian source package is written in C++.
then again, running `strings` on the Linux `sublime_text` binary shows the following shared libraries (equivalent of Windows DLLs) which might suggest gtk:
```
/lib/ld-linux.so.2
libgtk-x11-2.0.so.0
... |
What gui library is used by sublime text editor? | 7,102,378 | 50 | 2011-08-18T04:28:21Z | 7,135,574 | 11 | 2011-08-21T00:26:55Z | [
"python",
"user-interface",
"sublimetext"
] | I've downloaded an editor of [sublimetext](http://www.sublimetext.com/) and found that it's written in python.
I want to know what GUI library is used in there, but I'm not good at python.
The filenames of files that are in the editor executables directory are:
```
bz2.pyd
Microsoft.VC90.CRT.manifest
msvcp90.dll
... | It might not be written in Python. The reason you see Python code is users can write scripts/plugin in Pythons to extend Sublime Text. I suspect it is written in C++ with GTK as GUI toolkit. |
What gui library is used by sublime text editor? | 7,102,378 | 50 | 2011-08-18T04:28:21Z | 9,201,645 | 103 | 2012-02-08T21:23:52Z | [
"python",
"user-interface",
"sublimetext"
] | I've downloaded an editor of [sublimetext](http://www.sublimetext.com/) and found that it's written in python.
I want to know what GUI library is used in there, but I'm not good at python.
The filenames of files that are in the editor executables directory are:
```
bz2.pyd
Microsoft.VC90.CRT.manifest
msvcp90.dll
... | Sublime Text 2 is mostly coded in C++ and uses a custom UI toolkit. Here is the author, Jon Skinner, explaining it: <http://news.ycombinator.com/item?id=2822114>.
> I keep meaning to write a blog post with some details on this, but as
> with many things, I usually end up coding instead. Sublime Text 2 is
> almost enti... |
Is there a way to leave an argument out of the help using python argparse | 7,102,611 | 6 | 2011-08-18T05:04:18Z | 7,102,626 | 12 | 2011-08-18T05:06:06Z | [
"python",
"argparse"
] | I have an argument that is an internal debug flag and shouldn't be run by users who don't know what they are doing.
I realize that hiding it is in essence security by obscurity, but I'm not concerned about malice so much as incompetence.
Optparse had a SUPPRESS\_HELP option, is there and argparse equivalent? | ```
parser.add_argument('--secret', help=argparse.SUPPRESS)
```
From here: <http://argparse.googlecode.com/svn/trunk/doc/argparse-vs-optparse.html>
First Google result for `argparse suppress_help`, by the way. |
jsonify a SQLAlchemy result set in Flask | 7,102,754 | 69 | 2011-08-18T05:24:09Z | 7,103,486 | 93 | 2011-08-18T06:52:15Z | [
"python",
"sqlalchemy",
"flask",
"flask-sqlalchemy"
] | I'm trying to jsonify a SQLAlchemy result set in Flask/Python.
The Flask mailing list suggested the following method <http://librelist.com/browser//flask/2011/2/16/jsonify-sqlalchemy-pagination-collection-result/#04a0754b63387f87e59dda564bde426e> :
```
return jsonify(json_list = qryresult)
```
However I'm getting th... | It seems that you actually haven't executed your query. Try following:
```
return jsonify(json_list = qryresult.all())
```
**[Edit]**: Problem with jsonify is, that usually the objects cannot be jsonified automatically. Even Python's datetime fails ;)
What I have usually done, is to add an extra property (like `seri... |
jsonify a SQLAlchemy result set in Flask | 7,102,754 | 69 | 2011-08-18T05:24:09Z | 9,746,249 | 27 | 2012-03-17T00:42:52Z | [
"python",
"sqlalchemy",
"flask",
"flask-sqlalchemy"
] | I'm trying to jsonify a SQLAlchemy result set in Flask/Python.
The Flask mailing list suggested the following method <http://librelist.com/browser//flask/2011/2/16/jsonify-sqlalchemy-pagination-collection-result/#04a0754b63387f87e59dda564bde426e> :
```
return jsonify(json_list = qryresult)
```
However I'm getting th... | I had the same need, to serialize into json. Take a look at [this question](http://stackoverflow.com/questions/2441796/how-to-discover-table-properties-from-sqlalchemy-mapped-object). It shows how to discover columns programmatically. So, from that I created the code below. It works for me, and I'll be using it in my w... |
jsonify a SQLAlchemy result set in Flask | 7,102,754 | 69 | 2011-08-18T05:24:09Z | 14,322,313 | 14 | 2013-01-14T16:20:06Z | [
"python",
"sqlalchemy",
"flask",
"flask-sqlalchemy"
] | I'm trying to jsonify a SQLAlchemy result set in Flask/Python.
The Flask mailing list suggested the following method <http://librelist.com/browser//flask/2011/2/16/jsonify-sqlalchemy-pagination-collection-result/#04a0754b63387f87e59dda564bde426e> :
```
return jsonify(json_list = qryresult)
```
However I'm getting th... | Here's my approach:
MODEL:
```
class AutoSerialize(object):
'Mixin for retrieving public fields of model in json-compatible format'
__public__ = None
def get_public(self, exclude=(), extra=()):
"Returns model's PUBLIC data for jsonify"
data = {}
keys = self._sa_instance_state.attr... |
jsonify a SQLAlchemy result set in Flask | 7,102,754 | 69 | 2011-08-18T05:24:09Z | 27,951,648 | 9 | 2015-01-14T20:16:05Z | [
"python",
"sqlalchemy",
"flask",
"flask-sqlalchemy"
] | I'm trying to jsonify a SQLAlchemy result set in Flask/Python.
The Flask mailing list suggested the following method <http://librelist.com/browser//flask/2011/2/16/jsonify-sqlalchemy-pagination-collection-result/#04a0754b63387f87e59dda564bde426e> :
```
return jsonify(json_list = qryresult)
```
However I'm getting th... | Here's what's usually sufficient for me:
I create a serialization mixin which I use with my models. The serialization function basically fetches whatever attributes the SQLAlchemy inspector exposes and puts it in a dict.
```
from sqlalchemy.inspection import inspect
class Serializer(object):
def serialize(self)... |
Flask - Accessing the config variable in the template | 7,104,198 | 36 | 2011-08-18T08:02:16Z | 7,104,665 | 57 | 2011-08-18T08:44:51Z | [
"python",
"flask",
"jinja2"
] | I am using Flask version 0.7. I have stored the path of static content in a configuration file and loaded it using
```
app.config.from_envvar(<file_name>)
```
Can I be able to access this config variable in the template without passing the variables through the view? | There are a few global variables that are passed in the templates context by default by flask ([here](http://flask.pocoo.org/docs/templating/#standard-context) is the complete list), one of them being `config`, which allows you to access the application configuration from templates. Being a dictionary, it can be access... |
Can Pyramid's Built-in Authentication/Authorization Implement Complex Security Schemes? | 7,104,320 | 4 | 2011-08-18T08:16:29Z | 7,105,098 | 7 | 2011-08-18T09:20:03Z | [
"python",
"security",
"scaling",
"pyramid"
] | It seems like the security model fits very small projects, but that it is probably not feasible to write all possible registered users' hashed passwords in security.py. Do you know any examples of scaling up Pyramid's authentication, or are there any benefits to calling through Pyramid's security scheme into my own dat... | I dont think the size of the project is related to the security model. Either you want a simple or a complex security model. Both can be applied to projects of any size. One of Pyramid's strong points is its extensibility.
Why would you store hashed passwords in `security.py`? (cmiiw here, I probably misunderstood) If... |
[python]: change all the values | 7,104,436 | 3 | 2011-08-18T08:24:56Z | 7,104,545 | 9 | 2011-08-18T08:34:06Z | [
"python",
"dictionary"
] | Code goes below:
```
d = {'a':0, 'b':0, 'c':0, 'd':0} #at the beginning, all the values are 0.
s = 'cbad' #a string
indices = map(s.index, d.keys()) #get every key's index in s, i.e., a-2, b-1, c-0, d-3
#then set the values to keys' index
d = dict(zip(d.keys(), indices)) #this is how I do it, any better way?
print... | Something like this might make your code more readable:
```
dict([(x,y) for y,x in enumerate('cbad')])
```
But you should give more details what you really want to do. Your code will probably fail if the characters in `s` do not fit the keys of `d`. So `d` is just a container for the keys and the values are not impor... |
Why can't I get two lists from one list comprehension? | 7,105,006 | 5 | 2011-08-18T09:14:07Z | 7,105,059 | 8 | 2011-08-18T09:17:30Z | [
"python"
] | So I have an array of the following form:
```
[(1, u'first_type', u'data_gid_1'),
(2, u'first_type', u'data_gid_2'),
(3, u'first_type', u'data_gid_3'),
(4, u'first_type', u'data_gid_4')]
```
Now I want to extract the first and the last element of each inside list into separate lists. So if I do:
```
>>> ids = ... | It doesn't work because the length of `[(dat[0], dat[2]) for dat in all_data]` is the same as the lenght of `all_data`, which is not the same length as the tuple `(ids, gds)`.
Try this instead:
```
(ids, gds) = zip(*[(dat[0], dat[2]) for dat in all_data])
```
or even shorter:
```
(ids, gds) = zip(*all_data)[::2]
``... |
C++ equivalent of Python properties | 7,105,202 | 2 | 2011-08-18T09:27:19Z | 7,105,239 | 7 | 2011-08-18T09:30:43Z | [
"c++",
"python",
"properties"
] | Is there an equivalent of Python properties in C++? Or would it just be better to do this using getters and setters? | Yes, explicit getter and setters would be the closest construct in C++. |
C++ equivalent of Python properties | 7,105,202 | 2 | 2011-08-18T09:27:19Z | 7,105,289 | 8 | 2011-08-18T09:34:57Z | [
"c++",
"python",
"properties"
] | Is there an equivalent of Python properties in C++? Or would it just be better to do this using getters and setters? | In C++ you're either calling a member function, or you're accessing a data member. Python properties are essentially a way of doing the former using the syntax of the latter and there's no sensible way to do that in C++.
In theory you could hack together something with a macro, `#define looks_like_data really_a_functi... |
ValueError: unichr() arg not in range(0x10000) (narrow Python build), please help | 7,105,874 | 13 | 2011-08-18T10:20:38Z | 7,107,319 | 16 | 2011-08-18T12:21:44Z | [
"python",
"html"
] | i am trying to convert the html entity to unichar, the html entity is `󮠖`
when i try to do the following:
```
unichr(int(976918))
```
i got error that:
```
ValueError: unichr() arg not in range(0x10000) (narrow Python build)
```
seems like it is out of range conversion for unichar, any help in this regard i... | You can decode a string that has a Unicode escape (`\U` followed by 8 hex digits, zero-padded) using the `"unicode-escape"` encoding:
```
>>> s = "\\U%08x" % 976918
>>> s
'\\U000ee816'
>>> c = s.decode('unicode-escape')
>>> c
u'\U000ee816'
```
On a narrow build it's stored as a UTF-16 surrogate pair:
```
>>> list(c... |
convert decimal mark | 7,106,417 | 10 | 2011-08-18T11:08:18Z | 7,106,436 | 11 | 2011-08-18T11:09:42Z | [
"python",
"locale",
"decimal-point"
] | I have a csv file with data reading that I want to read into Python. I get lists that contain strings like "2,5". Now doing float("2,5") does not work, because it has the wrong decimal mark.
How do I read this into Python as 2.5? | `float("2,5".replace(',', '.'))` will do in most cases
If `value`is a large number and `.`has been used for thousands, you can:
Replace all commas for points: `value.replace(",", ".")`
Remove all but the last point: `value.replace(".", "", value.count(".") -1)` |
convert decimal mark | 7,106,417 | 10 | 2011-08-18T11:08:18Z | 7,106,835 | 36 | 2011-08-18T11:40:48Z | [
"python",
"locale",
"decimal-point"
] | I have a csv file with data reading that I want to read into Python. I get lists that contain strings like "2,5". Now doing float("2,5") does not work, because it has the wrong decimal mark.
How do I read this into Python as 2.5? | You may do it the locale-aware way:
```
import locale
# Set to users preferred locale:
locale.setlocale(locale.LC_ALL, '')
# Or a specific locale:
locale.setlocale(locale.LC_NUMERIC, "en_DK.UTF-8")
print locale.atof("3,14")
```
Read [this](http://docs.python.org/library/locale.html#background-details-hints-tips-and... |
Sending and Receiving arrays via Sockets | 7,107,075 | 8 | 2011-08-18T12:00:52Z | 7,107,234 | 13 | 2011-08-18T12:14:13Z | [
"python",
"sockets",
"udp"
] | Is it possible to send an array through UDP Sockets using Python? I am using Python 2.5 and trying to send a simple array but it's not working. It can send the array successfully but when I try to print it with an item of the array the program crashes. I'm not sure what the error is as I take the precaution of converti... | `eval` is doing something completely different than what you think.
To send data over network, you need to *serialize* it into an array of bytes, then *deserialize* it back. In Python, serialization of most objects can be done via `pickle` module:
```
if (UDPSock.sendto( pickle.dumps(a), addr)):
```
Deserialization:... |
Combine enumerate + itertools.izip in Python | 7,107,323 | 2 | 2011-08-18T12:22:02Z | 7,107,346 | 11 | 2011-08-18T12:23:57Z | [
"python",
"itertools",
"enumerate"
] | I would like to iterate + enumerate over two lists in Python. The following code looks ugly. Is there any better solution?
```
for id, elements in enumerate(itertools.izip(as, bs)):
a = elements[0]
b = elements[1]
# do something with id, a and b
```
Thank you. | You can assign a and b during the for loop:
```
for id, (a, b) in enumerate(itertools.izip(as, bs)):
# do something with id, a and b
``` |
Combine enumerate + itertools.izip in Python | 7,107,323 | 2 | 2011-08-18T12:22:02Z | 7,107,385 | 7 | 2011-08-18T12:26:56Z | [
"python",
"itertools",
"enumerate"
] | I would like to iterate + enumerate over two lists in Python. The following code looks ugly. Is there any better solution?
```
for id, elements in enumerate(itertools.izip(as, bs)):
a = elements[0]
b = elements[1]
# do something with id, a and b
```
Thank you. | You could use `itertools.count` instead of `enumerate`:
```
for id_, a, b in itertools.izip(itertools.count(), as_, bs):
# do something with id_, a and b
```
Note that I've changed the variable names slightly to avoid a reserved word and the name of a builtin. |
Why does pickle protocol 2 let me serialise an open file object? | 7,107,409 | 16 | 2011-08-18T12:28:39Z | 7,107,601 | 9 | 2011-08-18T12:43:21Z | [
"python",
"pickle",
"python-2.x"
] | Consider:
```
>>> import pickle
>>> thing = open('foobar.txt','w')
>>> pickle.dumps(thing)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.6/pickle.py", line 1366, in dumps
Pickler(file, protocol).dump(obj)
File "/usr/lib/python2.6/pickle.py", line 224, in dump
... | On the [Python Wiki](http://wiki.python.org/moin/UsingPickle), it says
> You cannot pickle open file objects, network connections, or database connections. When you think about it, it makes sense -- pickle cannot will the connection for file object to exist when you unpickle your object, and the process of creating th... |
python method as argument | 7,107,510 | 7 | 2011-08-18T12:35:32Z | 7,107,595 | 8 | 2011-08-18T12:43:02Z | [
"python"
] | So I know in python everything is an 'object' meaning that it can be passed as an argument to a method. But I'm trying to understand how exactly does this work. So I was trying out the following example:
```
class A:
def __init__(self):
self.value = 'a'
def my_method(self)
print self.value
c... | When you access `a.my_method` Python sees that it is an attribute of the class and that `A.my_method` has a method `__get__()` so it calls `A.my_method.__get__(a)`, that method creates a new object (the 'bound method') which contains both a reference to `A.my_method` and a reference to `a` itself. When you call the bou... |
Python: Get the first character of a the first string in a list? | 7,108,080 | 34 | 2011-08-18T13:21:30Z | 7,108,124 | 7 | 2011-08-18T13:24:23Z | [
"python",
"string",
"list",
"character"
] | How would I get the first character from the first string in a list in Python?
It seems that I could use `mylist[0][1:]` but that does not give me the first character.
```
>>> mylist = []
>>> mylist.append("asdf")
>>> mylist.append("jkl;")
>>> mylist[0][1:]
'sdf'
``` | Indexing in python starting from 0. You wrote [1:] this would not return you a first char in any case - this will return you a rest(except first char) of string.
If you have the following structure:
```
mylist = ['base', 'sample', 'test']
```
And want to get fist char for the first one string(item):
```
myList[0][0... |
Python: Get the first character of a the first string in a list? | 7,108,080 | 34 | 2011-08-18T13:21:30Z | 7,108,131 | 54 | 2011-08-18T13:25:16Z | [
"python",
"string",
"list",
"character"
] | How would I get the first character from the first string in a list in Python?
It seems that I could use `mylist[0][1:]` but that does not give me the first character.
```
>>> mylist = []
>>> mylist.append("asdf")
>>> mylist.append("jkl;")
>>> mylist[0][1:]
'sdf'
``` | You almost had it right. The simplest way is
```
mylist[0][0] # get the first character from the first item in the list
```
but
```
mylist[0][:1] # get up to the first character in the first item in the list
```
would also work.
You want to **end** after the first character (character zero), not **start** after... |
using two consecutive values from a list in each iteration | 7,108,184 | 4 | 2011-08-18T13:28:14Z | 7,108,228 | 7 | 2011-08-18T13:32:18Z | [
"python"
] | I have posted a part of my code below. Newton() function calls Bezier() function. The Bezier() function has a list from where I get p0 and p3. What I am trying to do is, in 1st iteration the program should take the first and second items from the plist as p0 and p3. Then in 2nd iteration, p0 and p3 are the second and t... | ```
>>> p = [1, 2, 3, 4, 5]
>>> for p1, p2 in zip(p, p[1:]):
... print p1, p2
...
1 2
2 3
3 4
4 5
```
Does it help? |
Frequently repeated try/except in Python | 7,108,193 | 20 | 2011-08-18T13:28:40Z | 7,108,276 | 22 | 2011-08-18T13:35:52Z | [
"python",
"exception"
] | Firstly, I'm not sure if my approach is proper, so I'm open to a variety of suggestions.
If try/except statements are frequently repeated in code, are there any good ways to shorten them or avoid fully writing them out?
```
try:
# Do similar thing
os.remove('/my/file')
except OSError, e:
# Same exception ... | The best way to abstract exception handling is with a context manager:
```
from contextlib import contextmanager
@contextmanager
def common_handling():
try:
yield
finally:
# whatever your common handling is
```
then:
```
with common_handling():
os.remove('/my/file')
with common_handling(... |
Checking for empty Queue in python's multiprocessing | 7,109,093 | 3 | 2011-08-18T14:30:25Z | 7,110,107 | 8 | 2011-08-18T15:36:23Z | [
"python",
"queue",
"multiprocessing"
] | I have a program using python's packages multiprocessing and Queue. One of my functions have this structure:
```
from multiprocessing import Process, Queue
def foo(queue):
while True:
try:
a = queue.get(block = False)
doAndPrintStuff(a)
except:
print "the end"
... | The exception should be `Queue.Empty`. But are you sure you got the *same* error? In your second example, you also switched the queue itself from `multiprocessing.Queue` to `Queue.Queue`, which I think may be the problem.
It might seem strange, but you have to use the `multiprocessing.Queue` class, but use the `Queue.... |
running hadoop on Google app engine? | 7,110,038 | 2 | 2011-08-18T15:31:27Z | 7,110,310 | 7 | 2011-08-18T15:50:22Z | [
"python",
"google-app-engine",
"hadoop",
"mapreduce"
] | Is it possible to run map reduce jobs on Google app engine?
Any reference or tutorial would help
Thanks | Sort of.
You can't use the actual MapReduce framework - the architecture is too incompatible with AppEngine.
However, there is an equivalent system built specficially for GAE - [appengine-mapreduce](http://code.google.com/p/appengine-mapreduce/). That site is a bit confusing, as the first version of the code only sup... |
SQLAlchemy - don't enforce foreign key constraint on a relationship | 7,110,118 | 10 | 2011-08-18T15:37:30Z | 7,111,348 | 11 | 2011-08-18T17:10:11Z | [
"python",
"sql-server",
"join",
"foreign-keys",
"sqlalchemy"
] | I have a `Test` model/table and a `TestAuditLog` model/table, using SQLAlchemy and SQL Server 2008. The relationship between the two is `Test.id == TestAuditLog.entityId`, with one test having many audit logs. `TestAuditLog` is intended to keep a history of changes to rows in the `Test` table. I want to track when a `T... | You can solve this by:
* **POINT-1:** not having a `ForeignKey` neither on the `RDBMS` level nor on the SA level
* **POINT-2:** explicitly specify join conditions for the relationship
* **POINT-3:** mark relationship cascades to rely on [passive\_deletes](http://www.sqlalchemy.org/docs/orm/relationships.html?highlight... |
faster membership testing in python than set() | 7,110,276 | 12 | 2011-08-18T15:47:50Z | 7,110,296 | 15 | 2011-08-18T15:49:19Z | [
"python",
"performance",
"set",
"fastq"
] | I have to check presence of millions of elements (20-30 letters str) in the list containing 10-100k of those elements. Is there faster way of doing that in python than `set()` ?
```
import sys
#load ids
ids = set( x.strip() for x in open(idfile) )
for line in sys.stdin:
id=line.strip()
if id in ids:
#... | `set` is as fast as it gets.
However, if you rewrite your code to create the `set` once, and not change it, you can use the `frozenset` built-in type. It's exactly the same except immutable.
If you're still having speed problems, you need to speed your program up in other ways, such as by using [PyPy](http://pypy.org... |
faster membership testing in python than set() | 7,110,276 | 12 | 2011-08-18T15:47:50Z | 7,112,339 | 8 | 2011-08-18T18:32:49Z | [
"python",
"performance",
"set",
"fastq"
] | I have to check presence of millions of elements (20-30 letters str) in the list containing 10-100k of those elements. Is there faster way of doing that in python than `set()` ?
```
import sys
#load ids
ids = set( x.strip() for x in open(idfile) )
for line in sys.stdin:
id=line.strip()
if id in ids:
#... | As I noted in my comment, what's probably slowing you down is that you're sequentially checking each line from `sys.stdin` for membership of your 'master' set. This is going to be really, really slow, and doesn't allow you to make use of the speed of set operations. As an example:
```
#!/usr/bin/env python
import ran... |
How do I provide an informal string representation of a python Class (not instance) | 7,110,311 | 6 | 2011-08-18T15:50:24Z | 7,110,542 | 8 | 2011-08-18T16:05:39Z | [
"python"
] | I understand how I can provide an informal representation of an *instance* of the object, but I am interested in providing an informal string representation of the Class name.
So specifically, I want to override what is returned when I print the Class (\_\_main\_\_.SomeClass).
```
>>> class SomeClass:
... def __str... | Your problem is called meta class confusion. Of class A, if `A.__str__(self)` is a template for methods of instances of A, how can I provide a method `__str__()` for A itself? Meta classes to the rescue.
The following links explain this better than I could here.
<http://gnosis.cx/publish/programming/metaclass_1.html>... |
Easy_install and Pip doesn't work | 7,110,360 | 15 | 2011-08-18T15:53:22Z | 7,110,428 | 9 | 2011-08-18T15:58:05Z | [
"python"
] | Easy\_install and Pip doesn't work anymore on python 2.7, when I try to do:
```
sudo easy_install pip
```
I get:
```
Traceback (most recent call last):
File "/usr/bin/easy_install", line 5, in <module>
from pkg_resources import load_entry_point
File "/usr/bin/lib/python2.7/site-packages/distribute-0.6.19-py2... | Try
```
sudo easy_install Distribute
```
and if that exists, but is too old
```
sudo easy_install -U Distribute
```
Looks like either Distribute/setuptools (it's old name) is messed up or Python package settings. If either of these do not help, try removing the full Python 2.7 installation and reinstall everyth... |
Easy_install and Pip doesn't work | 7,110,360 | 15 | 2011-08-18T15:53:22Z | 7,110,754 | 19 | 2011-08-18T16:21:01Z | [
"python"
] | Easy\_install and Pip doesn't work anymore on python 2.7, when I try to do:
```
sudo easy_install pip
```
I get:
```
Traceback (most recent call last):
File "/usr/bin/easy_install", line 5, in <module>
from pkg_resources import load_entry_point
File "/usr/bin/lib/python2.7/site-packages/distribute-0.6.19-py2... | If you installed a new version of `easy_install` through Distribute, the new command may have been installed in another directory, most likely `/usr/local/bin/`. But the traceback shows you were using `/usr/bin/easy_install`. Try this:
```
sudo /usr/local/bin/easy_install ...
``` |
Easy_install and Pip doesn't work | 7,110,360 | 15 | 2011-08-18T15:53:22Z | 13,649,511 | 33 | 2012-11-30T16:51:12Z | [
"python"
] | Easy\_install and Pip doesn't work anymore on python 2.7, when I try to do:
```
sudo easy_install pip
```
I get:
```
Traceback (most recent call last):
File "/usr/bin/easy_install", line 5, in <module>
from pkg_resources import load_entry_point
File "/usr/bin/lib/python2.7/site-packages/distribute-0.6.19-py2... | I had this issue where python's distribute package wasn't installed for some reason. After following the instructions on [python-distribute](https://web.archive.org/web/20100309145033/http://guide.python-distribute.org/installation.html), i got it working.
install the distribute package as follows:
```
$ wget https:/... |
Standard way to create debian packages for distributing Python programs? | 7,110,604 | 47 | 2011-08-18T16:10:36Z | 7,112,197 | 17 | 2011-08-18T18:22:50Z | [
"python",
"debian",
"packaging",
"distutils",
"debhelper"
] | There is a ton of information on how to do this, but since *"there is more than one way to skin a cat"*, and all the tutorials/manuals that cover a bit of the process seem to make certain assumptions which are different from other tutorials, I still didn't manage to grasp it.
So far this is what I think I understood.
... | It looks like [stdeb](http://pypi.python.org/pypi/stdeb) will do what you want.
Also, for installing scripts, I strongly recommend [distribute's console\_scripts](http://pythonhosted.org/setuptools/setuptools.html#automatic-script-creation) entry point support. |
Split string by count of characters | 7,111,068 | 12 | 2011-08-18T16:47:07Z | 7,111,143 | 15 | 2011-08-18T16:53:42Z | [
"python",
"string"
] | I can't figure out how to do this with string methods:
In my file I have something like 1.012345e0070.123414e-004-0.1234567891.21423... which means there is no delimiter between the numbers.
Now if I read a line from this file I get a string like above which I want to split after e.g. 12 characters.
There is no way t... | Since you want to iterate in an unusual way, a generator is a good way to abstract that:
```
def chunks(s, n):
"""Produce `n`-character chunks from `s`."""
for start in range(0, len(s), n):
yield s[start:start+n]
nums = "1.012345e0070.123414e-004-0.1234567891.21423"
for chunk in chunks(nums, 12):
... |
Python Read Formatted String | 7,111,690 | 3 | 2011-08-18T17:38:48Z | 7,111,745 | 9 | 2011-08-18T17:43:42Z | [
"python",
"io"
] | I have a file with a number of lines formatted with the following syntax:
```
FIELD POSITION DATA TYPE
------------------------------
COOP ID 1-6 Character
LATITUDE 8-15 Real
LONGITUDE 17-25 Real
ELEVATION 27-32 Real
STATE 34-35 Character
NAME 37-66 Character
COMPONEN... | **EDIT**: You can still use the struct module:
See the [struct module](http://docs.python.org/library/struct.html) documentation. Looks to me like you want to use `struct.unpack()`
What you want is probably something like:
```
import struct
with open("filename.txt", "r") as f:
for line in f:
(coop_id, la... |
Use Cython as Python to C Converter | 7,112,812 | 29 | 2011-08-18T19:11:21Z | 7,112,916 | 39 | 2011-08-18T19:20:50Z | [
"python",
"c",
"cython"
] | I am EE not so familiar with Python culture and new to it.My question is regarding using Cython for converting Python to C.
---
Background :
I have huge python modules(+8000 lines) .They basically have tons of functions for interacting
with a hardware platform via serial port by reading and writing to hardware regis... | 1. Yes, at its core this is what Cython does. But ...
2. You don't need Cython, however, you do need `libpython`. You may feel like it doesn't use that many Python features, but I think if you try this you'll find it's not true -- you won't be able to separate your program from its dependence on `libpython` while still... |
Overloaded functions in python? | 7,113,032 | 40 | 2011-08-18T19:31:00Z | 7,113,061 | 56 | 2011-08-18T19:33:14Z | [
"python",
"function",
"arguments",
"overloading"
] | Is it possible to have overloaded functions in Python? In C# I would do something like
```
void myfunction (int first, string second)
{
//some code
}
void myfunction (int first, string second , float third)
{
//some different code
}
// This maybe a little off, I haven't coded C# in a couple years
```
and then when I ... | **EDIT** For the new single dispatch generic functions in Python 3.4, see <http://www.python.org/dev/peps/pep-0443/>
You generally don't need to overload functions in Python. Python is [dynamically typed](http://python-history.blogspot.com/2009/02/pythons-use-of-dynamic-typing.html), and supports optional arguments to... |
Overloaded functions in python? | 7,113,032 | 40 | 2011-08-18T19:31:00Z | 7,113,162 | 25 | 2011-08-18T19:40:37Z | [
"python",
"function",
"arguments",
"overloading"
] | Is it possible to have overloaded functions in Python? In C# I would do something like
```
void myfunction (int first, string second)
{
//some code
}
void myfunction (int first, string second , float third)
{
//some different code
}
// This maybe a little off, I haven't coded C# in a couple years
```
and then when I ... | in normal python you can't do what you want. there are two close approximations:
```
def myfunction(first, second, *args):
# args is a tuple of extra arguments
def myfunction(first, second, third=None):
# third is optional
```
however, if you *really* want to do this, you can certainly make it work (at the r... |
does closing a file opened with os.fdopen close the os-level fd? | 7,114,059 | 8 | 2011-08-18T20:57:40Z | 7,114,103 | 9 | 2011-08-18T21:02:58Z | [
"python",
"file-io",
"operating-system"
] | I'm making a temporary file with `tempfile.mkstemp()`. It returns an os-level fd along with the path to the file. I want to `os.fdopen()` the os-level file descriptor to write to it. If I then close the file that `os.fdopen()` returned, will the os-level file descriptor be closed, or do I have to `os.close()` it explic... | I'm pretty sure the fd will be closed. If you don't want that you can dup it first. Of course you can always test this easily enough.
Test is like this:
```
from __future__ import print_function
import os
import tempfile
import errno
fd, tmpname = tempfile.mkstemp()
fo = os.fdopen(fd, "w")
fo.write("something\n")
f... |
What is the difference between `>>> some_object` and `>>> print some_object` in the Python interpreter? | 7,114,675 | 6 | 2011-08-18T22:01:06Z | 7,114,817 | 8 | 2011-08-18T22:16:24Z | [
"printing",
"behavior",
"python"
] | In the interpreter you can just write the name of an object e.g. a list `a = [1, 2, 3, u"hellö"]` at the interpreter prompt like this:
```
>>> a
[1, 2, 3, u'hell\xf6']
```
or you can do:
```
>>> print a
[1, 2, 3, u'hell\xf6']
```
which seems equivalent for lists. At the moment I am working with hdf5 to manage some... | Typing an object into the terminal calls `__repr__()`, which is for a detailed representation of the object you are printing (unambiguous). When you tell something to 'print', you are calling `__str__()` and therefore asking for something human readable.
Alex Martelli gave a great explanation [here](http://stackoverfl... |
General techniques to work with huge amounts of data on a non-super computer | 7,114,849 | 13 | 2011-08-18T22:20:14Z | 7,155,061 | 15 | 2011-08-23T00:22:27Z | [
"python",
"database",
"machine-learning",
"data-analysis"
] | I'm taking some AI classes and have learned about some basic algorithms that I want to experiment with. I have gotten access to several data sets containing lots of great real-world data through a website called Kaggle, which hosts data analysis competitions.
I have tried entering several competitions to improve my ma... | *Prototype*--that's the most important thing when working with big data. Sensibly carve it up so that you can load it in memory to access it with an interpreter--e.g., python, R. That's the best way to create and refine your analytics process flow at scale.
In other words, trim your multi-GB-sized data files so that t... |
How to "embed" a small numpy array into a predefined block of a large numpy array? | 7,115,437 | 10 | 2011-08-18T23:39:47Z | 7,115,957 | 16 | 2011-08-19T01:11:14Z | [
"python",
"numpy"
] | I have a small NXN array "block" that I want to plug into a specified region (i.e., a diagonal region at "start") of a large array "wall". Is there an efficient method to archive this?
```
wall[start:start+N][start:start+N] = block[:][:]
```
currently what I am doing is simply:
```
for i in xrange(N):
wall[start... | you can use multi dimension index:
```
import numpy as np
wall = np.zeros((10,10),dtype=np.int)
block = np.arange(1,7).reshape(2,3)
x = 2
y = 3
wall[x:x+block.shape[0], y:y+block.shape[1]] = block
```
the output is:
```
>>> wall
array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[... |
Python List operations | 7,115,525 | 5 | 2011-08-18T23:55:09Z | 7,115,685 | 7 | 2011-08-19T00:18:55Z | [
"python",
"list",
"coding-style"
] | This is code I have, but it looks like non-python.
```
def __contains__(self, childName):
"""Determines if item is a child of this item"""
for c in self.children:
if c.name == childName:
return True
return False
```
What is the most "python" way of doing this? Use a lambda filter funct... | I would use:
```
return any(childName == c.name for c in self.children)
```
This is short, and has the same advantage as your code, that it will stop when it finds the first match.
If you'll be doing this often, and speed is a concern, you can create a new attribute which is the set of child names, and then just use... |
what all python packages/libraries are in Google App Engine? | 7,115,587 | 5 | 2011-08-19T00:03:14Z | 7,115,639 | 7 | 2011-08-19T00:11:39Z | [
"python",
"google-app-engine",
"numpy",
"matplotlib",
"scipy"
] | a.) for example I want to know numpy, [scipy](http://scipy-lectures.github.com/), [scikits](http://scikit-learn.sourceforge.net/stable/index.html) and [matplotlib](http://matplotlib.sourceforge.net/) are there in google app engine
b.) is there a way to install them in there(insane question)? | App Engine bundles most of the standard library, with a few exceptions (`marshal` isn't available, `cPickle` is an alias for `pickle`, and modules dealing with, e.g., sockets, won't work), plus `webob`, `simplejson`, `django`, and `PyYAML`. You can see a listing [here](http://code.google.com/appengine/docs/python/runti... |
Python newline display in console | 7,115,829 | 4 | 2011-08-19T00:46:41Z | 7,115,846 | 11 | 2011-08-19T00:49:51Z | [
"python"
] | So, when I try to print help/info of Python functions `function.__doc__`, the console output instead of printing a newline when `\n` occurs in the doc string, prints `\n`. Can anyone help me with disabling/helping out with this?
This is my output:
```
'divmod(x, y) -> (div, mod)\n\nReturn the tuple ((x-x%y)/y, x%y). ... | Looks like you inspected the object in the interactive shell, not printed it. If you mean print, write it.
```
>>> "abc\n123"
"abc\n123"
>>> print "abc\n123"
abc
123
``` |
python tab completion Mac OSX 10.7 (Lion) | 7,116,038 | 35 | 2011-08-19T01:30:42Z | 7,116,997 | 88 | 2011-08-19T04:38:10Z | [
"python",
"readline",
"osx-lion"
] | Before upgrading to lion, I had tab complete working in a python shell via terminal. Following [these instructions](http://blog.e-shell.org/221), it was possible to have tab complete working.
Since upgrading to Lion, I am now unable to get tab complete working in a terminal session of Python. I've followed the above i... | Apple does not ship GNU `readline` with OS X. It does ship [BSD libedit](http://www.opensource.apple.com/source/libedit/libedit-28/) which includes a `readline` compatibility interface. The system Pythons shipped by Apple and the 64-bit/32-bit Pythons from python.org installers are built with `libedit`. The problem is ... |
python tab completion Mac OSX 10.7 (Lion) | 7,116,038 | 35 | 2011-08-19T01:30:42Z | 8,072,282 | 12 | 2011-11-09T21:56:05Z | [
"python",
"readline",
"osx-lion"
] | Before upgrading to lion, I had tab complete working in a python shell via terminal. Following [these instructions](http://blog.e-shell.org/221), it was possible to have tab complete working.
Since upgrading to Lion, I am now unable to get tab complete working in a terminal session of Python. I've followed the above i... | As it uses libedit/editline, the syntax to enable autocompletion is a little bit different.
You can first force emacs bindings (as it is with readline if I'm not wrong) by typing :
`readline.parse_and_bind("bind -e")`
Then you can add autocompletion linked to your TAB button (man editrc) :
`readline.parse_and_bind("... |
Python __file__ attribute absolute or relative? | 7,116,889 | 59 | 2011-08-19T04:18:08Z | 7,116,925 | 64 | 2011-08-19T04:23:49Z | [
"python"
] | I'm having trouble understanding `__file__`. From what I understand, `__file__` returns the absolute path from which the module was loaded.
I'm having problem producing this: I have a `abc.py` with one statement `print __file__`, running from `/d/projects/` `python abc.py` returns `abc.py`. running from `/d/` returns ... | > `__file__` is the pathname of the file from which the module was loaded, if it was loaded from a file. The `__file__` attribute is not present for C modules that are statically linked into the interpreter; for extension modules loaded dynamically from a shared library, it is the pathname of the shared library file.
... |
Python __file__ attribute absolute or relative? | 7,116,889 | 59 | 2011-08-19T04:18:08Z | 22,866,630 | 25 | 2014-04-04T15:14:31Z | [
"python"
] | I'm having trouble understanding `__file__`. From what I understand, `__file__` returns the absolute path from which the module was loaded.
I'm having problem producing this: I have a `abc.py` with one statement `print __file__`, running from `/d/projects/` `python abc.py` returns `abc.py`. running from `/d/` returns ... | `__file__` is always absolute [since Python 3.4](https://docs.python.org/3.4/whatsnew/3.4.html#other-language-changes). Not sure if it resolves symlinks though. |
Python __file__ attribute absolute or relative? | 7,116,889 | 59 | 2011-08-19T04:18:08Z | 23,616,783 | 10 | 2014-05-12T18:59:44Z | [
"python"
] | I'm having trouble understanding `__file__`. From what I understand, `__file__` returns the absolute path from which the module was loaded.
I'm having problem producing this: I have a `abc.py` with one statement `print __file__`, running from `/d/projects/` `python abc.py` returns `abc.py`. running from `/d/` returns ... | Late simple example:
```
from os import path, getcwd, chdir
def print_my_path():
print('cwd: {}'.format(getcwd()))
print('__file__:{}'.format(__file__))
print('abspath: {}'.format(path.abspath(__file__)))
print_my_path()
chdir('..')
print_my_path()
```
Under Python-2.\*, the second call incorrectl... |
Python: overloading tuple multi-assignment capabilities? | 7,117,331 | 8 | 2011-08-19T05:31:43Z | 7,117,412 | 10 | 2011-08-19T05:43:12Z | [
"python",
"tuples"
] | So i have made my own dict-based named-tuple class:
```
class t(dict):
def __getattr__(self, v):
try:
return self[v]
except KeyError:
raise AttributeError("Key " + str(v) + " does not exist.")
def __init__(self, *args, **kwargs):
for source in args:
for i, j in source... | Yes. Implement `__iter__()`.
```
class unpackable_dict(dict):
def __iter__(self):
return (self[key] for key in sorted(self.keys()))
d = unpackable_dict(a=1, b=2)
a, b = d
```
The reason you normally can't unpack values from a dict like you can a tuple is that dicts don't have a defined order. I've used a... |
How to remove specific element in an array using python | 7,118,276 | 53 | 2011-08-19T07:27:02Z | 7,118,295 | 62 | 2011-08-19T07:28:52Z | [
"python",
"arrays"
] | I'm new to Python and want to write something that removes a specific element in an array. I know that I have to `for` loop through the array to find the element that matches the content, but Python for loops are a bit funny.
lets say that I have an array of emails and I want to get rid of the element that matches som... | You don't need to iterate the array. Just:
```
>>> x = ['ala@ala.com', 'bala@bala.com']
>>> x
['ala@ala.com', 'bala@bala.com']
>>> x.remove('ala@ala.com')
>>> x
['bala@bala.com']
```
This will remove the first occurence that matches the string.
EDIT: After your edit, you still don't need to iterate over. Just do:
`... |
What are some good web apps for learning Flask? | 7,118,930 | 17 | 2011-08-19T08:33:14Z | 7,119,024 | 12 | 2011-08-19T08:40:16Z | [
"python",
"flask"
] | I'm looking for apps source code with user registration, login, session, oauth and SQLAlchemy for learning Flask. I have looked at the source for flask.pocoo.org website and also some repos at Github. I believe there are more out there. Appreciate any pointer. Thanks | For login / registration / etc. see [Flask user authentication](http://stackoverflow.com/questions/6972999/flask-user-authentication)
For Oauth see [WSGI Middleware for OAuth authentication](http://stackoverflow.com/questions/4648838/wsgi-middleware-for-oauth-authentication)
See [flask-sqlalchemy](/questions/tagged/f... |
What are some good web apps for learning Flask? | 7,118,930 | 17 | 2011-08-19T08:33:14Z | 9,809,245 | 7 | 2012-03-21T16:55:01Z | [
"python",
"flask"
] | I'm looking for apps source code with user registration, login, session, oauth and SQLAlchemy for learning Flask. I have looked at the source for flask.pocoo.org website and also some repos at Github. I believe there are more out there. Appreciate any pointer. Thanks | [Here](https://github.com/svenstaro/flamejam) is a decent-sized app based on Flask.
I'd also recommend searching github and bitbucket for the term 'Flask', or checking out [nullege's flask page](http://nullege.com/codes/search?cq=flask) (a valuable resource for finding how other projects use certain libraries).
Addit... |
In Python, what is the difference between an object and a dictionary? | 7,119,235 | 10 | 2011-08-19T08:58:45Z | 7,119,348 | 9 | 2011-08-19T09:07:48Z | [
"python",
"object-model"
] | After an object has been created, I can add and remove slots at will, as I can do with a dictionary. Even methods are just objects stored in slots, so I probably can add methods to a dictionary as well.
Is there something I can do with a (non-dictionary) object that I could never do with a dictionary?
Or is it possibl... | > After an object has been created, I can add and remove slots at will, as I can do with a dictionary. Even methods are just objects stored in slots,
Be careful saying slots -- [`__slots__` has a specific meaning in Python](http://docs.python.org/reference/datamodel.html#slots).
> so I probably can add methods to a d... |
Git commit from python | 7,119,452 | 5 | 2011-08-19T09:16:26Z | 7,119,539 | 7 | 2011-08-19T09:24:14Z | [
"python",
"git"
] | I want to write a module in python (This is the learning project) to enhance my git experience. Is there a python module for various git commands? At least the basic ones (commit/diff/log/add)?
I saw [GitPython](https://github.com/gitpython-developers/GitPython) but I couldn't find the support for (new) commits; its m... | Git is designed to consist of "plumbing" and "porcelain". Plumbing components form the foundation, low-level system: Managing objects, repositories, remotes, and so on. Porcelain, on the other hand, means more user-friendly high-level tools that use the plumbing.
Historically, only the most basic/performance-critical ... |
Git commit from python | 7,119,452 | 5 | 2011-08-19T09:16:26Z | 7,119,552 | 9 | 2011-08-19T09:25:15Z | [
"python",
"git"
] | I want to write a module in python (This is the learning project) to enhance my git experience. Is there a python module for various git commands? At least the basic ones (commit/diff/log/add)?
I saw [GitPython](https://github.com/gitpython-developers/GitPython) but I couldn't find the support for (new) commits; its m... | In GitPython you [create a commit from an index object](http://gitpython.readthedocs.org/en/stable/tutorial.html#the-index-object).
In libgit2 you [create a commit from a repository object](http://www.pygit2.org/objects.html#pygit2.Repository.create_commit).
You might also want to look at this question:
* [Python Gi... |
ImportError: No module named PyQt4.QtCore | 7,119,844 | 11 | 2011-08-19T09:51:05Z | 7,120,037 | 15 | 2011-08-19T10:07:36Z | [
"python"
] | I've reïnstalled my ssh server, so I also need to reïnstall my Python packages.
I did that, but I still get the error:
```
ImportError: No module named PyQt4.QtCore
```
I've already successfully installed:
```
sudo apt-get install libqt4-dev
```
But still it don't work, so I tried the installation [instruction o... | As mentioned in the comments, you need to install the `python-qt4` package - no need to recompile it yourself.
`sudo apt-get install python-qt4` |
Does Python have decorators in the standard library? | 7,120,342 | 15 | 2011-08-19T10:34:08Z | 7,120,385 | 20 | 2011-08-19T10:37:52Z | [
"python",
"decorator"
] | Apart from `@staticmethod` and `@classmethod`? Most languages have some basic libraries making use of most of the language features.
It seems that many of the decorators I find myself making are things which tons of people would use, but I haven't found any inbuilt python decorators which do them. Are there such thing... | [property](http://docs.python.org/library/functions.html#property) is usually used as a decorator.
[functools](http://docs.python.org/library/functools.html#module-functools) has several functions normally used as a decorator, such as `total_ordering`, `update_wrapped`, `lru_cache`, and `wraps`.
contextlib has the [`... |
When does a webbrowser send If-Modified-Since? | 7,120,934 | 3 | 2011-08-19T11:32:55Z | 7,121,025 | 9 | 2011-08-19T11:41:56Z | [
"python",
"browser",
"flask",
"if-modified-since"
] | I'm serving a dynamically created `recent.rss` via python flask and naturally that way it is always sent via `200 OK`. I was going to fix this by setting the header `Expires` a week into the future and checking if the browser sent `If-Modified-Since`.
If so (after comparing dates) I would just do `return nothing, 304`... | [RFC 2616 HTTP/1.1](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html) has this note in [14.25 If-Modified-Since](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.25):
> When handling an `If-Modified-Since` header field, some
> servers will use an exact date comparison function, rather than a
> less-t... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.