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 |
|---|---|---|---|---|---|---|---|---|---|
Updating GUI elements in MultiThreaded PyQT | 9,957,195 | 4 | 2012-03-31T15:28:55Z | 9,964,621 | 17 | 2012-04-01T13:09:12Z | [
"python",
"multithreading",
"pyqt"
] | I was researching for some time to find information **how to do multithreaded program using PyQT, updating GUI to show the results**.
I'm used to learning by example and i can't find (yes i was looking for weeks) any simple example of program using multithreading doing such simple task as for example connecting to lis... | Here some very basic examples.
You can pass references to GUI elements to threads, and update them in thread.
```
import sys
import urllib2
from PyQt4 import QtCore, QtGui
class DownloadThread(QtCore.QThread):
def __init__(self, url, list_widget):
QtCore.QThread.__init__(self)
self.url = url
... |
How do I split words in Python while keeping in consideration words with hyphens? | 9,958,102 | 3 | 2012-03-31T17:33:20Z | 9,958,115 | 7 | 2012-03-31T17:35:10Z | [
"python",
"regex"
] | In Python, `re.split("\W+", "fat-free milk")` yields `['fat', 'free', 'milk']`.
How do I produce `['fat-free', 'milk']` from `re.split()`?
I understand the problem to be that hyphens are not alphanumeric characters, but I'm not sure how to incorporate this fact into the regex. I have tried `re.split("[(^\-)\W]+", "fa... | No need for a regex:
```
>>> "fat-free milk".split()
['fat-free', 'milk']
```
If you want to split on any non-word character that is not a hyphen you can use a negated character group (like in John's) answer or a negative lookahead, which might be slightly more flexible:
```
>>> re.split(r'(?:(?!-)\W)+', "fat-free m... |
How do I split words in Python while keeping in consideration words with hyphens? | 9,958,102 | 3 | 2012-03-31T17:33:20Z | 9,958,118 | 8 | 2012-03-31T17:35:34Z | [
"python",
"regex"
] | In Python, `re.split("\W+", "fat-free milk")` yields `['fat', 'free', 'milk']`.
How do I produce `['fat-free', 'milk']` from `re.split()`?
I understand the problem to be that hyphens are not alphanumeric characters, but I'm not sure how to incorporate this fact into the regex. I have tried `re.split("[(^\-)\W]+", "fa... | ```
re.split("[^-\w]+", "fat-free milk")
``` |
Element-wise string concatenation in numpy | 9,958,506 | 11 | 2012-03-31T18:26:41Z | 13,906,671 | 16 | 2012-12-16T23:49:52Z | [
"python",
"arrays",
"string",
"numpy",
"elementwise-operations"
] | Is this a bug?
```
import numpy as np
a1=np.array(['a','b'])
a2=np.array(['E','F'])
In [20]: add(a1,a2)
Out[20]: NotImplemented
```
I am trying to do element-wise string concatenation. I thought Add() was the way to do it in numpy but obviously it is not working as expected. | This can be done using [numpy.core.defchararray.add](http://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.core.defchararray.add.html). Here is an example:
```
>>> import numpy as np
>>> a1 = np.array(['a', 'b'])
>>> a2 = np.array(['E', 'F'])
>>> np.core.defchararray.add(a1, a2)
array(['aE', 'bF'],
dtyp... |
changing the values of the diagonal of a matrix in numpy | 9,958,577 | 22 | 2012-03-31T18:35:58Z | 9,958,952 | 32 | 2012-03-31T19:24:21Z | [
"python",
"numpy"
] | how can I change the values of the diagonal of a matrix in numpy?
I checked [Numpy modify ndarray diagonal](http://stackoverflow.com/questions/7394760/numpy-modify-ndarray-diagonal), but the function there is not implemented in numpy v 1.3.0.
lets say we have a np.array X and I want to set all values of the diagonal ... | Did you try `numpy.fill_diagonal`? See the following [answer](http://stackoverflow.com/questions/5852495/scaling-an-array-in-python-with-numpy) and this [discussion](http://www.mail-archive.com/numpy-discussion@scipy.org/msg18274.html). Or the following from the documentation (although currently broken):
<http://docs.... |
changing the values of the diagonal of a matrix in numpy | 9,958,577 | 22 | 2012-03-31T18:35:58Z | 9,959,707 | 9 | 2012-03-31T21:09:34Z | [
"python",
"numpy"
] | how can I change the values of the diagonal of a matrix in numpy?
I checked [Numpy modify ndarray diagonal](http://stackoverflow.com/questions/7394760/numpy-modify-ndarray-diagonal), but the function there is not implemented in numpy v 1.3.0.
lets say we have a np.array X and I want to set all values of the diagonal ... | If you're using a version of numpy that doesn't have `fill_diagonal` (the [right way](http://stackoverflow.com/a/9958952/344821) to set the diagonal to a constant) or `diag_indices_from`, you can do this pretty easily with array slicing:
```
# assuming a 2d square array
n = mat.shape[0]
mat[range(n), range(n)] = 0
```... |
changing the values of the diagonal of a matrix in numpy | 9,958,577 | 22 | 2012-03-31T18:35:58Z | 17,120,126 | 7 | 2013-06-15T04:16:25Z | [
"python",
"numpy"
] | how can I change the values of the diagonal of a matrix in numpy?
I checked [Numpy modify ndarray diagonal](http://stackoverflow.com/questions/7394760/numpy-modify-ndarray-diagonal), but the function there is not implemented in numpy v 1.3.0.
lets say we have a np.array X and I want to set all values of the diagonal ... | Here's another good way to do this. If you want a one-dimensional view of the array's main diagonal use:
```
A.ravel()[:A.shape[1]**2:A.shape[1]+1]
```
For the i'th superdiagonal use:
```
A.ravel()[i:max(0,A.shape[1]-i)*A.shape[1]:A.shape[1]+1]
```
For the i'th subdiagonal use:
```
A.ravel()[A.shape[1]*i:A.shape[1... |
Converting int arrays to string arrays in numpy without truncation | 9,958,846 | 14 | 2012-03-31T19:10:50Z | 9,958,935 | 19 | 2012-03-31T19:20:30Z | [
"python",
"numpy"
] | Trying to convert int arrays to string arrays in numpy
```
In [66]: a=array([0,33,4444522])
In [67]: a.astype(str)
Out[67]:
array(['0', '3', '4'],
dtype='|S1')
```
Not what I intended
```
In [68]: a.astype('S10')
Out[68]:
array(['0', '33', '4444522'],
dtype='|S10')
```
This works but I had to know 1... | Again, this can be solved in pure Python:
```
>>> map(str, [0,33,4444522])
['0', '33', '4444522']
```
Or if you need to convert back and forth:
```
>>> a = np.array([0,33,4444522])
>>> np.array(map(str, a))
array(['0', '33', '4444522'],
dtype='|S7')
``` |
Converting int arrays to string arrays in numpy without truncation | 9,958,846 | 14 | 2012-03-31T19:10:50Z | 9,966,572 | 17 | 2012-04-01T17:30:49Z | [
"python",
"numpy"
] | Trying to convert int arrays to string arrays in numpy
```
In [66]: a=array([0,33,4444522])
In [67]: a.astype(str)
Out[67]:
array(['0', '3', '4'],
dtype='|S1')
```
Not what I intended
```
In [68]: a.astype('S10')
Out[68]:
array(['0', '33', '4444522'],
dtype='|S10')
```
This works but I had to know 1... | You can stay in numpy, doing
```
np.char.mod('%d', a)
```
This is twice faster than `map` or list comprehensions for 10 elements, four times faster for 100. |
Building Vim from Source in Cygwin | 9,959,243 | 2 | 2012-03-31T20:07:10Z | 9,959,486 | 11 | 2012-03-31T20:35:52Z | [
"python",
"vim",
"build",
"cygwin",
"ncurses"
] | I am trying to build Vim from the source packages, under Cygwin, to enable Python support. I am following the instructions given [here](http://cygwin.com/ml/cygwin/2004-06/msg00540.html), but I'm hitting this error when I run the `configure` script:
```
checking --with-tlib argument... empty: automatic terminal librar... | I think you're missing a required package. Lengthy explanation follows; jump to the end for the answer.
I ran the exact same `./configure ...` command on my own system (Windows 7, Cygwin). Part of its output was:
```
checking for tgetent in -lncurses... yes
```
which indicates that I don't have the same problem you ... |
multiprocessing and garbage collection | 9,959,598 | 8 | 2012-03-31T20:51:02Z | 9,964,605 | 7 | 2012-04-01T13:05:42Z | [
"python",
"unix",
"garbage-collection",
"multiprocessing"
] | In py2.6+, the `multiprocessing` module offers a `Pool` class, so one can do:
```
class Volatile(object):
def do_stuff(self, ...):
pool = multiprocessing.Pool()
return pool.imap(...)
```
However, with the standard Python implementation at 2.7.2, this approach soon leads to "IOError: [Errno 24] Too... | In the end, I ended up passing the `pool` reference around and terminating it manually once the `pool.imap` iterator was finished:
```
class Volatile(object):
def do_stuff(self, ...):
pool = multiprocessing.Pool()
return pool, pool.imap(...)
def call_stuff(self):
pool, results = self.d... |
How to serve admin static files with django.contrib.staticfiles in Django 1.4 (using one Apache server)? | 9,959,875 | 5 | 2012-03-31T21:33:49Z | 9,963,031 | 8 | 2012-04-01T08:39:21Z | [
"python",
"django",
"apache",
"django-templates",
"django-staticfiles"
] | Django is recommending me that if I am going to only use one server (Apache) to serve both dynamic and static files, then [I should serve static files using `django.contrib.staticfiles`](https://docs.djangoproject.com/en/1.4/howto/deployment/wsgi/modwsgi/#serving-the-admin-files).
So in my `settings.py` I have loaded ... | Thanks Daniel Roseman for the explanation and giving me the chance to learn it on my own (and now I won't forget!) :-).
Initially I was really confused and I didn't know you had to first *collect* the static files, then tell Apache to *serve* it. I thought simply using `STATICFILES_DIRS` and including the `static` app... |
How load a dict from a list in python? | 9,959,881 | 3 | 2012-03-31T21:34:10Z | 9,959,917 | 7 | 2012-03-31T21:38:07Z | [
"python",
"list",
"dictionary"
] | Have dict like:
```
mydict= {'a':[],'b':[],'c':[],'d':[]}
```
list like:
```
log = [['a',917],['b', 312],['c',303],['d',212],['a',215],['b',212].['c',213],['d',202]]
```
How do i get all 'a' from list into mydict['a'] as a list.
```
ndict= {'a':[917,215],'b':[312,212],'c':[303,213],'d':[212,202]}
``` | Iterate over the list, and append each value to the correct key:
```
for key, value in log:
my_dict[key].append(value)
```
I renamed `dict` to `my_dict` to avoid shadowing the built-in type. |
Difference between namedtuple and a frozen dict | 9,960,675 | 4 | 2012-03-31T23:45:09Z | 9,960,784 | 9 | 2012-04-01T00:03:50Z | [
"python",
"dictionary",
"namedtuple"
] | I know there is no frozen dict data type but If there was one how would it be different from namedtuple. It seems to me that namedtuple performs the required operations but obviously it does not. So what are the differences? | From an API viewpoint, probably not much, though:
* `namedtuple` keys are always strings with some limitations:
> Any valid Python identifier may be used for a fieldname except for
> names starting with an underscore. Valid identifiers consist of
> letters, digits, and underscores but do not start with a digit or
> u... |
Simple programming language with a md5/sha1 hash command? | 9,960,889 | 3 | 2012-04-01T00:23:41Z | 9,960,932 | 11 | 2012-04-01T00:31:57Z | [
"python",
"security",
"syntax",
"hash",
"programming-languages"
] | I'm looking to create a simple brute-force password-cracker which will hash an input from stdin and compare the result to an existing hash (for my securities class).
I've never done any actual programming involving hashes, though, since it's mostly been conceptual/mathematical parts so far. **Is there a (relatively) e... | Assuming that you're only being asked to *use* the hash functions, and not to implement the hash yourself, [Python's hashlib module](https://docs.python.org/3.4/library/hashlib.html) has routines for md5 and sha1:
[Updated for Python 3, in which `hashlib` wants bytes, not strings:]
```
>>> import hashlib
>>> s = 'som... |
How do I access my database level functions inside other classes/files in Tornado? | 9,960,967 | 7 | 2012-04-01T00:40:49Z | 10,037,640 | 9 | 2012-04-05T23:57:22Z | [
"python",
"mysql",
"tornado"
] | I'm new to Tornado, and I'm currently trying to get past this recent stumbling block. Currently I have some database variables defined, and I instantiate the handlers, settings, and database connection info when I init the Application class. I also have a base handler class (named BaseHandler) which provides a simple d... | I meet the same situation just now, then I view some examples on github and made that.
I separate my files like:
* server.py: run app
* urls.py: define handers and ui\_modules
* da.py: define helpful methods for data access
Following are some brief of each file, I think this can help you to solve your problem.
urls... |
Python max with same number of instances | 9,961,077 | 8 | 2012-04-01T01:06:00Z | 9,961,095 | 13 | 2012-04-01T01:09:45Z | [
"python",
"max",
"instances"
] | I have a list:
```
hello = ['1', '1', '2', '1', '2', '2', '7']
```
I wanted to display the most common element of the list, so I used:
```
m = max(set(hello), key=hello.count)
```
However, I realised that there could be two elements of the list that occur the same frequency, like the 1's and 2's in the list above. ... | Using an approach similar to your current, you would first find the maximum count and then look for every item with that count:
```
>>> m = max(map(hello.count, hello))
>>> set(x for x in hello if hello.count(x) == m)
set(['1', '2'])
```
Alternatively, you can use the nice [`Counter`](http://docs.python.org/library/c... |
Python + Tornado Restart after editing files | 9,961,357 | 9 | 2012-04-01T02:03:16Z | 9,961,405 | 8 | 2012-04-01T02:20:05Z | [
"python",
"reload",
"tornado",
"restart"
] | I just start learning Python + Tornado for my web servers. Every time I modify some code on my python scripts or templates I have to stop the in my terminal (CTRL+C) and restart it (python server.py) and I want a more effective way to do this, that after modifying code in some files the server automatically restarts.
... | If you are looking for automatic reloading of .py files during development. In your `tornado.web.Application()` put `debug=True` after your handlers.
I don't think you should do this in production environment, because such implementation typically use a background thread to actively scan files for changes, which may s... |
How can I make a sprite move when key is held down | 9,961,563 | 5 | 2012-04-01T03:03:24Z | 9,961,598 | 10 | 2012-04-01T03:11:58Z | [
"python",
"pygame"
] | Currently the sprite only moves 1 pixel every time a key is pressed. How could I cause the plumber sprite to move constantly when left or right key is being held down?
```
while running:
setup_background()
spriteimg = plumberright
screen.blit(spriteimg,(x1, y1))
for event in pygame.event.get():
... | You can use [pygame.key.get\_pressed](http://www.pygame.org/docs/ref/key.html#pygame.key.get_pressed) to do that.
example:
```
while running:
keys = pygame.key.get_pressed() #checking pressed keys
if keys[pygame.K_UP]:
y1 -= 1
if keys[pygame.K_DOWN]:
y1 += 1
``` |
Basic networking with Pygame | 9,961,752 | 12 | 2012-04-01T03:51:51Z | 9,967,553 | 11 | 2012-04-01T19:29:12Z | [
"python",
"networking",
"twisted",
"pygame"
] | I need to do some basic networking for a Pygame project.
Basically, it's a 2D single player or cooperative game. The networking only needs to support 2 players, with one as a host.
The only information that needs to be sent is the positions of players, creeps and bullets.
I've been reading around and Twisted keeps c... | This was asked recently on Reddit, so I'll more or less just copy my answer over from there. I apologize for not being able to provide more links, I have <10 rep so I can only post two at a time.
Twisted might work, but I don't have a whole lot of experience with it. I'd recommend going with sockets, as that's what Tw... |
Python's property decorator does not work as expected | 9,962,037 | 4 | 2012-04-01T05:04:06Z | 9,962,043 | 15 | 2012-04-01T05:05:42Z | [
"python",
"class",
"properties",
"decorator",
"new-style-class"
] | ```
class Silly:
@property
def silly(self):
"This is a silly property"
print("You are getting silly")
return self._silly
@silly.setter
def silly(self, value):
print("You are making silly {}".format(value))
self._silly = value
@silly.deleter
def silly(sel... | [The `property` decorator](http://docs.python.org/library/functions.html#property) only works with [new-style classes](http://docs.python.org/glossary.html#term-new-style-class) ([see also](http://stackoverflow.com/q/54867)). Make `Silly` extend from `object` explicitly to make it a new-style class. (In Python 3, all c... |
Control Charts in Python | 9,962,114 | 8 | 2012-04-01T05:25:20Z | 10,763,488 | 7 | 2012-05-26T04:06:49Z | [
"python",
"charts",
"pandas"
] | I currently use R routinely for [statistical process control](http://en.wikipedia.org/wiki/Statistical_process_control). With this I can produce [control charts](http://en.wikipedia.org/wiki/Control_chart) such as [EWMA](http://en.wikipedia.org/wiki/EWMA_chart), Shewhart, [CUSUM](http://en.wikipedia.org/wiki/CUSUM) and... | Just found [this package](https://launchpad.net/python-spc/+milestone/0.3) that has not been updated in a while, but works so far in Python 2.7.3 (on 64-bit Windows 7, using pretty up-to-date supporting packages):
```
In [1]: import spc
In [2]: import matplotlib.pyplot as plt
In [3]: x = [25,19,14,17,25,39,49,6,11,19,... |
Python turning a list into a list of tuples | 9,962,293 | 5 | 2012-04-01T06:05:38Z | 9,962,301 | 13 | 2012-04-01T06:07:55Z | [
"python",
"list"
] | What I want to accomplish:
```
[a, b, c, d] -> [ (a, x), (b, x), (c, x), (d, x) ]
```
What I have thought of so far:
```
done = []
for i in [a, b, c, d]:
done.append((i, x))
```
Is there a more Pythonic way of accomplishing this? | ```
done = [(el, x) for el in [a, b, c, d]]
``` |
Python turning a list into a list of tuples | 9,962,293 | 5 | 2012-04-01T06:05:38Z | 9,962,332 | 8 | 2012-04-01T06:17:20Z | [
"python",
"list"
] | What I want to accomplish:
```
[a, b, c, d] -> [ (a, x), (b, x), (c, x), (d, x) ]
```
What I have thought of so far:
```
done = []
for i in [a, b, c, d]:
done.append((i, x))
```
Is there a more Pythonic way of accomplishing this? | Using `itertools.repeat`
```
>>> x = 'apple'
>>> a,b,c,d = 'a','b','c','d'
>>> from itertools import repeat
>>> zip([a,b,c,d],repeat(x))
[('a', 'apple'), ('b', 'apple'), ('c', 'apple'), ('d', 'apple')]
```
Using `itertools.product`
```
>>> from itertools import product
>>> list(product([a,b,c,d],[x]))
[('a', 'ap... |
Pandas pivot_table on date | 9,962,822 | 8 | 2012-04-01T07:56:42Z | 9,966,022 | 10 | 2012-04-01T16:21:23Z | [
"python",
"datetime",
"pandas"
] | I have a pandas DataFrame with a date column. It is not an index.
I want to make a pivot\_table on the dataframe using counting aggregate per month for each location.
The data look like this:
```
['INDEX'] DATE LOCATION COUNT
0 2009-01-02 00:00:00 AAH 1
1 2009-01-03 00:00... | I would suggest:
```
months = cdiff.DATE.map(lambda x: x.month)
pivot_table(cdiff, values='COUNT', rows=[months, 'LOCATION'],
aggfunc=np.sum)
```
To get a month name, pass a different function or use the built-in `calendar.month_name`. To get the data in the format you want, you should call `reset_index` ... |
Developing a heuristic to test simple anonymous Python functions for equivalency | 9,963,155 | 14 | 2012-04-01T08:56:40Z | 9,963,552 | 8 | 2012-04-01T10:07:22Z | [
"python",
"function",
"python-3.x",
"bytecode"
] | I know how function comparison works in Python 3 (just comparing address in memory), and I understand why.
I also understand that "true" comparison (do functions `f` and `g` return the same result given the same arguments, for any arguments?) is practically impossible.
I am looking for something in between. I want th... | Edited to check whether external state will affect the sorting function as well as if the two functions are equivalent.
---
I hacked up `dis.dis` and friends to output to a global file-like object. I then stripped out line numbers and normalized variable names (without touching constants) and compared the result.
Yo... |
Google-app-engine NDB | 9,964,118 | 20 | 2012-04-01T11:49:13Z | 9,964,672 | 18 | 2012-04-01T13:15:28Z | [
"python",
"google-app-engine",
"app-engine-ndb"
] | With the recent release of [NDB](https://developers.google.com/appengine/docs/python/ndb/), is there any reason to keep using the old datastore API?
I'm working on an application that currently uses the old datastore API, and I have put quite some effort into caching objects in memcache. Am I correct in my understandi... | The main reason to keep using the old API is for legacy applications. The NDB API is not entirely the same as the existing DB API, so you'll need to make changes to your code to use it. You're correct that you won't need to use your own caching code any longer, at least for get operations - if you're caching the result... |
Howto use Django class based UpdateViews with FileFields | 9,964,229 | 4 | 2012-04-01T12:04:59Z | 9,964,316 | 17 | 2012-04-01T12:17:20Z | [
"python",
"django",
"django-views"
] | I have a simple model containing a FileField among others. When I use a class based UpdateView It is possible to modify all fields of the model and changes are saved to the database on submit.The only exception to this is the FileField, while it is displayed as part of the form, and I can choose I file I want to upload... | [Make sure your form is declared like so:](https://docs.djangoproject.com/en/dev/ref/forms/api/#binding-uploaded-files-to-a-form)
```
<form enctype="multipart/form-data" method="post" action="/foo/">
``` |
NumPy vs. multiprocessing and mmap | 9,964,809 | 17 | 2012-04-01T13:38:14Z | 9,975,475 | 21 | 2012-04-02T11:21:29Z | [
"python",
"numpy",
"multiprocessing",
"mmap"
] | I am using Python's `multiprocessing` module to process large numpy arrays in parallel. The arrays are memory-mapped using `numpy.load(mmap_mode='r')` in the master process. After that, `multiprocessing.Pool()` forks the process (I presume).
Everything seems to work fine, except I am getting lines like:
> AttributeEr... | My usual approach (if you can live with extra memory copies) is to do all IO in one process and then send things out to a pool of worker threads. To load a slice of a memmapped array into memory just do `x = np.array(data[yourslice])` (`data[yourslice].copy()` doesn't actually do this, which can lead to some confusion.... |
Returning an lvalue from a function in python | 9,965,115 | 8 | 2012-04-01T14:25:41Z | 9,965,140 | 8 | 2012-04-01T14:29:11Z | [
"python"
] | [Sorry, I'm new in Python. Although it seems to be a very basic question, I did my share of due diligence before asking this audience, trying to avoid really stupid questions].
I'm trying to figure out the correct idiom for returning an l-value from a function. Assume I've a container of 64 objects, and I want to be a... | In Python, *everything* is a reference. The only problem is that `None` is *immutable*, so you can't use the returned reference to change the value.
You also can't override the assignment operator, so you won't get this particular kind of behaviour. However, a good and very flexible solution would be to override the [... |
Google-app-engine NDB iter keys_only | 9,965,204 | 4 | 2012-04-01T14:37:35Z | 9,970,729 | 7 | 2012-04-02T03:57:13Z | [
"python",
"google-app-engine",
"app-engine-ndb"
] | Say I have a query that will be executed often, most likely yielding the same results.
Is it correct that using:
```
for key in qry.iter(keys_only=True):
item = key.get()
#do something with item
```
Would perform better than:
```
for item in qry:
#do something with item
```
Because in the first example... | I would doubt that the second form would perform better -- it is always possible that the values are *not* in the cache, and then, presuming you are getting more than one entity back, you'd be making multiple roundtrips. That quickly gets slower.
A better approach is indeed what's shown in <http://code.google.com/p/ap... |
Logic of triangle inequality as python conditionals? | 9,966,173 | 2 | 2012-04-01T16:41:48Z | 9,966,186 | 8 | 2012-04-01T16:43:47Z | [
"python"
] | *[community edit: original title was "python conditionals", OP is asking what is wrong with code below]*
I made a function that's supposed to determine if three sides can theoretically form a triangle. It works fine in my opinion , but when i input the code in pyschools.com website, it tells that in some test cases it... | It is easier to just do:
```
def isTriangle(sides):
smallest,medium,biggest = sorted(sides)
return smallest+medium>=biggest and all(s>0 for s in sides)
```
(edit: I have decided to say that `2,2,4` is technically a triangle, but a degenerate triangle; change `>=` to `>` if you do not consider it to be a trian... |
Counting abecedarian words in a list: Python | 9,967,395 | 4 | 2012-04-01T19:11:24Z | 9,967,505 | 11 | 2012-04-01T19:24:47Z | [
"python",
"list"
] | Working on a very common problem to identify whether word is abecedarian (all letters in alphabetical order). I can do one word in several ways as discovered in "Think Python"; but, would like to be able to iterate through a list of words determining which are abecedarian and counting those that are.
```
def start():
... | No need for low level programming on this one :-)
```
def is_abcedarian(s):
'Determine whether the characters are in alphabetical order'
return list(s) == sorted(s)
```
The use [*filter*](http://docs.python.org/library/functions.html#filter) to run over a list of words:
```
>>> filter(is_abcedarian, ['apple'... |
Python HTTP HEAD - dealing with redirects properly? | 9,967,632 | 5 | 2012-04-01T19:37:25Z | 9,967,683 | 8 | 2012-04-01T19:43:35Z | [
"python",
"redirect",
"urllib2",
"head"
] | I can use urllib2 to make HEAD requests like so:
```
import urllib2
request = urllib2.Request('http://example.com')
request.get_method = lambda: 'HEAD'
urllib2.urlopen(request)
```
The problem is that it appears that when this follows redirects, it uses GET instead of HEAD.
The purpose of this HEAD request is to che... | You can do this with the [requests](http://docs.python-requests.org/en/latest/user/quickstart/) library:
```
>>> import requests
>>> r = requests.head('http://github.com', allow_redirects=True)
>>> r
<Response [200]>
>>> r.history
[<Response [301]>]
>>> r.url
u'https://github.com/'
``` |
Python "While" Loop logic wrong? | 9,968,006 | 3 | 2012-04-01T20:25:02Z | 9,968,026 | 7 | 2012-04-01T20:27:40Z | [
"python",
"while-loop",
"logic"
] | I have a Python script that queries a MySQL database every 5 seconds, gathering the latest three ID's for helpdesk tickets. I am using MySQLdb as my driver. But the issue is in my "while" loop, when I check if two arrays are equal. If they are NOT equal, I print "A new ticket has arrived." But this never prints! See my... | The problem is the following line:
```
IDarray_prev = IDarray
```
In Python, this makes `IDarray_prev` refer to the *same* underlying list as `IDarray`. Changes in one will be reflected in the other, because they both point to the same thing.
To make a *copy* of the list that you can use to compare later, try:
```
... |
Django admin file upload with current model id | 9,968,532 | 12 | 2012-04-01T21:30:59Z | 15,776,267 | 24 | 2013-04-02T23:26:32Z | [
"python",
"django",
"django-models",
"upload",
"django-admin"
] | I'm trying to create a simple photo gallery with the default Django admin. I'd like to save a sample photo for each gallery, but I don't want to keep the filname. Instead of the filename, I'd like to save the id of the model (`N.jpg`). But the first time I want to save the object the id does not exist. How could I know... | I ran into the same problem. Okm's answer sent me on the right path but it seems to me it is possible to get the same functionality by just overriding the `save()` method.
```
def save(self, *args, **kwargs):
if self.pk is None:
saved_image = self.image
self.image = None
super(Material, sel... |
Turn functions with a callback into Python generators? | 9,968,592 | 17 | 2012-04-01T21:41:35Z | 9,968,886 | 10 | 2012-04-01T22:26:25Z | [
"python",
"generator",
"coroutine"
] | The Scipy minimization function (just to use as an example), has the option of adding a callback function at each step. So I can do something like,
```
def my_callback(x):
print x
scipy.optimize.fmin(func, x0, callback=my_callback)
```
Is there a way to use the callback function to create a generator version of f... | As pointed in the comments, you could do it in a new thread, using [`Queue`](http://docs.python.org/library/queue.html). The drawback is that you'd still need some way to access the final result (what `fmin` returns at the end). My example below uses an optional callback to do something with it (another option would be... |
How to implement Priority Queues in Python? | 9,969,236 | 16 | 2012-04-01T23:22:18Z | 9,969,324 | 22 | 2012-04-01T23:38:00Z | [
"python",
"queue",
"heap",
"priority-queue"
] | Sorry for such a silly question but Python docs are confusing.. .
**Link 1: Queue Implementation**
<http://docs.python.org/library/queue.html>
It says thats Queue has a contruct for priority queue. But I could not find how to implement it.
```
class Queue.PriorityQueue(maxsize=0)
```
**Link 2: Heap Implementation**... | *There is no such thing as a "most efficient priority queue implementation" in **any language**.*
A priority queue is all about trade-offs. See <http://en.wikipedia.org/wiki/Priority_queue>
You should choose one of these two, based on how you plan to use it:
* `O(log(N))` insertion time and `O(1)` findMin+deleteMin ... |
How to implement Priority Queues in Python? | 9,969,236 | 16 | 2012-04-01T23:22:18Z | 9,969,478 | 19 | 2012-04-02T00:05:34Z | [
"python",
"queue",
"heap",
"priority-queue"
] | Sorry for such a silly question but Python docs are confusing.. .
**Link 1: Queue Implementation**
<http://docs.python.org/library/queue.html>
It says thats Queue has a contruct for priority queue. But I could not find how to implement it.
```
class Queue.PriorityQueue(maxsize=0)
```
**Link 2: Heap Implementation**... | The version in the *Queue* module is [implemented](http://hg.python.org/cpython/file/2.7/Lib/Queue.py#l212) using the *heapq* module, so they have equal efficiency for the underlying heap operations.
That said, the *Queue* version is slower because it adds locks, encapsulation, and a nice object oriented API.
The [pr... |
Python raw socket listening for UDP packets; only half of the packets received | 9,969,259 | 7 | 2012-04-01T23:26:55Z | 9,969,618 | 7 | 2012-04-02T00:34:09Z | [
"python",
"sockets",
"networking",
"udp",
"packet-capture"
] | I am trying to create a **raw** socket in Python that listens for UDP packets only:
```
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_UDP)
s.bind(('0.0.0.0', 1337))
while True:
print s.recvfrom(65535)
```
This needs to be run as root, and creates a raw socket on port 1337, which ... | Solved it in kind of a silly manner; please let me know if there is another way, and I will change the accepted answer.
The solution is simply to use two sockets bound on the same port; one raw, one not raw:
```
import socket, select
s1 = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s1.bind(('0.0.0.0', 1337))
s2 ... |
"an integer is required" when open()'ing a file as utf-8? | 9,969,272 | 4 | 2012-04-01T23:29:24Z | 9,969,295 | 9 | 2012-04-01T23:33:28Z | [
"python",
"utf-8"
] | I have a file I'm trying to open up in python with the following line:
```
f = open("C:/data/lastfm-dataset-360k/test_data.tsv", "r", "utf-8")
```
Calling this gives me the error
> TypeError: an integer is required
I deleted all other code besides that one line and am still getting the error. What have I done wrong... | From the documentation for [`open()`](http://docs.python.org/library/functions.html#open):
> **`open(name[, mode[, buffering]])`**
>
> [...]
>
> The optional buffering argument specifies the fileâs desired buffer
> size: 0 means unbuffered, 1 means line buffered, any other positive
> value means use a buffer of (app... |
"an integer is required" when open()'ing a file as utf-8? | 9,969,272 | 4 | 2012-04-01T23:29:24Z | 9,969,312 | 7 | 2012-04-01T23:35:36Z | [
"python",
"utf-8"
] | I have a file I'm trying to open up in python with the following line:
```
f = open("C:/data/lastfm-dataset-360k/test_data.tsv", "r", "utf-8")
```
Calling this gives me the error
> TypeError: an integer is required
I deleted all other code besides that one line and am still getting the error. What have I done wrong... | You are using the wrong open.
```
>>> help(open)
Help on built-in function open in module __builtin__:
open(...)
open(name[, mode[, buffering]]) -> file object
Open a file using the file() type, returns a file object. This is the
preferred way to open a file. See file.__doc__ for further information.
`... |
Function closure performance | 9,969,463 | 6 | 2012-04-02T00:02:44Z | 9,969,503 | 9 | 2012-04-02T00:10:52Z | [
"python",
"performance",
"python-3.x",
"closures",
"implementation"
] | I thought that I improve performance when I replace this code:
```
def f(a, b):
return math.sqrt(a) * b
result = []
a = 100
for b in range(1000000):
result.append(f(a, b))
```
with:
```
def g(a):
def f(b):
return math.sqrt(a) * b
return f
result = []
a = 100
func = g(a)
for b in range(1000000):
result.... | > I assumed that since a is fixed when the closure is performed, the interpreter would precompute everything that involves a, and so
> math.sqrt(a) would be repeated just once instead of 1000000 times.
That assumption is wrong, I don't know where it came from. A closure just captures variable bindings, in your case it... |
Many to many using Flask-SQLAlchemy returns raw sql instead of executed | 9,969,527 | 4 | 2012-04-02T00:16:22Z | 9,998,006 | 7 | 2012-04-03T17:04:48Z | [
"python",
"sqlalchemy",
"flask",
"flask-sqlalchemy"
] | Im using the python framework flask with sqlalchemy.
My many-to-many looks like this:
```
collections_questions = db.Table('collections_questions',
db.Column('question_id',db.Integer,db.ForeignKey('question.id')),
db.Column('collection_id',db.Integer,db.ForeignKey('collection.id'))
)
class Collectio... | you're using lazy="dynamic", so collection.questions is a Query object. You need to iterate over it to emit SQL and get the contents:
```
list(collection.questions)
``` |
Two separate python lists acting as one | 9,969,609 | 2 | 2012-04-02T00:32:50Z | 9,969,651 | 7 | 2012-04-02T00:38:12Z | [
"python",
"list"
] | I've been working on the code shown below for udacity. I'm trying to figure out why the lists 'g' and 'p' are acting as the same list when 'g' is created by calling list(p). When the print statement (print[i][j]) is called in the move function it shows that 'p' is being overwritten when 'g' is changed. I just started p... | I haven't followed through your code in detail, but the source of your trouble is likely the use of two dimensional data structures (lists of lists). In Python, the `list()` constructor is a *shallow copy*, which only copies one level of list. You may be able to avoid the problem you're seeing using the [`copy.deepcopy... |
python Difference between reversed(list) and list.sort(reverse=True) | 9,969,698 | 13 | 2012-04-02T00:46:07Z | 9,969,709 | 17 | 2012-04-02T00:48:13Z | [
"python",
"sorting"
] | What is the difference between
```
mylist = reversed(sorted(mylist))
```
vs
```
mylist = sorted(mylist, reverse=True)
```
Why would one be used over the other?
How about for a stable sort on multiple columns such as
```
mylist.sort(key=itemgetter(1))
mylist.sort(key=itemgetter(0))
mylist.reverse()
```
is this th... | You have hit on *exactly* the difference. Since [Timsort](http://en.wikipedia.org/wiki/Timsort) is stable, sorting on the reverse versus reversing the sort will leave the *unsorted* elements in reverse orders.
```
>>> s = ((2, 3, 4), (1, 2, 3), (1, 2, 2))
>>> sorted(s, key=operator.itemgetter(0, 1), reverse=True)
[(2,... |
python: pass string instead of file as function parameter | 9,969,863 | 4 | 2012-04-02T01:17:10Z | 9,969,931 | 7 | 2012-04-02T01:29:03Z | [
"python"
] | I am beginner in python, and I need to use some thirdparty function which basically has one input - name of a file on a hard drive. This function parses file and then proceses it.
I am generating file contents in my code (it's CSV file which I generate from a list) and want to skip actual file creation. Is there any w... | It looks like you'll need to write your data to a file then pass the name of that file to the 3rd party library. You might want to consider using the [tempfile](http://docs.python.org/library/tempfile.html) module to create the file in a safe and easy way. |
lib2to3 Architecture Documentation | 9,969,941 | 8 | 2012-04-02T01:30:59Z | 13,735,314 | 10 | 2012-12-06T01:02:39Z | [
"python",
"documentation"
] | I want to get a feel for [`lib2to3`](http://docs.python.org/library/2to3.html) but can't find much in the way of documentation. Has anything in the way of an architecture overview been written? Where can I find more information on the library? | The only documentation that I am aware of (apart from the [source code](http://hg.python.org/cpython/file/tip/Lib/lib2to3)), is Lennart Regebro's excellent [Porting to Python 3](http://python3porting.com/) book (online in full).
The book has a [full chapter on writing your own `lib2to3` fixers](http://python3porting.c... |
Significance of double underscores in Python filename | 9,970,158 | 4 | 2012-04-02T02:13:22Z | 9,970,271 | 7 | 2012-04-02T02:35:16Z | [
"python"
] | Other than for `__init__.py` files, do the leading and trailing double underscores have any significance in a file name? For example, is `__model__.py` in any way more significant than `model.py`? | Double underscores in filenames other than `__init__.py` and [`__main__.py`](http://stackoverflow.com/questions/4042905/what-is-main-py) have no significance to Python itself, but frameworks may use them to indicate/identify various things. |
Moving Python Elements between Lists | 9,970,174 | 3 | 2012-04-02T02:17:12Z | 9,970,192 | 10 | 2012-04-02T02:20:54Z | [
"python"
] | ```
listA = [1,2,3]
listB = []
print listA
print listB
for i in listA:
if i >= 2:
listB.append(i)
listA.remove(i)
print listA
print listB
```
Why does this only add and remove element "2"?
Also, when I comment out "listA.remove(i)", it works as expected. | You should not modify the list you are iterating over, this results in surprising behaviour (because the iterator uses indices internally and those are changed by removing elements). What you can do is to iterate over a *copy* of `listA`:
```
for i in listA[:]:
if i >= 2:
listB.append(i)
listA.remove(i)
```
... |
Can someone please explain arguments of SubElement from the xml element tree module? | 9,971,538 | 9 | 2012-04-02T06:01:20Z | 9,972,072 | 13 | 2012-04-02T06:58:51Z | [
"python",
"xml",
"elementtree"
] | I have looked at the documentation here:
<http://docs.python.org/dev/library/xml.etree.elementtree.html#xml.etree.ElementTree.SubElement>
The parent and tag argument seems clear enough, but what format do I put the attribute name and value in? I couldn't find any previous example. What format is the extra\*\* argumen... | SubElement is a function of **ElementTree** (not Element) which allows to create child objects for an Element.
* **attrib** takes a dictionary containing the attributes
of the element you want to create.
* \***\*extra** is used for additional keyword arguments, those will be added as attributes to the Element.
## *... |
Python Array Slice With Comma? | 9,972,391 | 10 | 2012-04-02T07:28:06Z | 9,972,440 | 7 | 2012-04-02T07:31:56Z | [
"python",
"list",
"numpy",
"slice"
] | I was wondering what the use of the comma was when slicing Python arrays - I have an example that appears to work, but the line that looks weird to me is
```
p = 20*numpy.log10(numpy.abs(numpy.fft.rfft(data[:2048, 0])))
```
Now, I know that when slicing an array, the first number is start, the next is end, and the la... | It slices with a tuple. What exactly the tuple means depends on the object being sliced. In NumPy arrays, it performs a m-dimensional slice on a n-dimensional array.
```
>>> class C(object):
... def __getitem__(self, val):
... print val
...
>>> c = C()
>>> c[1:2,3:4]
(slice(1, 2, None), slice(3, 4, None))
>>> c... |
Want to prompt browser to save csv | 9,973,921 | 4 | 2012-04-02T09:28:04Z | 9,973,951 | 9 | 2012-04-02T09:30:21Z | [
"python",
"pyramid"
] | Want to prompt browser to save csv using pyramid.response.Response searched for clues and found here's [a link](https://docs.djangoproject.com/en/dev/howto/outputting-csv/?from=olddocs) Django answer but i can't use it with Pyramid wsgi my code looks like this:
```
from pyramid.response import Response
def get_list_na... | Try adding Content-Disposition:
```
response['Content-Disposition'] = 'attachment; filename="report.csv"'
``` |
Want to prompt browser to save csv | 9,973,921 | 4 | 2012-04-02T09:28:04Z | 9,981,791 | 14 | 2012-04-02T18:29:34Z | [
"python",
"pyramid"
] | Want to prompt browser to save csv using pyramid.response.Response searched for clues and found here's [a link](https://docs.djangoproject.com/en/dev/howto/outputting-csv/?from=olddocs) Django answer but i can't use it with Pyramid wsgi my code looks like this:
```
from pyramid.response import Response
def get_list_na... | As a cleaner way to do that, you can register a renderer.
In your configuration set-up, add:
```
config.add_renderer(name='csv',
factory='mypackage.renderers.CSVRenderer')
```
then in `mypackage/renderers.py`:
```
class CSVRenderer(object):
def __init__(self, info):
pass
... |
Mails not being sent to people in CC | 9,974,972 | 10 | 2012-04-02T10:45:12Z | 9,975,026 | 21 | 2012-04-02T10:48:57Z | [
"python",
"smtp",
"smtplib"
] | I have the following script for sending mails using python
```
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import os
FROMADDR = "myaddr@server.com"
PASSWORD = 'foo'
TOADDR = ['toaddr1@server.com', 'toaddr2@server.com']
CCADDR = ['ccaddr1@server.com', 'ccaddr... | I think that you will need to put the CCADDR with the TOADDR when sending the mail:
```
s.sendmail(FROMADDR, TOADDR+CCADDR, msg.as_string())
```
You're correctly adding the addresses to your message, but you will need the cc addresses on the envelope too.
From the [docs](http://docs.python.org/library/smtplib.html#m... |
i18n translation with a different domain in .py files | 9,977,267 | 2 | 2012-04-02T13:20:19Z | 9,978,576 | 8 | 2012-04-02T14:49:54Z | [
"python",
"internationalization",
"translation",
"plone"
] | I'm a little confused on i18n translations in py files. I have a string where what needs to be translated is already in the plone domain in plone.pot so I want to specify the domain to be plone for that translation only. When I do the following, I get an error. And, this does get rendered in a page template so there's ... | You need to have two different message factories, i.e. where you do
```
from zope.i18nmessageid import MessageFactory
_ = MessageFactory('my.package')
```
you should be also instantiating the Plone one.
```
_p = MessageFactory('plone')
```
Then `_p('Contributors')` would give you the translated string.
Have a look... |
Connecting to a remote IPython instance | 9,977,446 | 18 | 2012-04-02T13:33:13Z | 9,979,553 | 19 | 2012-04-02T15:51:48Z | [
"python",
"ipython",
"zeromq",
"jupyter",
"pyzmq"
] | I would like to run an IPython instance on one machine and connect to it (over LAN) from a different process (to run some python commands). I understand that it is possible with zmq : <http://ipython.org/ipython-doc/dev/development/ipythonzmq.html> .
However, I can not find documentation on how to do it and whether it... | If you want to run code in a kernel from another Python program, the easiest way is to connect a [BlockingKernelManager](https://github.com/ipython/ipython/blob/master/IPython/zmq/blockingkernelmanager.py). The best example of this right now is Paul Ivanov's [vim-ipython](https://github.com/ivanov/vim-ipython) client, ... |
Connecting to a remote IPython instance | 9,977,446 | 18 | 2012-04-02T13:33:13Z | 15,268,945 | 19 | 2013-03-07T10:39:13Z | [
"python",
"ipython",
"zeromq",
"jupyter",
"pyzmq"
] | I would like to run an IPython instance on one machine and connect to it (over LAN) from a different process (to run some python commands). I understand that it is possible with zmq : <http://ipython.org/ipython-doc/dev/development/ipythonzmq.html> .
However, I can not find documentation on how to do it and whether it... | If you just want to connect *interactively*, you can use SSH forwarding. I didn't find this documented anywhere on Stack Overflow yet, yet this question comes closest. This answer has been tested on Ipython 0.13. I got the information from [this blog post](http://rsb.io/posts/ripkern-remote-ipython-kernels/).
1. Run `... |
How to include license file in setup.py script? | 9,977,889 | 10 | 2012-04-02T14:00:42Z | 9,977,956 | 7 | 2012-04-02T14:05:38Z | [
"python",
"setuptools"
] | I have written a Python extension module in C++.
I plan to distribute the module with setuptools.
There will be binary distributions for 32- and 64-bit Windows (built with `setup.py bdist_egg`) and a source distribution for UNIX-like platforms (built with `setup.py sdist`).
I plan to license the module under the BSD l... | Use [`data_files`](http://docs.python.org/distutils/setupscript.html#installing-additional-files):
```
setup(
name = "Foo",
version = "0.1.0",
ext_modules = [Extension("Foo", glob("Source/*.cpp"))],
data_files = [("", ["LICENSE.txt"])]
)
```
Two remarks:
1. There is no direct need to ship a license w... |
Parsing a table with rowspan and colspan | 9,978,445 | 8 | 2012-04-02T14:41:56Z | 9,980,393 | 10 | 2012-04-02T16:46:14Z | [
"python",
"html-parsing",
"lxml",
"html-table"
] | I have a table that I need to parse, specifically it is a school schedule with 4 blocks of time, and 5 blocks of days for every week. I've attempted to parse it, but honestly have not gotten very far because I am stuck with how to deal with rowspan and colspan attributes, because they essentially mean there is a lack o... | **UPDATE** (removed previous function)
**UPDATE2** fixed and simplified.
My first function was wrong. Here's another one, it's working but needs tests:
```
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from collections import defaultdict
def table_to_list(table):
dct = table_to_2d_dict(table)
return list(i... |
match dates using python regular expressions | 9,978,534 | 4 | 2012-04-02T14:47:21Z | 9,978,701 | 15 | 2012-04-02T14:57:13Z | [
"python",
"regex",
"python-3.x"
] | I want to match dates that have the following format:
2010-08-27,
2010/08/27
Right now I am not very particular about the date being actually feasible, but just that it is in the correct format.
please tell the regular expression for this.
Thanks | You can use the `datetime` module to parse dates:
```
import datetime
print datetime.datetime.strptime('2010-08-27', '%Y-%m-%d')
print datetime.datetime.strptime('2010-15-27', '%Y-%m-%d')
```
output:
```
2010-08-27 00:00:00
Traceback (most recent call last):
File "./x.py", line 6, in <module>
print datetime.d... |
match dates using python regular expressions | 9,978,534 | 4 | 2012-04-02T14:47:21Z | 9,978,804 | 7 | 2012-04-02T15:03:36Z | [
"python",
"regex",
"python-3.x"
] | I want to match dates that have the following format:
2010-08-27,
2010/08/27
Right now I am not very particular about the date being actually feasible, but just that it is in the correct format.
please tell the regular expression for this.
Thanks | You can use this code:
```
import re
# regular expression to match dates in format: 2010-08-27 and 2010/08/27
# date_reg_exp = re.compile('(\d+[-/]\d+[-/]\d+)')
```
**updated regula expression below:**
```
# regular expression to match dates in format: 2010-08-27 and 2010/08/27
date_reg_exp = re.compile('\d{4}[-/]\... |
Python argument parser list of list or tuple of tuples | 9,978,880 | 23 | 2012-04-02T15:09:42Z | 9,979,169 | 30 | 2012-04-02T15:28:02Z | [
"python",
"argparse"
] | I'm trying to use argument parser to parse a 3D coordinate so I can use
```
--cord 1,2,3 2,4,6 3,6,9
```
and get
```
((1,2,3),(2,4,6),(3,6,9))
```
My attempt is
```
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--cord', help="Coordinate", dest="cord", type=tuple, nargs=3)
args = parser.pa... | You can add your own [type](http://docs.python.org/library/argparse.html#type). This also allows for additional validations, for example:
```
def coords(s):
try:
x, y, z = map(int, s.split(','))
return x, y, z
except:
raise argparse.ArgumentTypeError("Coordinates must be x,y,z")
parse... |
How to use the python interpreter in chef | 9,979,120 | 3 | 2012-04-02T15:24:48Z | 9,979,201 | 9 | 2012-04-02T15:29:47Z | [
"python",
"chef"
] | I am trying to use the python interpreter in chef. Below is my naive attempt that did not work. What is the proper way to accomplish the below in python?
```
script "install_something" do
interpreter "python"
user "root"
cwd "/tmp"
code <<-EOH
import boto
f = open('test.txt','r')
f.write('adfadf')
f.cl... | The contents of
```
code <<-EOH
import boto
f = open('test.txt','r')
f.write('adfadf')
f.close()
EOH
```
are passed to the interpreter verbatim, which is to say including the leading indent. Because indentation forms a part of the python syntax, your script (between the `<<-EOH`/`EOH`) is not valid python... |
how to visualize values on logarithmic scale on matplotalib? | 9,979,378 | 2 | 2012-04-02T15:40:51Z | 9,979,495 | 8 | 2012-04-02T15:48:04Z | [
"python",
"matplotlib",
"numeric"
] | I have vales with very small difference like... 0.000001. I want to visualize them on logarithmic scale. I am wondering how to do it in matplotlib.
Thanks a lot | <http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.axis>
Simply add the keyword argument `log=True`
Or, in an example:
```
from matplotlib import pyplot
import math
pyplot.plot([x for x in range(100)],[math.exp(y) for y in range(100)] )
pyplot.xlabel('arbitrary')
pyplot.ylabel('arbitrary')
pypl... |
how to find the middle number in python | 9,979,602 | 4 | 2012-04-02T15:55:40Z | 9,979,626 | 14 | 2012-04-02T15:56:49Z | [
"python"
] | Given 3 numbers, I need to find which number lies between the two others.
ie,given 3,5,2
I need 3 to be returned.
I tried to implement this by going thru all three and using if else conditions to check if each is between the other two.But this seems a naive way to do this.Is there a better way? | Put them in a list, sort them, pick the middle one. |
how to find the middle number in python | 9,979,602 | 4 | 2012-04-02T15:55:40Z | 9,979,690 | 7 | 2012-04-02T16:01:04Z | [
"python"
] | Given 3 numbers, I need to find which number lies between the two others.
ie,given 3,5,2
I need 3 to be returned.
I tried to implement this by going thru all three and using if else conditions to check if each is between the other two.But this seems a naive way to do this.Is there a better way? | ```
>>> x = [1,3,2]
>>> sorted(x)[len(x) // 2]
2
``` |
how to find the middle number in python | 9,979,602 | 4 | 2012-04-02T15:55:40Z | 9,980,390 | 8 | 2012-04-02T16:45:58Z | [
"python"
] | Given 3 numbers, I need to find which number lies between the two others.
ie,given 3,5,2
I need 3 to be returned.
I tried to implement this by going thru all three and using if else conditions to check if each is between the other two.But this seems a naive way to do this.Is there a better way? | The fastest obvious way for **three** numbers
```
def mean3(a, b, c):
if a <= b <= c or c <= b <= a:
return b
elif b <= a <= c or c <= a <= b:
return a
else:
return c
``` |
Why does python use 'else' after for and while loops? | 9,979,970 | 183 | 2012-04-02T16:18:45Z | 9,979,985 | 25 | 2012-04-02T16:20:03Z | [
"python",
"if-statement",
"for-loop",
"for-else"
] | I understand how this construct works:
```
for i in range(10):
print(i)
if i == 9:
print("Too big - I'm giving up!")
break;
else:
print("Completed successfully")
```
But I don't understand why `else` is used as the keyword here, since it suggests the code in question only runs if the `for... | Because they didn't want to introduce a new keyword to the language. Each one steals an identifier and causes backwards compatibility problems, so it's usually a last resort. |
Why does python use 'else' after for and while loops? | 9,979,970 | 183 | 2012-04-02T16:18:45Z | 9,979,993 | 10 | 2012-04-02T16:20:33Z | [
"python",
"if-statement",
"for-loop",
"for-else"
] | I understand how this construct works:
```
for i in range(10):
print(i)
if i == 9:
print("Too big - I'm giving up!")
break;
else:
print("Completed successfully")
```
But I don't understand why `else` is used as the keyword here, since it suggests the code in question only runs if the `for... | I read it something like:
If still on the conditions to run the loop, do stuff, *else* do something else. |
Why does python use 'else' after for and while loops? | 9,979,970 | 183 | 2012-04-02T16:18:45Z | 9,980,160 | 130 | 2012-04-02T16:30:48Z | [
"python",
"if-statement",
"for-loop",
"for-else"
] | I understand how this construct works:
```
for i in range(10):
print(i)
if i == 9:
print("Too big - I'm giving up!")
break;
else:
print("Completed successfully")
```
But I don't understand why `else` is used as the keyword here, since it suggests the code in question only runs if the `for... | It's a strange construct even to seasoned Python coders. When used in conjunction with for-loops it basically means "find some item in the iterable, else if none was found do ...". As in:
```
found_obj = None
for obj in objects:
if obj.key == search_key:
found_obj = obj
break
else:
print 'No ob... |
Why does python use 'else' after for and while loops? | 9,979,970 | 183 | 2012-04-02T16:18:45Z | 9,980,752 | 200 | 2012-04-02T17:13:15Z | [
"python",
"if-statement",
"for-loop",
"for-else"
] | I understand how this construct works:
```
for i in range(10):
print(i)
if i == 9:
print("Too big - I'm giving up!")
break;
else:
print("Completed successfully")
```
But I don't understand why `else` is used as the keyword here, since it suggests the code in question only runs if the `for... | A common construct is to run a loop until something is found and then to break out of the loop. The problem is that if I break out of the loop or the loop ends I need to determine which case happened. One method is to create a flag or store variable that will let me do a second test to see how the loop was exited.
For... |
Why does python use 'else' after for and while loops? | 9,979,970 | 183 | 2012-04-02T16:18:45Z | 23,626,222 | 7 | 2014-05-13T08:28:54Z | [
"python",
"if-statement",
"for-loop",
"for-else"
] | I understand how this construct works:
```
for i in range(10):
print(i)
if i == 9:
print("Too big - I'm giving up!")
break;
else:
print("Completed successfully")
```
But I don't understand why `else` is used as the keyword here, since it suggests the code in question only runs if the `for... | I think documentation has a great explanation of *else*, *continue*
> [...] it is executed when the loop terminates through exhaustion of the list (with for) or when the condition becomes false (with while), but not when the loop is terminated by a break statement."
Source: [Python 2 docs: Tutorial on control flow](h... |
Why does python use 'else' after for and while loops? | 9,979,970 | 183 | 2012-04-02T16:18:45Z | 23,748,240 | 81 | 2014-05-19T22:30:55Z | [
"python",
"if-statement",
"for-loop",
"for-else"
] | I understand how this construct works:
```
for i in range(10):
print(i)
if i == 9:
print("Too big - I'm giving up!")
break;
else:
print("Completed successfully")
```
But I don't understand why `else` is used as the keyword here, since it suggests the code in question only runs if the `for... | There's an excellent presentation by Raymond Hettinger, titled [*Transforming Code into Beautiful, Idiomatic Python*](https://www.youtube.com/watch?v=OSGv2VnC0go), in which he briefly addresses the history of the `for ... else` construct. The relevant section is "Distinguishing multiple exit points in loops" [starting ... |
Why does python use 'else' after for and while loops? | 9,979,970 | 183 | 2012-04-02T16:18:45Z | 28,344,513 | 9 | 2015-02-05T12:54:02Z | [
"python",
"if-statement",
"for-loop",
"for-else"
] | I understand how this construct works:
```
for i in range(10):
print(i)
if i == 9:
print("Too big - I'm giving up!")
break;
else:
print("Completed successfully")
```
But I don't understand why `else` is used as the keyword here, since it suggests the code in question only runs if the `for... | The easiest way I found to 'get' what the for/else did, and more importantly, when to use it, was to concentrate on where the break statement jumps to. The For/else construct is a single block. The break jumps out of the block, and so jumps 'over' the else clause. If the contents of the else clause simply followed the ... |
Python / Pymongo variable for collection name in db insert command | 9,980,307 | 4 | 2012-04-02T16:40:19Z | 9,981,249 | 7 | 2012-04-02T17:52:56Z | [
"python",
"mongodb",
"pymongo"
] | I have this small piece of code that basically takes a list and runs a loop, running search queries against twitter, for each item in the list. I want each item in the list to be a collection name but for some reason I can't figure out how to make `db<collection_name_variable>.insert(post)>` to actually work:
I get an... | Replace:
```
insert = db + nosql + ".insert(post)"
insert
```
with:
```
db[nosql].insert(post)
``` |
Python LIST functions not returning new lists | 9,983,254 | 4 | 2012-04-02T20:20:10Z | 9,983,341 | 7 | 2012-04-02T20:27:05Z | [
"python",
"list"
] | I'm having an issue considering the built-in Python List-methods.
As I learned Python, I always thought Python mutators, as any value class mutators should do, returned the new variable it created.
Take this example:
```
a = range(5)
# will give [0, 1, 2, 3, 4]
b = a.remove(1)
# as I learned it, b should now be [0, ... | Rather than *both* mutating and returning objects, the Python library chooses to have just one way of using the result of a mutator. From `import this`:
> There should be one-- and preferably only one --obvious way to do it.
Having said that, the more usual Python style for what you want to do is using *list comprehe... |
Crop the image using PIL in python | 9,983,263 | 43 | 2012-04-02T20:20:59Z | 9,983,361 | 93 | 2012-04-02T20:29:22Z | [
"python",
"python-imaging-library"
] | I want to crop image in the way by removing first 30 rows and last 30 rows from the given image. I have searched but did not get the exact solution. Does somebody have some suggestions? | There is a [`crop()`](http://effbot.org/imagingbook/image.htm#tag-Image.Image.crop) method:
```
w, h = yourImage.size
yourImage.crop((0, 30, w, h-30)).save(...)
``` |
Comparing two generators in Python | 9,983,547 | 14 | 2012-04-02T20:44:19Z | 9,983,574 | 7 | 2012-04-02T20:46:24Z | [
"python"
] | I am wondering about the use of `==` when comparing two generators
For example:
```
x = ['1','2','3','4','5']
gen_1 = (int(ele) for ele in x)
gen_2 = (int(ele) for ele in x)
```
**gen\_1** and **gen\_2** are the same for all practical purposes, and yet when I compare them:
```
>>> gen_1 == gen_2
False
```
My gues... | Because generators generate their values on-demand, there isn't any way to "compare" them without actually *consuming* them. And if your generators generate an infinite sequence of values, such an equality test as you propose would be useless. |
Comparing two generators in Python | 9,983,547 | 14 | 2012-04-02T20:44:19Z | 9,983,596 | 10 | 2012-04-02T20:48:03Z | [
"python"
] | I am wondering about the use of `==` when comparing two generators
For example:
```
x = ['1','2','3','4','5']
gen_1 = (int(ele) for ele in x)
gen_2 = (int(ele) for ele in x)
```
**gen\_1** and **gen\_2** are the same for all practical purposes, and yet when I compare them:
```
>>> gen_1 == gen_2
False
```
My gues... | You are right with your guess â the fallback for comparison of types that don't define `==` is comparison based on object identity.
A better way to compare the values they generate would be
```
from itertools import izip_longest, tee
sentinel = object()
all(a == b for a, b in izip_longest(gen_1, gen_2, fillvalue=se... |
Python Recursion through objects and child objects, Print child depth numbers | 9,984,513 | 5 | 2012-04-02T22:06:29Z | 9,984,919 | 7 | 2012-04-02T22:51:54Z | [
"python",
"tree",
"parent-child"
] | I have a simple class with an attribute that can contain a list of objects of the same class
```
class BoxItem:
def __init__(self, name, **kw):
self.name = name
self.boxItems = []
... #more attributes here
box1 = BoxItem('Normal Box')
box2 = BoxItem('Friendly Box')
box3 = BoxItem('Cool Box')
box4 ... | I think it might be more helpful to you if I post a working example of how to do this, as opposed to going through where you code is having problems. We might get to the point of understanding a lot faster that way. Your code has the correct idea that it needs to track the depth as it goes. But the only thing it is mis... |
How do I keep trying a web page that throws a "urllib2.HTTPError" error (python)? | 9,986,179 | 2 | 2012-04-03T01:58:26Z | 9,986,206 | 9 | 2012-04-03T02:04:27Z | [
"python",
"html"
] | I'm attempting to scrape the HTML from various webpages of a website. However, I am occasionally getting the following error:
```
urllib2.HTTPError: HTTP Error 500: Internal Server Error
```
I'm trying to do a "while" loop to keep trying until the error goes away, but I haven't figured out the correct format for the... | `urllib.urlopen` is throwing an [exception](http://docs.python.org/tutorial/errors.html). You need to use the `try` and `except` statements to "catch" the exception, like this:
```
while True:
try:
web_raw_results = urllib2.urlopen(web_url)
break
except urllib.HTTPError:
continue
```
This will loop co... |
Expand tabs to spaces in vim only in python files? | 9,986,475 | 26 | 2012-04-03T02:49:30Z | 9,986,497 | 47 | 2012-04-03T02:51:10Z | [
"python",
"coding-style",
"vim"
] | How do I have the tab key insert 4 spaces when I'm editing "\*.py" files and not any other files?
Following a recommendation from [Vim and PEP 8 -- Style Guide for Python Code](http://stackoverflow.com/questions/9864543/vim-and-pep-8-style-guide-for-python-code), I installed vim-flake8 (and vim-pathogen). This gives w... | ```
autocmd Filetype python setlocal expandtab tabstop=4 shiftwidth=4
```
Or even shorter:
```
au Filetype python setl et ts=4 sw=4
``` |
Reading from database with SQLite and Python: Incorrect number of binding supplied | 9,986,578 | 3 | 2012-04-03T03:05:30Z | 9,986,627 | 9 | 2012-04-03T03:11:53Z | [
"python",
"database",
"sqlite",
"binding"
] | am reading out of a database with the following python script:
```
cur.execute("SELECT * FROM pending where user = ?", (ID))
```
Where ID is someone's name, in this case "Jonathan".
However, when I try to run this script, I get the error saying
```
Traceback (most recent call last):
File "/usr/lib/pymodules/pytho... | You must supply a sequence of values for the binding. `ID` is a string, so it looks like a sequence of 8 values.
You're probably thinking that `(ID)` should be a tuple with one element, but it isn't. Parenthesis aren't the tuple-making syntax in Python (except for the empty tuple). Commas are. Use `(ID,)` instead to g... |
`elif` in list comprehension conditionals | 9,987,483 | 28 | 2012-04-03T05:16:30Z | 9,987,533 | 49 | 2012-04-03T05:23:03Z | [
"python",
"list"
] | can we use elif in list comprehension?
example :
```
l = [1, 2, 3, 4, 5]
for values in l:
if values==1:
print 'yes'
elif values==2:
print 'no'
else:
print 'idle'
```
can we use list comprehension for such 2 if conditions and one else condition?
foe example answer like :
```
['y... | Python's [conditional expressions](http://docs.python.org/release/2.5.3/whatsnew/pep-308.html) were designed exactly for this sort of use-case:
```
>>> l = [1, 2, 3, 4, 5]
>>> ['yes' if v == 1 else 'no' if v == 2 else 'idle' for v in l]
['yes', 'no', 'idle', 'idle', 'idle']
```
Hope this helps :-) |
`elif` in list comprehension conditionals | 9,987,483 | 28 | 2012-04-03T05:16:30Z | 9,987,535 | 16 | 2012-04-03T05:23:38Z | [
"python",
"list"
] | can we use elif in list comprehension?
example :
```
l = [1, 2, 3, 4, 5]
for values in l:
if values==1:
print 'yes'
elif values==2:
print 'no'
else:
print 'idle'
```
can we use list comprehension for such 2 if conditions and one else condition?
foe example answer like :
```
['y... | ```
>>> d = {1: 'yes', 2: 'no'}
>>> [d.get(x, 'idle') for x in l]
['yes', 'no', 'idle', 'idle', 'idle']
``` |
`elif` in list comprehension conditionals | 9,987,483 | 28 | 2012-04-03T05:16:30Z | 9,987,546 | 8 | 2012-04-03T05:25:10Z | [
"python",
"list"
] | can we use elif in list comprehension?
example :
```
l = [1, 2, 3, 4, 5]
for values in l:
if values==1:
print 'yes'
elif values==2:
print 'no'
else:
print 'idle'
```
can we use list comprehension for such 2 if conditions and one else condition?
foe example answer like :
```
['y... | You can, sort of.
Note that when you use sytax like:
```
['yes' if v == 1 else 'no' for v in l]
```
You are using the ternary form of the if/else operator (if you're familiar with languages like C, this is like the `?:` construct: `(v == 1 ? 'yes' : 'no')`).
The ternary form of the if/else operator doesn't have an ... |
How to close a Tkinter window by pressing a Button? | 9,987,624 | 7 | 2012-04-03T05:35:21Z | 9,987,684 | 13 | 2012-04-03T05:42:05Z | [
"python",
"tkinter"
] | Write a GUI application with a button labeled `"Good-bye"`. When the
`Button` is clicked, the window closes.
This is my code so far, but it is not working. Can anyone help me out with my code?
```
from Tkinter import *
window = Tk()
def close_window (root):
root.destroy()
frame = Frame(window)
frame.pack()
bu... | With minimal editing to your code (Not sure if they've taught classes or not in your course), change:
```
def close_window(root):
root.destroy()
```
to
```
def close_window():
window.destroy()
```
and it should work.
---
**Explanation:**
Your version of `close_window` is defined to expect a single argu... |
In python, how to check if a date is valid? | 9,987,818 | 11 | 2012-04-03T05:57:11Z | 9,987,935 | 13 | 2012-04-03T06:08:06Z | [
"python",
"validation",
"date",
"time"
] | I am building a kind of calender web app
I have set up the following form in HTML
```
<form action='/event' method='post'>
Year ("yyyy"): <input type='text' name='year' />
Month ("mm"): <input type='text' name='month' />
Day ("dd"): <input type='text' name='day' />
Hour ("hh"): <input type='text' name='hour' />
D... | You could try doing
```
import datetime
datetime.datetime(year=year,month=month,day=day,hour=hour)
```
that will eliminate somethings like months >12 , hours > 23, non-existent leapdays (month=2 has max of 28 on non leap years, 29 otherwise, other months have max of 30 or 31 days)(throws ValueError exception on error... |
In python, how to check if a date is valid? | 9,987,818 | 11 | 2012-04-03T05:57:11Z | 9,988,288 | 15 | 2012-04-03T06:39:36Z | [
"python",
"validation",
"date",
"time"
] | I am building a kind of calender web app
I have set up the following form in HTML
```
<form action='/event' method='post'>
Year ("yyyy"): <input type='text' name='year' />
Month ("mm"): <input type='text' name='month' />
Day ("dd"): <input type='text' name='day' />
Hour ("hh"): <input type='text' name='hour' />
D... | You can try using datetime and handle the exceptions to decide valid/invalid date :
Example : <http://codepad.org/XRSYeIJJ>
```
import datetime
correctDate = None
try:
newDate = datetime.datetime(2008,11,42)
correctDate = True
except ValueError:
correctDate = False
print(str(correctDate))
``` |
How to search document by oid in mongoengine | 9,988,352 | 2 | 2012-04-03T06:45:33Z | 9,988,847 | 17 | 2012-04-03T07:25:17Z | [
"python",
"mongodb",
"mongoengine"
] | I need get documents from db by oid, like:
```
Docs.objects(_id='4f4381f4e779897a2c000009')
```
But how to do it, if \_id requires ObjectId object and even I try to set ObjectId from pymongo it doesn't work.
```
Docs.objects(_id=pymongo.objectid.ObjectId('4f4381f4e779897a2c000009'))
```
return empty list | This should work:
```
Docs.objects(pk='4f4381f4e779897a2c000009')
``` |
How to search document by oid in mongoengine | 9,988,352 | 2 | 2012-04-03T06:45:33Z | 10,611,956 | 9 | 2012-05-16T04:22:02Z | [
"python",
"mongodb",
"mongoengine"
] | I need get documents from db by oid, like:
```
Docs.objects(_id='4f4381f4e779897a2c000009')
```
But how to do it, if \_id requires ObjectId object and even I try to set ObjectId from pymongo it doesn't work.
```
Docs.objects(_id=pymongo.objectid.ObjectId('4f4381f4e779897a2c000009'))
```
return empty list | How about just using the raw string:
```
Docs.objects.get(id='4f4381f4e779897a2c000009')
```
That is probably the easiest way ... right ? |
Resize GIF animation, pil/imagemagick, python | 9,988,517 | 6 | 2012-04-03T06:58:23Z | 10,031,281 | 11 | 2012-04-05T15:13:48Z | [
"python",
"imagemagick",
"python-imaging-library",
"gif",
"pythonmagick"
] | I want to change size of GIF animation image using python and PIL or PythonMagick. I can't find solution. PIL and thumbnail method works for jpg and png but not for gif. ImageMagick has command mogrify/convert -resize '1280x1024>' but i can't find documentation and i don't know how to do it with pythonmagick.
Anyone k... | You can use PIL and `images2gif`, a short PIL based module linked to on this [blog page](http://www.somethinkodd.com/oddthinking/2005/12/06/python-imaging-library-pil-and-animated-gifs/), and available [here](http://code.google.com/p/visvis/source/browse/vvmovie/images2gif.py). Code used to process this `rose.gif` is b... |
Create nice column output in python | 9,989,334 | 40 | 2012-04-03T08:00:18Z | 9,989,397 | 7 | 2012-04-03T08:06:23Z | [
"python"
] | I am trying to create a nice column list in python for use with commandline admin tools which I create.
Basicly, I want a list like:
```
[['a', 'b', 'c'], ['aaaaaaaaaa', 'b', 'c'], ['a', 'bbbbbbbbbb', 'c']]
```
To turn into:
```
a b c
aaaaaaaaaa b c
a bbbbbbbbbb c
```... | You have to do this with 2 passes:
1. get the maximum width of each column.
2. formatting the columns using our knowledge of max width from the first pass using `str.ljust()` and `str.rjust()` |
Create nice column output in python | 9,989,334 | 40 | 2012-04-03T08:00:18Z | 9,989,441 | 50 | 2012-04-03T08:10:28Z | [
"python"
] | I am trying to create a nice column list in python for use with commandline admin tools which I create.
Basicly, I want a list like:
```
[['a', 'b', 'c'], ['aaaaaaaaaa', 'b', 'c'], ['a', 'bbbbbbbbbb', 'c']]
```
To turn into:
```
a b c
aaaaaaaaaa b c
a bbbbbbbbbb c
```... | ```
>>> data = [['a', 'b', 'c'], ['aaaaaaaaaa', 'b', 'c'], ['a', 'bbbbbbbbbb', 'c']]
>>> col_width = max(len(word) for row in data for word in row) + 2 # padding
>>> for row in data:
... print "".join(word.ljust(col_width) for word in row)
a b c
aaaaaaaaaa b c ... |
Create nice column output in python | 9,989,334 | 40 | 2012-04-03T08:00:18Z | 9,996,049 | 36 | 2012-04-03T15:02:33Z | [
"python"
] | I am trying to create a nice column list in python for use with commandline admin tools which I create.
Basicly, I want a list like:
```
[['a', 'b', 'c'], ['aaaaaaaaaa', 'b', 'c'], ['a', 'bbbbbbbbbb', 'c']]
```
To turn into:
```
a b c
aaaaaaaaaa b c
a bbbbbbbbbb c
```... | In Python 2.6+, the following [format string](http://docs.python.org/2.7/library/string.html#format-specification-mini-language) can be used to set the columns to a minimum of 20 characters and align text to right.
```
>>> table_data = [['a', 'b', 'c'], ['aaaaaaaaaa', 'b', 'c'], ['a', 'bbbbbbbbbb', 'c']]
>>> for row i... |
Create nice column output in python | 9,989,334 | 40 | 2012-04-03T08:00:18Z | 12,065,663 | 19 | 2012-08-22T02:36:02Z | [
"python"
] | I am trying to create a nice column list in python for use with commandline admin tools which I create.
Basicly, I want a list like:
```
[['a', 'b', 'c'], ['aaaaaaaaaa', 'b', 'c'], ['a', 'bbbbbbbbbb', 'c']]
```
To turn into:
```
a b c
aaaaaaaaaa b c
a bbbbbbbbbb c
```... | I came here with the same requirements but @lvc and @Preet's answers seems more inline with what `column -t` produces in that columns have different widths:
```
>>> rows = [ ['a', 'b', 'c', 'd']
... , ['aaaaaaaaaa', 'b', 'c', 'd']
... , ['a', 'bbb... |
Type Error: Format Requires Mapping | 9,990,177 | 12 | 2012-04-03T09:05:13Z | 9,990,266 | 11 | 2012-04-03T09:09:57Z | [
"python",
"string",
"list",
"object",
"dictionary"
] | I have a string and a list of objects:
```
gpl = "%(id)s : %(atr)s"
objects = [{'id':1, 'content':[{'atr':'big', 'no':2}]}, {'id':2, 'content': [{'atr':'small', 'no':3}]}]
for obj in objects:
for con in obj['content']:
print gpl %(obj,con)
```
I get:
```
TypeError: format requires a mapping
```
How wou... | Since your formatting string uses named parameters:
```
gpl = "%(id)s : %(atr)s"
```
You need to provide keys (the names) in a dictionary as an argument to reference back to named formatting keys in the formatting string:
```
print gpl % {'id': obj['id'], 'atr': con['atr']}
```
So your code would be:
```
for obj i... |
How to force zero interception in linear regression? | 9,990,789 | 13 | 2012-04-03T09:45:12Z | 9,990,847 | 9 | 2012-04-03T09:49:19Z | [
"python",
"numpy",
"scipy",
"linear-regression"
] | I'm a bit of a newby so apologies if this question has already been answered, I've had a look and couldn't find specifically what I was looking for.
I have some more or less linear data of the form
```
x = [0.1, 0.2, 0.4, 0.6, 0.8, 1.0, 2.0, 4.0, 6.0, 8.0, 10.0, 20.0, 40.0, 60.0, 80.0]
y = [0.50505332505407008, 1.120... | I am not adept at these modules, but I have some experience in statistics, so here is what I see. You need to change your fit function from
```
fitfunc = lambda params, x: params[0] * x + params[1]
```
to:
```
fitfunc = lambda params, x: params[0] * x
```
Also remove the line:
```
init_b = min(y)
```
And change t... |
How to force zero interception in linear regression? | 9,990,789 | 13 | 2012-04-03T09:45:12Z | 9,994,484 | 20 | 2012-04-03T13:38:49Z | [
"python",
"numpy",
"scipy",
"linear-regression"
] | I'm a bit of a newby so apologies if this question has already been answered, I've had a look and couldn't find specifically what I was looking for.
I have some more or less linear data of the form
```
x = [0.1, 0.2, 0.4, 0.6, 0.8, 1.0, 2.0, 4.0, 6.0, 8.0, 10.0, 20.0, 40.0, 60.0, 80.0]
y = [0.50505332505407008, 1.120... | As @AbhranilDas mentioned, just use a linear method. There's no need for a non-linear solver like `scipy.optimize.lstsq`.
Typically, you'd use `numpy.polyfit` to fit a line to your data, but in this case you'll need to do use `numpy.linalg.lstsq` directly, as you want to set the intercept to zero.
As a quick example:... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.