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
Pythonically add header to a csv file
20,347,766
17
2013-12-03T09:52:26Z
20,348,305
24
2013-12-03T10:16:46Z
[ "python", "csv", "header" ]
I wrote a Python script merging two csv files, and now I want to add a header to the final csv. I tried following the suggestions reported [here](http://stackoverflow.com/questions/15907200/how-to-add-a-header-to-a-csv-file-in-python) and I got the following error: `expected string, float found`. What is the most pytho...
The `DictWriter()` class expects *dictionaries* for each row. If all you wanted to do was write an initial header, use a regular `csv.writer()` and pass in a simple row for the header: ``` import csv with open('combined_file.csv', 'wb') as outcsv: writer = csv.writer(outcsv) writer.writerow(["Date", "temperat...
python class: questions about creating instances
20,348,517
3
2013-12-03T10:26:31Z
20,348,732
9
2013-12-03T10:35:02Z
[ "python", "class" ]
I am using python 2.7 and I want to create some kind of data structure, using classes **Question A:** Let's say that I create this class: ``` class my_data(): def __init__(self,data1,data2,data3): self.data1 = data1 self.data2 = data2 self.data3 = data3 ``` and after that I create some instance...
You cannot materialize an object from a non-existing reference. Python names *have* to exist for them to work. Instead, give the `data3` keyword a default, then when the keyword is **not** specified, create the instance: ``` _sentinel = object() class my_data(): def __init__(self, data1, data2, data3=_sentinel): ...
why sqlalchemy default column value not work
20,348,801
9
2013-12-03T10:38:18Z
20,648,661
8
2013-12-18T02:28:35Z
[ "python", "postgresql" ]
I am using postgresql 9.1 and sqlalchemy 0.9 in ubuntu 12.04 The problem is, '***default=10***' not work. My Code: ``` conn_str = 'postgresql://test:pass@localhost/test' engine = create_engine(conn_str) metadata = MetaData(bind=engine) cols=[] cols += [Column('Name', VARCHAR(20), primary_key=True, nullable=False)] ...
instead of using default, use server\_default... fixed the problem for me <http://docs.sqlalchemy.org/en/rel_0_9/core/metadata.html#sqlalchemy.schema.Column>
SOCKET ERROR: [Errno 111] Connection refused
20,349,170
17
2013-12-03T10:55:21Z
20,352,563
11
2013-12-03T13:32:07Z
[ "python", "sockets", "python-2.7", "smtp" ]
I am using simple python lib for the SMTP But i am getting this error: ``` import smtplib smtpObj = smtplib.SMTP('localhost') Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python2.7/smtplib.py", line 249, in __init__ (code, msg) = self.connect(host, port) File "/usr/l...
**Start a simple SMTP server with Python like so:** ``` python -m smtpd -n -c DebuggingServer localhost:1025 ``` **or you can also try gmail smtp setting** ``` server = smtplib.SMTP(host='smtp.gmail.com', port=587) ```
Understanding LDA implementation using gensim
20,349,958
12
2013-12-03T11:31:04Z
20,350,229
11
2013-12-03T11:43:32Z
[ "python", "topic-modeling", "gensim", "dirichlet" ]
I am trying to understand how gensim package in Python implements Latent Dirichlet Allocation. I am doing the following: Define the dataset ``` documents = ["Apple is releasing a new product", "Amazon sells many things", "Microsoft announces Nokia acquisition"] ``` After removing stopwords...
The answer you're looking for is in the [genism tutorial](http://radimrehurek.com/gensim/wiki.html#latent-dirichlet-allocation). `lda.printTopics(k)` prints the most contributing words for `k` randomly selected topics. One can assume that this is (partially) the distribution of words over each of the given topics, mean...
Python, read CRLF text file as is, with CRLF
20,350,305
5
2013-12-03T11:47:00Z
20,350,545
8
2013-12-03T11:57:31Z
[ "python", "python-2.7", "file-io", "line-endings" ]
``` with open(fn, 'rt') as f: lines = f.readlines() ``` This reads CR LF text file (WinXP, Py 2.6) with LF line ends. So `lines` contain '\n' ends. How to get lines as is: * for CRLF file get lines with '\n\r' ends * for LF file get lines with '\n' ends
Instead of the built-in `open()` function, use [`io.open()`](http://docs.python.org/2/library/io.html#io.open). This gives you more control over how newlines are handled with the `newline` argument: ``` import io with io.open(fn, 'rt', newline='') as f: lines = f.readlines() ``` Setting `newline` to the empty st...
pyyaml is producing undesired !!python/unicode output
20,352,794
12
2013-12-03T13:43:16Z
20,369,984
19
2013-12-04T07:57:40Z
[ "python", "pyyaml" ]
I am using pyyaml to dump an object to a file. There are several unicode strings in the object. I've done this before, but now it's producing output items like this: ``` 'item': !!python/unicode "some string" ``` Instead of the desired: ``` 'item': 'some string' ``` I'm intending to output as utf-8. The current com...
I tried many combinations and the only one I can find that consistently produces the correct YAML output is: ``` yaml.safe_dump(data, file(filename,'w'), encoding='utf-8', allow_unicode=True) ```
Clarification on the Decimal type in Python
20,354,423
9
2013-12-03T14:54:51Z
20,356,293
18
2013-12-03T16:19:35Z
[ "python", "python-3.x", "floating-point", "decimal" ]
Everybody know, or at least, [every programmers should know](http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html), that using the `float` type could lead to precision errors. However, in some cases, an exact solution would be great and there are cases where comparing using an epsilon value is not enough. Any...
The Decimal class is best for financial type addition, subtraction multiplication, division type problems: ``` >>> (1.1+2.2-3.3)*10000000000000000000 4440.892098500626 # relevant for government invoices... >>> import decimal >>> D=decimal.Decimal >>> (D('1.1')+D('2.2')-D('3.3'))*100000000000...
How to replace values in a numpy array based on another column?
20,355,311
5
2013-12-03T15:36:39Z
20,355,379
11
2013-12-03T15:39:30Z
[ "python", "arrays", "numpy" ]
Let say i have the following: ``` import numpy as np data = np.array([ [1,2,3], [1,2,3], [1,2,3], [4,5,6], ]) ``` How would I go about changing values in column 3 based on values in column 2? For instance, If column 3 == 3, column 2 = 9. ``` [[1,9,3], [1,9,3], [1,9,3], [4,5,6]] ...
You can use [Numpy's slicing and indexing](http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html) to achieve this. Take all the rows where the third column is `3`, and change the second column of each of those rows to `9`: ``` >>> data[data[:, 2] == 3, 1] = 9 >>> data array([[1, 9, 3], [1, 9, 3], ...
delete U+200B zero-width space characters using sublime text 3
20,356,784
3
2013-12-03T16:42:44Z
20,357,538
12
2013-12-03T17:16:00Z
[ "python", "sublimetext3", "sublime-text-plugin" ]
How can I make U+200B character or delete them in using sublime text 3. I found <http://pastebin.com/ehWxNfMe> but I am not sure how to use it
The following will work in Sublime Text 2 and 3. However, due to some issues discussed later, it has the potential to block the program when editing large files, and/or on slow computers. A Sublime Text 3-specific version using an asynchronous method is at the bottom. Open a new file in Sublime, and set its syntax to ...
How To Get IPython Notebook To Run Python 3?
20,360,293
47
2013-12-03T19:49:48Z
28,866,474
42
2015-03-04T22:36:42Z
[ "python", "python-3.x", "ipython", "ipython-notebook" ]
I am new to Python to bear with me. 1. I installed Anaconda, works great. 2. I setup a Python 3 environment following the Anaconda [cmd line instructions](http://continuum.io/blog/anaconda-python-3), works great. 3. I [setup Anaconda's Python 3 environment as Pycharm's interpreter](http://docs.continuum.io/anaconda/id...
To set IPython Notebook to run Python 3 instead of 2 on my MAC 10.9, I did the following steps ``` $sudo pip3 install ipython[all] ``` Then ``` $ipython3 notebook ```
Compulsory usage of if __name__=="__main__" in windows while using multiprocessing
20,360,686
4
2013-12-03T20:09:57Z
20,361,032
7
2013-12-03T20:29:13Z
[ "python", "windows", "multiprocessing" ]
While using multiprocessing in python on windows, it is expected to protect the entry point of the program. The documentation says "Make sure that the main module can be safely imported by a new Python interpreter without causing unintended side effects (such a starting a new process)". Can anyone explain what exactly ...
Expanding a bit on the good answer you already got, it helps if you understand what Linux-y systems do. They spawn new processes using `fork()`, which has two *good* consequences: 1. All data structures existing in the main program are visible to the child processes. They actually work on *copies* of the data. 2. The ...
django - set user permissions when user is automatically created
20,361,235
11
2013-12-03T20:41:11Z
20,361,273
16
2013-12-03T20:44:04Z
[ "python", "django", "django-admin", "django-authentication" ]
Django 1.5, python 2.6 The model automatically creates a user under certain conditions: ``` User.objects.get_or_create(username=new_user_name, is_staff=True) u = User.objects.get(username=new_user_name) u.set_password('temporary') ``` In addition to setting the username, password, and is\_staff status, I would like...
Use [`add` and `remove`](https://docs.djangoproject.com/en/1.5/topics/auth/default/#permissions-and-authorization) methods: ``` permission = Permission.objects.get(name='Can view poll') u.user_permissions.add(permission) ```
django - set user permissions when user is automatically created
20,361,235
11
2013-12-03T20:41:11Z
31,437,124
15
2015-07-15T17:28:07Z
[ "python", "django", "django-admin", "django-authentication" ]
Django 1.5, python 2.6 The model automatically creates a user under certain conditions: ``` User.objects.get_or_create(username=new_user_name, is_staff=True) u = User.objects.get(username=new_user_name) u.set_password('temporary') ``` In addition to setting the username, password, and is\_staff status, I would like...
alko's answer above is correct, but omits an import statement. ``` from django.contrib.auth.models import Permission permission = Permission.objects.get(name='Can view poll') u.user_permissions.add(permission) ```
Cropping an image with Python Pillow
20,361,444
12
2013-12-03T20:53:25Z
20,361,739
31
2013-12-03T21:11:43Z
[ "python", "django", "python-imaging-library", "pillow" ]
I installed Python [Pillow](https://en.wikipedia.org/wiki/Python_Imaging_Library) and am trying to crop an image. Other effects work great (for example, thumbnail, blurring image, etc.) Whenever I run the code below I get the error: > tile cannot extend outside image ``` test_image = test_media.file original = Imag...
The problem is with logic, not Pillow. Pillow is nearly 100% PIL compatible. You created an image of `0 * 0` (`left = right & top = bottom`) size. No display can show that. My code is as follows ``` from PIL import Image test_image = "Fedora_19_with_GNOME.jpg" original = Image.open(test_image) original.show() width,...
Using Sikuli to verify text
20,362,028
3
2013-12-03T21:27:45Z
20,374,321
8
2013-12-04T11:36:57Z
[ "python", "sikuli" ]
I am using the Sikuli IDE to test an application that returns data in a text box. For example I search the name field for my test value 'FirstName01' the application returns the name and address in various text boxes. I then verify the data by using the exists() function in Sikuli. To do this I click on the exists fun...
Rather than using exists() to verify text (because the OCR in sikuli's IDE is pretty unreliable), if there is any way to get the text that you want to evaluate to the clipboard, you can use Env.getClipboard() to evaluate it with much more accuracy. To get it to the clipboard, you could use several approaches: 1. drag...
How to load sentences into Python gensim?
20,362,993
10
2013-12-03T22:25:56Z
20,363,116
9
2013-12-03T22:34:08Z
[ "python", "nlp", "gensim" ]
I am trying to use the [`word2vec`](http://radimrehurek.com/gensim/models/word2vec.html) module from `gensim` natural language processing library in Python. The docs say to initialize the model: ``` from gensim.models import word2vec model = Word2Vec(sentences, size=100, window=5, min_count=5, workers=4) ``` What fo...
[A list of `utf-8` sentences](http://radimrehurek.com/gensim/models/word2vec.html#gensim.models.word2vec.Word2Vec). You can also stream the data from the disk. Make sure it's `utf-8`, and split it: ``` sentences = [ "the quick brown fox jumps over the lazy dogs", "Then a cop quizzed Mick Jagger's ex-wives briefly." ]...
What is the fastest way to convert string to array in python?
20,363,395
3
2013-12-03T22:55:10Z
20,363,411
16
2013-12-03T22:56:48Z
[ "python", "string", "list" ]
This is a line I read from a text file: ``` [54, 95, 45, -97, -51, 84, 0, 32, -55, 14, 50, 54, 68, -3, 57, 88, -1] ``` I used readline() to read it in as a string. Now what is the fastest way to convert it back to an array? Thank you!
I'm not sure that this is the fastest, but it's definitely the safest/easiest: ``` import ast lst = ast.literal_eval(s) ``` regular `eval` would work too: ``` lst = eval(s) ``` Some basic timings from my machine: ``` >>> s = '[54, 95, 45, -97, -51, 84, 0, 32, -55, 14, 50, 54, 68, -3, 57, 88, -1]' >>> def f1(): .....
What is the fastest way to convert string to array in python?
20,363,395
3
2013-12-03T22:55:10Z
20,363,519
14
2013-12-03T23:05:13Z
[ "python", "string", "list" ]
This is a line I read from a text file: ``` [54, 95, 45, -97, -51, 84, 0, 32, -55, 14, 50, 54, 68, -3, 57, 88, -1] ``` I used readline() to read it in as a string. Now what is the fastest way to convert it back to an array? Thank you!
Since we care about speed, in this particular case I might use [`json.loads`](http://docs.python.org/2/library/json.html#json.loads): ``` >>> import ast, json >>> s = "[54, 95, 45, -97, -51, 84, 0, 32, -55, 14, 50, 54, 68, -3, 57, 88, -1]" >>> %timeit ast.literal_eval(s) 10000 loops, best of 3: 61.6 µs per loop >>> %...
PostgreSQL ILIKE query with SQLAlchemy
20,363,836
7
2013-12-03T23:28:18Z
20,367,821
16
2013-12-04T05:42:05Z
[ "python", "postgresql", "sqlalchemy", "flask", "flask-sqlalchemy" ]
I'd like to run a query that selects all posts, case insensitive, that have titles that match `'%' + [some_phrase] + '%'`. That is, select all rows that have titles that *contain* some phrase, case insensitive. From the research I've done, it looks like I need to use Postgres's ILIKE query for it to match case insensit...
I think it should work ``` Post.query.filter(Post.title.ilike('%some_phrase%')) ``` <http://docs.sqlalchemy.org/en/latest/orm/internals.html?highlight=ilike#sqlalchemy.orm.attributes.QueryableAttribute.ilike>
How to delete the first line of a text file using Python?
20,364,396
5
2013-12-04T00:16:54Z
20,364,437
10
2013-12-04T00:20:33Z
[ "python", "file" ]
I have been searching online, but have not found any good solution. Here is my text file: ``` [54, 95, 45, -97, -51, 84, 0, 32, -55, 14, 50, 54, 68, -3, 57, 88, -1] [24, 28, 38, 37, 9, 44, -14, 84, -40, -92, 86, 94, 95, -62, 12, -36, -12] [-26, -67, -89, -7, 12, -20, 76, 88, -15, 38, -89, -65, -53, -84, 31, -81, -91]...
Assuming you have enough memory to hold everything in memory: ``` with open('file.txt', 'r') as fin: data = fin.read().splitlines(True) with open('file.txt', 'w') as fout: fout.writelines(data[1:]) ``` We could get fancier, opening the file, reading and then seeking back to the beginning eliminating the secon...
Using two different Python Distributions
20,364,700
7
2013-12-04T00:47:16Z
20,364,875
12
2013-12-04T01:01:58Z
[ "python", "software-distribution", "anaconda" ]
I currently have continuum analytics' python distribution (called anaconda) downloaded and in use on my computer. My problem is that I want to use virtualenv for a flask project and anaconda flashes a warning that says "virtual env is not supported". Is there any way i can run two distributions, stock python and anacon...
Sure, if you want to use the Anaconda distribution separately, you can set up an alias to run that version and leave the stock python as the default. In your `.bash_profile` file, the Anaconda installer probably put the following line: ``` export PATH="/path/to/your/anaconda/bin:$PATH" ``` Comment this out, and add ...
how to make a grouped boxplot graph in matplotlib
20,365,122
4
2013-12-04T01:28:22Z
20,365,203
9
2013-12-04T01:36:38Z
[ "python", "matplotlib" ]
I have three algorithms, A, B, and C. I've run them on different datasets and would like to graph their runtimes on each as a grouped boxplot in Python. As a visual example of what I want, I made a terrible drawing, but hopefully it gets the point across. ![boxplot graph drawing](http://i.stack.imgur.com/ptSEr.jpg) ...
It's easiest to do this with independent subplots: ``` import matplotlib.pyplot as plt import numpy as np import random data = {} data['dataset1'] = {} data['dataset2'] = {} data['dataset3'] = {} n = 500 for k,v in data.iteritems(): upper = random.randint(0, 1000) v['A'] = np.random.uniform(0, upper, size=n)...
Django DecimalField generating "quantize result has too many digits for current context" error on save
20,365,585
8
2013-12-04T02:16:40Z
20,365,586
16
2013-12-04T02:16:40Z
[ "python", "django", "django-models", "decimal" ]
I've got a model like: ``` class ModelWithDecimal(models.Model): value = models.DecimalField(max_digits=2,decimal_places=2) ``` ...yet when I try... ``` obj = ModelWithDecimal(value="1.5") obj.save() ``` I get a `quantize result has too many digits for current context` error during the save. Shouldn't that be O...
The problem is that all the right-of-the-decimal `decimal_places` are consumed by every instance, regardless of whether you have non-zero digits there, leaving only `(max_digits - decimal_places)` digits for left-of-the-decimal. So for `DecimalField(max_digits=2,decimal_places=2)`, there's room for *zero* digits to th...
Comparing two date strings in Python
20,365,854
14
2013-12-04T02:44:56Z
20,365,917
15
2013-12-04T02:51:24Z
[ "python", "date", "datetime" ]
Let's say I have a string: "10/12/13" and "10/15/13", how can I convert them into date objects so that I can compare the dates? For example to see which date is before or after.
Use [`datetime.datetime.strptime`](http://docs.python.org/2/library/datetime.html#datetime.datetime.strptime): ``` >>> from datetime import datetime as dt >>> a = dt.strptime("10/12/13", "%m/%d/%y") >>> b = dt.strptime("10/15/13", "%m/%d/%y") >>> a > b False >>> a < b True >>> ```
What's the difference between pass and continue in python
20,367,583
5
2013-12-04T05:26:07Z
20,367,615
7
2013-12-04T05:28:19Z
[ "python", "for-loop" ]
My test shows that both `pass` and `continue` can be used equivalently to construct a empty `for`-loop for test purpose. Are there any difference between them?
The `pass` keyword is a no-op keyword. It does exactly nothing. It's often used as a placeholder for code which will be added later: ``` if response == "yes": pass # process "yes" case ``` The `continue` keyword, on the other hand, is used to restart a loop at the control point, such as with: ``` for i in range...
Stop cssutils from generating warning messages
20,371,448
6
2013-12-04T09:25:02Z
21,766,520
7
2014-02-13T22:04:27Z
[ "python", "css" ]
I am using the parseFile convenience method to read a css file but it is generating a huge amount of warning messages. I have set `validate=False` but it is still printing the messages. I have tried to create a CSSParser object and initialising the log object and logging level to none but it is still printing warn...
The logger is a singleton, so, put this line above your instruction ``` import logging cssutils.log.setLevel(logging.CRITICAL) ``` This disables the warning and error logging.
iphone push notifications passphrase issue (pyAPns)
20,372,128
11
2013-12-04T09:56:50Z
20,375,745
20
2013-12-04T12:43:10Z
[ "python", "django", "push-notification", "apple-push-notifications", "django-1.2" ]
I'm trying to implement push notifications for iphone based on PyAPNs When I run it on local but it blocks and prompts me to enter the passphrase manually and doesn't work until I do I don't know how to set it up so to work without prompt This is my code: ``` from apns import APNs, Payload import optparse import os...
When you create a .pem file without phrase specify `-nodes` **To Create .pem file without phrase** ``` openssl pkcs12 -nocerts -out Pro_Key.pem -in App.p12 -nodes ``` **To Create .pem file with phrase** ``` openssl pkcs12 -nocerts -out Pro_Key.pem -in App.p12 ``` If you have a .pem file with password you can **get...
Plotting two ranges on one colorbar
20,372,509
2
2013-12-04T10:14:25Z
20,375,828
7
2013-12-04T12:47:25Z
[ "python", "matplotlib", "colorbar" ]
Is it possible to get one colorbar to have two ranges? Basically I have two plots (created separatly and pasted into a blank image). They use the same colormap (hot), but the color is over a different range due to the nature of the data in each plot. Basically on the left side of the colorbar I would like the range t...
Basically, you can use `twinx` to create another Y-axis, but when I try it to the colobar axe, the aspect setting cause some problem, so I use `set_position()` to change the width of the two axes, here is the code: ``` import pylab as pl import numpy as np a = np.random.rand(10, 10) pl.imshow(a) cb = pl.colorbar(pad=0...
What is the difference between \d+ and \d- OR \w+ and \w- in regular expression terms?
20,375,551
3
2013-12-04T12:35:37Z
20,375,638
10
2013-12-04T12:38:39Z
[ "python", "regex" ]
As per title, what is the difference between: `\d+` and `\d-` `\w+` and `\w-` in regular expression terms? What influence has `+` and `-` ?
`\d+` means one or more digit `[0-9]` (depending on LOCALE) `\d-` means a digit followed by a dash `-` `\w+` means one or more word character `[a-zA-Z0-9_]` (depending on LOCALE) `\w-` means a word char followed by a dash `-`
Joining pandas dataframes by column names
20,375,561
13
2013-12-04T12:35:48Z
20,375,692
23
2013-12-04T12:41:06Z
[ "python", "pandas", "dataframe" ]
I have two dataframes with the following column names: ``` frame_1: event_id, date, time, county_ID frame_2: countyid, state ``` I would like to get a dataframe with the following columns by joining (left) on `county_ID = countyid`: ``` joined_dataframe event_id, date, time, county, state ``` I cannot figure out h...
you can use the left\_on and right\_on options as follows: ``` pd.merge(frame_1, frame_2, left_on = 'county_ID', right_on = 'countyid') ``` I was not sure from the question if you only wanted to merge if the key was in the left hand dataframe. If that is the case then the following will do that (the above will in eff...
Cannot run Hello World on Google App Engine Windows
20,378,641
4
2013-12-04T14:58:19Z
20,379,021
11
2013-12-04T15:14:19Z
[ "python", "google-app-engine", "python-2.7" ]
I have [downaloded and installed Python 2.7.6](http://www.python.org/download/releases/2.7.6/) in my Windows and I have also installed the latest version of the [GAE SDK](https://developers.google.com/appengine/downloads#Google_App_Engine_SDK_for_Python) for Windows as well. I have the following configurations on my G...
According to the regex that isn't matching, the app name needs to be lowercase: ``` >>> regex = r'^(?:(?:[a-z\d\-]{1,100}\~)?(?:(?!\-)[a-z\d\-\.]{1,100}:)?(?!-)[a-z\d\-]{0,99}[a-z\d])$' >>> print(re.match(regex, 'HelloWorld')) None >>> print(re.match(regex, 'helloworld')) <_sre.SRE_Match object at 0x13ac308> ```
How to use function returnig dictionary in django template?
20,378,924
2
2013-12-04T15:10:42Z
20,379,050
7
2013-12-04T15:15:34Z
[ "python", "django", "django-templates" ]
I got something like this ``` class MyModel(models.Model): ... def status(self): return{'status':1, 'days':10} ``` and in the template ``` {{ mymodel.status['status'] }} ``` but it gives my `Could not parse the remainder: '['status']' from 'mymodel.status['status']'` what is the best way to make it...
In django template, accesing the item `'item'` also use `.item` form. So, use `.status`: ``` {{ mymodel.status.status }} ``` See [The Django template language - Variables - Behind the scenes](https://docs.djangoproject.com/en/1.6/topics/templates/#variables).
django filter by datetime on a range of dates
20,379,246
5
2013-12-04T15:25:09Z
20,379,589
11
2013-12-04T15:39:47Z
[ "python", "django", "datetime" ]
I have a model with field "created\_at", and I have a list of dates. So, I want to get all the models that are created in the date range. How ? I know that we can compare datetime and date easily using: ``` queryset.filter(created_at__startswith=date) ``` But, I have a range of dates, so how ? Let me know for more...
You can use [range](https://docs.djangoproject.com/en/dev/ref/models/querysets/#range) lookup. Just find the lowest and greater date and then apply it as: ``` queryset.filter(created_at__range=(start_date, end_date)) ```
Cyclic dependencies and interfaces in Golang
20,380,333
13
2013-12-04T16:12:55Z
20,394,211
29
2013-12-05T07:44:06Z
[ "python", "go" ]
I am a long time python developer. I was trying out Go, converting an existing python app to Go. It is modular and works really well for me. Upon creating the same structure in Go, I seem to land in cyclic import errors, a lot more than I want to. Never had any import problems in python. I never even had to use import...
The short version: * Write config functions for hooking packages up to each other *at run time rather than compile time*. Instead of `routes` importing all the packages that define routes, it can *export* `routes.Register`, which `main` (or code in each app) can call. * As a rule, *split a package up when each piece c...
Networkx: how to show node and edge attributes in a graph drawing
20,381,460
5
2013-12-04T17:02:09Z
20,382,152
10
2013-12-04T17:39:39Z
[ "python", "graphviz", "networkx" ]
I have a graph G with attribute 'state' for nodes and edges. I want to draw the graph, all nodes labelled, and with the state marked outside the corresponding edge/node. ``` for v in G.nodes(): G.node[v]['state']='X' G.node[1]['state']='Y' G.node[2]['state']='Y' for n in G.edges_iter(): G.edge[n[0]]...
It's not so pretty - but it works like this: ``` from matplotlib import pyplot as plt import networkx as nx G = nx.Graph() G.add_edge(1,2) G.add_edge(2,3) for v in G.nodes(): G.node[v]['state']='X' G.node[1]['state']='Y' G.node[2]['state']='Y' for n in G.edges_iter(): G.edge[n[0]][n[1]]['state']='X' G.edge[2]...
Python sphinx autosummary error
20,381,883
9
2013-12-04T17:24:47Z
20,392,926
14
2013-12-05T06:21:49Z
[ "python", "python-sphinx" ]
I have a sphinx document and when I include the following lines: ``` .. currentmodule:: myMod .. autosummary:: MyClass ``` I get the following error ``` ERROR: Unknown directive type "autosummary". ``` Yet, autosummary is available since version 0.6, and I use Sphinx 1.1.3. What could potentially cause the pro...
[`sphinx.ext.autosummary`](http://sphinx-doc.org/ext/autosummary.html) is a [Sphinx extension](http://sphinx-doc.org/extensions.html). In order to use the extension, you must add its name to the [`extensions`](http://sphinx-doc.org/config.html#confval-extensions) configuration variable in conf.py: ``` extensions = ['s...
Is there an equivalent of Python's `pass` in c++ std11?
20,382,278
7
2013-12-04T17:45:18Z
20,382,311
12
2013-12-04T17:47:00Z
[ "c++", "python" ]
Title pretty much asks the short but sweet question. I want a statement that does nothing but can be used in places requiring a statement. Pass: <http://docs.python.org/release/2.5.2/ref/pass.html> Edit: can close. Just saw: [How does one execute a no-op in C/C++?](http://stackoverflow.com/questions/300208/how-does-on...
Semicolon, or empty brackets should work for you For example Python's ``` while some_condition(): # presumably one that eventually turns false pass ``` Could translate to the following C++ ``` while (/* some condition */) ; ``` Or ``` while (/* some condition */) {} ``` Perhaps for the ternary operato...
Documentation and syntax for ggplot in python
20,383,305
9
2013-12-04T18:41:55Z
20,974,678
11
2014-01-07T14:50:10Z
[ "python", "ggplot2", "python-ggplot" ]
Does anybody know of documentation of ggplot2 in python? To my knowledge the syntax is similar to R syntax, but is there any information or code examples out there yet? Any tutorials....?
We'll be uploading the docs to ggplot.readthedocs.org this week (will update w/ url). Aside from that the best resources are here: * <http://blog.yhathq.com/posts/aggregating-and-plotting-time-series-in-python.html> * <http://blog.yhathq.com/posts/ggplot-for-python.html> * <http://ggplot.yhathq.com/> The docs just go...
Pandas selecting by label sometimes return series, sometimes returns dataframe
20,383,647
12
2013-12-04T19:01:40Z
20,384,317
12
2013-12-04T19:36:17Z
[ "python", "pandas" ]
In Pandas, when I select a label that only has one entry in the index I get back a Series, but when I select an entry that has more then one entry I get back a data frame. Why is that? Is there a way to ensure I always get back a data frame? ``` In [1]: import pandas as pd In [2]: df = pd.DataFrame(data=range(5), in...
Granted that the behavior is inconsistent, but I think it's easy to imagine cases where this is convenient. Anyway, to get a DataFrame every time, just pass a list to `loc`. There are other ways, but in my opinion this is the cleanest. ``` In [2]: type(df.loc[[3]]) Out[2]: pandas.core.frame.DataFrame In [3]: type(df....
How to unit test Google Cloud Endpoints
20,384,743
33
2013-12-04T19:59:46Z
20,986,246
27
2014-01-08T03:04:45Z
[ "python", "google-app-engine", "unit-testing", "google-cloud-endpoints" ]
I'm needing some help setting up unittests for Google Cloud Endpoints. Using WebTest all requests answer with AppError: Bad response: 404 Not Found. I'm not really sure if endpoints is compatible with WebTest. This is how the application is generated: ``` application = endpoints.api_server([TestEndpoint], restricted=...
After much experimenting and looking at the SDK code I've come up with two ways to test endpoints within python: ## 1. Using webtest + testbed to test the SPI side You are on the right track with webtest, but just need to make sure you correctly transform your requests for the SPI endpoint. The Cloud Endpoints API f...
Installing pylibmc on Ubuntu
20,388,722
20
2013-12-05T00:00:46Z
20,388,723
44
2013-12-05T00:00:46Z
[ "python", "ubuntu", "memcached", "pip", "libmemcached" ]
When running ``` pip install pylibmc ``` on Ubuntu, I get the following error: ``` _pylibmcmodule.h:42:36: fatal error: libmemcached/memcached.h: No such file or directory ```
``` sudo apt-get install libmemcached-dev zlib-dev ```
Installing pylibmc on Ubuntu
20,388,722
20
2013-12-05T00:00:46Z
22,813,508
8
2014-04-02T13:47:02Z
[ "python", "ubuntu", "memcached", "pip", "libmemcached" ]
When running ``` pip install pylibmc ``` on Ubuntu, I get the following error: ``` _pylibmcmodule.h:42:36: fatal error: libmemcached/memcached.h: No such file or directory ```
Zags answer didn't do the trick for me on Ubuntu 13.10. libmemcached-dev had already been installed. I had to also do: > sudo apt-get install zlib1g-dev Maybe that will help someone else.
Python does not consider equivalent objects to be equivalent
20,388,777
4
2013-12-05T00:04:47Z
20,388,855
7
2013-12-05T00:09:53Z
[ "python", "class", "object", "logic" ]
I am pickling, compressing, and saving python objects. I want to be able to double-check that that the object I saved is the exact same object that is returned after decompression and depickling. I thought there was an error in my code, but when I boiled the problem down to a reproducible example I found that python do...
The default equality comparison in Python is to check for identity (i.e. two objects are the same object). According to the [Python Library Reference](http://docs.python.org/2/library/stdtypes.html#comparisons): > Non-identical instances of a class normally compare as non-equal > unless the class defines the \_\_eq\_...
pyqt dynamic generate QMenu action and connect
20,390,323
3
2013-12-05T02:35:49Z
20,392,756
9
2013-12-05T06:10:45Z
[ "python", "pyqt4" ]
Still learning how pyqt works. I want to dynamically generate a customContextMenu and connect with a function. So far I got the following but the connect part not working ? ``` import sys from PyQt4 import QtGui, QtCore class MainForm(QtGui.QMainWindow): def __init__(self, parent=None): super(MainForm, se...
Your code is almost right. You just need to connect the signals to a `lambda` with a default argument, like this: ``` for item in testItems: action = self.popMenu.addAction('Selected %s' % item) action.triggered[()].connect( lambda item=item: self.printItem(item)) ``` The default argum...
fill missing indices in pandas
20,392,265
4
2013-12-05T05:36:16Z
20,392,317
8
2013-12-05T05:40:41Z
[ "python", "pandas" ]
I have data like follows: ``` import pandas as pd from datetime import datetime x = pd.Series([1, 2, 4], [datetime(2013,11,1), datetime(2013,11, 2), datetime(2013, 11, 4)]) ``` The missing index at November 3rd corresponds to a zero value, and I want it to look like this: ``` y = pd.Series([1,2,0,4], pd.date_range(...
You can use [`pandas.Series.resample()`](http://pandas.pydata.org/pandas-docs/dev/generated/pandas.Series.resample.html) for this: ``` >>> x.resample('D').fillna(0) 2013-11-01 1 2013-11-02 2 2013-11-03 0 2013-11-04 4 ``` There's `fill_method` parameter in the `resample()` function, but I don't know if it'...
Generate a random alphanumeric string as a primary key for a model
20,392,497
6
2013-12-05T05:53:12Z
20,392,692
8
2013-12-05T06:05:43Z
[ "python", "django", "postgresql" ]
I would like a model to generate automatically a random alphanumeric string as its primary key when I create a new instance of it. example: ``` from django.db import models class MyTemporaryObject(models.Model): id = AutoGenStringField(lenght=16, primary_key=True) some_filed = ... some_other_field = ... ...
One of the simplest way to generate unique strings in python is to use `uuid` module. If you want to get alphanumeric output, you can simply use base64 encoding as well: ``` import uuid import base64 uuid = base64.b64encode(uuid.uuid4().bytes).replace('=', '') # sample value: 1Ctu77qhTaSSh5soJBJifg ``` You can then p...
How to get rid of 'quot' in Python json.dumps
20,396,912
3
2013-12-05T10:03:33Z
20,397,114
8
2013-12-05T10:12:23Z
[ "javascript", "python", "django", "json" ]
In Django, I have a view that requests a JSON feed and renders the response along with a template. I need to convert the JSON object to a Javascript JSON object. I have managed to console.log the JSON object in my template, but something is wrong with the format. This is what I expect: ``` {"lat": 58.548703, "referen...
As Armance says in the comments, you need to mark the variable as safe in the template so it is not escaped: ``` {{ myJson|safe }} ```
Running Django tests in PyCharm
20,399,046
12
2013-12-05T11:40:40Z
20,836,704
14
2013-12-30T09:25:54Z
[ "python", "django", "testing", "pycharm" ]
I am trying to run a simple Django test in PyCharm, but its failing with the following stack trace- ``` /home/ramashishb/local/pyenv/testenv/bin/python /opt/pycharm-3.0.2/helpers/pycharm/django_test_manage.py test snippets.SimpleTest.test_simple /home/ramashishb/mine/learn/django-rest/django-rest-tutorial Testing star...
Go to menu `file > settings > Django Support` and select correct settings file. ![enter image description here](http://i.stack.imgur.com/krBrU.png)
Python 2.7 mock/patch: understanding assert_called_XYZ()
20,399,327
8
2013-12-05T11:53:27Z
20,399,801
8
2013-12-05T12:15:47Z
[ "python", "unit-testing", "python-2.7", "mocking" ]
I'm relatively new to Python and unit testing in Python. From the Java world I know the concept of mocking but it seem to be much different from what I can see in Python. I found this guide, which I found very helpful: <http://www.voidspace.org.uk/python/mock/index.html> But as I wrote my (a bit more complex) tests w...
The method `assert_called_once` does not exist and it does not perform an assertion. It's no different from writing `StringIOMock.assert_foo_bar_does_not_exist()` or any other method. The mock library doesn't check whether the method called on the mock actually exists. If you use [`assert_called_once_with`](http://www...
Error importing hashlib with python 2.7 but not with 2.6
20,399,331
11
2013-12-05T11:53:35Z
20,419,131
11
2013-12-06T08:15:17Z
[ "python", "python-2.7", "solaris", "solaris-10", "hashlib" ]
I'm on Solaris 10 (x86). Until now, I was using python2.6. Today, I installed python2.7 and I have a weird error occuring when importing hashlib on 2.7, but not on 2.6: Python 2.6: ``` root@myserver [PROD] # python2.6 -c "import hashlib" root@myserver [PROD] # ``` Python 2.7: ``` root@myserver [PROD] # python2.7 -...
The python2.7 package is dependent to the `libssl1_0_0` package (openssl\_1.0 runtime librairies). I installed it, and added the `/usr/local/ssl/lib` directory in `$LD_LIBRARY_PATH` environnent variable. And now it works perfectly! :)
How to store empty value as an Integerfield
20,399,717
6
2013-12-05T12:12:11Z
20,399,819
22
2013-12-05T12:16:29Z
[ "python", "mysql", "django", null ]
I've seen all the similar threads, read the docs, and tried many combinations to store an empty value as `IntegerField` in db and failed every single time. I am using MySQL. My `models.py` defines an `age=models.IntegerField()` field. I populate db from csv file, and some cells have no value. Django docs says: ``` F...
A string is not an integer; and a blank string is not `None` or `NULL`. What you need to do is catch those instances where the field is blank and then cast it to `None`. ``` foo = "something" # "something" is coming from your CSV file try: val = int(foo) except ValueError: # foo is something that cannot be conv...
Python: Trying to Deserialize Multiple JSON objects in a file with each object spanning multiple but consistently spaced number of lines
20,400,818
14
2013-12-05T13:05:54Z
20,400,897
16
2013-12-05T13:09:24Z
[ "python", "json" ]
Ok, after nearly a week of research I'm going to give SO a shot. I have a text file that looks as follows (showing 3 separate json objects as an example but file has 50K of these): ``` { "zipcode":"00544", "current":{"canwc":null,"cig":7000,"class":"observation"}, "triggers":[178,30,176,103,179,112,21,20,48,7,50,40,57...
Load 6 extra lines instead, and pass the *string* to `json.loads()`: ``` with open(file) as f: for line in f: # slice the next 6 lines from the iterable, as a list. lines = [line] + list(itertools.islice(f, 6)) jfile = json.loads(''.join(lines)) # do something with jfile ``` `json...
Python - Any way to avoid several if-statements inside each other in a for-loop?
20,401,260
9
2013-12-05T13:26:53Z
20,401,308
12
2013-12-05T13:29:13Z
[ "python", "for-loop", "comparison", "iteration", "list-comparison" ]
I need a better way to do this. I'm new with programming but I know that this is a very inefficient way of doing it and that I need a function for this, I just don't know how to do it exactly. any suggestions? I'm VERY grateful for any help! ``` for H in range(0,len(a_list)): if a_list[H] > list4[0]: list5...
Use the [`all()` function](http://docs.python.org/2/library/functions.html#all) to test multiple related conditions: ``` if all(function(lst, list5) == lst[1] for lst in (list1, list2, list3, list4)): ``` and ``` if all(function(lst, list6) == lst[1] for lst in (list1, list2, list3, list4, list5)): ``` Like the nes...
Want to multiply, not repeat variable
20,401,871
2
2013-12-05T13:56:55Z
20,401,912
7
2013-12-05T13:58:50Z
[ "python" ]
I want to input a command-line variable and then multiply it, but when I print the variable it repeats by the number I want to multiply it by. eg: ``` #!/usr/bin/env python3 import sys st_run_time_1 = sys.argv[1]*60 print ("Station 1 : %s" % st_run_time_1) ``` When I run the script I get the following: python3 test...
`sys.argv[x]` is string. Multiplying string by number casue that string repeated. ``` >>> '2' * 5 # str * int '22222' >>> int('2') * 5 # int * int 10 ``` To get multiplied number, first convert `sys.argv[1]` to numeric object using [`int`](http://docs.python.org/3/library/functions.html#int) or [`float`](...
Python inheritance - how to inherit class function?
20,403,317
5
2013-12-05T15:01:12Z
20,403,350
7
2013-12-05T15:02:24Z
[ "python", "class", "inheritance" ]
I'm new with python and having some trouble regarding inheritance. i have this class: ``` class A(object): def __init__(self, foo, bar): pass def func1(self): op1() op2() def func2(self): pass ``` I'm using another class that is overriding it : ``` class B(A): de...
You can call the super-class implementation in `func1`: ``` class B(A): def func1(self): super(B, self).func1() op3() ``` Here `super(B, self).func1` will search the class hierarchy in MRO (method resolution order), from class `B` onwards for the next `func1()` method, bind it to `self` and let yo...
How to remove a package from Pypi
20,403,387
16
2013-12-05T15:03:31Z
20,403,468
16
2013-12-05T15:07:53Z
[ "python", "pypi" ]
How do I remove a package from Pypi? I uploaded a package to Pypi several months ago. The package is now obsolete and I'd like to formally remove it. I cannot find any documentation on how to *remove* my package.
* Login. * Go to your packages. * Check the "remove" checkbox for the particular package. * Click "Remove" button.
Python check for NoneType not working
20,405,628
6
2013-12-05T16:39:57Z
20,405,656
22
2013-12-05T16:41:02Z
[ "python", "if-statement", "nonetype" ]
I'm trying to check whether an object has a None type before checking it's length. For this, I've done an if statement with an or operator: ``` if (cts is None) | (len(cts) == 0): return ``` As far as I can tell, the object `cts` will be checked if it's None, and if it is, the length check won't run. However, the fol...
In Python, `|` is a [bitwise or](http://docs.python.org/release/2.5.2/ref/bitwise.html). You want to use a [logical or](http://docs.python.org/release/2.5.2/lib/boolean.html) here: ``` if (cts is None) or (len(cts) == 0): return ```
Python check for NoneType not working
20,405,628
6
2013-12-05T16:39:57Z
20,406,198
12
2013-12-05T17:05:11Z
[ "python", "if-statement", "nonetype" ]
I'm trying to check whether an object has a None type before checking it's length. For this, I've done an if statement with an or operator: ``` if (cts is None) | (len(cts) == 0): return ``` As far as I can tell, the object `cts` will be checked if it's None, and if it is, the length check won't run. However, the fol...
You can also use - ``` if not cts: return ```
Python - Why do the find and index methods work differently?
20,410,385
21
2013-12-05T20:49:07Z
20,410,998
16
2013-12-05T21:21:49Z
[ "python", "methods", "indexing", "find", "consistency" ]
In Python, find and index are very similar methods, used to look up values in a sequence type. find is used for strings, while index is for lists and tuples. They both return the lowest index (the index furthest to the left) that the supplied argument is found. For example, both of the following would return one: ```...
This has always been annoying ;-) Contrary to one answer, there's nothing special about -1 with respect to strings; e.g., ``` >>> "abc"[-1] 'c' >>> [2, 3, 42][-1] 42 ``` The problem with `find()` in practice is that -1 is in fact **not** special as an index. So code using `find()` is prone to surprises when the thing...
Django Import-Export: Admin interface "TypeError at /"
20,411,760
3
2013-12-05T22:04:23Z
20,413,436
13
2013-12-06T00:07:48Z
[ "python", "django" ]
I am trying to figure out how to use Django Import-Export, <https://pypi.python.org/pypi/django-import-export> by reading the docs <https://django-import-export.readthedocs.org/en/latest/getting_started.html#admin-integration> ## Admin Integration: The gap between the example code and its resulting photo that foll...
Although I'm not familiar with this particular app, what you should do is replace ``` admin.site.register(Regional_Units) admin.site.register(Regional_Units_Resource_Admin) ``` with ``` admin.site.register(Regional_Units, Regional_Units_Resource_Admin) ``` and if everything else is ok it should work. The admin `reg...
Solve multi-objectives optimization of a graph in Python
20,411,847
4
2013-12-05T22:09:43Z
20,431,641
7
2013-12-06T19:04:06Z
[ "python", "genetic-algorithm" ]
I'm trying to find what seems to be a complicated and time-consuming multi-objective optimization on a large-ish graph. Here's the problem: I want to find a graph of n vertices (n is constant at, say 100) and m edges (m can change) where a set of metrics are optimized: * Metric A needs to be as high as possible * Met...
Disclaimer: I am one of DEAP lead developer. Your individual could be represented by a binary string. Each bit would indicate whether there is an edge between two vertices. Therefore, your individuals would be composed of n \* (n - 1) / 2 bits, where n is the number of vertices. To evaluate your individual, you would ...
No module named flask using virtualenv
20,414,015
11
2013-12-06T00:59:38Z
20,414,437
16
2013-12-06T01:45:54Z
[ "python", "flask", "virtualenv" ]
I am following these steps to learn flask <http://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-i-hello-world/page/0#comments> I ran this command to create the virtual env: ``` python virtualenv.py flask ``` When I try to start flask, it says ``` No module named flask ``` My PATH is set to the python d...
Make sure your virtualenv is activated. Then You check on the `PYTHONPATH` of that virtualenv. Is there a flask package (folder) installed in that directory. If you unsure whether you have installed flask, just run the following command to see all the packages you have installed `pip list` or `pip show flask`. Do you ...
Properly formatted multiplication table
20,415,384
6
2013-12-06T03:26:22Z
20,415,415
8
2013-12-06T03:30:03Z
[ "python", "string", "algorithm", "python-3.x", "formatting" ]
How would I make a multiplication table that's organized into a neat table? My current code is: ``` n=int(input('Please enter a positive integer between 1 and 15: ')) for row in range(1,n+1): for col in range(1,n+1): print(row*col) print() ``` This correctly multiplies everything but has it in list fo...
Quick way (Probably too much horizontal space though): ``` n=int(input('Please enter a positive integer between 1 and 15: ')) for row in range(1,n+1): for col in range(1,n+1): print(row*col, end="\t") print() ``` Better way: ``` n=int(input('Please enter a positive integer between 1 and 15: ')) for r...
Running a bash script from Python
20,415,522
3
2013-12-06T03:40:21Z
20,415,591
7
2013-12-06T03:47:32Z
[ "python", "linux", "bash" ]
I need to run a bash script from Python. I got it to work as follows: ``` import os os.system("xterm -hold -e scipt.sh") ``` That isn't exactly what I am doing but pretty much the idea. That works fine, a new terminal window opens and I hold it for debugging purposes, but my problem is I need the python script to kee...
I recommend you use `subprocess` module: [docs](http://docs.python.org/2/library/subprocess.html) And you can ``` import subprocess cmd = "xterm -hold -e scipt.sh" # no block, it start a sub process. p = subprocess.Popen(cmd , shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) # and you can block util the ...
Append tuples to a tuples
20,415,822
4
2013-12-06T04:11:14Z
20,415,831
10
2013-12-06T04:12:37Z
[ "python", "append", "tuples" ]
I can do append value to a tuples ``` >>> x = (1,2,3,4,5) >>> x += (8,9) >>> x (1, 2, 3, 4, 5, 8, 9) ``` But how can i append a tuples to a tuples ``` >>> x = ((1,2), (3,4), (5,6)) >>> x ((1, 2), (3, 4), (5, 6)) >>> x += (8,9) >>> x ((1, 2), (3, 4), (5, 6), 8, 9) >>> x += ((0,0)) >>> x ((1, 2), (3, 4), (5, 6), 8, 9,...
``` x + ((0,0),) ``` should give you ``` ((1, 2), (3, 4), (5, 6), (8, 9), (0, 0)) ``` Python has a wonky syntax for one-element tuples: `(x,)` It obviously can't use just `(x)`, since that's just `x` in parentheses, thus the weird syntax. Using `((0, 0),)`, I concatenate your 4-tuple of pairs with a 1-tuple of pairs...
Numerical simulation giving different results in Python 3.2 vs 3.3
20,416,337
4
2013-12-06T05:00:32Z
20,416,402
9
2013-12-06T05:06:50Z
[ "python", "python-3.x", "numerical-methods" ]
This might be a weird question, but here it goes: I have a numerical simulation. It's not a particularly long program, but somewhat lengthy to explain what it's doing. I am running the simulation a thousand times and computing the average result and the variance, and the variance is quite small, on the order of 10^(-3...
Your last bullet point is most likely the cause. At [python3.3](http://docs.python.org/3/whatsnew/3.3.html), hash randomization was enabled by default to address a security concern. Basically, the idea is that you now never know exactly how your strings will hash (which determines their order in the dictionary). Here'...
Flask-Login check if user is authenticated without decorator
20,419,228
12
2013-12-06T08:22:31Z
20,422,317
15
2013-12-06T11:05:59Z
[ "python", "flask", "flask-login" ]
From the Flask-Login docs, it's described how a user of the system can require an authenticated User-model to access a method utilising the decorator syntax: ``` from flask_login import login_required @app.route("/settings") @login_required def settings(): pass ``` Now thats all well and good, but I want to ...
This is very simple in flask: ``` from flask.ext.login import current_user @app.route(...) def main_route(): if current_user.is_authenticated(): return render_template("main_for_user.html") else: return render_template("main_for_anonymous.html") ``` See [the documentation on anonymous users...
passing global variables to another file in Python?
20,419,827
2
2013-12-06T08:59:40Z
20,419,971
7
2013-12-06T09:07:51Z
[ "python", "global-variables" ]
I have ``` # file1.py global a, b, c, d, e, f, g def useful1(): # a lot of things that uses a, b, c, d, e, f, g def useful2(): useful1() # a lot of things that uses a, b, c, d, e, f, g def bonjour(): # a lot of things that uses a, b, c, d, e, f, g useful2() ``` and ``` # main.py (main file) impor...
You don't need to pass them. If you've done `import file1` at the top of main.py, you can just refer to `file1.a` etc directly. However, having this many global variables smells very bad. You probably should refactor using a class.
Python booleans - if x:, vs if x == True, vs if x is True
20,420,934
12
2013-12-06T09:55:57Z
20,421,262
15
2013-12-06T10:12:35Z
[ "python", "if-statement", "boolean" ]
Apologies if this has been asked before, but I have searched in vain for an answer to my *exact* question. Basically, with Python 2.7, I have a program running a series of geoprocessing tools, depended on what is reqested via a series of True/False variables that the user adjusts in the script e.g. ``` x = True if x:...
The following values in Python are false in the context of `if` and other logical contexts: * `False` * `None` * numeric values equal to 0, such as `0`, `0.0`, `-0.0` * empty strings: `''` and `u''` * empty containers (such as lists, tuples and dictionaries) * anything that implements `__bool__` (in Python3) to return...
Why is b=(a+=1) an invalid syntax in python?
20,423,599
4
2013-12-06T12:11:45Z
20,423,944
7
2013-12-06T12:28:23Z
[ "python", "python-2.7" ]
If I write the following in python, I get a syntax error, why so? ``` a = 1 b = (a+=1) ``` I am using python version 2.7 what I get when I run it, the following: ``` >>> a = 1 >>> b = (a +=1) File "<stdin>", line 1 b = (a +=1) ^ SyntaxError: invalid syntax >>> ```
Unlike in some other languages, assignment (including augmented assignment, like `+=`) in Python is *not* an expression. This also affects things like this: ``` (a=1) > 2 ``` which is legal in C, and several other languages. The reason generally given for this is because it helps to prevent a class of bugs like this...
Override JSONSerializer on django rest framework
20,424,521
5
2013-12-06T12:58:31Z
20,426,493
8
2013-12-06T14:35:24Z
[ "python", "django", "django-rest-framework" ]
I'm trying to apply this fix on my django rest framework [Adding root element to json response (django-rest-framework)](http://stackoverflow.com/questions/14824807/adding-root-element-to-json-response-django-rest-framework) But I'm not sure how to override the json serializer on django rest framework, any help would b...
I think you have your answer there in the post you've given. You need to define custom JSON renderer ``` from rest_framework.renderers import JSONRenderer class EmberJSONRenderer(JSONRenderer): def render(self, data, accepted_media_type=None, renderer_context=None): data = {'element': data} retu...
Why I have 2 after second call?
20,424,736
2
2013-12-06T13:09:34Z
20,424,779
10
2013-12-06T13:11:51Z
[ "python" ]
``` class s: i = [] def inc(): t = s() t.i.append(len(t.i)) return len(t.i) print(inc()) print(inc()) ``` my output: ``` 1 2 ``` but I expected: ``` 1 1 ``` becouse everytime created new object, where my mistake?
You are appending to a variable of the *class*, not a variable of the *instance* ``` class s: i = [] ``` This code creates a variable in the class. This is similar to the concept of a **static** variable in Java or C++. In java: ``` class S { static List i = new ... } ``` You probably wanted to do this...
How do I concatenate many objects into one object using inheritence in python? (during runtime)
20,425,800
15
2013-12-06T14:03:01Z
20,425,848
13
2013-12-06T14:06:25Z
[ "python", "oop", "python-2.7", "superclass" ]
I have the following classes: ``` class hello(object): def __init__(self): pass class bye(object): def __init__(self): pass l = [hello, bye] ``` If I do the following I get an error: ``` >>> class bigclass(*l): File "<stdin>", line 1 class bigclass(*l): ^ SyntaxErr...
You could use the [3-argument form of `type`](http://docs.python.org/2/library/functions.html#type) to create the class: ``` bigclass = type('bigclass', (hello, bye), {}) ```
Can I POST data with python requests lib with http-gzip or deflate compression?
20,425,901
3
2013-12-06T14:08:53Z
25,284,140
8
2014-08-13T10:46:39Z
[ "python", "http", "gzip", "deflate" ]
I use the request-module of python 2.7 to post a bigger chunk of data to a service I can't change. Since the data is mostly text, it is large but would compress quite well. The server would accept gzip- or deflate-encoding, however I do not know how to instruct requests to do a POST and encode the data correctly automa...
I've tested the solution proposed by Robᵩ with some modifications and it works. PSEUDOCODE (sorry I've extrapolated it from my code so I had to cut out some parts and haven't tested, anyway you can get your idea) ``` additional_headers['content-encoding'] = 'gzip' s = StringIO.StringIO() g = gzip.GzipFile(fileobj=s...
Appending Column to Frame of HDF File in Pandas
20,428,355
3
2013-12-06T16:03:35Z
20,428,786
16
2013-12-06T16:25:24Z
[ "python", "csv", "pandas", "hdf5" ]
I am working with a large dataset in CSV format. I am trying to process the data column-by-column, then append the data to a frame in an HDF file. All of this is done using Pandas. My motivation is that, while the entire dataset is much bigger than my physical memory, the column size is managable. At a later stage I wi...
complete docs are [here](http://pandas.pydata.org/pandas-docs/dev/io.html#hdf5-pytables), and some cookbook strategies [here](http://pandas.pydata.org/pandas-docs/dev/cookbook.html#hdfstore) PyTables is row-oriented, so you can only append rows. Read the csv chunk-by-chunk then append the entire frame as you go, somet...
Python: convert defaultdict to dict
20,428,636
25
2013-12-06T16:17:32Z
20,428,703
39
2013-12-06T16:21:14Z
[ "python", "defaultdict" ]
How can i convert a defaultdict ``` number_to_letter defaultdict(<class 'list'>, {'2': ['a'], '3': ['b'], '1': ['b', 'a']}) ``` to be a common dict? ``` {'2': ['a'], '3': ['b'], '1': ['b', 'a']} ```
You can simply call `dict`: ``` >>> a defaultdict(<type 'list'>, {'1': ['b', 'a'], '3': ['b'], '2': ['a']}) >>> dict(a) {'1': ['b', 'a'], '3': ['b'], '2': ['a']} ``` but remember that a defaultdict *is* a dict: ``` >>> isinstance(a, dict) True ``` just with slightly different behaviour, in that when you try access ...
Python's assert_called_with, is there a wildcard character?
20,428,750
17
2013-12-06T16:23:24Z
20,429,069
22
2013-12-06T16:39:24Z
[ "python", "testing", "mocking", "assert" ]
Suppose I have a class in python set up like this. ``` from somewhere import sendmail class MyClass: def __init__(self, **kargs): self.sendmail = kwargs.get("sendmail", sendmail) #if we can't find it, use imported def def publish(): #lots of irrelevant code #and then self....
If you're calling `sendmail` with a named parameter `subject` then it's better to check whether the named argument matches what you expect: ``` args, kwargs = self.myclass.sendmail.call_args self.assertEqual(kwargs['subject'], "Hello World") ``` This does assume both implementations of `sendmail` have a named paramet...
How to write to .txt files in Python 3
20,429,246
7
2013-12-06T16:49:12Z
20,429,275
12
2013-12-06T16:50:49Z
[ "python", "file", "text", "file-io" ]
I have a `.txt` file in the same folder as this `.py` file and it has this in it: ``` cat\n dog\n rat\n cow\n ``` How can I save a var (var = 'ant') to the next line of the `.txt` file?
Open the file in append mode and write a new line (including a `\n` line separator): ``` with open(filename, 'a') as out: out.write(var + '\n') ``` This adds the line at the end of the file after all the other contents.
Get TCP Flags with Scapy
20,429,674
8
2013-12-06T17:10:35Z
20,430,555
8
2013-12-06T18:01:09Z
[ "python", "tcp", "packet", "packet-capture", "scapy" ]
I'm parsing a PCAP file and I need to extract TCP flags (SYN, ACK, PSH, URG, ...). I'm using the `packet['TCP'].flags` value to obtain all the flags at once. ``` pkts = PcapReader(infile) for p in pkts: F = bin(p['TCP'].flags) print F, bin(F), p.summary() # manual flags extraction from F ``` I...
Normally, the usual way to handle FLAGS is with a bitmap and bitwise operators. If your `Packet` class doesn't have specific method to test for flags, the best thing you can do IMHO is to: ``` FIN = 0x01 SYN = 0x02 RST = 0x04 PSH = 0x08 ACK = 0x10 URG = 0x20 ECE = 0x40 CWR = 0x80 ``` And test them like this: ``` F =...
issues working with python generators and openstack swift client
20,429,971
18
2013-12-06T17:27:00Z
20,616,197
13
2013-12-16T16:50:08Z
[ "python", "openstack", "openstack-swift" ]
I'm having a problem with Python generators while working with the Openstack Swift client library. The problem at hand is that I am trying to retrieve a large string of data from a specific url (about 7MB), chunk the string into smaller bits, and send a generator class back, with each iteration holding a chunked bit o...
In your `get_object` method, you're assigning the return value of `_object_body()` to the `contents` variable. However, that variable is also the one that holds your actual data, and it's used early on in `_object_body`. The problem is that `_object_body` is a generator function (it uses `yield`). Therefore, when you ...
Django haystack EdgeNgramField given different results than elasticsearch
20,430,449
12
2013-12-06T17:55:36Z
20,461,477
9
2013-12-09T01:14:47Z
[ "python", "django", "elasticsearch", "django-haystack" ]
I'm currently running haystack with an elasticsearch backend, and now I'm building an autocomplete for cities names. The problem is that SearchQuerySet is giving me different results, which from my perspective are wrong, than the same query executed directly in elasticsearch, which are for me the expected results. I'm...
After a deep look into the code I found that the search generated by haystack was: ``` { "query":{ "filtered":{ "filter":{ "fquery":{ "query":{ "query_string":{ "query": "django_ct:(csi.geoname)" } }, ...
Mongodb TTL expires documents early
20,431,833
3
2013-12-06T19:16:02Z
20,433,249
9
2013-12-06T20:44:00Z
[ "python", "mongodb", "ttl" ]
I am trying insert a document into a Mongo database and have it automatically expire itself after a predetermine time. So far, my document get inserted but always get deleted from the database from 0 - 60 seconds even though I set the 'expireAfterSeconds' to much longer. I know mongodb deletes expired documents about e...
Your problems come from using naive timestamps in your local timezone. The [FAQ of pymongo](http://api.mongodb.org/python/current/faq.html#what-is-the-correct-way-to-handle-time-zones-with-pymongo) has an entry which includes a warning not to use `datetime.datetime.now()`. Using `utcnow`, the `ttl`-setting works as exp...
Calculate numpy.std of each pandas.DataFrame's column?
20,432,278
2
2013-12-06T19:44:34Z
20,432,396
9
2013-12-06T19:50:41Z
[ "python", "numpy", "pandas" ]
I want to get the `numpy.std` of each column of my `pandas.DataFrame`. Here is my code: ``` import pandas as pd import numpy as np prices = pd.DataFrame([[-0.33333333, -0.25343423, -0.1666666667], [+0.23432323, +0.14285714, -0.0769230769], [+0.42857143, +0.07692308, +0.1...
They're both right: they just differ on what the default delta degrees of freedom is. `np.std` uses 0, and `DataFrame.std` uses 1: ``` >>> prices.std(axis=0, ddof=0) 0 0.323259 1 0.173375 2 0.147740 dtype: float64 >>> prices.std(axis=0, ddof=1) 0 0.395909 1 0.212340 2 0.180943 dtype: float64 >>> np.s...
What is pythonic way to do dt[,y:=myfun(x),by=list(a,b,c)] in R?
20,433,315
7
2013-12-06T20:48:41Z
20,433,837
9
2013-12-06T21:25:20Z
[ "python", "pandas" ]
Suppose I have a data frame which have column `x, a, b, c` And I would like to aggregate over `a, b, c` to get a value y from a list of x via a function `myfun`, then duplicate the value for all rows within each window/partition. In R in `data.table` this is just 1 line: `dt[,y:=myfun(x),by=list(a,b,c)]`. In Python t...
Use a `DataFrame` and its `groupby` method from `pandas`: ``` import pandas as pd df = pd.DataFrame({'a': ['x', 'y', 'x', 'y'], 'x': [1, 2, 3, 4]}) df.groupby('a').apply(myfun) ``` The exact usage depends on how you wrote your function `myfun`. Where the column used is static (e.g. always `x`) I w...
Local MySQLdb connection fails with AttributeError for paramstyle when running GAE development server
20,433,973
19
2013-12-06T21:34:34Z
20,433,974
8
2013-12-06T21:34:34Z
[ "python", "google-app-engine", "sqlalchemy", "google-cloud-sql" ]
I'm building a GAE Flask application with Flask-Alchemy, against Cloud SQL, and running `dev_appserver` to test the application as I build it. However, if I set the `SQLALCHEMY_DATABASE_URI` to a `mysql+gaerdbms:///appname?instance=instanceid` URL, I get the following traceback when trying to call `db.create_all()`: ...
This means the `MySQLdb` module is missing and failed to import. The GAE SDK does not itself come with the MySQLdb client library; install MySQLdb ([as instructed in the SDK documentation](https://developers.google.com/appengine/docs/python/cloud-sql/#Python_Using_a_local_MySQL_instance_during_development)): ``` venv/...
Can't run PhantomJS in python via Selenium
20,435,220
5
2013-12-06T23:09:07Z
20,480,844
8
2013-12-09T21:09:35Z
[ "python", "selenium", "phantomjs" ]
I have been trying to run PhantomJS via selenium for past 3 days and have had no success. So far i have tried installing PhantomJS via npm, building it from source, installing via apt-get and downloading prebuilt executable and placing it in /usr/bin/phantomjs. Every time I was able to run this example script loadspee...
There seems to be some issue introduced in newer Selenium, see <http://code.google.com/p/selenium/issues/detail?id=6690> I got a bit further using by using ``` pip install selenium==2.37 ``` Avoids the stack trace above. Still having problems with driver.save\_screenshot('foo.png') resulting in an empty file though...
Minimizing the number of costly function calls when the parameters remain the same (python)
20,435,245
3
2013-12-06T23:11:20Z
20,435,335
11
2013-12-06T23:20:46Z
[ "python", "optimization" ]
Suppose that there is a function `costly_function_a(x)` such that: 1. it is very costly in terms of execution time; 2. it returns the same output whenever the same `x` is fed to it; and 3. it does not perform "additional tasks" besides returning an output. In these conditions, instead of calling the function twice in...
What you are looking for is a LRU cache; only most-recently used items are cached, limiting memory usage to balance invocation cost with memory requirements. As your costly function is invoked with different values for `x`, up to a number of return values (per unique `x` value) is cached, with the least-recently used ...
Empty list returned from ElementTree findall
20,435,500
7
2013-12-06T23:36:46Z
20,447,459
16
2013-12-07T22:23:55Z
[ "python", "xml", "parsing", "elementtree", "wikimedia-dumps" ]
I'm new to xml parsing and Python so bear with me. I'm using lxml to parse a wiki dump, but I just want for each page, its title and text. For now I've got this: ``` from xml.etree import ElementTree as etree def parser(file_name): document = etree.parse(file_name) titles = document.findall('.//title') p...
The problem is that you are not taking XML namespaces into account. The XML document (and all the elements in it) is in the `http://www.mediawiki.org/xml/export-0.7/` namespace. To make it work, you need to change ``` titles = document.findall('.//title') ``` to ``` titles = document.findall('.//{http://www.mediawik...
Analytics API + Python Server, NotImplementedError Hello Analytics
20,436,277
5
2013-12-07T01:06:59Z
20,976,328
11
2014-01-07T16:06:09Z
[ "python", "google-analytics-api" ]
A little background: I've been trying to make a restful server that can query and insert via the management API. After banging my head against the wall using node.js and javascript I switched over to python knowing it has more support. Currently I am trying to follow the GA [Tutorial: Hello Analytics API](https://deve...
I received the same error while running through a tutorial for google APIs called 'Google APIs Console Help'. The fix was simple in my case, just update the gflags library: easy\_install --upgrade python-gflags
"pip install SQLAlchemy" Results in "fatal error: Python.h: No such file or directory"
20,436,528
13
2013-12-07T01:42:22Z
20,437,483
22
2013-12-07T04:11:02Z
[ "python", "sqlalchemy" ]
Calling ``` pip install SQLAlchemy ``` I get an error: ``` lib/sqlalchemy/cextension/processors.c:10:20: fatal error: Python.h: No such file or directory ``` As far as I know, I have the correct Python version (2.7.3) and OS (Ubuntu 12.04) (See below.) for this to work. Am I doing anything wrong? The install ***do...
You need to install the `python-dev` (or similar name) package for your version of Python. It includes all the header files needed to compile C extensions. These files are (unfortunately) not included in the default `python` packages. For Ubuntu, the command is ``` sudo apt-get install python-dev ``` or ``` sudo ap...
Is there multiple cursor-like functionality in PyCharm?
20,437,515
8
2013-12-07T04:17:27Z
23,725,224
10
2014-05-18T18:07:31Z
[ "python", "editor", "sublimetext2", "pycharm" ]
I love multiple cursors in Sublime Text and was wondering if there was anything close to equivalent in PyCharm. I haven't been able to find anything other than [Extract Variable](http://www.jetbrains.com/pycharm/webhelp/extract-variable.html) which kind of does something similar I suppose, but it's definitely not the s...
This is an old thread, but I thought I should mention that, after a mere four years, the [pycharm EAP release](http://confluence.jetbrains.com/display/PYH/JetBrains+PyCharm+Preview+%28EAP%29) includes multiple cursors.
Change button or label text color in kivy
20,437,728
9
2013-12-07T04:48:40Z
20,437,806
15
2013-12-07T04:58:56Z
[ "python", "kivy" ]
I'm following [this kivy book](http://my.safaribooksonline.com/book/programming/python/9781783281596), and while I can understand how to change the background color of buttons, I haven't found the keyword to change the text color. I saw [this](http://stackoverflow.com/questions/20181250/changing-the-background-color-o...
Use [`color`](http://kivy.org/docs/api-kivy.uix.label.html#kivy.uix.label.Label.color) (all lowercase): ``` <RootLayout>: rows: 1 Label: text: "Why does this not work?" color: 1,0,1,1 # <----------- canvas.before: Color: rgba: 0, 0, 0, 1 Rectangle...
Strange behavior when comparing unicode objects with string objects
20,438,652
6
2013-12-07T06:56:46Z
20,438,660
12
2013-12-07T06:57:54Z
[ "python", "python-2.7", "unicode" ]
when comparing two strings in python, it works fine and when comparing a `string` object with a `unicode` object it fails as expected however when comparing a `string` object with a converted unicode *`(unicode --> str)`* object it fails # A Demo: *Works as expected:* ``` >>> if 's' is 's': print "Hurrah!" ... Hurr...
Don't use `is` for this, use `==`. You're comparing whether the objects have the same *identity*, not whether they are equal. Of course, if the are the same object, they will be equal (`==`), but if they are equal, they aren't necessarily the same object. The fact that the first one works is an *implementation detail*...
Custom attributes for Flask WTForms
20,440,056
8
2013-12-07T10:03:31Z
20,440,443
9
2013-12-07T10:50:22Z
[ "javascript", "python", "angularjs", "flask", "wtforms" ]
I develop website on Flask and AngularJS. I need to send a form whith AJAX using AngularJS but it requires a custom attribute for input field. For example I have a form in Jinja2 template: ``` <form method="post" action="/"> {{ form.hidden_tag() }} {{ form.name(placeholder="Name") }} </form> ``` So how can I ...
You'll have to use a custom widget for this case; subclass the widget of your choice with: ``` class AngularJSTextInput(TextInput): def __call__(self, field, **kwargs): for key in list(kwargs): if key.startswith('ng_'): kwargs['ng-' + key[3:]] = kwargs.pop(key) return su...
Unsupported operand type(s) for +: 'int' and 'str'
20,441,035
2
2013-12-07T11:53:12Z
20,441,046
8
2013-12-07T11:55:02Z
[ "python", "list", "python-3.x", "int", "pop" ]
I am currently learning Python so I have no idea what is going on. ``` num1 =int(input("What is your first number? ")) num2 =int(input("What is your second number? ")) num3 =int(input("What is your third number? ")) numlist=[num1, num2, num3] print(numlist) print("Now I will remove the 3rd number") print(numlist.pop(2...
You're trying to concatenate a string and an integer, which is incorrect. Change `print(numlist.pop(2)+" has been removed")` to either of these: Explicit `int` to `str` conversion: ``` print(str(numlist.pop(2)) + " has been removed") ``` Use `,` instead of `+`: ``` print(numlist.pop(2), "has been removed") ``` St...
Is there a simpler way to construct Mandelbrot set in Matlab?
20,441,659
3
2013-12-07T13:00:36Z
20,443,091
8
2013-12-07T15:32:04Z
[ "python", "matlab", "matrix" ]
The code shown below for drawing a [Mandelbrot set](http://en.wikipedia.org/wiki/Mandelbrot_set), I think my code a bit redundancy to construction the *Matrix* `M`. In *Python* I know there is a clean way do this, `M = [[mandel(complex(r, i)) for r in np.arange(-2, 0.5,0.005) ] for i in np.range(-1,1,0.005)]` Is ther...
You can avoid the loop altogether. You can do the iteration `z = z.^2 + c` in a vectorized manner. To avoid unnecessary operations, at each iteration keep track of which points `c` have already surpassed your threshold, and continue iterating only with the remaining points (that's the purpose of indices `ind` and `ind2...
How do I separate slides when exporting an IPython notebook to reveal.js?
20,441,848
6
2013-12-07T13:22:09Z
20,442,095
9
2013-12-07T13:47:44Z
[ "python", "ipython", "ipython-notebook", "reveal.js" ]
When I execute an IPython notebook to a reveal.js presentation using ``` ipython nbconvert mynotebook.ipynb --to slides --post serve ``` I am getting all the content as a single slide. How do I separate my content into several slides? ![presentation screenshot](http://i.stack.imgur.com/hg8fL.png) I tried using `---...
In main toolbar, select the "slideshow" cell toolbar. Then select if you want each cell to be a new "slide", "subslide","fragment"...etc
Add item to pandas.Series?
20,441,980
6
2013-12-07T13:36:53Z
20,442,063
14
2013-12-07T13:45:00Z
[ "python", "pandas", "series" ]
I want to add an integer to my `pandas.Series` Here is my code: ``` import pandas as pd input = pd.Series([1,2,3,4,5]) input.append(6) ``` When i run this, i get the following error: ``` Traceback (most recent call last): File "<pyshell#9>", line 1, in <module> f.append(6) File "C:\Python33\lib\site-packag...
Convert appended item to `Series`: ``` >>> ds = pd.Series([1,2,3,4,5]) >>> ds.append(pd.Series([6])) 0 1 1 2 2 3 3 4 4 5 0 6 dtype: int64 ``` or use `DataFrame`: ``` >>> df = pd.DataFrame(ds) >>> df.append([6], ignore_index=True) 0 0 1 1 2 2 3 3 4 4 5 5 6 ``` and last option if your inde...
Right way to reverse pandas.DataFrame?
20,444,087
21
2013-12-07T17:07:58Z
20,444,256
46
2013-12-07T17:24:42Z
[ "python", "pandas", "reverse" ]
Here is my code: ``` import pandas as pd data = pd.DataFrame({'Odd':[1,3,5,6,7,9], 'Even':[0,2,4,6,8,10]}) for i in reversed(data): print(data['Odd'], data['Even']) ``` When I run this code, i get the following error: ``` Traceback (most recent call last): File "C:\Python33\lib\site-packages\pandas\core\gene...
``` data.reindex(index=data.index[::-1]) ``` or simply: ``` data.iloc[::-1] ``` will reverse your data frame, if you want to have a `for` loop which goes from down to up you may do: ``` for idx in reversed(data.index): print(idx, data.loc[idx, 'Even'], data.loc[idx, 'Odd']) ``` or ``` for idx in reversed(data...