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
delay a task until certain time
6,579,127
3
2011-07-05T07:17:20Z
6,579,198
7
2011-07-05T07:25:19Z
[ "python", "datetime", "time" ]
What I want to do in a python script is sleep a number of seconds until the required time is reached. IE: if runAt setting is 15:20 and current time is 10:20, how can I work out how many seconds to sleep? I'm not sure how to convert 15:20 to a time and current date then deduct the actual time to get the seconds.
If you subtract one [datetime](http://docs.python.org/library/datetime.html) object from another you get a [timedelta](http://docs.python.org/library/datetime.html#timedelta-objects) object, which has a seconds property, so you can do: ``` t1 = datetime.datetime.now() # other stuff here t2 = datetime.datetime.now() d...
What is a good strategy to group similar words?
6,579,263
6
2011-07-05T07:33:11Z
6,579,334
13
2011-07-05T07:41:07Z
[ "python", "algorithm", "redis" ]
Say I have a list of movie names with misspellings and small variations like this - ``` "Pirates of the Caribbean: The Curse of the Black Pearl" "Pirates of the carribean" "Pirates of the Caribbean: Dead Man's Chest" "Pirates of the Caribbean trilogy" "Pirates of the Caribbean" "Pirates Of The Carribean" ``` Ho...
Have a look at "fuzzy matching". Some great tools in the thread below that calculates similarities between strings. I'm especially fond of the [difflib](http://docs.python.org/library/difflib.html) module ``` >>> get_close_matches('appel', ['ape', 'apple', 'peach', 'puppy']) ['apple', 'ape'] >>> import keyword >>> ge...
Is it ok to spawn threads in a wsgi-application?
6,579,467
14
2011-07-05T07:53:24Z
6,587,335
12
2011-07-05T18:42:07Z
[ "python", "django", "multithreading", "wsgi", "flask" ]
To achieve something similar to google app engines 'deferred calls' (i.e., the request is handled, and afterwards the deferred task is handled), i experimented a little and came up with the solution to spawn a thread in which my deferred call is handled. I am now trying to determine if this is an acceptable way. Is i...
WSGI does not specify the lifetime of an application process (as WSGI application is a Python callable object). You can run it in a way that is completely independent of the web server, in which case, only you control the lifetime. There is also nothing in the WSGI that would prohibit you from spawning threads, or pro...
Is it ok to spawn threads in a wsgi-application?
6,579,467
14
2011-07-05T07:53:24Z
6,604,492
7
2011-07-07T00:14:20Z
[ "python", "django", "multithreading", "wsgi", "flask" ]
To achieve something similar to google app engines 'deferred calls' (i.e., the request is handled, and afterwards the deferred task is handled), i experimented a little and came up with the solution to spawn a thread in which my deferred call is handled. I am now trying to determine if this is an acceptable way. Is i...
FWIW, also have a read of: <http://code.google.com/p/modwsgi/wiki/RegisteringCleanupCode> The hooking of actions to close() of iterable is the only way within context of the WSGI specification itself for doing deferred work. That isn't in a separate thread though and would occur within the context of the actual reque...
Using print statements only to debug
6,579,496
50
2011-07-05T07:55:45Z
6,579,522
73
2011-07-05T07:59:32Z
[ "python" ]
I have been coding a lot in Python of late. And I have been working with data that I haven't worked with before, using formulae never seen before and dealing with huge files. All this made me write a lot of print statements to verify if it's all going right and identify the points of failure. But, generally, outputting...
The [`logging`](http://docs.python.org/library/logging.html) module has everything you could want. It may seem excessive at first, but only use the parts you need. I'd recommend using [`logging.basicConfig`](http://docs.python.org/library/logging.html#logging.basicConfig) to toggle the logging level to `stderr` and the...
Using print statements only to debug
6,579,496
50
2011-07-05T07:55:45Z
6,579,525
14
2011-07-05T07:59:42Z
[ "python" ]
I have been coding a lot in Python of late. And I have been working with data that I haven't worked with before, using formulae never seen before and dealing with huge files. All this made me write a lot of print statements to verify if it's all going right and identify the points of failure. But, generally, outputting...
Use the [logging](http://docs.python.org/library/logging.html) built-in library module instead of printing. You create a `Logger` object (say `logger`), and then after that, whenever you insert a debug print, you just put: ``` logger.debug("Some string") ``` You can use `logger.setLevel` at the start of the program ...
Using print statements only to debug
6,579,496
50
2011-07-05T07:55:45Z
6,579,527
11
2011-07-05T07:59:53Z
[ "python" ]
I have been coding a lot in Python of late. And I have been working with data that I haven't worked with before, using formulae never seen before and dealing with huge files. All this made me write a lot of print statements to verify if it's all going right and identify the points of failure. But, generally, outputting...
A simple way to do this is to call a logging function: ``` DEBUG = True def log(s): if DEBUG: print s log("hello world") ``` Then you can change the value of `DEBUG` and run your code with or without logging. The standard [`logging`](http://docs.python.org/library/logging.html) module has a more elabor...
Duck typing and (java) interface concept
6,579,671
18
2011-07-05T08:15:36Z
6,583,157
14
2011-07-05T13:08:46Z
[ "python", "design", "interface" ]
I just read the Wikipedia article about [duck typing](http://en.wikipedia.org/wiki/Duck_typing), and I feel like I miss an important point about the interface concept I used to in Java: ``` "When I see a bird that walks like a duck and swims like a duck and quacks like a duck, I call that bird a duck." class Duck: ...
Duck typing isn't really about checking whether the things you need are there and then using them. Duck typing is about just using what you need. The `in_the_forest` function was written by a developer who was thinking about ducks. It was designed to operate on a `Duck`. A `Duck` can `quack` and `feathers`, so the cod...
Memory-usage of dictionary in Python?
6,579,757
10
2011-07-05T08:23:44Z
6,579,836
8
2011-07-05T08:30:08Z
[ "python", "dictionary", "memory-management" ]
I am slightly confused when I use the `getsizeof` method in the `sys` module for dictionaries. Below I have created a simple dictionary of two strings. The two strings' sizes are clearly larger than the one of the dictionary. The dictionary size is probably the dictionary overhead only, i.e., it doesn't take the actual...
From the [PythonDocs](http://docs.python.org/dev/library/sys.html#sys.getsizeof) > See [recursive sizeof recipe](http://code.activestate.com/recipes/577504/) for an example of using getsizeof() recursively to find the size of containers and all their contents. So it only counts the overhead, but you can use the funct...
How to match a substring in a string ignoring case in Python
6,579,876
18
2011-07-05T08:33:31Z
6,579,933
22
2011-07-05T08:38:49Z
[ "python", "perl" ]
I'm looking for ignore case string comparison in python. I tried with --> ``` if line.find('mandy') >= 0: ``` but no success for ignore case. I need to find a set of words in a given text file, am reading the file line by line. word on a line can be --> mandy, Mandy, MANDY etc. [i don't want to use toupper/tolower et...
If you don't want to use `str.lower()`, you can use regexp: ``` import re if re.search('mandy', 'Mandy Pande', re.IGNORECASE): # is True ```
What type to store time length in python?
6,580,168
6
2011-07-05T08:59:40Z
6,580,215
10
2011-07-05T09:03:13Z
[ "python", "datetime" ]
I was using : ``` total_time=datetime.time(int(total_time_text.replace("h","").replace("m","").split(" ")[0]),int(total_time_text.replace("h","").replace("m","").split(" ")[1]),0) ``` to store the time length. But when I have : ``` total_time_text ="26h 50m" ``` I get an exception that ``` 'hour must be in 0..23'...
[`datetime.timedelta`](http://docs.python.org/library/datetime.html#timedelta-objects)
how to do a join in sqlalchemy session query?
6,580,835
4
2011-07-05T09:57:04Z
6,581,576
12
2011-07-05T11:00:32Z
[ "python", "orm", "sqlalchemy" ]
I need to find the equivalent of this query in sqlalchemy. ``` SELECT u.user_id, u.user_name, c.country FROM table_user u , table_country c WHERE u.user_email = 'abc@def.com' ``` i tried this below code: ``` session.query(User).join(Country.country).filter(User.user_email == 'abc@def.com').first() ``` and this gave...
Try this, assuming your User mapper has a relationship to Country configured. ``` user, country = session.query(User, Country.country).join(Country).filter(User.user_email == 'abc@def.com').first() ```
filtering dropdown values in django admin
6,581,520
9
2011-07-05T10:54:14Z
6,582,108
11
2011-07-05T11:44:52Z
[ "python", "django", "django-models", "django-admin" ]
``` class Foo(models.Model): title = models.TextField() userid = models.IntegerField() image = models.CharField(max_length=100) def __unicode__(self): return self.title class Bar(models.Model): foo = models.ForeignKey(Foo, related_name='Foo_picks', unique=True) added_on = models.DateTime...
You can provide your own form for ModelAdmin, with custom queryset for foo field. ``` #Create custom form with specific queryset: class CustomBarModelForm(forms.ModelForm): class Meta: model = Bar def __init__(self, *args, **kwargs): super(CustomBarModelForm, self).__init__(*args, **kwargs) ...
How to read numbers from file in Python?
6,583,573
25
2011-07-05T13:40:24Z
6,583,635
52
2011-07-05T13:44:36Z
[ "python", "file", "python-3.x" ]
I'd like to read numbers from file into two dimensional array. File contents: * line containing w, h * h lines containing w integers separated with space For example: ``` 4 3 1 2 3 4 2 3 4 5 6 7 8 9 ```
Assuming you don't have extraneous whitespace: ``` with open('file') as f: w, h = [int(x) for x in next(f).split()] # read first line array = [] for line in f: # read rest of lines array.append([int(x) for x in line.split()]) ``` You could condense the last for loop into a nested list comprehensio...
How to read numbers from file in Python?
6,583,573
25
2011-07-05T13:40:24Z
6,583,736
10
2011-07-05T13:51:22Z
[ "python", "file", "python-3.x" ]
I'd like to read numbers from file into two dimensional array. File contents: * line containing w, h * h lines containing w integers separated with space For example: ``` 4 3 1 2 3 4 2 3 4 5 6 7 8 9 ```
To me this kind of seemingly simple problem is what Python is all about. Especially if you're coming from a language like C++, where simple text parsing can be a pain in the butt, you'll really appreciate the functionally unit-wise solution that python can give you. I'd keep it really simple with a couple of built-in f...
How to override and extend basic Django admin templates?
6,583,877
57
2011-07-05T13:59:39Z
6,586,068
60
2011-07-05T16:48:05Z
[ "python", "django", "django-admin" ]
How do I override an admin template (e.g. admin/index.html) while at the same time extending it (see <https://docs.djangoproject.com/en/dev/ref/contrib/admin/#overriding-vs-replacing-an-admin-template>)? First - I know that this question has been asked and answered before (see [Django: Overriding AND extending an app ...
I had the same issue about a year and a half ago and I found a nice [template loader on djangosnippets.org](http://djangosnippets.org/snippets/1376/) that makes this easy. It allows you to extend a template in a specific app, giving you the ability to create your own **admin/index.html** that extends the admin/index.ht...
How to override and extend basic Django admin templates?
6,583,877
57
2011-07-05T13:59:39Z
17,232,425
9
2013-06-21T09:57:25Z
[ "python", "django", "django-admin" ]
How do I override an admin template (e.g. admin/index.html) while at the same time extending it (see <https://docs.djangoproject.com/en/dev/ref/contrib/admin/#overriding-vs-replacing-an-admin-template>)? First - I know that this question has been asked and answered before (see [Django: Overriding AND extending an app ...
With `django` 1.5 (at least) you can define the template you want to use for a particular `modeladmin` see <https://docs.djangoproject.com/en/1.5/ref/contrib/admin/#custom-template-options> You do something like ``` class Myadmin(admin.ModelAdmin): change_form_template = 'change_form.htm' ``` With `change_form....
How to override and extend basic Django admin templates?
6,583,877
57
2011-07-05T13:59:39Z
20,790,068
28
2013-12-26T19:21:00Z
[ "python", "django", "django-admin" ]
How do I override an admin template (e.g. admin/index.html) while at the same time extending it (see <https://docs.djangoproject.com/en/dev/ref/contrib/admin/#overriding-vs-replacing-an-admin-template>)? First - I know that this question has been asked and answered before (see [Django: Overriding AND extending an app ...
if you need to overwrite the `admin/index.html`, you can set the [index\_template](https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.AdminSite.index_template) parameter of the `AdminSite`. e.g. ``` # urls.py ... from django.contrib import admin admin.site.index_template = 'admin/my_custom...
How to override and extend basic Django admin templates?
6,583,877
57
2011-07-05T13:59:39Z
29,997,719
28
2015-05-02T02:29:28Z
[ "python", "django", "django-admin" ]
How do I override an admin template (e.g. admin/index.html) while at the same time extending it (see <https://docs.djangoproject.com/en/dev/ref/contrib/admin/#overriding-vs-replacing-an-admin-template>)? First - I know that this question has been asked and answered before (see [Django: Overriding AND extending an app ...
As for Django 1.8 being the current release, there is no need to symlink, copy the admin/templates to your project folder, or install middlewares as suggested by the answers above. Here is what to do: 1. create the following tree structure(recommended by the [official documentation](https://docs.djangoproject.com/en/1...
Django: Want to display an empty field as blank rather displaying None
6,584,235
4
2011-07-05T14:23:42Z
6,585,842
37
2011-07-05T16:24:59Z
[ "python", "django", null ]
I have a template called client\_details.html that displays `user`, `note` and `datetime`. Now sometimes, a client may not have an entry for user, note and datetime. What my program will do instead is display `None` if these fields are empty. I do not want the to display None. If a field has no value I don't want to se...
Use the built-in [`default_if_none`](https://docs.djangoproject.com/en/dev/ref/templates/builtins/#default-if-none) filter. ``` {{ client.user|default_if_none:"&nbsp;" }} {{ client.user|default_if_none:"" }} ```
What is the precedence of python compiled files in imports?
6,584,457
9
2011-07-05T14:38:08Z
6,584,552
8
2011-07-05T14:43:43Z
[ "python", "compilation", "bytecode", "cython" ]
Python files are compiled to bytecode (\*.pyc). Using Cython you can compile them to machine code (\*.so in Linux). If you use have both files in the same folder, under the same name what is the precedence between them? Is there an automatic way to ensure that the \*.so file is used instead of the \*.pyc one? Or you...
Python will load the `.so` file first. See [this question](http://stackoverflow.com/q/6319379/577088) for an ordered list of the suffixes that python searches for. Well, I'll just tell you: ``` foo (a directory) foo.so foomodule.so foo.py foo.pyc ```
Remove last character if it's a backslash
6,584,871
32
2011-07-05T15:07:02Z
6,584,893
54
2011-07-05T15:08:44Z
[ "python", "string" ]
Is there a function to chomp last character in the string if it's some special character? For example, I need to remove backslash if it's there, and do nothing, if not. I know I can do it with regex easily, but wonder if there something like a small built-in function for that.
Use `rstrip` to strip the specified character(s) from the right side of the string. ``` my_string = my_string.rstrip('\\') ``` See: <http://docs.python.org/library/stdtypes.html#str.rstrip>
Remove last character if it's a backslash
6,584,871
32
2011-07-05T15:07:02Z
6,584,914
16
2011-07-05T15:09:53Z
[ "python", "string" ]
Is there a function to chomp last character in the string if it's some special character? For example, I need to remove backslash if it's there, and do nothing, if not. I know I can do it with regex easily, but wonder if there something like a small built-in function for that.
If you don't mind all trailing backslashes being removed, you can use [`string.rstrip()`](http://docs.python.org/library/stdtypes.html#str.rstrip) For example: ``` x = '\\abc\\' print x.rstrip('\\') ``` prints: ``` \abc ``` But there is a slight problem with this (based on how your question is worded): This will s...
Remove last character if it's a backslash
6,584,871
32
2011-07-05T15:07:02Z
6,585,016
7
2011-07-05T15:16:17Z
[ "python", "string" ]
Is there a function to chomp last character in the string if it's some special character? For example, I need to remove backslash if it's there, and do nothing, if not. I know I can do it with regex easily, but wonder if there something like a small built-in function for that.
If you only want to remove *one* backslash in the case of multiple, do something like: ``` s = s[:-1] if s.endswith('\\') else s ```
Python: Multi-Dimensional Array Using ctypes?
6,585,031
3
2011-07-05T15:16:58Z
6,585,177
7
2011-07-05T15:30:03Z
[ "python", "ctypes" ]
How do I define a multi-dimensional float array using `ctypes` in `python`? Is there a limitation to the number of dimensions that can be defines?
Here's one quick-and-dirty method: ``` >>> A = ((ctypes.c_float * 10) * 10) >>> a = A() >>> a[5][5] 0.0 ```
Dynamic user based authorization in Pyramid
6,585,370
5
2011-07-05T15:41:42Z
6,588,230
8
2011-07-05T20:04:59Z
[ "python", "authorization", "pyramid" ]
I'm following [security guidelines found on Pyramid docs](http://docs.pylonsproject.org/projects/pyramid/1.1/narr/security.html) along with wiki tutorial [Adding Authorization](http://docs.pylonsproject.org/projects/pyramid/1.0/tutorials/wiki2/authorization.html) Now I need to add restrictions based un single user rat...
You already have a "Resource Tree" by creating the `Root` resource in your project. You just need to add a node on it for `posts` that will return a `Post` object with a particular `__acl__` that contains only the authorized user id. You can then have your `edit_posts` route use `traverse='/posts/{post_id}'` to travers...
Machine learning for weighting adjustment
6,585,734
10
2011-07-05T16:15:23Z
6,588,584
9
2011-07-05T20:39:05Z
[ "python", "machine-learning", "weighting" ]
I'm trying to work out how to implement some machine learning library to help me find out what the correct weighting for each parameter is in order to make a good decision. In more detail: Context: trying to implement a date of publication extractor for html files. This is for news sites, so I don't have a generic da...
Given your problem description, the characteristics of yoru data, and your ML background and personal preferences, i would recommend [Orange](http://orange.biolab.si). Orange is a mature, free and open source project with a large selection of ML algorithms and excellent documentation and training materials. Most users...
Python: Convert list of key-value tuples into dictionary?
6,586,310
40
2011-07-05T17:09:21Z
6,586,330
82
2011-07-05T17:10:58Z
[ "python", "list", "dictionary" ]
I have a list that looks like this ``` [(A, 1), (B, 2), (C, 3)] ``` And want to turn it into a dictionary that looks like ``` (A: 1, B: 2, C: 3) ``` What's the best way to go about this? Thanks. EDIT: It's actually more like ``` [(A, 12937012397), (BERA, 2034927830), (CE, 2349057340)] ```
``` >>> dict([('A', 1), ('B', 2), ('C', 3)]) {'A': 1, 'C': 3, 'B': 2} ```
Python: Convert list of key-value tuples into dictionary?
6,586,310
40
2011-07-05T17:09:21Z
6,586,350
10
2011-07-05T17:12:28Z
[ "python", "list", "dictionary" ]
I have a list that looks like this ``` [(A, 1), (B, 2), (C, 3)] ``` And want to turn it into a dictionary that looks like ``` (A: 1, B: 2, C: 3) ``` What's the best way to go about this? Thanks. EDIT: It's actually more like ``` [(A, 12937012397), (BERA, 2034927830), (CE, 2349057340)] ```
Have you tried this? ``` >>> l=[('A',1), ('B',2), ('C',3)] >>> d=dict(l) >>> d {'A': 1, 'C': 3, 'B': 2} ```
Python: Convert list of key-value tuples into dictionary?
6,586,310
40
2011-07-05T17:09:21Z
6,586,521
32
2011-07-05T17:28:34Z
[ "python", "list", "dictionary" ]
I have a list that looks like this ``` [(A, 1), (B, 2), (C, 3)] ``` And want to turn it into a dictionary that looks like ``` (A: 1, B: 2, C: 3) ``` What's the best way to go about this? Thanks. EDIT: It's actually more like ``` [(A, 12937012397), (BERA, 2034927830), (CE, 2349057340)] ```
> This gives me the same error as trying to split the list up and zip it. ValueError: dictionary update sequence element #0 has length 1916; 2 is required THAT is your **actual** question. The answer is that the elements of your list are not what you think they are. If you type `myList[0]` you will find that the firs...
Django: how to do get_or_create() in a threadsafe way?
6,586,552
13
2011-07-05T17:31:31Z
22,095,136
14
2014-02-28T12:23:03Z
[ "python", "database", "django", "concurrency", "thread-safety" ]
In my Django app very often I need to do something similar to `get_or_create()`. E.g., > User submits a tag. Need to see if > that tag already is in the database. > If not, create a new record for it. If > it is, just update the existing > record. But looking into the doc for `get_or_create()` it looks like it's not ...
Since 2013 or so, get\_or\_create is atomic, so it handles concurrency nicely: > This method is atomic assuming correct usage, correct database > configuration, and correct behavior of the underlying database. > However, if uniqueness is not enforced at the database level for the > kwargs used in a get\_or\_create cal...
parse comma separated csv file with quotes in python
6,586,748
5
2011-07-05T17:48:32Z
6,586,792
13
2011-07-05T17:53:13Z
[ "python", "csv" ]
Below i have a string which represents a single row pulled from a csv file. Each column is separated by a comma and the value is wrapped in "". What is the simplest way to parse out the value from each column in python? ``` "Mr","Bob","","Boberton","","President","","","","Blah, Inc. of Iowa","blah blah blah","","Gran...
Python has a module for that: <http://docs.python.org/library/csv.html> ``` import csv, sys filename = 'some.csv' with open(filename, 'rb') as f: reader = csv.reader(f) try: for row in reader: print row except csv.Error, e: sys.exit('file %s, line %d: %s' % (filename, reader.li...
no cpickle module
6,586,888
2
2011-07-05T18:03:28Z
6,586,919
8
2011-07-05T18:06:14Z
[ "python" ]
When I tried ``` import cpikcle as pickle ``` I got an error message saying `no module named cpickle`. Does anybody know how to get `cpickle` module? Because I heard that `cpickle` is faster than `pickle`. Thanks
Try `import cPickle as pickle` instead. Note the upper-case **'P'**. Also, you misspelled `cPickle` as `cpikcle` in your question.
Haskell vs. Python threading model
6,587,095
6
2011-07-05T18:22:08Z
6,587,439
7
2011-07-05T18:51:38Z
[ "python", "haskell", "multicore" ]
Maybe there's someone out there with the right interests that will know how to answer this. Basically the question is: What are the differences between the `multiprocessing` module in Python, and the parallelism in Haskell. For instance: are threads created in Python mapped to OS threads? If so, what if there are more ...
As opposed to Python (See [Eli's answer](http://stackoverflow.com/questions/6587095/haskell-vs-python-threading-model/6587378#6587378)), the threading model of Haskell is quite different. You have a difference between concurrency (multiple threads handling different aspects of the program) and parallelism (multiple thr...
How to install pip with Python 3?
6,587,507
149
2011-07-05T18:58:49Z
6,587,528
144
2011-07-05T19:01:07Z
[ "python", "python-3.x", "packages", "setuptools", "pip" ]
I want to install [pip](http://pypi.python.org/pypi/pip). It should support Python 3, but it requires setuptools, which is available only for Python 2. How can I install pip with Python 3?
edit: Manual installation and use of `setuptools` is not the standard process anymore. ## If you're running Python 2.7.9+ or Python 3.4+ Congrats, you *should* already have `pip` installed. If you do not, read onward. ## If you're running a Unix-like System You can usually install the package for `pip` through your...
How to install pip with Python 3?
6,587,507
149
2011-07-05T18:58:49Z
13,554,557
146
2012-11-25T19:22:31Z
[ "python", "python-3.x", "packages", "setuptools", "pip" ]
I want to install [pip](http://pypi.python.org/pypi/pip). It should support Python 3, but it requires setuptools, which is available only for Python 2. How can I install pip with Python 3?
I was able to install pip for python 3 on Ubuntu just by running `sudo apt-get install python3-pip`.
How to install pip with Python 3?
6,587,507
149
2011-07-05T18:58:49Z
15,211,599
71
2013-03-04T21:36:59Z
[ "python", "python-3.x", "packages", "setuptools", "pip" ]
I want to install [pip](http://pypi.python.org/pypi/pip). It should support Python 3, but it requires setuptools, which is available only for Python 2. How can I install pip with Python 3?
## Python 3.4+ and Python 2.7.9+ Good news! [Python 3.4](https://docs.python.org/3/whatsnew/3.4.html) (released March 2014) ships with Pip. This is the best feature of any Python release. It makes the community's wealth of libraries accessible to everyone. Newbies are no longer excluded by the prohibitive difficulty o...
How to install pip with Python 3?
6,587,507
149
2011-07-05T18:58:49Z
17,517,654
21
2013-07-08T00:17:44Z
[ "python", "python-3.x", "packages", "setuptools", "pip" ]
I want to install [pip](http://pypi.python.org/pypi/pip). It should support Python 3, but it requires setuptools, which is available only for Python 2. How can I install pip with Python 3?
## Update 2015-01-20: As per <https://pip.pypa.io/en/latest/installing.html> the current way is: ``` wget https://bootstrap.pypa.io/get-pip.py python get-pip.py ``` I think that should work for any version --- ## Original Answer: ``` wget http://python-distribute.org/distribute_setup.py python distribute_setup.py...
How to install pip with Python 3?
6,587,507
149
2011-07-05T18:58:49Z
21,548,772
27
2014-02-04T09:42:22Z
[ "python", "python-3.x", "packages", "setuptools", "pip" ]
I want to install [pip](http://pypi.python.org/pypi/pip). It should support Python 3, but it requires setuptools, which is available only for Python 2. How can I install pip with Python 3?
For Ubuntu 12.04 or older, ``` sudo apt-get install python3-pip ``` won't work. Instead, use: ``` sudo apt-get install python3-setuptools sudo easy_install3 pip ```
how to concisely create a temporary file that is a copy of another file in python
6,587,516
5
2011-07-05T18:59:56Z
6,587,648
10
2011-07-05T19:11:33Z
[ "python" ]
I know that it is possible to create a temporary file, and write the data of the file I wish to copy to it. I was just wondering if there was a function like: ``` create_temporary_copy(file_path) ```
There isn't one directly, but you can use a combination of `tempfile` and `shutil.copy2` to achieve the same result: ``` import tempfile, shutil, os def create_temporary_copy(path): temp_dir = tempfile.gettempdir() temp_path = os.path.join(temp_dir, 'temp_file_name') shutil.copy2(path, temp_path) retur...
How to elegantly check the existence of an object/instance/variable and simultaneously assign it to variable if it exists in python?
6,587,879
21
2011-07-05T19:33:12Z
6,588,221
10
2011-07-05T20:04:10Z
[ "python", "sqlalchemy" ]
I am using SQLAlchemy to populate a database and often I need to check if a orm object exists in a database before processing. This may be an unconventional question, but I found myself encountering this pattern often: ``` my_object = session.query(SomeObject).filter(some_fiter).first() if my_object: # Mostly in datab...
wrap it on a function (shamelessly stolen from django get\_or\_create, this doesnt return a tuple though) ``` get_or_create(model, **kwargs): try: # basically check the obj from the db, this syntax might be wrong object = session.query(model).filter(**kwargs).first() return object excep...
How to elegantly check the existence of an object/instance/variable and simultaneously assign it to variable if it exists in python?
6,587,879
21
2011-07-05T19:33:12Z
13,053,819
16
2012-10-24T16:46:59Z
[ "python", "sqlalchemy" ]
I am using SQLAlchemy to populate a database and often I need to check if a orm object exists in a database before processing. This may be an unconventional question, but I found myself encountering this pattern often: ``` my_object = session.query(SomeObject).filter(some_fiter).first() if my_object: # Mostly in datab...
This has been asked a long time ago but for future visitors a more concise way to check is ``` if session.query(model).filter(some_filter).count(): # do stuff ```
How to elegantly check the existence of an object/instance/variable and simultaneously assign it to variable if it exists in python?
6,587,879
21
2011-07-05T19:33:12Z
16,003,360
32
2013-04-14T19:30:11Z
[ "python", "sqlalchemy" ]
I am using SQLAlchemy to populate a database and often I need to check if a orm object exists in a database before processing. This may be an unconventional question, but I found myself encountering this pattern often: ``` my_object = session.query(SomeObject).filter(some_fiter).first() if my_object: # Mostly in datab...
You want to execute a Exist query to be efficient ``` (ret, ), = Session.query(exists().where(SomeObject.field==value)) ``` Mike Bayer explain it in his blog post: <http://techspot.zzzeek.org/2008/09/09/selecting-booleans/> You can use scalar if you don't want to have a tuple as result: ``` ret = Session.query(ex...
Python - can a dict have a value that is a list?
6,588,056
4
2011-07-05T19:48:28Z
6,588,064
16
2011-07-05T19:49:50Z
[ "python", "list", "dictionary", "key-value" ]
When using Python is it possible that a dict can have a value that is a list? for example, a dictionary that would look like the following (see KeyName3's values): ``` { keyName1 : value1, keyName2: value2, keyName3: {val1, val2, val3} } ``` I already know that I can use 'defaultdict' however single values are (unde...
Yes. The values in a dict can be any kind of python object. The keys can be any hashable object (which does not allow a list, but does allow a tuple). You need to use `[]`, not `{}` to create a list: ``` { keyName1 : value1, keyName2: value2, keyName3: [val1, val2, val3] } ```
Convert SVG to PNG in Python
6,589,358
52
2011-07-05T21:59:55Z
6,599,172
36
2011-07-06T15:40:12Z
[ "python", "svg", "rendering", "cairo" ]
How do I convert an `svg` to `png`, in Python? I am storing the `svg` in an instance of `StringIO`. Should I use the pyCairo library? How do I write that code?
The answer is "[**pyrsvg**](http://cairographics.org/pyrsvg/)" - a Python binding for [librsvg](https://wiki.gnome.org/action/show/Projects/LibRsvg). There is an Ubuntu [python-rsvg package](http://packages.ubuntu.com/trusty/python-rsvg) providing it. Searching Google for its name is poor because its source code seems...
Convert SVG to PNG in Python
6,589,358
52
2011-07-05T21:59:55Z
6,790,715
10
2011-07-22T13:30:22Z
[ "python", "svg", "rendering", "cairo" ]
How do I convert an `svg` to `png`, in Python? I am storing the `svg` in an instance of `StringIO`. Should I use the pyCairo library? How do I write that code?
Try this: <http://cairosvg.org/> The site says: > CairoSVG is written in pure python and only depends on Pycairo. It is > known to work on Python 2.6 and 2.7.
Convert SVG to PNG in Python
6,589,358
52
2011-07-05T21:59:55Z
10,130,023
26
2012-04-12T19:01:25Z
[ "python", "svg", "rendering", "cairo" ]
How do I convert an `svg` to `png`, in Python? I am storing the `svg` in an instance of `StringIO`. Should I use the pyCairo library? How do I write that code?
Install Inkscape and call it as command line: ``` ${INKSCAPE_PATH} -z -f ${source_svg} -w ${width} -j -e ${dest_png} ``` You can also snap specific rectangular area only using parameter `-j`, e.g. co-ordinate "0:125:451:217" ``` ${INKSCAPE_PATH} -z -f ${source_svg} -w ${width} -j -a ${coordinates} -e ${dest_png} ```...
Convert SVG to PNG in Python
6,589,358
52
2011-07-05T21:59:55Z
13,320,450
22
2012-11-10T08:20:43Z
[ "python", "svg", "rendering", "cairo" ]
How do I convert an `svg` to `png`, in Python? I am storing the `svg` in an instance of `StringIO`. Should I use the pyCairo library? How do I write that code?
Here is what I did using [cairosvg](http://cairosvg.org/): ``` import cairosvg fout = open('output.png','w') svg_code = """<?xml version="1.0" standalone="no"?> <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"> <svg width="5cm" height="4cm" version="1.1" xmlns...
Convert SVG to PNG in Python
6,589,358
52
2011-07-05T21:59:55Z
19,718,153
16
2013-10-31T23:07:14Z
[ "python", "svg", "rendering", "cairo" ]
How do I convert an `svg` to `png`, in Python? I am storing the `svg` in an instance of `StringIO`. Should I use the pyCairo library? How do I write that code?
I'm using [Wand-py](http://docs.wand-py.org/) (an implementation of the Wand wrapper around ImageMagick) to import some pretty advanced SVGs and so far have seen great results! This is all the code it takes: ``` with wand.image.Image( blob=svg_file.read(), format="svg" ) as image: png_image = image.make_bl...
How can I determine a Unicode character from its name in Python, even if that character is a control character?
6,589,586
9
2011-07-05T22:31:50Z
6,590,632
13
2011-07-06T01:30:46Z
[ "python", "unicode" ]
I'd like to create an array of the Unicode code points which constitute white space in JavaScript (minus the Unicode-white-space code points, which I address separately). These characters are horizontal tab, vertical tab, form feed, space, non-breaking space, and BOM. I could do this with magic numbers: ``` whitespace...
Kerrek SB's comment is a good one: just put the names in a comment. BTW, Python also supports a named unicode literal: ``` >>> u"\N{NO-BREAK SPACE}" u'\xa0' ``` But it uses the same unicode name database, and the control characters are not in it.
What is the difference between dict and collections.defaultdict?
6,589,814
8
2011-07-05T23:02:10Z
6,589,839
9
2011-07-05T23:05:28Z
[ "python", "dictionary" ]
I was checking out Peter Norvig's [code](http://norvig.com/spell-correct.html) on how to write simple spell checkers. At the beginning, he uses this code to insert words into a dictionary. ``` def train(features): model = collections.defaultdict(lambda: 1) for f in features: model[f] += 1 return mo...
The difference is that a `defaultdict` will "default" a value if that key has not been set yet. If you didn't use a `defaultdict` you'd have to check to see if that key exists, and if it doesn't, set it to what you want. The lambda is defining a factory for the default value. That function gets called whenever it need...
How to find source of error in Python Pickle on massive object
6,589,869
3
2011-07-05T23:09:19Z
6,590,198
9
2011-07-05T23:58:30Z
[ "python", "oop", "serialization", "software-engineering", "pickle" ]
I've taken over somebody's code for a fairly large project. I'm trying to save program state, and there's one massive object which stores pretty much all the other objects. I'm trying to pickle this object, but I get this error: ``` pickle.PicklingError: Can't pickle <type 'module'>: it's not found as __builtin__.modu...
2) You can subclass pickle.Pickler and monkey-patch it to show a log of what it's pickling. This should make it easier to trace where the problem is. ``` import pickle class MyPickler (pickle.Pickler): def save(self, obj): print 'pickling object', obj, 'of type', type(obj) pickle.Pickler.save(self,...
How to handle "duck typing" in Python?
6,589,967
25
2011-07-05T23:24:18Z
6,590,087
17
2011-07-05T23:41:39Z
[ "python", "oop", "types", "duck-typing" ]
I usually want to keep my code as generic as possible. I'm currently writing a simple library and being able to use different types with my library feels extra important this time. One way to go is to force people to subclass an "interface" class. To me, this feels more like Java than Python and using `issubclass` in ...
I'm not a python pro but I believe that **unless** you can try an alternative for when the parameter doesn't implement a given method, you shoudn't prevent exceptions from being thrown. Let the caller handle these exceptions. This way, you would be hidding problems from the developers. As I have read in [Clean Code](h...
How to handle "duck typing" in Python?
6,589,967
25
2011-07-05T23:24:18Z
6,590,101
7
2011-07-05T23:44:03Z
[ "python", "oop", "types", "duck-typing" ]
I usually want to keep my code as generic as possible. I'm currently writing a simple library and being able to use different types with my library feels extra important this time. One way to go is to force people to subclass an "interface" class. To me, this feels more like Java than Python and using `issubclass` in ...
If you just want the unimplemented methods to do nothing, you can try something like this, rather than the multi-line `try/except` construction: ``` getattr(obj, "sleep", lambda: None)() ``` However, this isn't necessarily obvious as a function call, so maybe: ``` hasattr(obj, "sleep") and obj.sleep() ``` or if you...
How to handle "duck typing" in Python?
6,589,967
25
2011-07-05T23:24:18Z
6,590,283
12
2011-07-06T00:16:10Z
[ "python", "oop", "types", "duck-typing" ]
I usually want to keep my code as generic as possible. I'm currently writing a simple library and being able to use different types with my library feels extra important this time. One way to go is to force people to subclass an "interface" class. To me, this feels more like Java than Python and using `issubclass` in ...
If your code *requires* a particular interface, and the user passes an object without that interface, then nine times out of ten, it's inappropriate to catch the exception. Most of the time, an `AttributeError` is not only reasonable but expected when it comes to interface mismatches. Occasionally, it may be appropria...
Multiple mod_wsgi apps on one virtual host directing to wrong app
6,590,587
34
2011-07-06T01:19:12Z
6,591,232
40
2011-07-06T03:23:58Z
[ "python", "apache", "apache2", "mod-wsgi", "wsgi" ]
I'm trying to get two (or more) Django applications set up at subdirectories under the same domain, e.g.: ``` http://example.com/site1/ http://example.com/site2/ ``` I know that normally this works fine by setting up an apache virtualhost like this: ``` <VirtualHost *:80> ... WSGIScriptAlias /site1 /path/to/...
I've had multiple WSGI apps running on a single Apache install, and found that the easiest thing to do is just have multiple process groups-- one for each of the apps. One downside, versus actually trying to get a single process to run both (or more) apps, is that this might use a little more resident memory than you ...
Is it bad to have my virtualenv directory inside my git repository?
6,590,688
99
2011-07-06T01:42:04Z
6,590,783
104
2011-07-06T01:58:33Z
[ "python", "django", "virtualenv" ]
I'm thinking about putting the virtualenv for a Django web app I am making inside my git repository for the app. It seems like an easy way to keep deploy's simple and easy. Is there any reason why I shouldn't do this? I'm totally new to virtualenv, so there is a good chance this is a really stupid question.
I use `pip freeze` to get the packages I need into a `requirements.txt` file and add that to my repository. I tried to think of a way of why you would want to store the entire virtualenv, but I could not.
Is it bad to have my virtualenv directory inside my git repository?
6,590,688
99
2011-07-06T01:42:04Z
6,591,061
25
2011-07-06T02:52:16Z
[ "python", "django", "virtualenv" ]
I'm thinking about putting the virtualenv for a Django web app I am making inside my git repository for the app. It seems like an easy way to keep deploy's simple and easy. Is there any reason why I shouldn't do this? I'm totally new to virtualenv, so there is a good chance this is a really stupid question.
I used to do the same until I started using libraries that are compiled differently depending on the environment such as PyCrypto. My PyCrypto mac wouldn't work on Cygwin wouldn't work on Ubuntu. It becomes an utter nightmare to manage the repository. Either way I found it easier to manage the pip freeze & a requirem...
Is it bad to have my virtualenv directory inside my git repository?
6,590,688
99
2011-07-06T01:42:04Z
12,657,803
18
2012-09-30T00:57:14Z
[ "python", "django", "virtualenv" ]
I'm thinking about putting the virtualenv for a Django web app I am making inside my git repository for the app. It seems like an easy way to keep deploy's simple and easy. Is there any reason why I shouldn't do this? I'm totally new to virtualenv, so there is a good chance this is a really stupid question.
Storing the virtualenv directory inside git will, as you noted, allow you to deploy the whole app by just doing a git clone (plus installing and configuring Apache/mod\_wsgi). One potentially significant issue with this approach is that on Linux the full path gets hard-coded in the venv's activate, django-admin.py, eas...
Following links, Scrapy web crawler framework
6,591,255
8
2011-07-06T03:27:56Z
6,593,158
10
2011-07-06T07:51:01Z
[ "python", "web-crawler", "scrapy" ]
After several readings to Scrapy docs I'm still not catching the diferrence between using CrawlSpider rules and implementing my own link extraction mechanism on the callback method. I'm about to write a new web crawler using the latter approach, but just becuase I had a bad experience in a past project using rules. I'...
CrawlSpider inherits BaseSpider. It just added rules to extract and follow links. If these rules are not enough flexible for you - use BaseSpider: ``` class USpider(BaseSpider): """my spider. """ start_urls = ['http://www.amazon.com/s/?url=search-alias%3Dapparel&sort=relevance-fs-browse-rank'] allowed_dom...
How to convert a set to a list in python?
6,593,979
58
2011-07-06T09:08:37Z
6,594,009
83
2011-07-06T09:11:16Z
[ "python", "python-2.6" ]
I am trying to convert a set to a list in Python 2.6. I'm using this syntax: ``` first_list = [1,2,3,4] my_set=set(first_list) my_list = list(my_set) ``` However, I get the following stack trace: ``` Traceback (most recent call last): File "<console>", line 1, in <module> TypeError: 'set' object is not callable ``...
It is already a list ``` type(my_set) >>> <type 'list'> ``` Do you want something like ``` my_set = set([1,2,3,4]) my_list = list(my_set) print my_list >> [1, 2, 3, 4] ``` EDIT : Output of your last comment ``` >>> my_list = [1,2,3,4] >>> my_set = set(my_list) >>> my_new_list = list(my_set) >>> print my_new_list [...
When I create a virtualenv, python runs in 64-bit even when already set to 32-bit in OSX
6,594,558
2
2011-07-06T09:55:32Z
6,606,937
8
2011-07-07T06:55:27Z
[ "python", "osx", "32bit-64bit", "virtualenv", "mysql-python" ]
My setup is: 2.6.1 python (apple default, snow leopard), virtualenv, and using virtualenvwrapper Outside the environment, everything runs in 32-bit which is fine. But with a new project I'm going to work on needs django 1.3 and tons of dependencies, so I made a virtualenv. I've managed to install everything well, exc...
Much of the "magic" that Apple used to implement their `Prefer-32-bit` for the system Pythons in OS X 10.6 is in `/usr/bin/python` which then calls the real Python interpreters which are symlinked at `/usr/bin/python2.6` and `/usr/bin/python2.5`. `virtualenv` copies the real interpreter into the virtualenv `bin` direct...
What are equivalents to R's "phyper" function in Python?
6,594,840
4
2011-07-06T10:20:45Z
6,595,443
7
2011-07-06T11:11:13Z
[ "python", "statistics" ]
In R, I use the `phyper` function to do a hypergeometric test for bioinformatics analysis. However I use a lot of Python code and using rpy2 here is quite slow. So, I started looking for alternatives. It seemed that `scipy.stats.hypergeom` had something similar. Currently, I call `phyper` like this: ``` pvalue <- 1-p...
From the [docs](http://docs.scipy.org/doc/scipy-0.7.x/reference/generated/scipy.stats.hypergeom.html), you could try: > `hypergeom.sf(x,M,n,N,loc=0)` : > survival function (1-cdf — sometimes > more accurate) Also, I think you might have the values mixed up. > Models drawing objects from a bin. M > is total number ...
Selecting elements in numpy array using regular expressions
6,595,759
8
2011-07-06T11:39:51Z
6,597,138
15
2011-07-06T13:25:10Z
[ "regex", "numpy", "python" ]
One may select elements in numpy arrays as follows ``` a = np.random.rand(100) sel = a > 0.5 #select elements that are greater than 0.5 a[sel] = 0 #do something with the selection b = np.array(list('abc abc abc')) b[b==a] = 'A' #convert all the a's to A's ``` This property is used by the `np.where` function to retri...
There's some setup involved here, but unless numpy has some kind of direct support for regular expressions that I don't know about, then this is the most "numpytonic" solution. It tries to make iteration over the array more efficient than standard python iteration. ``` import numpy as np import re r = re.compile('[Ab...
Python Multiprocess diff between Windows and Linux
6,596,617
5
2011-07-06T12:48:55Z
6,596,695
10
2011-07-06T12:54:47Z
[ "python", "multiprocessing", "globals" ]
I have a script called jobrunner.py that calls class methods in main.py. See below... ``` # jobrunner.py from multiprocessing import Process import main from main import BBOX def _a(arg): f = main.a() print f.run() def _b(arg): p = main.b() print p.run() if __name__ == '__main__': world = '-180,...
**You shouldn't expect the values of global variables that you set in the parent process to be automatically propagated to the child processes.** Your code happens to work on Unix-like platforms because on those platforms `multiprocessing` uses [`fork()`](http://en.wikipedia.org/wiki/Fork_%28operating_system%29). This...
Python Global Exception Handling
6,598,053
22
2011-07-06T14:28:18Z
6,598,135
12
2011-07-06T14:33:37Z
[ "python", "exception", "exception-handling" ]
So I want to catch `KeyboardInterrupt` globally, and deal with it nicely. I don't want to encase my entire script in a huge try/except statement, because that just sounds gross. Is there any way to do this?
If this is a script for execution on the command line, you can encapsulate your run-time logic in `main()`, call it in an `if __name__ == '__main__'` and wrap that. ``` if __name__ == '__main__': try: main() except KeyboardInterrupt: print 'Killed by user' sys.exit(0) ```
Python Global Exception Handling
6,598,053
22
2011-07-06T14:28:18Z
6,598,286
62
2011-07-06T14:42:58Z
[ "python", "exception", "exception-handling" ]
So I want to catch `KeyboardInterrupt` globally, and deal with it nicely. I don't want to encase my entire script in a huge try/except statement, because that just sounds gross. Is there any way to do this?
You could change `sys.excepthook` if you really don't want to use a `try/except`. ``` import sys def myexcepthook(exctype, value, traceback): if exctype == KeyboardInterrupt: print "Handler code goes here" else: sys.__excepthook__(exctype, value, traceback) sys.excepthook = myexcepthook ```
Colorbar for matplotlib plot_surface command
6,600,579
20
2011-07-06T17:33:06Z
6,601,210
31
2011-07-06T18:27:49Z
[ "python", "matplotlib" ]
I have modified the mplot3d [example code](http://matplotlib.sourceforge.net/examples/mplot3d/surface3d_demo2.html) for my application with Paul's help. The code reads: ``` from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt import numpy as np fig = plt.figure() ax = fig.add_subplot(111, projectio...
You can use a proxy mappable object since your surface array is not mapped. The mappable simply converts the values of any array to RGB colors defined by a colormap. In your case you want to do this with the z1 array: ``` import matplotlib.cm as cm m = cm.ScalarMappable(cmap=cm.jet) m.set_array(z1) plt.colorbar(m) ``...
Find all packages installed with easy_install/pip?
6,600,878
228
2011-07-06T18:00:02Z
6,600,907
224
2011-07-06T18:02:35Z
[ "python", "pip", "easy-install", "pypi" ]
Is there a way to find all Python PyPI packages that were installed with easy\_install or pip? I mean, excluding everything that was/is installed with the distributions tools (in this case apt-get on Debian).
`pip freeze` will output a list of installed packages and their versions. It also allows you to write those packages to a file that can later be used to set up a new environment. <http://www.pip-installer.org/en/latest/index.html#freezing-requirements>
Find all packages installed with easy_install/pip?
6,600,878
228
2011-07-06T18:00:02Z
15,024,813
13
2013-02-22T12:57:37Z
[ "python", "pip", "easy-install", "pypi" ]
Is there a way to find all Python PyPI packages that were installed with easy\_install or pip? I mean, excluding everything that was/is installed with the distributions tools (in this case apt-get on Debian).
If Debian behaves like recent Ubuntu versions regarding `pip install` default target, it's dead easy: it installs to `/usr/local/lib/` instead of `/usr/lib` (`apt` default target). Check <http://askubuntu.com/questions/173323/how-do-i-detect-and-remove-python-packages-installed-via-pip/259747#259747> I am an ArchLinux...
Find all packages installed with easy_install/pip?
6,600,878
228
2011-07-06T18:00:02Z
16,759,140
158
2013-05-26T12:16:59Z
[ "python", "pip", "easy-install", "pypi" ]
Is there a way to find all Python PyPI packages that were installed with easy\_install or pip? I mean, excluding everything that was/is installed with the distributions tools (in this case apt-get on Debian).
As of version 1.3 of pip you can now use `pip list` It has some useful options including the ability to show outdated packages. Here's the documentation: <https://pip.pypa.io/en/latest/reference/pip_list/>
Find all packages installed with easy_install/pip?
6,600,878
228
2011-07-06T18:00:02Z
26,539,939
73
2014-10-24T01:03:49Z
[ "python", "pip", "easy-install", "pypi" ]
Is there a way to find all Python PyPI packages that were installed with easy\_install or pip? I mean, excluding everything that was/is installed with the distributions tools (in this case apt-get on Debian).
If anyone is wondering you can use the 'pip show' command. ``` pip show [options] <package> ``` This will list the install directory of the given package.
Converting a django ValuesQuerySet to a json object
6,601,174
14
2011-07-06T18:25:23Z
6,601,250
8
2011-07-06T18:31:24Z
[ "python", "django", "json" ]
I'm trying to use the ValuesQuerySet feature in Django to limit the number of fields returned from query to only those I need. I would like to serialize this data set a JSON object However, Django keeps throwing an error. Below I've included my code and the error I receive: ``` objectList = ConventionCard.objects.val...
Try [subsetting the fields](https://docs.djangoproject.com/en/dev/topics/serialization/#subset-of-fields) in your values list through the `serialize` method using a QuerySet instead: ``` from django.core import serializers objectQuerySet = ConventionCard.objects.filter(ownerUser = user) data = serializers.serialize('j...
Converting a django ValuesQuerySet to a json object
6,601,174
14
2011-07-06T18:25:23Z
9,205,541
27
2012-02-09T04:45:02Z
[ "python", "django", "json" ]
I'm trying to use the ValuesQuerySet feature in Django to limit the number of fields returned from query to only those I need. I would like to serialize this data set a JSON object However, Django keeps throwing an error. Below I've included my code and the error I receive: ``` objectList = ConventionCard.objects.val...
Cast the ValuesQuerySet to a list first: ``` query_set = ConventionCard.objects.values('fileName','id').filter(ownerUser = user) list(query_set) ``` Removing the `values` call as suggested by ars causes the manager to pull all columns from the table, instead of only the two you need.
sending NaN in json
6,601,812
20
2011-07-06T19:26:15Z
6,601,873
10
2011-07-06T19:30:47Z
[ "python", "json" ]
I am trying to encode an array which contains floats and `NaN` into JSON string from Python using `json.dumps()`. But the encoded JSON string is not being decoded successfully in PHP. Is the `NaN` causing this problem? How can I work around this situation?
NaN is not a valid JSON symbol, see the spec at <http://json.org/> Your encoder should probably have encoded the NaN as `null` instead.
sending NaN in json
6,601,812
20
2011-07-06T19:26:15Z
6,602,204
19
2011-07-06T20:01:54Z
[ "python", "json" ]
I am trying to encode an array which contains floats and `NaN` into JSON string from Python using `json.dumps()`. But the encoded JSON string is not being decoded successfully in PHP. Is the `NaN` causing this problem? How can I work around this situation?
`json.dumps` has an `allow_nan` parameter, which defaults to True. NaN, Infinity and -Infinity are not part of JSON, but they are standard in Javascript, so they're commonly used extensions. If the recipient can't handle them, set `allow_nan=False`. But then you'll get ValueError when you try to serialise NaN.
How to group a list of tuples/objects by similar index/attribute in python?
6,602,172
8
2011-07-06T19:59:01Z
6,602,203
20
2011-07-06T20:01:35Z
[ "python" ]
Given a list ``` old_list = [obj_1, obj_2, obj_3, ...] ``` I want to create a list: ``` new_list = [[obj_1, obj_2], [obj_3], ...] ``` where `obj_1.some_attr == obj_2.some_attr`. I could throw some `for` loops and `if` checks together, but this is ugly. Is ther a pythonic way for this? by the way, the attributes of...
[`defaultdict`](http://docs.python.org/2/library/collections.html#collections.defaultdict) is how this is done. While `for` loops are largely essential, `if` statements aren't. ``` from collections import defaultdict groups = defaultdict(list) for obj in old_list: groups[obj.some_attr].append(obj) new_list = ...
How to group a list of tuples/objects by similar index/attribute in python?
6,602,172
8
2011-07-06T19:59:01Z
6,602,381
8
2011-07-06T20:15:08Z
[ "python" ]
Given a list ``` old_list = [obj_1, obj_2, obj_3, ...] ``` I want to create a list: ``` new_list = [[obj_1, obj_2], [obj_3], ...] ``` where `obj_1.some_attr == obj_2.some_attr`. I could throw some `for` loops and `if` checks together, but this is ugly. Is ther a pythonic way for this? by the way, the attributes of...
Think you can also try to use [itertools.groupby](http://docs.python.org/library/itertools.html?highlight=groupby#itertools.groupby). Please note that code below is just a sample and should be modified according to your needs: ``` data = [[1,2,3],[3,2,3],[1,1,1],[7,8,9],[7,7,9]] from itertools import groupby # for e...
How to group a list of tuples/objects by similar index/attribute in python?
6,602,172
8
2011-07-06T19:59:01Z
6,602,441
11
2011-07-06T20:20:05Z
[ "python" ]
Given a list ``` old_list = [obj_1, obj_2, obj_3, ...] ``` I want to create a list: ``` new_list = [[obj_1, obj_2], [obj_3], ...] ``` where `obj_1.some_attr == obj_2.some_attr`. I could throw some `for` loops and `if` checks together, but this is ugly. Is ther a pythonic way for this? by the way, the attributes of...
Here are two cases. Both require the following imports: ``` import itertools import operator ``` You'll be using [itertools.groupby](http://docs.python.org/library/itertools.html#itertools.groupby) and either [operator.attrgetter](http://docs.python.org/library/operator.html#operator.attrgetter) or [operator.itemgett...
Django Background Task
6,602,761
12
2011-07-06T20:47:53Z
6,603,688
15
2011-07-06T22:12:51Z
[ "python", "database", "django", "multithreading", "background-thread" ]
I need to populate a SQLite database every few minutes in Django, but I want to serve stale data until the data is available for the database to be updated. (i.e. I don't want to block for the data to be gathered; the *only* time I can block is if there is a lock on the database, during which I have no choice.) I also...
[Celery](http://celeryproject.org/). > Celery is an asynchronous task queue/job queue based on distributed message passing. It is focused on real-time operation, but supports scheduling as well. > > Celery is written in Python, but the protocol can be implemented in any language. It can also operate with other languag...
Django Background Task
6,602,761
12
2011-07-06T20:47:53Z
9,239,023
13
2012-02-11T09:04:15Z
[ "python", "database", "django", "multithreading", "background-thread" ]
I need to populate a SQLite database every few minutes in Django, but I want to serve stale data until the data is available for the database to be updated. (i.e. I don't want to block for the data to be gathered; the *only* time I can block is if there is a lock on the database, during which I have no choice.) I also...
If you're looking for a lightweight solution for just executing stuff in background rather than a full-blown task management system, take a look at [django-utils](https://django-utils.readthedocs.org/). It includes, among other things, an [@async](https://django-utils.readthedocs.org/en/latest/django-utils/decorators.h...
Why aren't Python dicts unified?
6,602,816
12
2011-07-06T20:52:22Z
6,602,853
7
2011-07-06T20:55:43Z
[ "python" ]
After reading [this question](http://stackoverflow.com/questions/6602172/how-to-group-a-list-of-tuples-objects-by-similar-index-attribute-in-python), I noticed that S. Lott might have liked to use an “ordered defaultdict”, but it doesn't exist. Now, I wonder: Why do we have so many dict classes in Python? * dict *...
Those extra options don't come for free. Since 99.9% of Python is built on `dict`, it is *very* important to make it as minimal and fast as possible.
Why aren't Python dicts unified?
6,602,816
12
2011-07-06T20:52:22Z
6,602,868
11
2011-07-06T20:57:24Z
[ "python" ]
After reading [this question](http://stackoverflow.com/questions/6602172/how-to-group-a-list-of-tuples-objects-by-similar-index-attribute-in-python), I noticed that S. Lott might have liked to use an “ordered defaultdict”, but it doesn't exist. Now, I wonder: Why do we have so many dict classes in Python? * dict *...
One issue is that making this change would break backward-compatibility, due to this type of constructor usage that exists now: ``` >>> dict(one=1, two=2) {'two': 2, 'one': 1} ```
Python __repr__ for numbers?
6,603,134
5
2011-07-06T21:18:38Z
6,603,147
9
2011-07-06T21:20:17Z
[ "python" ]
I have the following (example) code: ``` class _1DCoord(): def __init__(self, i): self.i = i def pixels(self): return self.i def tiles(self): return self.i/TILE_WIDTH ``` What I want to do is this: ``` >>> xcoord = _1DCoord(42) >>> print xcoord 42 ``` But instead I see this: ...
``` def __repr__(self): return repr(self.i) ```
Scrapy, hash tag on URLs
6,604,690
3
2011-07-07T00:51:48Z
6,604,833
7
2011-07-07T01:18:38Z
[ "python", "url", "web-scraping", "scrapy" ]
I'm on the middle of a scrapping project using Scrapy. I realized that Scrapy strips the URL from a hash tag to the end. Here's the output from the shell: ``` [s] request <GET http://www.domain.com/b?ie=UTF8&node=3006339011&ref_=pe_112320_20310580%5C#/ref=sr_nr_p_8_0?rh=n%3A165796011%2Cn%3A%212334086011%2Cn%3A%...
--- This isn't something scrapy itself can change--the portion following the hash in the url is the [fragment identifier](http://en.wikipedia.org/wiki/Fragment_identifier) which is used by the client (scrapy here, usually a browser) instead of the server. What probably happens when you fetch the page in a browser is ...
Adding payload in packet (scapy)
6,605,118
5
2011-07-07T02:13:15Z
10,639,623
7
2012-05-17T16:25:19Z
[ "python", "packet", "packet-capture", "scapy" ]
Can I insert image or document (in MB´s) as a data in packet using scapy? Help will be greatly appreciated. This is what i did to send data. > > > data= "University of texas at San Antonio" > > > > > > a=IP(dst="129.132.2.21")/TCP()/data > > > > > > send(a)
Yes, you can send raw data like this. In this example, data will be ASCII encoded. ``` >>> data = 'University of Texas at San Antonio' >>> a = IP(dst='129.132.2.21') / TCP() / Raw(load=data) >>> sendp(a) ```
How do Python dictionary hash lookups work?
6,605,279
18
2011-07-07T02:45:28Z
6,607,353
9
2011-07-07T07:39:34Z
[ "python", "algorithm", "dictionary" ]
How do Python dictionary lookup algorithms work internally? ``` mydi['foo'] ``` If the dictionary has 1,000,000 terms, is a tree search executed? Would I expect performance in terms of the length of the key string, or the size of the dictionary? Maybe stuffing everything into a dictionary is just as good as writing a...
Here's some pseudo-code closer to what actually happens. Imagine the dictionary has a `data` attribute containing the key,value pairs and a `size` which is the number of cells allocated. ``` def lookup(d, key): perturb = j = hash(key) while True: cell = d.data[j % d.size] if cell.key is EMPTY: ...
Python newbie working with argparse
6,605,851
8
2011-07-07T04:34:04Z
6,605,952
33
2011-07-07T04:49:38Z
[ "python", "argparse" ]
I'm trying to get the argparse module working in python. I was initially following both the documentation and a few miscellaneous guides I found. My problem is that on a fresh install I get the following ``` File "test.py", line 3, in <module> import argparse File "/home/jon/Pythons/realmine/argparse.py", line 3, in <...
Usually this symptom is the result of shadowing a builtin module with one of your own. And from the error message: ``` File "/home/jon/Pythons/realmine/argparse.py", line 3, in <module> ``` it looks like you have your own module argparse.py, which is causing the problem, because it's the one which test.py is trying t...
Best way to integrate SqlAlchemy into a Django project
6,606,725
13
2011-07-07T06:32:19Z
6,607,461
23
2011-07-07T07:52:24Z
[ "python", "django", "sqlalchemy" ]
I changed my Django application to use SQLAlchemy, and it works now. But I'm wondering where I should put these lines: ``` engine = sqlalchemy.create_engine(settings.DATABASE_URL) Session = sqlalchemy.orm.sessionmaker(bind=engine) session = Session() ``` The reason I'm asking is because I want to use SQLAlchemy at m...
for the first two, `engine` and `Session`, you can put them in `settings.py`; they are, configuration, after all. Actually creating a session requires slightly more care, since a `session` is essentially a 'transaction'. The simplest thing to do is to create it in each view function when needed, and commit them just b...
django - How to redirect django.contrib.auth.views.login after login?
6,606,827
2
2011-07-07T06:43:14Z
19,039,157
9
2013-09-26T21:37:26Z
[ "python", "django", "redirect", "login", "authentication" ]
I added django.contrib.auth.views.login **everywhere in my webpage**, for that I had to load a [templatetag](https://docs.djangoproject.com/en/1.2/ref/templates/builtins/) (that returns the AuthenticationForm) in my base.html. This templatetags includes the `registration/login.html` template. The login is working ok b...
Found answer: Change settings.LOGIN\_REDIRECT\_URL in your settings.py, below code is copy from django: ``` if request.method == "POST": form = authentication_form(data=request.POST) if form.is_valid(): # Ensure the user-originating redirection url is safe. if not is_safe_url(url=redirect_...
Scikits-learn: Use custom vocabulary together with Pipeline
6,608,241
4
2011-07-07T09:08:19Z
6,631,530
8
2011-07-08T23:19:05Z
[ "python", "machine-learning", "scikits", "scikit-learn" ]
In my scikits-learn Pipeline, I would like to pass a custom vocabulary to CountVectorizer(): ``` text_classifier = Pipeline([ ('count', CountVectorizer(vocabulary=myvocab)), ('tfidf', TfidfTransformer()), ('clf', LinearSVC(C=1000)) ]) ``` However, as far as I understand when I call ``` text_classifier.fi...
This was a bug in scikit-learn that I fixed [five minutes ago](https://github.com/scikit-learn/scikit-learn/commit/e5ca264f4b4b7764e07bf63c14294263c4a4bd84). Thanks for spotting it. I suggest you either upgrade to the newest version from Github, or separate the vectorizer from the pipeline as a workaround: ``` count =...
Python shorthand conditional
6,608,512
15
2011-07-07T09:33:30Z
6,608,523
30
2011-07-07T09:34:35Z
[ "python", "if-statement", "conditional" ]
Here's a quick one... In Python one can do: ``` foo = foo1 if bar1 else foo2 ``` And that's cool, but how can I just get a True or False without having to write ``` foo = True if bar1 else False ``` For example, in JS you can forcibly cast a boolean type by doing ``` var foo = !!bar1; ```
Call `bool` on the object: ``` bool(bar1) ```
Given the my code is open source and I'm running on a server, and I accept nearly-raw code, what's the worst that can happen to me?
6,609,664
3
2011-07-07T11:10:03Z
6,609,766
13
2011-07-07T11:19:06Z
[ "python", "security", "code-injection" ]
I'm looking at several cases where it would be far, far, far easier to accept nearly-raw code. So, 1. What's the worst you can do with an expression if you can't lambda, and how? 2. What's the worst you can do with executed code if you can't use import and how? (can't use X == string is scanned for X) Also, B is u...
The worst you can do with an expression is on the order of ``` __import__('os').system('rm -rf /') ``` if the server process is running as `root`. Otherwise, you can fill up memory and crash the process with ``` 2**2**1024 ``` or bring the server to a grinding halt by executing a [shell fork bomb](https://secure.wi...
Jinja2: How to create multidimensional javascript array?
6,609,833
4
2011-07-07T11:25:28Z
6,610,603
7
2011-07-07T12:29:16Z
[ "javascript", "python", "flask", "jinja2" ]
I am using [Flask](http://flask.pocoo.org/) with [Jinja2](http://jinja.pocoo.org/) as templating language. How do you convert a multidimensional Python structure to a corresponding structure in javascript using Jinja2? Example (Python/Flask): ``` pyStruct = [{key1:value1, key2:value2, [{subkey1:subvalue1, subkey2:su...
You can use the `json` module, either as a Jinja filter ou directly passing the results of `json.dumps()` to your template. ``` pyStruct = [{key1:value1, key2:value2, [{subkey1:subvalue1, subkey2:subvalue2,}]}, {key1:value1, key2:value2, [{subkey1:subvalue1, subkey2:subvalue2,}]},] render_template('jinjat...
efficiently replace bad characters
6,609,895
19
2011-07-07T11:31:07Z
6,609,998
18
2011-07-07T11:39:26Z
[ "python", "string", "unicode", "replace" ]
I often work with utf-8 text containing characters like: > \xc2\x99 > > \xc2\x95 > > \xc2\x85 > > etc These characters confuse other libraries I work with so need to be replaced. What is an efficient way to do this, rather than: ``` text.replace('\xc2\x99', ' ').replace('\xc2\x85, '...') ```
There is always regular expressions; just list all of the offending characters inside square brackets like so: ``` import re print re.sub(r'[\xc2\x99]'," ","Hello\xc2There\x99") ``` This prints: 'Hello There ', with the unwanted characters replaced by spaces. Alternately, if you have a different replacement characte...
efficiently replace bad characters
6,609,895
19
2011-07-07T11:31:07Z
6,610,088
7
2011-07-07T11:47:22Z
[ "python", "string", "unicode", "replace" ]
I often work with utf-8 text containing characters like: > \xc2\x99 > > \xc2\x95 > > \xc2\x85 > > etc These characters confuse other libraries I work with so need to be replaced. What is an efficient way to do this, rather than: ``` text.replace('\xc2\x99', ' ').replace('\xc2\x85, '...') ```
If you want to remove all non-ASCII characters from a string, you can use ``` text.encode("ascii", "ignore") ```
efficiently replace bad characters
6,609,895
19
2011-07-07T11:31:07Z
6,625,625
17
2011-07-08T14:07:03Z
[ "python", "string", "unicode", "replace" ]
I often work with utf-8 text containing characters like: > \xc2\x99 > > \xc2\x95 > > \xc2\x85 > > etc These characters confuse other libraries I work with so need to be replaced. What is an efficient way to do this, rather than: ``` text.replace('\xc2\x99', ' ').replace('\xc2\x85, '...') ```
I think that there is an underlying problem here, and it might be a good idea to investigate and maybe solve it, rather than just trying to cover up the symptoms. `\xc2\x95` is the UTF-8 encoding of the character U+0095, which is a [C1 control character](http://www.unicode.org/charts/PDF/U0080.pdf) (MESSAGE WAITING). ...
Python function argument list formatting
6,609,956
18
2011-07-07T11:35:39Z
6,610,002
14
2011-07-07T11:40:14Z
[ "python", "formatting", "indentation", "pep8" ]
What is the best way to format following piece of code accordingly to PEP8: ``` oauth_request = oauth.OAuthRequest.from_consumer_and_token(consumer, token=token, verifier=verifier, http_url=ACCESS_TOKEN_URL) ``` The problem is that if I place more than one parameter on the first line, the line exceeds 79 characte...
My reading of the [documentation](http://legacy.python.org/dev/peps/pep-0008/#indentation) suggests that 2 and 3 are both acceptable, but it looks like 2 is preferred (I say this because it looks like 2 vs. 3 is handled this way in the examples, I don't think that the style specification is very specific here). 1 is ou...
Python string processing based on the numeric part: '5a+6b' + '2a+3b+9c' = '7a+9b+9c'
6,609,982
4
2011-07-07T11:37:52Z
6,610,126
8
2011-07-07T11:50:29Z
[ "python" ]
I need to add two simple polynomials (represented as strings). The following example would clarify my requirement. ``` input1 = '5a+6b' input2 = '2a+3b+9c' ``` The required sum should be as follows: ``` '7a+9b+9c' ``` Currently I have created a function (of 20 lines) to perform this task for me, but I think this c...
**[sympy](http://code.google.com/p/sympy/)** does close to what you want ``` >>> import sympy >>> a,b,c = sympy.symbols('abc') >>> 5*a+6*b + 2*a+9*b+9*c 7*a + 9*c + 15*b ```
Is there a difference between using a dict literal and a dict constructor?
6,610,606
92
2011-07-07T12:29:41Z
6,610,783
55
2011-07-07T12:43:37Z
[ "python", "pycharm" ]
Using PyCharm, I noticed it offers to convert a **dict literal**: ``` d = { 'one': '1', 'two': '2', } ``` into a **dict constructor**: ``` d = dict(one='1', two='2') ``` **Do these different approaches differ in some significant way?** (While writing this question I noticed that using `dict()` it seems imp...
I think you have pointed out the most obvious difference. Apart from that, the first doesn't need to lookup `dict` which should make it a tiny bit faster the second looks up `dict` in `locals()` and then `globals()` and the finds the builtin, so you can switch the behaviour by defining a local called `dict` for examp...