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 |
|---|---|---|---|---|---|---|---|---|---|
Numpy longdouble arithmetic does not seem to be in long double with conversion | 18,536,820 | 8 | 2013-08-30T15:43:57Z | 18,537,604 | 7 | 2013-08-30T16:31:16Z | [
"python",
"numpy",
"floating-point"
] | I have been playing C99's [quad precision](http://en.wikipedia.org/wiki/Quadruple-precision_floating-point_format) long double. It is my understanding that (platform specific) numpy supports [long double](http://docs.scipy.org/doc/numpy/reference/c-api.dtype.html#NPY_LONGDOUBLE) and 128bit floats.
I have run across so... | You're trying to perform a type conversion between non-directly-convertible types. Take a look at the stack:
```
#0 0x00002aaaaab243a0 in PyLong_AsDouble ()
from libpython2.7.so.1.0
#1 0x00002aaaaab2447a in ?? ()
from libpython2.7.so.1.0
#2 0x00002aaaaaaf8357 in PyNumber_Float ()
from libpython2.7.so.1.0
#... |
Set window icon | 18,537,918 | 15 | 2013-08-30T16:51:37Z | 18,538,416 | 16 | 2013-08-30T17:27:50Z | [
"python",
"windows-7",
"python-3.x",
"tkinter",
"favicon"
] | When I tried to change the window icon in the top left corner from the ugly red "TK" to my own favicon using the code below, Python threw an error:
```
from tkinter import *
root = Tk()
#some buttons, widgets, a lot of stuff
root.iconbitmap('favicon.ico')
```
This should set the icon to 'favicon.ico' (according to ... | You must not have `favicon.ico` in the same folder as your script or, namely, on your path. Put in the full pathname. For example, this works:
```
from tkinter import *
root = Tk()
root.iconbitmap(r'c:\Python32\DLLs\py.ico')
root.mainloop()
```
But this blows up with your same error:
```
from tkinter import *
root ... |
Class constructors and keyword arguments - How does Python determine which one is unexpected? | 18,539,171 | 19 | 2013-08-30T18:19:02Z | 18,539,255 | 17 | 2013-08-30T18:24:18Z | [
"python"
] | Say I define the following class:
```
class MyClass(object):
def __init__(self, x, y):
self.x = x
self.y = y
```
Normally, one would instantiate this class in one of the following ways:
```
>>> MyClass(1,2)
<__main__.MyClass object at 0x8acbf8c>
>>> MyClass(1, y=2)
<__main__.MyClass object at 0x8... | Keyword arguments are stored in a dictionary, and dictionary order (e.g. arbitrary, based on the hashing algorithm, hash collisions and insertion history) applies.
For your first sample, a dictionary with both `i` and `j` keys results in `i` being listed first:
```
>>> dict(j=2, i=1)
{'i': 1, 'j': 2}
```
Note that t... |
How to validate a specific Date and Time format using Python | 18,539,266 | 3 | 2013-08-30T18:24:47Z | 18,539,406 | 13 | 2013-08-30T18:33:34Z | [
"python",
"datetime",
"format"
] | I am writing a program to validate portions of an XML file. One of the points I would like to validate is a Date Time format. I've read up on the forum about using `time.strptime()` but the examples weren't quite working for me and were a little over my expertise. Anyone have any ideas how I could validate the followin... | Yes, you can use [`datetime.strptime()`](http://docs.python.org/2/library/datetime.html#datetime.datetime.strptime):
```
from datetime import datetime
def validate_date(d):
try:
datetime.strptime(d, '%m/%d/%Y %I:%M %p')
return True
except ValueError:
return False
print validate_date... |
Remove whitespace in for loop | 18,540,415 | 3 | 2013-08-30T19:44:52Z | 18,540,457 | 9 | 2013-08-30T19:47:16Z | [
"python",
"loops",
"for-loop",
"whitespace"
] | I've made a simple script in python which shifts the letters up 5 spaces in the ASCII table using chr and ord. See below:
```
word = "python"
print 'Shifted 5 letters are: '
for letters in word:
print chr(ord(letters)+5),
```
The output is:
```
Shifted 5 letters is:
u ~ y m t s
```
The output is great, bu... | If you don't need to use the for loop, simply do this:
```
print ''.join([chr(ord(letter) + 5) for letter in word])
```
instead of the whole loop. |
datetime and timezone conversion with pytz - mind blowing behaviour | 18,541,051 | 11 | 2013-08-30T20:32:21Z | 18,541,344 | 22 | 2013-08-30T20:55:07Z | [
"python",
"django",
"datetime",
"timezone",
"pytz"
] | I'm trying to convert timezone aware `datetime` object to UTC and then back to it's original timezone. I have a following snippet
```
t = datetime(
2013, 11, 22, hour=11, minute=0,
tzinfo=pytz.timezone('Europe/Warsaw')
)
```
now in ipython:
```
In [18]: t
Out[18]: datetime.datetime(
2013, 11, 22, 11, 0, ... | The documentation <http://pytz.sourceforge.net/> states "Unfortunately using the tzinfo argument of the standard datetime constructors 'does not work' with pytz for many timezones." The code
```
t = datetime(
2013, 5, 11, hour=11, minute=0,
tzinfo=pytz.timezone('Europe/Warsaw')
)
```
doesn't work according to... |
Multiple Output Files for Hadoop Streaming with Python Mapper | 18,541,503 | 4 | 2013-08-30T21:09:47Z | 18,562,328 | 14 | 2013-09-01T19:58:39Z | [
"python",
"hadoop"
] | I am looking for a little clarification on the the answers to this question here:
[Generating Separate Output files in Hadoop Streaming](http://stackoverflow.com/questions/1626786/generating-separate-output-files-in-hadoop-streaming)
My use case is as follows:
I have a map-only mapreduce job that takes an input file... | You can do something like the following, but it involves a little Java compiling, which I think shouldn't be a problem, if you want your use case done anyways with Python-
From Python, as far as I know it's not directly possible to skip the filename from the final output as your use case demands in a single job. But wh... |
Invert position of sublists | 18,543,452 | 3 | 2013-08-31T01:04:19Z | 18,543,462 | 8 | 2013-08-31T01:05:56Z | [
"python",
"list",
"numpy",
"position"
] | I have a list composed of several sublists:
```
list_1 = [[x1,y1,z1], [x2,y2,z2], [x3,y3,z3], [x4,y4,z4]]
```
How can I invert the position of the sublists so that it will look like:
```
list_2 = [[x4,y4,z4], [x3,y3,z3], [x2,y2,z2], [x1,y1,z1]]
```
without having to use a `for` loop.
I've tried `sorted(list_1, rev... | Use [`reversed`](http://docs.python.org/2/library/functions.html#reversed):
```
>>> list_1 = [[1,2,3], [4,5,6], [0,1,2], [6,5,3]]
>>> list(reversed(list_1))
[[6, 5, 3], [0, 1, 2], [4, 5, 6], [1, 2, 3]]
```
or `[::-1]`:
```
>>> list_1[::-1]
[[6, 5, 3], [0, 1, 2], [4, 5, 6], [1, 2, 3]]
```
or copy `list_1`, then [`re... |
How to convert numbers to alphabet in Python? | 18,544,419 | 7 | 2013-08-31T04:19:21Z | 18,544,440 | 22 | 2013-08-31T04:22:20Z | [
"python"
] | I read [this thread](http://stackoverflow.com/questions/4528982/convert-alphabet-letters-to-number-in-python) about converting the alphabet to numbers but I don't understand how to convert the numbers back into letters.
I would appreciate if someone could expand on that, especially and more specifically, the `chr()` fu... | If you have a number, for example 7, and if you want to get the corresponding lowercase character,
```
>>> print chr(7 + ord('a'))
h
```
For uppercase
```
>>> print chr(7 + ord('A'))
H
```
**EDIT:** The above solution works for 8 bit characters or ASCII characters. If you are dealing with unicode characters, you ha... |
Convert a HTML Table to JSON | 18,544,634 | 4 | 2013-08-31T04:53:04Z | 18,544,794 | 12 | 2013-08-31T05:19:44Z | [
"python",
"html",
"json",
"table"
] | I'm trying to convert a table I have extracted via BeautifulSoup into JSON.
So far I've managed to isolate all the rows, though I'm not sure how to work with the data from here. Any advice would be very much appreciated.
```
[<tr><td><strong>Balance</strong></td><td><strong>$18.30</strong></td></tr>,
<tr><td>Card na... | Probably your data is something like:
```
html_data = """
<table>
<tr>
<td>Card balance</td>
<td>$18.30</td>
</tr>
<tr>
<td>Card name</td>
<td>NAMEn</td>
</tr>
<tr>
<td>Account holder</td>
<td>NAME</td>
</tr>
<tr>
<td>Card number</td>
<td>1234</td>
</tr>
<tr>
<td>S... |
How do you uninstall the package manager "pip", if installed from source? | 18,546,321 | 13 | 2013-08-31T08:51:46Z | 18,548,347 | 8 | 2013-08-31T12:52:07Z | [
"python",
"pip",
"uninstall",
"system-administration"
] | I was unaware that pip could be installed via my operating system's package manager, so I compiled and installed pip via source with the following command:
```
wget https://bitbucket.org/pypa/setuptools/raw/bootstrap/ez_setup.py -O - | sudo python
```
I would like to uninstall pip, and instead install it from my oper... | That way you haven't installed pip, you installed just the `easy_install` i.e. `setuptools`.
First you should remove all the packages you installed with `easy_install` using (see [uninstall](http://pythonhosted.org/setuptools/easy_install.html#uninstalling-packages)):
```
easy_install -m PackageName
```
This include... |
How do you uninstall the package manager "pip", if installed from source? | 18,546,321 | 13 | 2013-08-31T08:51:46Z | 29,808,986 | 16 | 2015-04-22T21:14:24Z | [
"python",
"pip",
"uninstall",
"system-administration"
] | I was unaware that pip could be installed via my operating system's package manager, so I compiled and installed pip via source with the following command:
```
wget https://bitbucket.org/pypa/setuptools/raw/bootstrap/ez_setup.py -O - | sudo python
```
I would like to uninstall pip, and instead install it from my oper... | `pip uninstall pip` will work |
dbscan - setting limit on maximum cluster span | 18,547,147 | 5 | 2013-08-31T10:29:20Z | 18,553,115 | 7 | 2013-08-31T21:47:20Z | [
"python",
"algorithm",
"cluster-analysis",
"data-mining",
"dbscan"
] | By my understanding of DBSCAN, it's possible for you to specify an epsilon of, say, 100 meters and â because DBSCAN takes into account *density-reachability* and **not** *direct density-reachability* when finding clusters â end up with a cluster in which the maximum distance between any two points is > 100 meters. ... | DBSCAN indeed does not impose a total size constraint on the cluster.
The epsilon value is best interpreted as the **size of the gap separating two clusters** (that may at most contain minpts-1 objects).
I believe, you are in fact not even looking for clustering: clustering is the task of **discovering structure in d... |
multiple databases and multiple models in django | 18,547,468 | 9 | 2013-08-31T11:06:20Z | 18,547,515 | 11 | 2013-08-31T11:12:08Z | [
"python",
"database",
"django",
"django-models"
] | I have two databases and two models:the Admin and the user.
I want to sync my models to the two databases;
admin model to database A and user model to database B;
If I am setting the model path to INSTALLED\_APPS and syncdb,the two models will sync to the default database.
if I set the database in the syncdb command... | In order to define specific databases used for specific models, you need to define a [database router](https://docs.djangoproject.com/en/dev/topics/db/multi-db/#database-routers):
> The easiest way to use multiple databases is to set up a database
> routing scheme. The default routing scheme ensures that objects remai... |
multiple databases and multiple models in django | 18,547,468 | 9 | 2013-08-31T11:06:20Z | 18,548,287 | 12 | 2013-08-31T12:46:07Z | [
"python",
"database",
"django",
"django-models"
] | I have two databases and two models:the Admin and the user.
I want to sync my models to the two databases;
admin model to database A and user model to database B;
If I am setting the model path to INSTALLED\_APPS and syncdb,the two models will sync to the default database.
if I set the database in the syncdb command... | I fully agree with @alecxe on using the database router. I am currently using a single admin interface to manage multiple databases. Note that authentication for all databases are stored in the default database, so when you do the `syncdb` (with no arguments).
**Generic Database Router**
I found [this](http://diegobz... |
Attribute Error: next() | 18,547,878 | 3 | 2013-08-31T11:57:13Z | 18,547,901 | 13 | 2013-08-31T12:00:01Z | [
"python"
] | I want to loop one level deep using `next()` with `os.walk`
Critical line of my code:
```
for root, dirs, files in os.walk(dir).next(1):
```
Error:
> AttributeError: 'generator' object has no attribute 'next'
I tried using `.next(x)` to replace old `next()[1]` as suggested by community, but this also doesnt work. | You are using python3. In python3 the `next()` method was replaced by `__next__`.
These method do **not** accept any argument(i.e. `a.__next__(1)` is an error).
They advance the iterator by *one*. To advance it by more elements call `next` repeatedly.
If you want to advance the iterator by one use, I'd suggest to use ... |
Pandas "Can only compare identically-labeled DataFrame objects" error | 18,548,370 | 7 | 2013-08-31T12:54:12Z | 18,548,888 | 10 | 2013-08-31T13:53:28Z | [
"python",
"pandas"
] | I'm using Pandas to compare the outputs of two files loaded into two data frames (uat, prod):
...
```
uat = uat[['Customer Number','Product']]
prod = prod[['Customer Number','Product']]
print uat['Customer Number'] == prod['Customer Number']
print uat['Product'] == prod['Product']
print uat == prod
The first two matc... | Here's a small example to demonstrate this (which seems not to be a restriction when comparing Series - I'm not sure why it's imposed only on DataFrames):
```
In [1]: df1 = pd.DataFrame([[1, 2], [3, 4]])
In [2]: df2 = pd.DataFrame([[3, 4], [1, 2]], index=[1, 0])
In [3]: df1 == df2
Exception: Can only compare identic... |
Python Firefox Webdriver tmp files | 18,549,105 | 9 | 2013-08-31T14:16:48Z | 18,584,684 | 16 | 2013-09-03T05:26:19Z | [
"python",
"selenium-webdriver",
"tmp"
] | My python application loads webpages using Selenium Webdriver for a total of 20000 pages more or less in several hours of work. My problem is that "something" is creating a lot of tmp files, filling all my hard drive. For example, this morning the application generates 70GB of tmp files in 6 hours of work :( after rebo... | Ok, the solution to the problem is to substitute:
```
driver.close()
```
with:
```
driver.quit()
```
Bye |
python find the 2nd highest element | 18,549,730 | 5 | 2013-08-31T15:31:02Z | 18,549,768 | 14 | 2013-08-31T15:34:50Z | [
"python"
] | 1.In a given array how to find the 2nd or 3rd,4th ,5th values.
2.Also if we use max() function in python what is the order of complexity i.e, associated with this function max()
```
def nth_largest(li,n):
li.remove(max(li))
print max(ele) //will give me the second largest
#how to make a general algor... | I'd go for:
```
import heapq
res = heapq.nlargest(2, some_sequence)
print res[1] # to get 2nd largest
```
This is more efficient than sorting the entire list, then taking the first `n` many elements. See the [heapq documentation](http://docs.python.org/2/library/heapq.html) for further info. |
virtual file processing in python? | 18,550,127 | 25 | 2013-08-31T16:14:03Z | 18,550,157 | 35 | 2013-08-31T16:16:45Z | [
"python",
"file",
"virtual"
] | So for creating files I use the following:
```
fileHandle = open('fileName', 'w')
```
then write the contents to the file, close the file.
In the next step I process the file.
At the end of the program, I end up with a "physical file" that I need to delete.
Is there a way to write a "virtual" file that behaves exact... | You have `StringIO` and `BytesIO` in the `io` module.
`StringIO` behaves like a file opened in text mode - reading and writing unicode strings (equivalent to opening a file with `io.open(filename, mode, encoding='...')`), and the `BytesIO` behaves like a file opened in binary mode (`mode='[rw]b'`), and can read write ... |
virtual file processing in python? | 18,550,127 | 25 | 2013-08-31T16:14:03Z | 18,550,652 | 17 | 2013-08-31T17:06:10Z | [
"python",
"file",
"virtual"
] | So for creating files I use the following:
```
fileHandle = open('fileName', 'w')
```
then write the contents to the file, close the file.
In the next step I process the file.
At the end of the program, I end up with a "physical file" that I need to delete.
Is there a way to write a "virtual" file that behaves exact... | You might want to consider using a [`tempfile.SpooledTemporaryFile`](https://docs.python.org/3/library/tempfile.html#tempfile.SpooledTemporaryFile) which gives you the best of both worlds in the sense that it will create a temporary memory-based virtual file initially but will automatically switch to a physical disk-ba... |
Python loop efficiency | 18,550,334 | 4 | 2013-08-31T16:34:57Z | 18,550,374 | 8 | 2013-08-31T16:39:15Z | [
"python",
"performance",
"loops"
] | I was just wondering if there is a more cpu efficient way of writing the following loop as I need to speed my program up?
```
for char in data:
if char in self.key:
match += chr(self.key.index(char))
```
Thanks in advance for any help. | *Replace* `self.key` with a dictionary; it is the membership testing against a list, as well as the `.index()` calls that are costing you the most performance; both require scans across the list.
Use `str.join()` to concatenate a series of characters; that builds *one* new string object instead of N new objects:
```
... |
How to frame two for loops in list comprehension python | 18,551,458 | 23 | 2013-08-31T18:25:52Z | 18,551,475 | 27 | 2013-08-31T18:28:04Z | [
"python",
"list",
"for-loop",
"list-comprehension"
] | I have two lists as below
```
tags = [u'man', u'you', u'are', u'awesome']
entries = [[u'man', u'thats'],[ u'right',u'awesome']]
```
I want to extract entries from `entries` when they are in `tags`:
```
result = []
for tag in tags:
for entry in entries:
if tag in entry:
result.extend(entry)
`... | This should do it:
```
[entry for tag in tags for entry in entries if tag in entry]
``` |
How to frame two for loops in list comprehension python | 18,551,458 | 23 | 2013-08-31T18:25:52Z | 18,551,476 | 39 | 2013-08-31T18:28:05Z | [
"python",
"list",
"for-loop",
"list-comprehension"
] | I have two lists as below
```
tags = [u'man', u'you', u'are', u'awesome']
entries = [[u'man', u'thats'],[ u'right',u'awesome']]
```
I want to extract entries from `entries` when they are in `tags`:
```
result = []
for tag in tags:
for entry in entries:
if tag in entry:
result.extend(entry)
`... | The best way to remember this is that the order of for loop inside the list comprehension is based on the order in which they appear in traditional loop approach. Outer most loop comes first, and then the inner loops subsequently.
So, the equivalent list comprehension would be:
```
[entry for tag in tags for entry in... |
How to use terminal color palette with curses | 18,551,558 | 8 | 2013-08-31T18:36:30Z | 22,166,613 | 22 | 2014-03-04T08:30:09Z | [
"python",
"colors",
"curses"
] | I can't get the terminal color palette to work with curses.
```
import curses
def main(stdscr):
curses.use_default_colors()
for i in range(0,7):
stdscr.addstr("Hello", curses.color_pair(i))
stdscr.getch()
curses.wrapper(main)
```
This python script yields the following screen:
![enter image des... | The following I figured out by experience.
* There are 256 colors (defined by the first 8 bits).
* The other bits are used for additional attributes, such as highlighting.
* Passing the number -1 as color falls back to the default background and foreground colors.
* The color pair 0 (mod 256) is fixed on (-1, -1).
* T... |
Python - split sentence after words but with maximum of n characters in result | 18,551,752 | 4 | 2013-08-31T19:01:49Z | 18,551,782 | 12 | 2013-08-31T19:05:17Z | [
"python",
"regex",
"string",
"python-2.7"
] | I want to display some text on a scrolling display with a width of 16 characters.
To improve readability I want to flip through the text, but not by simply splitting every 16. character, I rather want to split on every ending of a word or punctuation, before the 16 character limit exceeds..
Example:
```
text = 'Hello... | I'd look at the [textwrap](http://docs.python.org/2/library/textwrap.html) module:
```
>>> text = 'Hello, this is an example of text shown in the scrolling display. Bla, bla, bla!'
>>> from textwrap import wrap
>>> wrap(text, 16)
['Hello, this is', 'an example of', 'text shown in', 'the scrolling', 'display. Bla,', 'b... |
Find if a number exists between a range of numbers specified by a list | 18,551,848 | 5 | 2013-08-31T19:11:50Z | 18,551,882 | 7 | 2013-08-31T19:16:20Z | [
"python"
] | I have a list:
```
timestamp_list = ['1377091800', '1377093000', '1377094500', '1377095500']
```
Target number:
```
ptime = 1377091810
```
I want to find between which pair of timestamp does `ptime` lie in. For e.g. in this case, it lies between the first and the second timestamp. So I want to return the value `137... | Since the timestamps are sorted, you can use [`bisect`](http://docs.python.org/2/library/bisect.html) for that:
```
In [24]: timestamp_list = [1377091800, 1377093000, 1377094500, 1377095500]
In [25]: timestamp_list[bisect.bisect_right(timestamp_list, 1377093100)]
Out[25]: 1377094500
```
(I've converted the strings t... |
Accessing dict_keys element by index in Python3 | 18,552,001 | 26 | 2013-08-31T19:30:57Z | 18,552,025 | 33 | 2013-08-31T19:33:10Z | [
"python",
"dictionary",
"python-3.x",
"key"
] | I'm trying to access a dict\_key's element by its index:
```
test = {'foo': 'bar', 'hello': 'world'}
keys = test.keys() # dict_keys object
keys.index(0)
AttributeError: 'dict_keys' object has no attribute 'index'
```
I want to get `foo`.
same with:
```
keys[0]
TypeError: 'dict_keys' object does not support indexi... | Call `list()` on the dictionary instead:
```
keys = list(test)
```
In Python 3, the `dict.keys()` method returns a [dictionary view object](http://docs.python.org/3/library/stdtypes.html#dictionary-view-objects), which acts as a set. Iterating over the dictionary directly also yields keys, so turning a dictionary int... |
Accessing dict_keys element by index in Python3 | 18,552,001 | 26 | 2013-08-31T19:30:57Z | 27,638,751 | 10 | 2014-12-24T14:59:20Z | [
"python",
"dictionary",
"python-3.x",
"key"
] | I'm trying to access a dict\_key's element by its index:
```
test = {'foo': 'bar', 'hello': 'world'}
keys = test.keys() # dict_keys object
keys.index(0)
AttributeError: 'dict_keys' object has no attribute 'index'
```
I want to get `foo`.
same with:
```
keys[0]
TypeError: 'dict_keys' object does not support indexi... | Not a full answer but perhaps a useful hint. If it is really the first item you want\*, then
```
next(iter(q))
```
is much faster than
```
list(q)[0]
```
for large dicts, since the whole thing doesn't have to be stored in memory.
For 10.000.000 items I found it to be almost 40.000 times faster.
\*The first item i... |
Python: How do I save generator output into text file? | 18,552,758 | 5 | 2013-08-31T20:56:36Z | 18,552,801 | 8 | 2013-08-31T21:03:02Z | [
"python",
"printing",
"save",
"generator"
] | I am using the following generator to calculate a moving average:
```
import itertools
from collections import deque
def moving_average(iterable, n=50):
it = iter(iterable)
d = deque(itertools.islice(it, n-1))
d.appendleft(0)
s = sum(d)
for elem in it:
s += elem - d.popleft()
d.... | ```
def generator(howmany):
for x in xrange(howmany):
yield x
g = generator(10)
with open('output.txt', 'w') as f:
for x in g:
f.write(str(x))
with open('output.txt', 'r') as f:
print f.readlines()
```
output:
```
>>>
['0123456789']
``` |
No web processes running Django in heroku | 18,552,846 | 2 | 2013-08-31T21:07:58Z | 22,746,975 | 12 | 2014-03-30T17:04:49Z | [
"python",
"django",
"heroku",
"deployment"
] | I was trying to deploy my application in heroku, but when i finally try to run my application in heroku I het in the browser this:
```
Application Error
An error occurred in the application and your page could not be served. Please try again in a few moments.
If you are the application owner, check your logs for deta... | Benjamin Manns' solution worked for me, though I needed one additional step as well.
According to [this](http://vibhurishi.blogspot.com/2013/02/heroku-error-h14-with-django.html), after the `Procfile` solution has been pushed, run the following:
**`heroku ps:scale web=1`**
website should load correctly now.
for mor... |
Reading comma separated tuples from a file in python | 18,553,224 | 2 | 2013-08-31T22:03:48Z | 18,553,238 | 10 | 2013-08-31T22:05:50Z | [
"python",
"file",
"input"
] | I am trying to read from a file with several tuples separated by commas. A sample input file looks like:
> (0, 0), (0, 2), (0, 4), (-1, -1), (0, -2), (1, -1), (-1, -3),
>
> (-1, 1), (-1, 3), (1, 1), (1, 3), (1, 5), (2, 0), (2, 2), (3, 3),
>
> (2, 4), (3, 5), (4, 4), (5, 3), (6, 4), (5, 5), (7, 5)
After reading from t... | Since they look like proper python tuples you can use `literal_eval`. Its fast as safe:
> Safely evaluate an expression node or a string containing a Python
> expression. The string or node provided may only consist of the following
> Python literal structures: strings, numbers, tuples, lists, dicts, booleans,
> and N... |
How to rename a column of a pandas.core.series.TimeSeries object? | 18,553,503 | 4 | 2013-08-31T22:45:46Z | 18,553,730 | 15 | 2013-08-31T23:23:04Z | [
"python",
"pandas"
] | Substracting the `Settle` column of a `pandas.core.frame.DataFrame` from the `Settle` column of another `pandas.core.frame.DataFrame` resulted in a `pandas.core.series.TimeSeries` object (the `subs` object).
Now, when I plot `subs` and add a legend, it reads `Settle`.
How can I change the name of a column of a `panda... | I think your wording is a bit confusing, but it sounds like you want to rename a `Series` object (`TimeSeries` is an alias for `Series`). You can do this by changing the `name` attribute of your `subs` object:
Assuming its name is `'Settle'` and you want to change it to, say, `'Unsettle'`, just update the `name` attri... |
Difference between Kivy and Java for android apps | 18,553,849 | 11 | 2013-08-31T23:44:24Z | 18,558,963 | 10 | 2013-09-01T13:37:14Z | [
"java",
"android",
"python",
"kivy"
] | For a python developer that has some experience creating android apps with java.
I want to create a small app that access my university portal and retrieve some data to easy access it on android.
**1)** Which one its easier and faster to develop android apps?
**2)** Does Kivy has limitations to access certain parts o... | This is a rather subjective question.
> 1) Which one its easier and faster to develop android apps?
I think there's a strong argument for kivy, but this doesn't have an objective answer.
> 2) Does Kivy has limitations to access certain parts of android (like not fully integrated with its api)?
The kivy project incl... |
Difference between Kivy and Java for android apps | 18,553,849 | 11 | 2013-08-31T23:44:24Z | 18,563,503 | 8 | 2013-09-01T22:17:58Z | [
"java",
"android",
"python",
"kivy"
] | For a python developer that has some experience creating android apps with java.
I want to create a small app that access my university portal and retrieve some data to easy access it on android.
**1)** Which one its easier and faster to develop android apps?
**2)** Does Kivy has limitations to access certain parts o... | To complete inclement's answer, pyjnius indeed allows to access a lot of the android api. But it's not perfect, calling existing classes is not always enough, and an android programmer often need to create code that will be called by android to manage events, there are two ways to do that, both used by the android api.... |
Differentiating a product with an unknown function - sympy | 18,553,896 | 3 | 2013-08-31T23:52:54Z | 18,554,088 | 7 | 2013-09-01T00:26:47Z | [
"python",
"numpy",
"sympy"
] | I tried various searches but couldn't find a good google string to bring up the right results.
I have a product of the form
```
y = x*f(x)
```
where f is a function of x which is not known. I want sympy to differentiate y with respect to x. Does anyone know how I can do this? | How about:
```
>>> x = sympy.Symbol("x")
>>> f = sympy.Function("f")
>>> y = x * f(x)
>>> y
x*f(x)
>>> y.diff(x)
x*Derivative(f(x), x) + f(x)
``` |
Intersecting two dictionaries in Python | 18,554,012 | 28 | 2013-09-01T00:13:52Z | 18,554,039 | 27 | 2013-09-01T00:18:58Z | [
"python",
"dictionary",
"iteration",
"intersection"
] | I am working on a search program over an inverted index. The index itself is a dictionary whose keys are terms and whose values are themselves dictionaries of short documents, with ID numbers as keys and their text content as values.
To perform an 'AND' search for two terms, I thus need to intersect their postings lis... | You can easily calculate the intersection of sets, so create sets from the keys and use them for the intersection:
```
keys_a = set(dict_a.keys())
keys_b = set(dict_b.keys())
intersection = keys_a & keys_b # '&' operator is used for set intersection
``` |
Intersecting two dictionaries in Python | 18,554,012 | 28 | 2013-09-01T00:13:52Z | 18,554,081 | 57 | 2013-09-01T00:25:56Z | [
"python",
"dictionary",
"iteration",
"intersection"
] | I am working on a search program over an inverted index. The index itself is a dictionary whose keys are terms and whose values are themselves dictionaries of short documents, with ID numbers as keys and their text content as values.
To perform an 'AND' search for two terms, I thus need to intersect their postings lis... | A little known fact is that you don't need to construct `set`s to do this:
In Python 2:
```
In [78]: d1 = {'a': 1, 'b': 2}
In [79]: d2 = {'b': 2, 'c': 3}
In [80]: d1.viewkeys() & d2.viewkeys()
Out[80]: {'b'}
```
In Python 3 replace `viewkeys` with `keys`; the same applies to `viewvalues` and `viewitems`.
From the... |
Intersecting two dictionaries in Python | 18,554,012 | 28 | 2013-09-01T00:13:52Z | 18,555,143 | 32 | 2013-09-01T04:11:23Z | [
"python",
"dictionary",
"iteration",
"intersection"
] | I am working on a search program over an inverted index. The index itself is a dictionary whose keys are terms and whose values are themselves dictionaries of short documents, with ID numbers as keys and their text content as values.
To perform an 'AND' search for two terms, I thus need to intersect their postings lis... | ```
In [1]: d1 = {'a':1, 'b':4, 'f':3}
In [2]: d2 = {'a':1, 'b':4, 'd':2}
In [3]: d = {x:d1[x] for x in d1 if x in d2}
In [4]: d
Out[4]: {'a': 1, 'b': 4}
``` |
What is the purpose of `__metaclass__ = type`? | 18,554,525 | 4 | 2013-09-01T02:01:56Z | 18,554,674 | 8 | 2013-09-01T02:32:19Z | [
"python",
"packages",
"python-2.x",
"metaclass"
] | Python (2 only?) looks at the value of variable `__metaclass__` to determine how to create a `type` object from a class definition. [It is possible to define `__metaclass__` at the module or package level](http://stackoverflow.com/questions/7023932/python-metaclasses-at-module-level), in which case it applies to all su... | In Python 2, a declaration `__metaclass__ = type` makes declarations that would otherwise create old-style classes create new-style classes instead. Only old-style classes use a module level `__metaclass__` declaration. New-style classes inherit their metaclass from their base class (e.g. `object`), unless `__metaclass... |
Pandas aggregate count distinct | 18,554,920 | 29 | 2013-09-01T03:25:36Z | 18,554,949 | 52 | 2013-09-01T03:31:03Z | [
"python",
"pandas"
] | Let's say I have a log of user activity and I want to generate a report of total duration and the number of unique users per day.
```
import numpy as np
import pandas as pd
df = pd.DataFrame({'date': ['2013-04-01','2013-04-01','2013-04-01','2013-04-02', '2013-04-02'],
'user_id': ['0001', '0001', '0002', '0002', '0... | How about either of:
```
>>> df
date duration user_id
0 2013-04-01 30 0001
1 2013-04-01 15 0001
2 2013-04-01 20 0002
3 2013-04-02 15 0002
4 2013-04-02 30 0002
>>> df.groupby("date").agg({"duration": np.sum, "user_id": pd.Series.nunique})
dura... |
Python modules with submodules and functions | 18,555,193 | 4 | 2013-09-01T04:20:13Z | 18,555,203 | 7 | 2013-09-01T04:22:28Z | [
"python",
"function",
"module"
] | I had a question on how libraries like numpy work. When I import numpy, I'm given access to a host of built in classes, functions, and constants such as numpy.array, numpy.sqrt etc.
But within numpy there are additional submodules such as numpy.testing.
How is this done? In my limited experience, modules with submodu... | A folder with `.py` files and a `__init__.py` is called a `package`. One of those files containing classes and functions is a `module`. Folder nesting can give you subpackages.
So for example if I had the following structure:
```
mypackage
__init__.py
module_a.py
module_b.py
mysubpackage
... |
how to break out of only one nested loop | 18,556,403 | 7 | 2013-09-01T07:55:11Z | 18,556,425 | 12 | 2013-09-01T07:57:53Z | [
"python",
"loops",
"nested",
"break"
] | I have two tab-delimited files, and I need to test every row in the first file against all the rows in the other file. For instance,
file1:
```
row1 c1 36 345 A
row2 c3 36 9949 B
row3 c4 36 858 C
```
file2:
```
row1 c1 3455 3800
row2 c3 6784 7843
row3 c3 10564 993... | `break` and `continue` apply to the innermost loop.
The issue is that you open the second file only once, and therefore it's only read once. When you execute `for y in file2.readlines():` for the second time, `file2.readlines()` returns an empty iterable.
Either move `file2 = open(filename2, 'r')` into the outer loop... |
locating, entering a value in a text box using selenium and python | 18,557,275 | 10 | 2013-09-01T09:59:01Z | 18,558,014 | 21 | 2013-09-01T11:33:23Z | [
"python",
"python-2.7",
"selenium-webdriver"
] | ```
<div class="MY_HEADING_A">
<div class="TitleA">My title</div>
<div class="Foobar"></div>
<div class="PageFrame" area="W">
<span class="PageText">PAGE <input id="a1" type="txt" NUM="" /> of <span id="MAX"></span> </span>
</div>
```
Hi
I have the above code and I am try... | Assuming your page is available under "<http://example.com>"
```
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
driver = webdriver.Firefox()
driver.get("http://example.com")
```
Select element by id:
```
inputElement = driver.find_element_by_id("a1")
inputElement.send_keys('1')
```
... |
How to show result of python script in a console when running from ST editor? | 18,557,668 | 7 | 2013-09-01T10:51:00Z | 19,281,965 | 7 | 2013-10-09T20:27:05Z | [
"python",
"windows-7",
"sublimetext",
"sublimetext3",
"build-system"
] | I'm new to Sublime Text so am unfamiliar with its internals so far. From what I could tell the problem could be something related to [this](http://ptomato.wordpress.com/2012/02/09/geek-tip-running-python-guis-in-sublime-text-2/).
I have a python script
```
var = raw_input("Enter something: ")
print "You entered ", va... | This is actually surprisingly easy, but it took a lot of digging to connect the pieces. I first came up with a more roundabout way using a batch file, but after some more thinking put it all together into a single Sublime build system.
## The Easy Way
The following works just fine:
```
{
"cmd": ["start", "cmd", ... |
How do I get py.test to recognize conftest.py in a subdirectory? | 18,558,666 | 11 | 2013-09-01T13:00:30Z | 18,559,125 | 7 | 2013-09-01T13:56:41Z | [
"python",
"py.test"
] | So, I just lost a *day* trying to find out why `py.test` isn't executing my autouse, session-scoped setup and teardown fixtures. In the end I stumbled over (hat tip to [this SO comment](http://stackoverflow.com/a/13686206/599884)!) this little tidbit in the [plugins documentation](http://pytest.org/latest/plugins.html#... | After some help on the #pylib IRC channel, it turns out that this was a bug that has been fixed in [py.test 2.3.4](http://pytest.org/latest/changelog.html#changes-between-2-3-3-and-2-3-4). |
How can I install a .egg Python package on Windows (attempt using easy_install not working) | 18,558,733 | 10 | 2013-09-01T13:07:43Z | 18,559,411 | 7 | 2013-09-01T14:33:35Z | [
"python",
"python-2.7",
"packages",
"qstk"
] | I am trying to install a package named QSTK for a course that I am doing. The course points to an installation package for the 32 bit version, but I have 64 Python installed. I have found a .egg file listed on the [Python packages index](https://pypi.python.org/packages/2.7/Q/QSTK/).
It seems to have an exe for 32 bit... | I have finally found another place to download this from with a package that works: <https://pypi.python.org/pypi/QSTK/0.2.6> has a QSTK-0.2.6.tar.gz option to build it from the source code.
Unzipping this (then again once down to the .tar), I could find the setup.py file and install by going to the directory with the... |
Why is the size of an empty dict same as that of a non empty dict in Python? | 18,558,865 | 7 | 2013-09-01T13:24:44Z | 18,558,905 | 7 | 2013-09-01T13:30:27Z | [
"python",
"memory",
"python-2.7",
"dictionary"
] | This may be trivial, but I'm not sure I understand, I tried googling around but did not find a convincing answer.
```
>>> sys.getsizeof({})
140
>>> sys.getsizeof({'Hello':'World'})
140
>>>
>>> yet_another_dict = {}
>>> for i in xrange(5000):
yet_another_dict[i] = i**2
>>>
>>> sys.getsizeof(yet_another_dict)
... | Dictionaries in CPython allocate a small amount of key space directly in the dictionary object itself (4-8 entries depending on version and compilation options). From `dictobject.h`:
```
/* PyDict_MINSIZE is the minimum size of a dictionary. This many slots are
* allocated directly in the dict object (in the ma_smal... |
Why is the size of an empty dict same as that of a non empty dict in Python? | 18,558,865 | 7 | 2013-09-01T13:24:44Z | 18,558,907 | 9 | 2013-09-01T13:30:39Z | [
"python",
"memory",
"python-2.7",
"dictionary"
] | This may be trivial, but I'm not sure I understand, I tried googling around but did not find a convincing answer.
```
>>> sys.getsizeof({})
140
>>> sys.getsizeof({'Hello':'World'})
140
>>>
>>> yet_another_dict = {}
>>> for i in xrange(5000):
yet_another_dict[i] = i**2
>>>
>>> sys.getsizeof(yet_another_dict)
... | There are two reasons for that:
1. Dictionary only holds references to the objects, not the objects themselves, so it's size is no correlated with the size of objects it contains, but with by the number of references (items) the dictionary contains.
2. More important, dictionary preallocates memory for the references ... |
Python strings aren't equal | 18,560,318 | 2 | 2013-09-01T16:12:24Z | 18,560,366 | 9 | 2013-09-01T16:17:48Z | [
"python"
] | Sorry if the answer to this question may be obvious, but I'm very new to Python (just first started reading a small document about the differing structure and other things from C this morning). While practicing, I decided to make an ATM. However, something weird in the verification process happened, where it compares t... | You are comparing `ccn` to the password - not the `password` arg with the user's stored password...
```
if ccn == self.data[ccn]['Password']:
```
should be
```
if password == self.data[ccn]['Password']:
``` |
enforce column encoding with sqlalchemy | 18,561,190 | 4 | 2013-09-01T17:49:23Z | 18,561,417 | 7 | 2013-09-01T18:17:47Z | [
"python",
"mysql",
"encoding",
"utf-8",
"sqlalchemy"
] | I am using sqlalchemy to create the schema of my database. I have no success in enforcing the use of utf-8, no matter what I tried.
Here is a minimal python script that recreates my problem:
```
from sqlalchemy import create_engine, Column, Unicode
from sqlalchemy.ext.declarative import declarative_base
engine = crea... | To specify a specific collation per column, use the [`collation`](http://docs.sqlalchemy.org/en/latest/dialects/mysql.html#sqlalchemy.dialects.mysql.NVARCHAR) parameter on the data type:
```
class MyTableName(Base):
__tablename__ = "mytablename2"
test_column = Column(Unicode(2),
primar... |
OpenCV Python can't use SURF, SIFT | 18,561,910 | 18 | 2013-09-01T19:09:53Z | 18,590,112 | 11 | 2013-09-03T10:36:47Z | [
"python",
"opencv",
"sift",
"surf"
] | I'm trying a simple thing like
```
detector = cv2.SIFT()
```
and get this bad error
```
detector = cv2.SIFT()
AttributeError: 'module' object has no attribute 'SIFT'
```
I do not understand that because cv2 is installed.
cv2.**version** is
```
$Rev: 4557 $
```
my system is Ubuntu 12.04
maybe someone has got... | I think this is far from the "correct" way to do it (the "correct" way on Ubuntu seems to be to stick to a broken and/or outdated OpenCV), but for me building opencv-2.4.6.1 from source brings back cv2.SIFT and cv2.SURF.
Steps:
1. Download opencv-2.4.6.1.tar.gz from [opencv.org](http://opencv.org).
2. Extract the sou... |
OpenCV Python can't use SURF, SIFT | 18,561,910 | 18 | 2013-09-01T19:09:53Z | 25,626,875 | 18 | 2014-09-02T15:18:07Z | [
"python",
"opencv",
"sift",
"surf"
] | I'm trying a simple thing like
```
detector = cv2.SIFT()
```
and get this bad error
```
detector = cv2.SIFT()
AttributeError: 'module' object has no attribute 'SIFT'
```
I do not understand that because cv2 is installed.
cv2.**version** is
```
$Rev: 4557 $
```
my system is Ubuntu 12.04
maybe someone has got... | FYI, as of 3.0.0 SIFT and friends are in a contrib repo located at <https://github.com/Itseez/opencv_contrib> and are not included with opencv by default. |
OpenCV Python can't use SURF, SIFT | 18,561,910 | 18 | 2013-09-01T19:09:53Z | 32,735,795 | 8 | 2015-09-23T09:28:32Z | [
"python",
"opencv",
"sift",
"surf"
] | I'm trying a simple thing like
```
detector = cv2.SIFT()
```
and get this bad error
```
detector = cv2.SIFT()
AttributeError: 'module' object has no attribute 'SIFT'
```
I do not understand that because cv2 is installed.
cv2.**version** is
```
$Rev: 4557 $
```
my system is Ubuntu 12.04
maybe someone has got... | For recent information on this issue (as of Sept 2015) consult [this page](http://www.pyimagesearch.com/2015/07/16/where-did-sift-and-surf-go-in-opencv-3/).
Most information on this question here is obsolete.
What pyimagesearch is saying is that SURF/SIFT were moved to `opencv_contrib` because of patent issues.
For ... |
Interaction between networkx and matplotlib | 18,563,766 | 5 | 2013-09-01T23:01:07Z | 18,563,973 | 11 | 2013-09-01T23:38:07Z | [
"python",
"graph",
"matplotlib",
"networkx"
] | I am trying networkx and visualization in matplotlib an I'm confused becouse I do not clearly understand how do they interact with each other?
There simple example
```
import matplotlib.pyplot
import networkx as nx
G=nx.path_graph(8)
nx.draw(G)
matplotlib.pyplot.show()
```
Where do I tell pyplot, that I want to draw ... | Just create two different axes if you want to draw the graphs separately or create a single `Axes` object an pass it to `nx.draw`. For example:
```
G = nx.path_graph(8)
E = nx.path_graph(30)
# one plot, both graphs
fig, ax = subplots()
nx.draw(G, ax=ax)
nx.draw(E, ax=ax)
```
to get:
, 5))
```
You can add **1** if you want to include the last number.
**Explanation**:
* `iter(function, val)` returns an iterator that calls `function` until
`val` is returned.
* `lambda: randint(0, 9)` is function (can be ... |
Counting random numbers | 18,564,443 | 3 | 2013-09-02T01:05:12Z | 18,564,457 | 9 | 2013-09-02T01:06:34Z | [
"python"
] | Suppose I repeatedly generate random integers from 0-9 until a given number comes out. What I need is a function that counts how many integers are generated until this happens. Please help me with this.
This is what I have tried, I put 1000 becasue it is big enough but I don't think it is correct because my number can... | A few things:
* If you want your loop to continue until you stop it, use a `while` loop instead of a `for` loop.
* You should use `!=` as the inequality operator instead of `<>`.
Here's something to get you started:
```
import random
count = 0
while True:
n = random.randint(0, 9)
count += 1
if n == 5:... |
can't pip install mysql-python | 18,564,745 | 13 | 2013-09-02T01:59:19Z | 18,564,899 | 39 | 2013-09-02T02:26:53Z | [
"python",
"django",
"pip"
] | I'm trying to get django/pip/mysql working and i can't seem to figure out how to install mysql-python. this is the error i receive when trying to install mysql-python
```
pip install mysql-python
Downloading/unpacking mysql-python
Downloading MySQL-python-1.2.4.zip (113kB): 113kB downloaded
Running setup.py egg_i... | try downloading python-dev through software manager:
```
sudo apt-get install python-dev
``` |
Why this string matches the regular expression? | 18,565,413 | 2 | 2013-09-02T03:47:38Z | 18,565,435 | 9 | 2013-09-02T03:51:30Z | [
"python",
"regex"
] | Why this string matches the pattern ?
```
pattern = """
^Page \d of \d$|
^Group \d Notes$|
^More word lists and tips at http://wwwmajortests.com/word-lists$|
"""
re.match(pattern, "stackoverflow", re.VERBOSE)
```
According to me it should match strings like "Page 1 of 1" or "Group 1 Notes". | In your regular expression, there's trailing `|`:
```
# ^More word lists and tips at http://wwwmajortests.com/word-lists$|
# ^
```
Empty pattern matches any string:
```
>>> import re
>>> re.match('abc|', 'abc')
<_sre.SRE_Match object at 0x7fc63f3ff3d8>... |
python list comprehension: gathering duplicate columns | 18,566,317 | 3 | 2013-09-02T05:40:56Z | 18,566,448 | 8 | 2013-09-02T05:52:51Z | [
"python"
] | I have a sorted list of lists that contain duplicate first elements.
Currently I'm iterating over it to get the solution.
```
[['5th ave', 111, -30.00, 38.00],
['5th ave', 222, -30.00, 33.00],
['6th ave', 2224, -32.00, 34.90]]
```
I'd like an elegant list comprehension to convert this to a list of lists based on the ... | Looks like a job for [`collections.defaultdict`](http://docs.python.org/2/library/collections.html#defaultdict-objects):
```
>>> from collections import defaultdict
>>> L = [['5th ave', 111, -30.00, 38.00],
... ['5th ave', 222, -30.00, 33.00],
... ['6th ave', 2224, -32.00, 34.90]]
>>> d = defaultdict(list)
>>> for sub... |
Simple way to convert list to dict | 18,568,705 | 4 | 2013-09-02T08:28:46Z | 18,568,754 | 13 | 2013-09-02T08:31:41Z | [
"python"
] | Please, tell me the simplest way to convert list object to dictionary.
All parameters are looks like this:
```
['a=1', 'b=2', ...]
```
And I want to convert it into:
```
{'a': '1', 'b': '2' ...}
``` | You could use:
```
>>> x
['a=1', 'b=2']
>>>
>>> dict( i.split('=') for i in x )
{'a': '1', 'b': '2'}
>>>
``` |
How to access request in Flask MIddleware | 18,573,712 | 5 | 2013-09-02T12:48:07Z | 18,574,670 | 8 | 2013-09-02T13:38:55Z | [
"python",
"flask",
"wsgi"
] | I want to access request.url in middleware.
Flask app - test.py
```
from flask import Flask
from middleware import TestMiddleware
app = Flask(__name__)
app.wsgi_app = TestMiddleware(app.wsgi_app)
@app.route('/')
def hello_world():
return 'Hello World!'
if __name__ == '__main__':
app.run()
```
middleware.p... | It's the application object that constructs the request object: it doesn't exist until the app is called, so there's no way for middleware to look at it beforehand. You can, however, construct your own request object within the middleware (using Werkzeug directly rather than Flask):
```
from werkzeug.wrappers import R... |
How do convert a pandas/dataframe to XML? | 18,574,108 | 4 | 2013-09-02T13:09:44Z | 18,576,067 | 7 | 2013-09-02T14:56:51Z | [
"python",
"xml",
"pandas"
] | is there a simple way to take a pandas/df table:
```
field_1 field_2 field_3 field_4
cat 15,263 2.52 00:03:00
dog 1,652 3.71 00:03:47
test 312 3.27 00:03:41
book 300 3.46 00:02:40
```
And convert it to XML along the lines of:
```
<item>
<field name="field_1">cat</field>
<fiel... | You can create a function that creates the `item` node from a row in your DataFrame:
```
def func(row):
xml = ['<item>']
for field in row.index:
xml.append(' <field name="{0}">{1}</field>'.format(field, row[field]))
xml.append('</item>')
return '\n'.join(xml)
```
And then apply the function a... |
How do convert a pandas/dataframe to XML? | 18,574,108 | 4 | 2013-09-02T13:09:44Z | 18,579,083 | 9 | 2013-09-02T18:36:36Z | [
"python",
"xml",
"pandas"
] | is there a simple way to take a pandas/df table:
```
field_1 field_2 field_3 field_4
cat 15,263 2.52 00:03:00
dog 1,652 3.71 00:03:47
test 312 3.27 00:03:41
book 300 3.46 00:02:40
```
And convert it to XML along the lines of:
```
<item>
<field name="field_1">cat</field>
<fiel... | To expand on Viktor's excellent answer (and tweaking it slightly to work with duplicate columns), you could set this up as a `to_xml` DataFrame method:
```
def to_xml(df, filename=None, mode='w'):
def row_to_xml(row):
xml = ['<item>']
for i, col_name in enumerate(row.index):
xml.append(... |
Python: AttributeError: _dep_map | 18,577,975 | 2 | 2013-09-02T17:08:27Z | 18,578,329 | 9 | 2013-09-02T17:33:56Z | [
"python",
"pyramid"
] | I have an issue.
I'm installing pyramid application on Ubuntu / Python 2.7 on virtual environment.
I'm running setup.py as
```
../bin/python2.7 setup.py develop
```
from root project directory and after:
```
Traceback (most recent call last):
File "setup.py", line 48, in <module>
""",
File "/usr/lib/python2.... | Without knowing your exact setup.py or your code layout: Do have by any chance a module called [*parser*](https://bitbucket.org/pypa/setuptools/issue/48/attributeerror-_dep_map) in your path? That's your problem. |
Check nested dictionary values in python | 18,578,190 | 4 | 2013-09-02T17:23:22Z | 18,578,210 | 20 | 2013-09-02T17:25:10Z | [
"python",
"dictionary",
"nested"
] | For a large list of nested dictionaries, I want to check if they contain or not a key.
Each of them may or may not have one of the nested dictionaries, so if I loop this search through all of them raises an error:
```
for Dict1 in DictionariesList:
if "Dict4" in Dict1['Dict2']['Dict3']:
print "Yes"
```
... | Use `.get()` with empty dictionaries as defaults:
```
if 'Dict4' in Dict1.get('Dict2', {}).get('Dict3', {}):
print "Yes"
```
If the `Dict2` key is not present, an empty dictionary is returned, so the next chained `.get()` will also not find `Dict3` and return an empty dictionary in turn. The `in` test then return... |
Django Unittests Client Login: fails in test suite, but not in Shell | 18,578,265 | 3 | 2013-09-02T17:29:46Z | 18,578,373 | 21 | 2013-09-02T17:38:01Z | [
"python",
"django",
"unit-testing"
] | I'm running a basic test of my home view. While logging the client in from the shell works, the same line of code fails to log the client in when using the test suite.
*What is the correct way to log the client in when using the Django test suite?*
Or
*Any idea why the client is not logging in with my current method... | A test user should be created. Something like:
```
def setUp(self):
self.client = Client()
self.username = 'agconti'
self.email = '[email protected]'
self.password = 'test'
self.test_user = User.objects.create_user(self.username, self.email, self.password)
login = self.client.login(userna... |
using requests with TLS doesn't give SNI support | 18,578,439 | 34 | 2013-09-02T17:43:28Z | 18,579,484 | 78 | 2013-09-02T19:12:07Z | [
"python",
"ssl",
"ssl-certificate",
"python-requests",
"sni"
] | I'm using requests to communicate with a django app but
When I try
```
requests.get('https://mysite.com', verify=True)
```
I get the error:
> hostname 'mysite.com' doesn't match either of '\*.myhost.com', 'myhost.com'
However, when I look at the browser, or <http://www.digicert.com/help/> the certificate looks fin... | The current version of Requests should be just fine with SNI. [Further down the GitHub issue](https://github.com/kennethreitz/requests/issues/749#issuecomment-19187417) you can see the requirements:
* [pyOpenSSL](https://launchpad.net/pyopenssl)
* [ndg-httpsclient](https://pypi.python.org/pypi/ndg-httpsclient)
* [pyas... |
using requests with TLS doesn't give SNI support | 18,578,439 | 34 | 2013-09-02T17:43:28Z | 26,392,858 | 12 | 2014-10-15T22:00:49Z | [
"python",
"ssl",
"ssl-certificate",
"python-requests",
"sni"
] | I'm using requests to communicate with a django app but
When I try
```
requests.get('https://mysite.com', verify=True)
```
I get the error:
> hostname 'mysite.com' doesn't match either of '\*.myhost.com', 'myhost.com'
However, when I look at the browser, or <http://www.digicert.com/help/> the certificate looks fin... | In order for me to get the accepted answer to work, I had to install a bunch of other packages, in this order:
* yum install libffi-devel
* yum install gcc
* yum install openssl-devel
* pip install urllib3
* pip install pyopenssl
* pip install ndg-httpsclient
* pip install pyasn1 |
Sqlalchemy, relation vs relationship | 18,578,549 | 5 | 2013-09-02T17:53:37Z | 18,578,577 | 8 | 2013-09-02T17:56:22Z | [
"python",
"sqlalchemy"
] | In some sqlalchemy tutorials, `relation` function used to define sql-relationships. like this:
```
class Movie(DeclarativeBase):
__tablename__ = "movies"
movie_id = Column(Integer, primary_key=True)
title = Column(String(100), nullable=False)
description = Column(Text, nullable=True)
genre_id = Co... | According to [docs](http://docs.sqlalchemy.org/en/latest/orm/relationships.html#sqlalchemy.orm.relation), they are synonyms:
> `sqlalchemy.orm.relation(*arg, **kw)`
>
> A synonym for relationship().
And, actually:
> Changed in version 0.6: relationship() was renamed from its previous
> name relation().
So, better u... |
How to execute/call on a .py file in command prompt? | 18,579,650 | 3 | 2013-09-02T19:26:13Z | 18,579,850 | 10 | 2013-09-02T19:44:21Z | [
"python",
"eclipse",
"python-3.x",
"pydev"
] | I have written a .py file using Eclipse. I want to run that file in command prompt. How do I go about that? I'm running it on Windows.
I tried
python D:\Python Work/class/src/hello.py
The error I received was python: can't open file 'D:\Python':[Errno 2] No such file or directory. Also 'D:\Python' is not the entire ad... | Assuming you are running on windows - either:
```
python "D:\\Folder name\\Project name\\src\\module name.py"
```
Or:
```
python "D:/Folder name/Project name/src/module name.py"
```
Your choice basically.
The rules for windows file names are:
Back slashes, `\` must be escaped by doubling to `\\` spaces **must** b... |
Supervising celerybeat with supervisor and virtualenv | 18,580,423 | 10 | 2013-09-02T20:34:40Z | 20,206,070 | 11 | 2013-11-26T00:05:52Z | [
"python",
"celery",
"supervisord",
"celerybeat"
] | My celerybeat.conf
```
[program:celerybeat]
command=/path/app/env/bin/celery beat -A project.tasks --loglevel=INFO
environment=PYTHONPATH=/path/app/env/bin
user=nobody
numprocs=1
stdout_logfile=/var/log/celeryd.log
stderr_logfile=/var/log/celeryd.log
autostart=true
autorestart=true
startsecs=10
stopwaitsecs = 600
kil... | The problem is that you have not specified any directory in the config file and the default directory then is '/' (root) which your user does not have permissions to write.
Setting the user as root solved your problem because now you had permission to write to '/' however it might not be the best solution. There are m... |
Eliminating all data over a given percentile | 18,580,461 | 9 | 2013-09-02T20:37:48Z | 18,580,496 | 17 | 2013-09-02T20:40:45Z | [
"python",
"pandas",
"filtering",
"percentile"
] | I have a pandas `DataFrame` called `data` with a column called `ms`. I want to eliminate all the rows where `data.ms` is above the 95% percentile. For now, I'm doing this:
```
limit = data.ms.describe(90)['95%']
valid_data = data[data['ms'] < limit]
```
which works, but I want to generalize that to any percentile. Wh... | Use the `Series.quantile()` method:
```
In [48]: cols = list('abc')
In [49]: df = DataFrame(randn(10, len(cols)), columns=cols)
In [50]: df.a.quantile(0.95)
Out[50]: 1.5776961953820687
```
To filter out rows of `df` where `df.a` is greater than or equal to the 95th percentile do:
```
In [72]: df[df.a < df.a.quanti... |
Trigger an event in Python traits package when an Array element is changed | 18,581,404 | 3 | 2013-09-02T22:09:19Z | 18,587,527 | 7 | 2013-09-03T08:31:12Z | [
"python",
"arrays",
"numpy",
"traits",
"traitsui"
] | I'm using Python's traits package, and I'm trying to figure out the right way to use the traits.trait\_numeric.Array class. It's straightforward to write a subclass of traits.api.HasTraits with an Array trait, so that when the Array changes, an on\_trait\_change is triggered, but I can't figure out how to trigger any s... | I'm afraid that it's not really possible. numpy arrays view raw memory. Anything can change that memory without going through the numpy array object itself. The pattern we usually use is to reassign the whole array after doing the slice/index assignment.
```
import numpy as np
from traits.api import Array, HasTraits, ... |
How to return all the minimum indices in numpy | 18,582,178 | 11 | 2013-09-02T23:50:24Z | 18,582,224 | 11 | 2013-09-02T23:56:55Z | [
"python",
"numpy"
] | I am a little bit confuses reading the documentation of [argmin function in numpy](http://docs.scipy.org/doc/numpy/reference/generated/numpy.argmin.html).
It looks like it should do the job:
Reading this
> Return the indices of the minimum values along an axis.
I might assume that
```
np.argmin([5, 3, 2, 1, 1, 1, 6... | See the documentation for [`numpy.argmax`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.argmax.html#numpy.argmax) (which is referred to by the docs for `numpy.argmin`):
> In case of multiple occurrences of the maximum values, the indices corresponding to the first occurrence are returned.
The phrasing of... |
How to return all the minimum indices in numpy | 18,582,178 | 11 | 2013-09-02T23:50:24Z | 18,582,228 | 18 | 2013-09-02T23:57:06Z | [
"python",
"numpy"
] | I am a little bit confuses reading the documentation of [argmin function in numpy](http://docs.scipy.org/doc/numpy/reference/generated/numpy.argmin.html).
It looks like it should do the job:
Reading this
> Return the indices of the minimum values along an axis.
I might assume that
```
np.argmin([5, 3, 2, 1, 1, 1, 6... | That documentation makes more sense when you think about multidimensional arrays.
```
>>> x = numpy.array([[0, 1],
... [3, 2]])
>>> x.argmin(axis=0)
array([0, 0])
>>> x.argmin(axis=1)
array([0, 1])
```
It returns the first index of each minimum value, not all indices of a single minimum value.
To ge... |
Difference between if <obj> and if <obj> is not None | 18,583,162 | 7 | 2013-09-03T02:23:30Z | 18,583,185 | 8 | 2013-09-03T02:26:16Z | [
"python",
"python-2.7",
"xml-parsing"
] | In writing some XML parsing code, I received the warning:
```
FutureWarning: The behavior of this method will change in future versions. Use specific 'len(elem)' or 'elem is not None' test instead.
```
where I used `if <elem>:` to check if a value was found for a given element.
Can someone elaborate on the differen... | `if obj is not None` test whether the object is not None. `if obj` tests whether `bool(obj)` is True.
There are many objects which are not None but for which `bool(obj)` is False: for instance, an empty list, an empty dict, an empty set, an empty string. . .
Use `if obj is not None` when you want to test if an object... |
Calculate angle of triangle Python | 18,583,214 | 3 | 2013-09-03T02:30:59Z | 18,583,456 | 7 | 2013-09-03T03:02:29Z | [
"python",
"math",
"geometry",
"angle"
] | I'm trying to find out the angle of the triangle in the following, I know it should be 90 degrees, however I don't know how to actually calculate it in the following:

Here's what I've tried:
```
angle = math.cos(7/9.899)
angleToDegrees = math.degree... | It's a little more compicated than that. You need to use the [law of cosines](http://en.wikipedia.org/wiki/Law_of_cosines)
```
>>> A = 7
>>> B = 7
>>> C = 9.899
>>> from math import acos, degrees
>>> degrees(acos((A * A + B * B - C * C)/(2.0 * B * C)))
89.99594878743945
```
This is accurate to 4 significant figures. ... |
XMLHttpRequest multipart/form-data: Invalid boundary in multipart | 18,590,630 | 5 | 2013-09-03T11:02:08Z | 18,590,706 | 7 | 2013-09-03T11:06:24Z | [
"javascript",
"python",
"xmlhttprequest"
] | I am sending post data via XMLHttpRequest:
```
var xmlHttp=new XMLHttpRequest();
xmlHttp.open("POST", domain, true);
xmlHttp.setRequestHeader("Content-type","multipart/form-data");
var formData = new FormData();
formData.append("data", data_json_string);
xmlHttp.send(formData);
```
In Python, I get an error if I tr... | Do not set the `Content-Type` header yourself. It will be properly set when `.send()`ing the data, including the proper generated boundary, which your manually generated header lacks.
The [spec](http://www.w3.org/TR/XMLHttpRequest2/#the-send-method) clearly states that `.send(FormData)` will use multipart/form-data en... |
How to pass an operator to a python function? | 18,591,778 | 10 | 2013-09-03T11:58:24Z | 18,591,860 | 19 | 2013-09-03T12:01:39Z | [
"python",
"function",
"python-2.7"
] | I'd like to pass a math operator, along with the numeric values to compare, to a function. Here is my broken code:
```
def get_truth(inp,relate,cut):
if inp print(relate) cut:
return True
else:
return False
```
and call it with
```
get_truth(1.0,'>',0.0)
```
which should return True.
(Y... | Have a look at the [operator module](http://docs.python.org/2/library/operator.html):
```
import operator
get_truth(1.0, operator.gt, 0.0)
...
def get_truth(inp, relate, cut):
return relate(inp, cut)
# you don't actually need an if statement here
``` |
How to pass an operator to a python function? | 18,591,778 | 10 | 2013-09-03T11:58:24Z | 18,591,880 | 13 | 2013-09-03T12:02:37Z | [
"python",
"function",
"python-2.7"
] | I'd like to pass a math operator, along with the numeric values to compare, to a function. Here is my broken code:
```
def get_truth(inp,relate,cut):
if inp print(relate) cut:
return True
else:
return False
```
and call it with
```
get_truth(1.0,'>',0.0)
```
which should return True.
(Y... | Make a mapping of strings and [operator](http://docs.python.org/2/library/operator.html) functions. Also, you don't need if/else condition:
```
import operator
def get_truth(inp, relate, cut):
ops = {'>': operator.gt,
'<': operator.lt,
'>=': operator.ge,
'<=': operator.le,
... |
Sum of all counts in a collections.Counter | 18,593,519 | 12 | 2013-09-03T13:24:29Z | 18,593,563 | 23 | 2013-09-03T13:25:59Z | [
"python",
"python-3.x",
"counter"
] | What is the best way of establishing the sum of all counts in a collections.Counter object?
I've tried:
`sum(Counter([1,2,3,4,5,1,2,1,6]))`
but this gives 21 instead of 9? | The code you have adds up the keys (i.e. the unique values in the list: `1+2+3+4+5+6=21`).
To add up the counts, use:
```
In [4]: sum(Counter([1,2,3,4,5,1,2,1,6]).values())
Out[4]: 9
```
This idiom is mentioned in the [documentation](http://docs.python.org/2/library/collections.html#collections.Counter), under "Comm... |
How do I strftime a date object in a different locale? | 18,593,661 | 15 | 2013-09-03T13:31:06Z | 24,070,673 | 13 | 2014-06-05T21:41:50Z | [
"python",
"locale",
"strftime",
"setlocale"
] | I have a date object in python and I need to generate a time stamp in the C locale for a legacy system, using the %a (weekday) and %b (month) codes. However I do not wish to change the application's locale, since other parts need to respect the user's current locale. Is there a way to call strftime() with a certain loc... | The example given by Rob is great, but isn't threadsafe. Here's a version that works with threads:
```
import locale
import threading
from datetime import datetime
from contextlib import contextmanager
LOCALE_LOCK = threading.Lock()
@contextmanager
def setlocale(name):
with LOCALE_LOCK:
saved = locale.... |
Normalizing a pandas DataFrame by row | 18,594,469 | 22 | 2013-09-03T14:09:24Z | 18,594,595 | 39 | 2013-09-03T14:15:46Z | [
"python",
"pandas",
"normalization",
"dataframe"
] | What is the most idiomatic way to normalize each row of a pandas DataFrame? Normalizing the columns is easy, so one (very ugly!) option is
`(df.T / df.T.sum()).T`
Pandas broadcasting rules prevent `df / df.sum(axis=1)` from doing this | To overcome the broadcasting issue, you can use the `div` method:
```
df.div(df.sum(axis=1), axis=0)
```
See <http://pandas.pydata.org/pandas-docs/stable/basics.html#matching-broadcasting-behavior> |
<Python, openCV> How I can use cv2.ellipse? | 18,595,099 | 5 | 2013-09-03T14:39:59Z | 27,202,073 | 7 | 2014-11-29T12:11:40Z | [
"python",
"opencv"
] | OpenCV2 for python have 2 function
---
### [Function 1]
* Python: cv2.ellipse(img, center, axes, angle, startAngle, endAngle, color[, thickness[, lineType[, shift]]]) â None
### [Function 2]
* Python: cv2.ellipse(img, box, color[, thickness[, lineType]]) â None
---
I want to use [Function 1]
But when I use ... | The fact that Python [doesn't support multiple dispatch](http://stackoverflow.com/a/5079643/777285) by default doesn't help here: having two functions with the same name but different parameters is not pythonic. So the question is:Â how does `cv2` guess the version we'd like to call ? I couldn't find any explicit doc o... |
how does operator.itemgetter and sort() work in Python? | 18,595,686 | 13 | 2013-09-03T15:08:55Z | 18,596,183 | 32 | 2013-09-03T15:35:42Z | [
"python",
"sorting",
"operator-keyword"
] | I have the following code:
```
# initialize
a = []
# create the table (name, age, job)
a.append(["Nick", 30, "Doctor"])
a.append(["John", 8, "Student"])
a.append(["Paul", 22, "Car Dealer"])
a.append(["Mark", 66, "Retired"])
# sort the table by age
import operator
a.sort(key=operator.itemgetter(1))
# print the t... | Looks like you're a little bit confused about all that stuff.
`operator` is a built-in module providing a set of convenient operators. In two words `operator.itemgetter(n)` constructs a callable that assumes iterable object (list, tuple, set) as input an fetches n-th element out of it.
So, you can't use `key=a[x][1]`... |
how does operator.itemgetter and sort() work in Python? | 18,595,686 | 13 | 2013-09-03T15:08:55Z | 29,629,451 | 7 | 2015-04-14T14:03:19Z | [
"python",
"sorting",
"operator-keyword"
] | I have the following code:
```
# initialize
a = []
# create the table (name, age, job)
a.append(["Nick", 30, "Doctor"])
a.append(["John", 8, "Student"])
a.append(["Paul", 22, "Car Dealer"])
a.append(["Mark", 66, "Retired"])
# sort the table by age
import operator
a.sort(key=operator.itemgetter(1))
# print the t... | ## Answer for Python beginners
In simpler words:
1. The `key=` parameter of `sort` requires a key *function* (to be applied to be objects to be sorted) rather than a single key *value* and
2. that is just what `operator.itemgetter(1)` will give you: A *function* that grabs the first item from a list-like object.
(Mo... |
Python: Create a "Table Of Contents" with python-docx/lxml | 18,595,864 | 3 | 2013-09-03T15:17:54Z | 18,603,050 | 7 | 2013-09-03T23:27:38Z | [
"python",
"docx",
"wordml",
"python-docx"
] | I'm trying to automate the creation of .docx files (WordML) with the help of python-docx (<https://github.com/mikemaccana/python-docx>). My current script creates the ToC manually with following loop:
```
for chapter in myChapters:
body.append(paragraph(chapter.text, style='ListNumber'))
```
Does anyone know of a... | The key challenge is that a rendered ToC depends on pagination to know what page number to put for each heading. Pagination is a function provided by the layout engine, a very complex piece of software built into the Word client. Writing a page layout engine in Python is probably not a good idea, definitely not a proje... |
ImportError: No module named mpl_toolkits with maptlotlib 1.3.0 and py2exe | 18,596,410 | 6 | 2013-09-03T15:46:38Z | 19,848,039 | 10 | 2013-11-07T22:30:27Z | [
"python",
"matplotlib",
"py2exe",
"python-import"
] | I can't figure out how to be able to package this via py2exe now:
I am running the command:
```
python setup2.py py2exe
```
via python 2.7.5 and matplotlib 1.3.0 and py2exe 0.6.9 and 0.6.10dev
This worked with matplotlib 1.2.x
I have read <http://www.py2exe.org/index.cgi/ExeWithEggs> and tried to implement the sug... | There is a quite simple workaround to this problem. Find the directory from which mpl\_tools is imported and simply add an empty text file named `__init__.py` in that directory. py2exe will now find and include this module without any special imports needed in the setup file.
You can find the mpl\_tools directory by t... |
clicking on a link via selenium in python | 18,597,735 | 9 | 2013-09-03T17:03:18Z | 18,597,860 | 14 | 2013-09-03T17:10:55Z | [
"python",
"python-2.7",
"python-3.x",
"selenium-webdriver",
"web-scraping"
] | I am trying to do some webscraping via Selenium. My question is very simple: How do you find a link and then how do you click on it? For instance: The following is the HTML that I am trying to web-scrape:
```
<td bgcolor="#E7EFF9">
<a href="javascript:selectDodasaDetdasdasy(220011643,'Kdasdası');" target="_self">
... | You can use [`find_element_by_link_text`](https://selenium-python.readthedocs.org/en/latest/locating-elements.html#locating-elements):
For example:
```
link = driver.find_element_by_link_text('Details')
```
To Click on it, just call click method:
```
link.click()
``` |
Emacs Org Mode: Executing simple python code | 18,598,870 | 6 | 2013-09-03T18:12:49Z | 18,599,134 | 9 | 2013-09-03T18:29:59Z | [
"python",
"emacs",
"org-mode"
] | How can I execute very simple Python-Code in Emacs' Org Mode?
The first example works fine, however I can't make it give me the result of simplest computations:
```
; works
#+begin_src python
def foo(x):
if x>0:
return x+10
else:
return x-1
return foo(50)
#+end_src
#+RESULTS:
: 60
; does not work
#+be... | There are [two ways](http://orgmode.org/manual/Results-of-evaluation.html) of getting
the result of a source block - `output` and `value`. You mixed them up, hence the troubles.
First block is fine.
To fix the second block:
```
#+begin_src python :results value
return 1+1
#+end_src
```
To fix the third block:
```
... |
When running Python's pdb as a script, how do I autostart the script? | 18,599,029 | 8 | 2013-09-03T18:23:30Z | 19,383,826 | 8 | 2013-10-15T14:29:33Z | [
"python",
"pdb"
] | If I want to run a script and have `pdb` catch any exceptions come up, I invoke it like so:
```
python -m pdb script.py
```
Or:
```
pdb script.py
```
The problem is that it stops at the debugging prompt right away:
```
> /home/coiax/Junkyard/script.py(1)<module>()
-> import sys
(Pdb)
```
And I have to type `c` or... | What you want can trivially be achieved using `ipython`:
```
ipython yourmodule.py --pdb
```
Whenever an exception is raised which is not caught properly (i.e. the program crashes), you instantly land in ipython's debugger at the point where the exception was raised. From there on you can move the stack up and down, ... |
python watchdog monitoring file for changes | 18,599,339 | 18 | 2013-09-03T18:42:27Z | 18,599,427 | 40 | 2013-09-03T18:48:40Z | [
"python",
"file",
"monitoring",
"watchdog"
] | Folks, I have a need to watch a log file for changes. After looking through stackoverflow questions, I see people recommending 'watchdog'. So i'm trying to test, and am not sure where to add the code for when files change:
```
#!/usr/bin/python
import time
from watchdog.observers import Observer
from watchdog.events i... | Instead of `LoggingEventHandler` define your handler:
```
#!/usr/bin/python
import time
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
class MyHandler(FileSystemEventHandler):
def on_modified(self, event):
print "Got it!"
if __name__ == "__main__":
event_... |
Changing the active class of a link with the twitter bootstrap css in python/flask | 18,600,031 | 14 | 2013-09-03T19:30:15Z | 18,600,623 | 29 | 2013-09-03T20:07:51Z | [
"python",
"class",
"twitter-bootstrap",
"flask",
"jinja2"
] | I got the following html snippet from my page `template.html`.
```
<ul class='nav'>
<li class="active"><a href='/'>Home</a></li>
<li><a href='/lorem'>Lorem</a></li>
{% if session['logged_in'] %}
<li><a href="/account">Account</a></li>
<li><a href="/projects">Projects</a>
<li><a hre... | Have you looked at this ? <http://jinja.pocoo.org/docs/tricks/>
## Highlighting Active Menu Items
Often you want to have a navigation bar with an active navigation item. This is really simple to achieve. Because assignments outside of blocks in child templates are global and executed before the layout template is eva... |
Why does assigning to self not work, and how to work around the issue? | 18,600,382 | 3 | 2013-09-03T19:51:21Z | 18,600,396 | 16 | 2013-09-03T19:52:32Z | [
"python",
"self"
] | I have a class (list of `dict`s) and I want it to sort itself:
```
class Table(list):
â¦
def sort (self, in_col_name):
self = Table(sorted(self, key=lambda x: x[in_col_name]))
```
but it doesn't work at all. Why? How to avoid it? Except for sorting it externally, like:
```
new_table = Table(sorted(old_table, ... | You can't re-assign to `self` from within a method and expect it to change external references to the object.
`self` is just an argument that is passed to your function. It's a name that points to the instance the method was called on. "Assigning to `self`" is equivalent to:
```
def fn(a):
a = 2
a = 1
fn(a)
# a is... |
Selenium / Python - Selecting via css selector | 18,600,391 | 4 | 2013-09-03T19:52:00Z | 18,600,739 | 10 | 2013-09-03T20:15:44Z | [
"python",
"selenium",
"webdriver"
] | Issue:
Can not select from css selector specific element. Need to verify that the registered user can change their password successfully. I have tried the different attributes of the class to call it. The result is an exception error in the method when trying with the first two examples. The final try calls the first ... | ```
driver.find_element_by_css_selector(".test_button4[value='Update']").click()
```
EDIT:
Because the selector needs a `class`, `id`, or `tagname`, but `value.Update` by itself is none of these.
`.test_button4` provides a classname to match against, and from there, `[value='Update']` specifies which particular match... |
numpy.r_ is not a function. What is it? | 18,601,001 | 15 | 2013-09-03T20:34:19Z | 18,601,018 | 14 | 2013-09-03T20:35:31Z | [
"python",
"function",
"numpy"
] | According to the numpy/scipy doc on `numpy.r_` [here](http://docs.scipy.org/doc/numpy/reference/generated/numpy.r_.html), it is "not a function, so takes no parameters".
If it is not a function, what is the proper term for "functions" such as `numpy.r_`? | It's a class instance (aka an object):
```
In [2]: numpy.r_
Out[2]: <numpy.lib.index_tricks.RClass at 0x1923710>
```
A class is a construct which is used to define a distinct *type* - as such a class allows *instances* of itself. Each instance can have properties (member/instance variables and methods).
One of the m... |
numpy.r_ is not a function. What is it? | 18,601,001 | 15 | 2013-09-03T20:34:19Z | 18,623,190 | 12 | 2013-09-04T20:29:02Z | [
"python",
"function",
"numpy"
] | According to the numpy/scipy doc on `numpy.r_` [here](http://docs.scipy.org/doc/numpy/reference/generated/numpy.r_.html), it is "not a function, so takes no parameters".
If it is not a function, what is the proper term for "functions" such as `numpy.r_`? | I would argue that for all purposes `r_` **is** a function, but one implemented by a clever hack using different syntax. Mike already explained how `r_` is in reality not a function, but a class instance of `RClass`, which has `__getindex__` implemented, so that you can use it as `r_[1]`. The cosmetic difference is tha... |
basic strings and variables python | 18,601,319 | 2 | 2013-09-03T20:55:01Z | 18,601,338 | 7 | 2013-09-03T20:56:16Z | [
"python",
"string",
"variables"
] | Write a function, called introduction(name, school) that takes, as input, a name (as a string) and a school, and returns the following text: âHello. My name is name. I have always wanted to go to school.â
This is my code
```
def introduction("name","school"):
return ("Hello. My name is ") + str(name) + (". ... | ```
def introduction("name","school"):
```
should be
```
def introduction(name,school):
```
The names you provide as the formal parameters of the function are essentially variables that the values of the actual parameters get assigned to. Including a literal value (like a string) wouldn't make much sense.
When you ... |
Python command line argument semicolon-loop error | 18,602,119 | 3 | 2013-09-03T21:54:25Z | 18,602,584 | 7 | 2013-09-03T22:34:32Z | [
"python",
"bash",
"timeit"
] | First, for those who only noticed python and semicolon in the title and want to furiously bash me up, I **deeply** apologize, and this is only in the command mode
I was trying out `python -mtimeit`so I put `python -mtimeit "n = 0; while n < 10: pass"`
Then an invalid syntax error showed up. same with semicolon and for... | `while`, `for` can't have semicolon before, they need to be on one line. If you looked at [Python grammar](http://docs.python.org/2/reference/grammar.html):
```
compound_stmt ::= if_stmt
| while_stmt
| for_stmt
| try_stmt
| with_stmt
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.