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
Django adaptors CSV taking hours to import
16,004,844
7
2013-04-14T21:56:47Z
16,094,242
7
2013-04-18T22:39:51Z
[ "python", "django" ]
I'm using [Django adaptors](http://django-adaptors.readthedocs.org/en/latest/) to upload a simple CSV. It seems to work perfectly when I'm importing 100 or 200 contacts. But when I try to upload a 165kb file with 5000 contacts, it never completes. I let let it keep trying, and when I came back after 1 hour it was still...
Split up your larger task into smaller pieces. **Step 1 - Just read a CSV file** Both ContactCSVModel.import\_from\_filename() and ContactCSVModel.import\_from\_file() return the csv lines. Disable the interaction with your django model to skip interaction with your database. This should speed up the task considerabl...
Terminating QThread gracefully on QDialog reject()
16,005,075
5
2013-04-14T22:23:49Z
16,005,351
8
2013-04-14T22:59:45Z
[ "python", "multithreading", "qt", "pyqt" ]
I have a QDialog which creates a QThread to do some work while keeping the UI responsive, based on the structure given here: [How To Really, Truly Use QThreads; The Full Explanation](http://mayaposch.wordpress.com/2011/11/01/how-to-really-truly-use-qthreads-the-full-explanation/). However, if reject() is called (due to...
Your problem is: `self.thread` is freed by Python after the dialog is closed or the cancel button is pressed, while Qt thread is still running. To avoid such situation, you can designate a parent to that thread. For example, ``` def run(self): # start the worker thread self.thread = QtCore.QThread...
How do I define a settings.LOGGING so that gunicorn will find the version value it wants?
16,005,245
5
2013-04-14T22:44:17Z
19,107,195
12
2013-10-01T02:54:39Z
[ "python", "django", "gunicorn" ]
I am trying to run Gunicorn, and I am running into an error (pasted below). At present it looks like Gunicorn or one of its dependencies is attempting to read settings.LOGGING, and the settings.py file does not appear to define a settings.LOGGING. So I'd like to know what sort of literal or other code I can add so tha...
I had the same error and I fixed it by adding logging configuration to the project's settings file, I used the example from this page <https://docs.djangoproject.com/en/dev/topics/logging/> here is the code from my settings file ``` LOGGING = { 'version': 1, 'disable_existing_loggers': True, 'formatters'...
How do I define a settings.LOGGING so that gunicorn will find the version value it wants?
16,005,245
5
2013-04-14T22:44:17Z
20,351,080
7
2013-12-03T12:22:14Z
[ "python", "django", "gunicorn" ]
I am trying to run Gunicorn, and I am running into an error (pasted below). At present it looks like Gunicorn or one of its dependencies is attempting to read settings.LOGGING, and the settings.py file does not appear to define a settings.LOGGING. So I'd like to know what sort of literal or other code I can add so tha...
The easiest way is to add in settings.py: ``` LOGGING = { 'version': 1, } ```
plotting different colors in matplotlib
16,006,572
9
2013-04-15T01:58:44Z
16,006,810
9
2013-04-15T02:30:14Z
[ "python", "matplotlib" ]
Suppose I have a for loop and I want to plot points in different colors: ``` for i in range(5): plt.plot(x,y,col=i) ``` How do I automatically change colors in the for loop?
``` for color in ['r', 'b', 'g', 'k', 'm']: plot(x, y, color=color) ```
plotting different colors in matplotlib
16,006,572
9
2013-04-15T01:58:44Z
16,006,929
38
2013-04-15T02:45:38Z
[ "python", "matplotlib" ]
Suppose I have a for loop and I want to plot points in different colors: ``` for i in range(5): plt.plot(x,y,col=i) ``` How do I automatically change colors in the for loop?
@tcaswell already answered, but I was in the middle of typing my answer up, so I'll go ahead and post it... There are a number of different ways you could do this. To begin with, `matplotlib` will automatically cycle through colors. By default, it cycles through blue, green, red, cyan, magenta, yellow, black: ``` imp...
How to organize list by frequency of occurrence and alphabetically (in case of a tie) while eliminating duplicates?
16,006,630
6
2013-04-15T02:08:07Z
16,006,698
14
2013-04-15T02:16:12Z
[ "python", "frequency" ]
Basically if given a list: ``` data = ["apple", "pear", "cherry", "apple", "pear", "apple", "banana"] ``` I'm trying to make a function that returns a list like this: ``` ["apple", "pear", "banana", "cherry"] ``` I'm trying to make the return list ordered by most frequently occurring word first while breaking ties ...
You could do something like this: ``` from collections import Counter data = ["apple", "pear", "cherry", "apple", "pear", "apple", "banana"] counts = Counter(data) words = sorted(counts, key=lambda word: (-counts[word], word)) print words ```
Python: How to hash a string into 8 digits?
16,008,670
17
2013-04-15T06:10:19Z
16,008,760
37
2013-04-15T06:17:59Z
[ "python", "hash" ]
Is there anyway that I can hash a random string into a 8 digit number without implementing any algorithms myself? Thanks.
Yes, you can use the built-in [*hashlib*](http://docs.python.org/2.7/library/hashlib.html#module-hashlib) modules or the built-in [*hash*](http://docs.python.org/2.7/library/functions.html#hash) function. Then, chop-off the last eight digits using modulo operations or string slicing operations on the integer form of th...
use of // in python
16,009,050
3
2013-04-15T06:36:26Z
16,009,110
7
2013-04-15T06:40:05Z
[ "python", "python-2.7", "numpy", "python-3.x", "matplotlib" ]
I am new in python programming. I have come to piece of program in which ``` if (pos.x//1,pos.y//1) not in self.cleaned: self.cleaned.append((pos.x//1,pos.y//1)) ``` is used. It might be silly of me. But can anyone please tell me what the code means. And please tell me the function of "//".
`a // b` is [floor division](http://docs.python.org/2/reference/expressions.html#binary-arithmetic-operations). It's basically `floor(a / b)`, but it preserves the number type.
use of // in python
16,009,050
3
2013-04-15T06:36:26Z
16,009,130
8
2013-04-15T06:40:54Z
[ "python", "python-2.7", "numpy", "python-3.x", "matplotlib" ]
I am new in python programming. I have come to piece of program in which ``` if (pos.x//1,pos.y//1) not in self.cleaned: self.cleaned.append((pos.x//1,pos.y//1)) ``` is used. It might be silly of me. But can anyone please tell me what the code means. And please tell me the function of "//".
It is the explicit floor division operator. ``` 5 // 2 # 2 ``` In Python 2.x and below the `/` would do integer division if both of the operands were integers and would do floating point division if at least one argument was a float. In Python 3.x this was changed, and the `/` operator does floating-point division a...
Django: How to get the root path of a site in template?
16,009,691
6
2013-04-15T07:19:26Z
16,009,916
13
2013-04-15T07:34:46Z
[ "python", "django" ]
I want to design a go back home button for my site and how can I get the root path of my site in the template so I can do something like this: ``` <a href="{{ root_url }}">Go back home</a> ``` Or I should first figure out the path in my views and then pass it to the template to render by some context. Thanks.
I think the proper way here is use the `{% url %}` tag and I'm assuming that you have a root url in your url conf. **urls.py** ``` url(r'^mah_root/$', 'someapp.views.mah_view', name='mah_view'), ``` Then in your template: ``` <a href="{% url mah_view %}">Go back home</a> ```
python: plot a bar using matplotlib using a dictionary
16,010,869
24
2013-04-15T08:34:47Z
16,014,873
48
2013-04-15T12:13:32Z
[ "python", "matplotlib", "plot" ]
Is there any way to plot a bar plot using `matplotlib` using data directly from a dict? My dict looks like this: ``` D = {u'Label1':26, u'Label2': 17, u'Label3':30} ``` I was expecting ``` fig = plt.figure(figsize=(5.5,3),dpi=300) ax = fig.add_subplot(111) bar = ax.bar(D,range(1,len(D)+1,1),0.5) ``` to work, but i...
You can do it in two lines by first plotting the bar chart and then setting the appropriate ticks: ``` import matplotlib.pyplot as plt D = {u'Label1':26, u'Label2': 17, u'Label3':30} plt.bar(range(len(D)), D.values(), align='center') plt.xticks(range(len(D)), D.keys()) plt.show() ``` Note that the penultimate line...
python: plot a bar using matplotlib using a dictionary
16,010,869
24
2013-04-15T08:34:47Z
29,114,698
11
2015-03-18T05:25:27Z
[ "python", "matplotlib", "plot" ]
Is there any way to plot a bar plot using `matplotlib` using data directly from a dict? My dict looks like this: ``` D = {u'Label1':26, u'Label2': 17, u'Label3':30} ``` I was expecting ``` fig = plt.figure(figsize=(5.5,3),dpi=300) ax = fig.add_subplot(111) bar = ax.bar(D,range(1,len(D)+1,1),0.5) ``` to work, but i...
For future reference, the above code does not work with Python 3. For Python 3, the D.keys() needs to be converted to a list. ``` import matplotlib.pyplot as plt D = {u'Label1':26, u'Label2': 17, u'Label3':30} plt.bar(range(len(D)), D.values(), align='center') plt.xticks(range(len(D)), list(D.keys())) plt.show() ``...
how to use "/" (directory separator) in both Linux and Windows?
16,010,992
52
2013-04-15T08:42:12Z
16,011,057
14
2013-04-15T08:45:32Z
[ "python", "linux", "windows", "unix" ]
I have written a code in python which uses / to make a particular file in a folder, if I want to use the code in windows it will not work, is there a way by which I can use the code in Windows and Linux. In python I am using this command: ``` pathfile=os.path.dirname(templateFile) rootTree.write(''+pathfile+'/output/...
You can use [os.sep](http://docs.python.org/3.3/library/os.html?highlight=os.sep#os.sep): ``` >>> import os >>> os.sep '/' ```
how to use "/" (directory separator) in both Linux and Windows?
16,010,992
52
2013-04-15T08:42:12Z
16,011,083
32
2013-04-15T08:47:19Z
[ "python", "linux", "windows", "unix" ]
I have written a code in python which uses / to make a particular file in a folder, if I want to use the code in windows it will not work, is there a way by which I can use the code in Windows and Linux. In python I am using this command: ``` pathfile=os.path.dirname(templateFile) rootTree.write(''+pathfile+'/output/...
Use: ``` import os print os.sep ``` to see how separator looks on a current OS. In your code you can use: ``` import os path = os.path.join('folder_name', 'file_name') ```
how to use "/" (directory separator) in both Linux and Windows?
16,010,992
52
2013-04-15T08:42:12Z
16,011,098
81
2013-04-15T08:48:03Z
[ "python", "linux", "windows", "unix" ]
I have written a code in python which uses / to make a particular file in a folder, if I want to use the code in windows it will not work, is there a way by which I can use the code in Windows and Linux. In python I am using this command: ``` pathfile=os.path.dirname(templateFile) rootTree.write(''+pathfile+'/output/...
Use `os.path.join()`. Example: `os.path.join(pathfile,"output","log.txt")`. In your code that would be: `rootTree.write(os.path.join(pathfile,"output","log.txt"))`
How to avoid global variables
16,011,056
7
2013-04-15T08:45:31Z
16,011,147
10
2013-04-15T08:51:24Z
[ "python", "global-variables" ]
when reading python documentation and various mailing lists I always read what looks a little bit like a dogma. Global variables should be avoided like hell, they are poor design ... OK, why not ? But there are some real lifes situation where I do not how to avoid such a pattern. Say that I have a GUI from which sever...
Global variables should be avoided because they inhibit code reuse. Multiple widgets/applications can nicely live within the same main loop. This allows you to abstract what you now think of as a single GUI into a library that creates such GUI on request, so that (for instance) a single launcher can launch multiple top...
Counting the amount of occurences in a list of tuples
16,013,485
9
2013-04-15T10:59:41Z
16,013,517
14
2013-04-15T11:01:27Z
[ "python", "list", "tuples", "counting" ]
I am fairly new to python, but I haven't been able to find a solution to my problem anywhere. I want to count the occurences of a string inside a list of tuples. Here is the list of tuples: ``` list1 = [ ('12392', 'some string', 'some other string'), ('12392', 'some new string', 'some other string'...
Maybe [`collections.Counter`](http://docs.python.org/2/library/collections.html#collections.Counter) could solve your problem: ``` from collections import Counter Counter(elem[0] for elem in list1) ``` returns ``` Counter({'12392': 2, '7862': 1}) ``` It is fast since it iterates over your list just once. You iterat...
Adding a jQuery script to the Django admin interface
16,014,719
8
2013-04-15T12:04:37Z
16,014,827
20
2013-04-15T12:10:51Z
[ "jquery", "python", "django", "admin" ]
I'm gonna slightly simplify the situation. Let's say I've got a model called Lab. ``` from django.db import models class Lab(models.Model): acronym = models.CharField(max_length=20) query = models.TextField() ``` The field `query` is nearly always the same as the field `acronym`. Thus, I'd like the `query` f...
To add media to the admin you can simply add it to the meta class Media of your admin class, e.g.: **admin.py** ``` class FooAdmin(admin.ModelAdmin): # regular stuff class Media: js = ( '//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js', # jquery 'js/myscript.js', ...
In what way is grequests asynchronous?
16,015,749
20
2013-04-15T12:57:57Z
16,016,635
32
2013-04-15T13:38:05Z
[ "python", "python-requests", "gevent" ]
I've been using the python requests library for some time, and recently had a need to make a request asynchronously, meaning I would like to send off the HTTP request, have my main thread continue to execute, and have a callback called when the request returns. Naturally, I was lead to the grequests library (<https://...
`.map()` is meant to run retrieval of several URLs in parallel, and will indeed wait for these tasks to complete (`gevent.joinall(jobs)`) is called). Use `.send()` instead to spawn jobs, using a [`Pool` instance](http://www.gevent.org/gevent.pool.html#gevent.pool.Pool): ``` req = grequests.get('http://www.codehenge.n...
Django: How to get a time difference from the time post?
16,016,002
5
2013-04-15T13:09:14Z
16,016,130
16
2013-04-15T13:15:53Z
[ "python", "django", "datetime", "django-models" ]
Say I have a class in model ``` class Post(models.Model): time_posted = models.DateTimeField(auto_now_add=True, blank=True) def get_time_diff(self): timediff = timediff = datetime.datetime.now() - self.time_posted print timediff # this line is never executed return timediff ``` ...
Your code is already working; a [`datetime.timedelta` object](http://docs.python.org/2/library/datetime.html#datetime.timedelta) is returned. To get the total number of *seconds* instead, you need to call the [`.total_seconds()` method](http://docs.python.org/2/library/datetime.html#datetime.timedelta.total_seconds) o...
Django: openpyxl saving workbook as attachment
16,016,039
12
2013-04-15T13:11:07Z
16,016,944
23
2013-04-15T13:50:36Z
[ "python", "django", "excel", "xlsx", "openpyxl" ]
Hi I have a quick question. I didn't find answer in internet maybe someone of you can help me. So i want to save workbook as attachment but I don't know how lets see an example : ``` from openpyxl import Workbook from openpyxl.cell import get_column_letter wb = Workbook(encoding='utf-8') dest_filename...
Give it a try: ``` from openpyxl.writer.excel import save_virtual_workbook ... response = HttpResponse(save_virtual_workbook(wb), content_type='application/vnd.ms-excel') ``` `save_virtual_workbook` was specially designed for your use case. Here's a docstring: > """Return an in-memory workbook, suitable for a Django...
Using pySerial with Python 3.3
16,017,288
8
2013-04-15T14:05:27Z
16,054,617
10
2013-04-17T07:59:51Z
[ "python", "pyserial", "python-3.3" ]
I've seen many code samples using the serial port and people say they are working codes too. The thing is, when I try the code it doesn't work. ``` import serial ser = serial.Serial( port=0, baudrate=9600 # parity=serial.PARITY_ODD, # stopbits=serial.STOPBITS_TWO, # bytesize=serial.SEVENBITS ) se...
So the moral of the story is.. the port is opened when initialized. `ser.open()` fails because the serial port is already opened by the `ser = serial.Serial(.....)`. And that is one thing. The other problem up there is `ser.write(0xAA)` - I expected this to mean "send one byte 0xAA", what it actually did was send 170(...
When are parentheses required around a tuple?
16,017,811
31
2013-04-15T14:31:31Z
16,018,059
31
2013-04-15T14:40:52Z
[ "python", "syntax", "tuples" ]
Is there a reference somewhere defining precisely when enclosing tuples with parentheses is or is not required? Here is an example that surprised me recently: ``` >>> d = {} >>> d[0,] = 'potato' >>> if 0, in d: File "<stdin>", line 1 if 0, in d: ^ SyntaxError: invalid syntax ```
The combining of expressions to create a tuple using the comma token is termed an [`expression_list`](http://docs.python.org/3/reference/expressions.html#expression-lists). The rules of [operator precedence](http://docs.python.org/3/reference/expressions.html#operator-precedence) do not cover expression lists; this is ...
When are parentheses required around a tuple?
16,017,811
31
2013-04-15T14:31:31Z
16,018,082
10
2013-04-15T14:41:43Z
[ "python", "syntax", "tuples" ]
Is there a reference somewhere defining precisely when enclosing tuples with parentheses is or is not required? Here is an example that surprised me recently: ``` >>> d = {} >>> d[0,] = 'potato' >>> if 0, in d: File "<stdin>", line 1 if 0, in d: ^ SyntaxError: invalid syntax ```
Anywhere you are allowed to use the [`expression_list`](http://docs.python.org/2/reference/expressions.html#expression-lists) term, you do not need to use parenthesis. The [`if` statement](http://docs.python.org/2/reference/compound_stmts.html#the-if-statement) requires an `expression`, and does not support an `expres...
How to implement a timeout control for urlllib2.urlopen
16,018,007
2
2013-04-15T14:39:13Z
16,018,206
8
2013-04-15T14:47:08Z
[ "python", "timer", "timeout", "urllib2" ]
How to implement a controlling for urlllib2.urlopen in Python ? I just wanna monitor that if in 5 seconds no xml data return, cut this connection and connect again? Should I use some timer? thx
``` urllib2.urlopen("http://www.example.com", timeout=5) ```
Heroku app runs locally but gets H12 timeout error (uses a package)
16,020,749
3
2013-04-15T17:00:23Z
16,025,879
10
2013-04-15T22:43:47Z
[ "python", "heroku", "flask", "gunicorn" ]
Similar questions have been asked but the H12 seems to be caused by many things and none of the answers apply here. I have built python apps with heroku before but now I'm using a package structure per Miguel Grinberg's [Flask Mega-Tutorial](http://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-i-hello-world...
The issue is that `run.py` unguardedly calls `app.run` - this actually calls `werkzeug.serving.run_simple` which starts a sub-process to handle incoming requests ... which you don't want to do when running under gunicorn (since gunicorn will handle the process management for you). Simply add an `if __name__ == "__main...
Inline CSV File Editing with Python
16,020,858
11
2013-04-15T17:08:16Z
16,020,923
25
2013-04-15T17:12:12Z
[ "python", "csv", "file-io" ]
Can I modify a CSV file inline using Python's CSV library, or similar technique? Current I am processing a file and updating the first column (a name field) to change the formatting. A simplified version of my code looks like this: ``` with open('tmpEmployeeDatabase-out.csv', 'w') as csvOutput: writer = csv.write...
No, you should not attempt to write to the file you are currently reading from. You *can* do it if you keep `seek`ing back after reading a row but it is not advisable, especially if you are writing back more data than you read. The canonical method is to write to a *new, temporary* file and move that into place over t...
Python: Best way to check if list is empty without not?
16,021,096
11
2013-04-15T17:22:53Z
16,021,135
37
2013-04-15T17:24:53Z
[ "python", "list", "is-empty" ]
How can I find out if a list is empty without using the not command? Here is what I tried: ``` if list3[0] == []: print "No matches found" else: print list3 ``` I am very much a beginner so excuse me if I do dumb mistakes.
In order of preference: ``` # Good if not list3: # Okay if len(list3) == 0: # Ugly if list3 == []: # Silly try: next(iter(list3)) # list has elements except StopIteration: # list is empty ``` If you have both an if and an else you might also re-order the cases: ``` if list3: # list has elements el...
iterating quickly through list of tuples
16,021,571
14
2013-04-15T17:50:03Z
16,021,600
12
2013-04-15T17:51:23Z
[ "python" ]
I wonder whether there's a quicker and less time consuming way to iterate over a list of tuples, finding the right match. What I do is: ``` # this is a very long list. my_list = [ (old1, new1), (old2, new2), (old3, new3), ... (oldN, newN)] # go through entire list and look for match for j in my_list: if j[0] == V...
I think that you can use ``` for j,k in my_list: [ ... stuff ... ] ```
iterating quickly through list of tuples
16,021,571
14
2013-04-15T17:50:03Z
16,021,667
12
2013-04-15T17:55:02Z
[ "python" ]
I wonder whether there's a quicker and less time consuming way to iterate over a list of tuples, finding the right match. What I do is: ``` # this is a very long list. my_list = [ (old1, new1), (old2, new2), (old3, new3), ... (oldN, newN)] # go through entire list and look for match for j in my_list: if j[0] == V...
Assuming a bit more memory usage is not a problem and if the first item of your tuple is hashable, you can create a [dict](http://docs.python.org/2/tutorial/datastructures.html#dictionaries) out of your list of tuples and then looking up the value is as simple as looking up a key from the `dict`. Something like: ``` d...
Using pandas to read text file with leading whitespace gives a NaN column
16,022,094
9
2013-04-15T18:19:23Z
16,022,930
12
2013-04-15T19:06:34Z
[ "python", "python-2.7", "pandas" ]
I am using pandas.read\_csv to read a whitespace delimited file. The file has a variable number of whitespace characters in front of every line (the numbers are right-aligned). When I read this file, it creates a column of NaN. Why does this happen, and what is the best way to prevent it? Example: Text file: ``` 9...
FWIW I tend to use `\s+` instead, and it doesn't suffer the same problem: ``` >>> pd.read_csv("wspace.csv", header=None, delim_whitespace=True) 0 1 2 3 0 NaN 9.0 3.3 4.0 1 NaN 32.3 44.3 5.1 2 NaN 7.2 1.1 0.9 >>> pd.read_csv("wspace.csv", header=None, sep=r"\s+") 0 1 2 0 9.0 ...
Selenium Desired Capabilities - set handlesAlerts for PhantomJS driver
16,022,226
11
2013-04-15T18:27:29Z
16,034,243
11
2013-04-16T10:07:34Z
[ "python", "selenium", "phantomjs" ]
I'm trying out phantomJS with webdriver and I'm having trouble with handling javascript alerts. I notice the phantomjs driver desired\_capabilities has a field `'handlesAlerts': False` Is there a way to set this value to true? I've tried the obvious way but that doesn't have any effect: ``` drv = webdriver.PhantomJS(d...
The API specifies that desired capabilities be passed into the constructor. However, it may be the case that a driver does not support a feature requested in the desired capabilities. In that case, no error is thrown by the driver, and this is intentional. A capabilities object is returned by the session which indicate...
Has Python 3.2 to_bytes been back-ported to python 2.7?
16,022,556
6
2013-04-15T18:45:33Z
16,022,768
8
2013-04-15T18:57:16Z
[ "python" ]
This is the function I'm after: - <http://docs.python.org/3.2/library/stdtypes.html#int.to_bytes> I need big endianness support.
To answer your original question, the `to_bytes` method for `int` objects was not back ported to Python 2.7 from Python 3. It was considered but ultimately rejected. See the discussion [here](http://bugs.python.org/issue1023290).
Has Python 3.2 to_bytes been back-ported to python 2.7?
16,022,556
6
2013-04-15T18:45:33Z
20,793,663
10
2013-12-27T01:51:13Z
[ "python" ]
This is the function I'm after: - <http://docs.python.org/3.2/library/stdtypes.html#int.to_bytes> I need big endianness support.
Based on the answer from @nneonneo, here is a function that emulates the to\_bytes API: ``` def to_bytes(n, length, endianess='big'): h = '%x' % n s = ('0'*(len(h) % 2) + h).zfill(length*2).decode('hex') return s if endianess == 'big' else s[::-1] ```
'backwards' enumerate
16,023,390
4
2013-04-15T19:35:57Z
16,023,436
13
2013-04-15T19:38:49Z
[ "python" ]
Is there a way to get a generator/iterator that yields the reverse of `enumerate`: ``` from itertools import izip, count enumerate(I) # -> (indx, v) izip(I, count()) # -> (v, indx) ``` without pulling in `itertools`?
You can do this with a simple [generator expression](http://www.youtube.com/watch?v=pShL9DCSIUw): ``` ((v, i) for i, v in enumerate(some_iterable)) ``` Here as a list comprehension to easily see the output: ``` >>> [(v, i) for i, v in enumerate(["A", "B", "C"])] [('A', 0), ('B', 1), ('C', 2)] ```
'backwards' enumerate
16,023,390
4
2013-04-15T19:35:57Z
16,023,439
11
2013-04-15T19:39:06Z
[ "python" ]
Is there a way to get a generator/iterator that yields the reverse of `enumerate`: ``` from itertools import izip, count enumerate(I) # -> (indx, v) izip(I, count()) # -> (v, indx) ``` without pulling in `itertools`?
``` ((v, indx) for indx, v in enumerate(I)) ``` if you really want to avoid `itertools`. Why would you?
Download file as string in python
16,025,368
4
2013-04-15T21:57:39Z
16,025,389
8
2013-04-15T21:59:14Z
[ "python", "string", "file", "python-3.x", "download" ]
I want to download a file to python as a string. I have tried the following, but it doesn't seem to work. What am I doing wrong, or what else might I do? ``` from urllib import request webFile = request.urlopen(url).read() print(webFile) ```
I would recommend that you use [urllib2](http://docs.python.org/2/library/urllib2.html) instead. ``` import urllib2 url = 'http://www.google.se' output = urllib2.urlopen(url).read() print(output) ``` Alternatively, you could use [requests](http://docs.python-requests.org/en/latest/index.html) which provides a more h...
What is the right way to put a docstring on Python property?
16,025,462
21
2013-04-15T22:04:31Z
16,025,754
20
2013-04-15T22:30:20Z
[ "python", "properties", "decorator" ]
Should I make several docstrings, or just one (and where should I put it)? ``` @property define x(self): return 0 @x.setter define x(self, values): pass ``` I see that `property()` accepts a doc argument.
Write the docstring on the getter, because 1) that's what `help(MyClass)` shows, and 2) it's also how it's done in the [Python docs -- see the x.setter example](http://docs.python.org/2/library/functions.html#property). Regarding 1): ``` class C(object): @property def x(self): """Get x""" retu...
Making the eyeD3-module available for import in python
16,025,662
2
2013-04-15T22:22:37Z
16,025,847
7
2013-04-15T22:40:29Z
[ "python", "windows", "eyed3" ]
On Windows, I have installed Python 2.7 and added *python.exe's* directory to PATH. Then I installed *pip* und used `pip install eyeD3` to install the eyeD3 module successfully. However, using `import eyeD3` doesn't work, but throws an `ImportError`. I had the idea to adjust the `PYTHONPATH`-environment-variable in my ...
try `import eyed3` (without capital D)
Why does pip fail with bad md5 hash for package?
16,025,788
15
2013-04-15T22:33:57Z
16,025,887
13
2013-04-15T22:44:54Z
[ "python", "django", "hash", "virtualenv", "pypi" ]
I'm trying to install Django package in a virtualenv. I'm on a new computer (OSX 10.8.2). I installed virtualenv via easy\_install. With the virtualenv activated, I ran: ``` (pyenv)$ pip install Django Downloading/unpacking Django Downloading Django-1.5.1.tar.gz (8.0MB): 2.0MB downloaded Hash of the package https:...
If it's just this package that you can't get to install, you could download the tarball manually, and then use pip to install it from that file. The [Django download site](https://www.djangoproject.com/download/) has checksums that you can validate manually as well. I don't use osx, but probably something like this wou...
Why does pip fail with bad md5 hash for package?
16,025,788
15
2013-04-15T22:33:57Z
31,827,160
8
2015-08-05T08:24:08Z
[ "python", "django", "hash", "virtualenv", "pypi" ]
I'm trying to install Django package in a virtualenv. I'm on a new computer (OSX 10.8.2). I installed virtualenv via easy\_install. With the virtualenv activated, I ran: ``` (pyenv)$ pip install Django Downloading/unpacking Django Downloading Django-1.5.1.tar.gz (8.0MB): 2.0MB downloaded Hash of the package https:...
I have the same problem when I try `sudo pip install Pillow`, and I try `sudo pip install --no-cache-dir Pillow`, it works for me.
Generator functions in R
16,028,374
11
2013-04-16T03:41:44Z
16,028,448
10
2013-04-16T03:49:11Z
[ "python", "python-3.x", "generator" ]
Is there a package or language construct in R that facilitates or provides the implementation of "[Python-like generators](http://docs.python.org/3/tutorial/classes.html#generators)"? By "Python-like generators" I mean functions that keep state between calls, in R syntax and borrowing the keyword **yield** from Python...
The `iterators` package has this functionality ``` library(iterators) abc <- iter(c('a','b','c')) nextElem(abc) ## [1] "a" nextElem(abc) ## [1] "b" nextElem(abc) ## [1] "c" ``` Or you could use `lambda.r` and `<<-`. This example is modified from <http://cartesianfaith.wordpress.com/2013/01/05/infinite-generators-in-...
How to run os.mkdir() with -p option in Python?
16,029,871
6
2013-04-16T06:05:50Z
16,029,908
15
2013-04-16T06:08:22Z
[ "python", "mkdir" ]
I want to run `mkdir` command as: ``` mkdir -p directory_name ``` What's the method to do that in Python? ``` os.mkdir(directory_name [, -p]) didn't work for me. ```
You can try this: ``` # top of the file import os import errno # the actual code try: os.makedirs(directory_name) except OSError as exc: if exc.errno == errno.EEXIST and os.path.isdir(path): pass else: raise ```
How to run os.mkdir() with -p option in Python?
16,029,871
6
2013-04-16T06:05:50Z
16,029,919
10
2013-04-16T06:09:07Z
[ "python", "mkdir" ]
I want to run `mkdir` command as: ``` mkdir -p directory_name ``` What's the method to do that in Python? ``` os.mkdir(directory_name [, -p]) didn't work for me. ```
Something like this: ``` if not os.path.exists(directory_name): os.makedirs(directory_name) ``` UPD: as it is said in a comments you need to check for exception for thread safety ``` try: os.makedirs(directory_name) except OSError as err: if err.errno!=17: raise ```
How to re-assign items in a list in Python?
16,030,891
3
2013-04-16T07:11:59Z
16,030,937
7
2013-04-16T07:14:58Z
[ "python", "list", "iteration" ]
I want to re-assign each item in a list in Python. ``` In [20]: l = [1,2,3,4,5] In [21]: for i in l: ....: i = i + 1 ....: ....: ``` But the list didn't change at all. ``` In [22]: l Out[22]: [1, 2, 3, 4, 5] ``` I want to know why this happened. Could any body explain the list iterating in detail?...
You can't do it like that, you are merely changing the value binded to the name `i`. On each iteration of the `for` loop, `i` is binded to a value in the list. It is not a pointer in the sense that by changing the value of `i` you are changing a value in the list. Instead, as I said before, it is simply a name and you ...
How to form tuple column from two columns in Pandas
16,031,056
21
2013-04-16T07:21:52Z
16,033,048
14
2013-04-16T09:13:01Z
[ "python", "dataframe", "pandas", "tuples" ]
I've got a Pandas DataFrame and I want to combine the 'lat' and 'long' columns to form a tuple. ``` <class 'pandas.core.frame.DataFrame'> Int64Index: 205482 entries, 0 to 209018 Data columns: Month 205482 non-null values Reported by 205482 non-null values Falls within 205482 non-null values Easting...
``` In [10]: df Out[10]: A B lat long 0 1.428987 0.614405 0.484370 -0.628298 1 -0.485747 0.275096 0.497116 1.047605 2 0.822527 0.340689 2.120676 -2.436831 3 0.384719 -0.042070 1.426703 -0.634355 4 -0.937442 2.520756 -1.662615 -1.377490 5 -0.154816 0.617671 -0.090484 -0.191906 6...
How to form tuple column from two columns in Pandas
16,031,056
21
2013-04-16T07:21:52Z
16,068,497
27
2013-04-17T19:24:48Z
[ "python", "dataframe", "pandas", "tuples" ]
I've got a Pandas DataFrame and I want to combine the 'lat' and 'long' columns to form a tuple. ``` <class 'pandas.core.frame.DataFrame'> Int64Index: 205482 entries, 0 to 209018 Data columns: Month 205482 non-null values Reported by 205482 non-null values Falls within 205482 non-null values Easting...
Get comfortable with `zip`. It comes in handy when dealing with column data. ``` df['new_col'] = zip(df.lat, df.long) ``` It's less complicated and faster than using `apply` or `map`. Something like `np.dstack` is twice as fast as `zip`, but wouldn't give you tuples.
Using an asynchronous warning source for CodeMirror's lint feature
16,031,072
8
2013-04-16T07:22:55Z
16,031,073
14
2013-04-16T07:22:55Z
[ "javascript", "python", "ajax", "syntax-highlighting", "codemirror" ]
The examples only show how to implement the JSON and Javascript lint addons with CodeMirror (syntax-highlighting Javascript-based editor), which are synchronous. Unfortunately, there aren't Javascript-based parsers/lint'ers readily available for most languages. I'd like to implement my own linter for Python. Unfortuna...
Sure there is. A quick look through the contents of the last version of remoting-lint.js (<https://github.com/marijnh/CodeMirror/commit/27f097ed75561e846bdb955f13f8dd2bcf0b589e>) shows that it was little more than a jQuery AJAX request, which invokes a callback provided to the function as a parameter. This callback wil...
Function inside function - every time?
16,031,092
25
2013-04-16T07:24:16Z
16,031,125
9
2013-04-16T07:26:06Z
[ "python", "performance", "closures", "nested-function" ]
Let we have this code: ``` def big_function(): def little_function(): ....... ......... ``` The Python documentation says about `def` statement: > A function definition is an executable statement. Its execution binds > the function name... So, the question is: Does `def little_function()` execute e...
The code in the inner function is compiled only once, so there shouldn't be a significant runtime penalty. Only inner's function *closure* gets updated each time the outer function is called. See [here](http://ynniv.com/blog/2007/08/closures-in-python.html), for example, for more details about closures. Here's a quic...
Function inside function - every time?
16,031,092
25
2013-04-16T07:24:16Z
16,031,170
30
2013-04-16T07:29:00Z
[ "python", "performance", "closures", "nested-function" ]
Let we have this code: ``` def big_function(): def little_function(): ....... ......... ``` The Python documentation says about `def` statement: > A function definition is an executable statement. Its execution binds > the function name... So, the question is: Does `def little_function()` execute e...
You can check the bytecode with the `dis` module: ``` >>> import dis >>> def my_function(): ... def little_function(): ... print "Hello, World!" ... ... >>> dis.dis(my_function) 2 0 LOAD_CONST 1 (<code object little_function at 0xb74ef9f8, file "<stdin>", line 2>) ...
Python extract sentence containing word
16,032,832
6
2013-04-16T09:03:12Z
16,032,922
14
2013-04-16T09:07:14Z
[ "python", "regex", "text-segmentation" ]
I am trying to extract all the sentence containing a specified word from a text. ``` txt="I like to eat apple. Me too. Let's go buy some apples." txt = "." + txt re.findall(r"\."+".+"+"apple"+".+"+"\.", txt) ``` but it is returning me : ``` [".I like to eat apple. Me too. Let's go buy some apples."] ``` instead of ...
No need for regex: ``` >>> txt = "I like to eat apple. Me too. Let's go buy some apples." >>> [sentence + '.' for sentence in txt.split('.') if 'apple' in sentence] ['I like to eat apple.', " Let's go buy some apples."] ```
How to override the slice functionality of list in its derived class
16,033,017
9
2013-04-16T09:11:45Z
16,033,058
21
2013-04-16T09:13:28Z
[ "python", "list", "override" ]
I make a class like below: ``` class MyList(list): def __init__(self, lst): self.list = lst ``` I want slice functionality to be overridden in MyList
You need to provide custom [`__getitem__()`](http://docs.python.org/2/reference/datamodel.html#object.__getitem__), [`__setitem__`](http://docs.python.org/2/reference/datamodel.html#object.__setitem__) and [`__delitem__`](http://docs.python.org/2/reference/datamodel.html#object.__delitem__) hooks. These are passed a [...
How do numpy's in-place operations (e.g. `+=`) work?
16,034,672
11
2013-04-16T10:26:28Z
16,035,329
10
2013-04-16T10:59:41Z
[ "python", "numpy" ]
The basic question is: What happens under the hood when doing: `a[i] += b`? Given the following: ``` import numpy as np a = np.arange(4) i = a > 0 i = array([False, True, True, True], dtype=bool) ``` I understand that: * `a[i] = x` is the same as `a.__setitem__(i, x)`, which assigns directly to the items indicat...
The first thing you need to realise is that `a += x` doesn't map exactly to `a.__iadd__(x)`, instead it maps to `a = a.__iadd__(x)`. Notice that the [documentation](http://docs.python.org/3.3/reference/datamodel.html#object.__iadd__) specifically says that in-place operators return their result, and this doesn't have t...
details of /proc/net/ip_conntrack / nf_conntrack
16,034,698
9
2013-04-16T10:27:41Z
16,197,923
19
2013-04-24T16:59:28Z
[ "python", "linux", "kernel" ]
I'm looking for a detailed documentation about content of files /proc/net/nf\_conntrack and/or /proc/net/ip\_contrack on linux systems. Yes, I know, there are many utilites which can show me the content of these files in human readable format, but... I'd like to do it on a SOHO router, with Tomato USB firmware (by Shi...
The format of a line from `/proc/net/ip_conntrack` is the same as for `/proc/net/nf_conntrack`, except the first two columns are missing. I'll try to summarize the format of the latter file, as I understand it from the [`net/netfilter/nf_conntrack_standalone.c`](https://git.kernel.org/cgit/linux/kernel/git/torvalds/li...
Python code. Is it comma operator?
16,037,494
13
2013-04-16T12:48:22Z
16,037,517
20
2013-04-16T12:49:39Z
[ "python", "matplotlib", "tuples" ]
I don't understand what does comma after variable **lines,** means: <http://matplotlib.org/examples/animation/simple_anim.html> ``` line, = ax.plot(x, np.sin(x)) ``` If I remove comma and variable "line," becomes variable "line" then program is broken. Full code from url given above: ``` import numpy as np import ma...
`ax.plot()` returns a *tuple* with *one* element. By adding the comma to the assignment target list, you ask Python to unpack the return value and assign it to each variable named to the left in turn. Most often, you see this being applied for functions with more than one return value: ``` base, ext = os.path.splitex...
simplest possible way git can output the number of commits between "branch" and "remotes/origin/branch"
16,037,623
5
2013-04-16T12:53:58Z
16,041,978
12
2013-04-16T16:12:16Z
[ "python", "git" ]
I'm working with custom a build system that manages a large number of git repositories and written primarily in python. It would save me a lot of time if I could write a command that would report the current branch of all repositories, then report if the head of "branch" is the same as the head of "remotes/origin/bran...
If you have a new enough version of git, you can use: ``` $ git rev-list --count --left-right branch...origin/branch 2 1 ``` The first number if the number of commits `branch` is ahead of `origin/branch`, and the second is the number of commits behind. So this branch has two commits that are not upstream yet, and t...
Mutability of the **kwargs argument in Python
16,039,280
7
2013-04-16T14:06:27Z
16,039,299
12
2013-04-16T14:07:07Z
[ "python", "dictionary", "immutability" ]
Consider a case where I change the `kwargs` dict inside a method: ``` def print_arg(**kwargs): print kwargs.pop('key') ``` If I call the method `pop_arg` with a dictionary like this: ``` mydict = {'key':'value'} print_arg(**mydict) ``` will `mydict` be changed by this call? I am also interested in a more detai...
No, `mydict` won't be changed. kwargs get unpacked into a new dictionary. Consider the case where you have: ``` def print_arg(key=1,**kwargs): print key print kwargs print_arg(**{'key':2,'foo':3,'bar':4}) ``` In this case, it's obvious that kwargs is a different dict than you pass in because when it gets un...
Call external function without sending 'self' arg
16,039,459
5
2013-04-16T14:14:15Z
16,039,505
9
2013-04-16T14:16:06Z
[ "python" ]
I'm writing tests for a Django application and using a attribute on my test class to store which view it's supposed to be testing, like this: ``` # IN TESTS.PY class OrderTests(TestCase, ShopTest): _VIEW = views.order def test_gateway_answer(self): url = 'whatever url' request = self.request_f...
This happens because in Python functions are [*descriptors*](http://docs.python.org/dev/reference/datamodel.html#invoking-descriptors), so when they are accessed on class instances they bind their first (assumed `self`) parameter to the instance. You could access `_VIEW` on the class, not on the instance: ``` class O...
Understanding celery task prefetching
16,040,039
31
2013-04-16T14:42:30Z
16,061,666
13
2013-04-17T13:40:36Z
[ "python", "celery", "celeryd" ]
I just found out about the configuration option `CELERYD_PREFETCH_MULTIPLIER` ([docs](http://docs.celeryproject.org/en/latest/configuration.html#std%3asetting-CELERYD_PREFETCH_MULTIPLIER)). The default is 4, but (I believe) I want the prefetching off or as low as possible. I set it to 1 now, which is close enough to wh...
1. Prefetching can improve the performance. Workers don't need to wait for the next message from a broker to process. Communicating with a broker once and processing a lot of messages gives a performance gain. Getting a message from a broker (even from a local one) is expensive compared to the local memory access. Work...
Understanding celery task prefetching
16,040,039
31
2013-04-16T14:42:30Z
33,357,180
8
2015-10-26T23:07:59Z
[ "python", "celery", "celeryd" ]
I just found out about the configuration option `CELERYD_PREFETCH_MULTIPLIER` ([docs](http://docs.celeryproject.org/en/latest/configuration.html#std%3asetting-CELERYD_PREFETCH_MULTIPLIER)). The default is 4, but (I believe) I want the prefetching off or as low as possible. I set it to 1 now, which is close enough to wh...
Just a warning: as of my testing with the redis broker + Celery 3.1.15, all of the advice I've read pertaining to `CELERYD_PREFETCH_MULTIPLIER = 1` disabling prefetching is demonstrably false. To demonstrate this: 1. Set `CELERYD_PREFETCH_MULTIPLIER = 1` 2. Queue up 5 tasks that will each take a few seconds (ex, `tim...
Rearrange tuple of tuples in Python
16,040,156
6
2013-04-16T14:47:24Z
16,040,205
12
2013-04-16T14:49:49Z
[ "python", "tuples", "transpose" ]
I have a tuple of tuples: ``` t = ((1, 'one'), (2, 'two')) ``` I need it in the following format: ``` ((1, 2), ('one', 'two')) ``` How can I convert it? I can do something like: ``` digits = tuple ( digit for digit, word in t ) words = tuple ( word for digit, word in t ) rearranged = tuple ( digits, wo...
Use the following: ``` tuple(zip(*t)) ```
Python class __init__ layout?
16,040,784
4
2013-04-16T15:17:32Z
16,040,971
11
2013-04-16T15:25:34Z
[ "python", "class", "init" ]
In python, is it bad form to write an `__init__` definition like: ``` class someFileType(object): def __init__(self, path): self.path = path self.filename = self.getFilename() self.client = self.getClient() self.date = self.getDate() self.title = self.getTitle() self...
Nope, I don't see why that would be bad form. Calculating those values only once when the instance is created can be a great idea, in fact. You could also postpone the calculations until needed by using caching `property`s: ``` class SomeFileType(object): _filename = None _client = None def __init__(self...
Python: convert list to generator
16,041,405
8
2013-04-16T15:45:29Z
16,041,523
10
2013-04-16T15:50:48Z
[ "python" ]
say I have a list ``` data = [] data.append("A") data.append("B") data.append("C") data.append("D") ``` How do I convert this one to a generator type ? Any help with a sample code is highly appreciated... Found an URL <http://eli.thegreenplace.net/2012/04/05/implementing-a-generatoryield-in-a-pyt...
``` >>> (n for n in [1,2,3,5]) <generator object <genexpr> at 0x02A52940> ``` works in Python 2.7.4+ ``` >>> a2g = lambda x : (n for n in x) >>> a2g([1,2,3,4,5]) <generator object <genexpr> at 0x02A57CD8> ``` Edit: One more slight variation of a lambda generator factory pattern ``` >>> a2g = lambda *args: (n for n...
How to force an exception in django in order to test it in django
16,042,762
3
2013-04-16T16:54:34Z
16,043,392
8
2013-04-16T17:31:35Z
[ "python", "django", "unit-testing", "exception", "mocking" ]
I've really searched for how to patch Whatever.objects.get\_or\_create, but I can't get any suggestion or idea how to do it. Well, my problem is that I have something like this: ``` def create_and_get_object( name, request, save_url=True, data=None): try: (object_type_, created) = Object.objects.get_...
I like to use python's `with` statement with mock's [patch.object](http://www.voidspace.org.uk/python/mock/patch.html#patch-object). In your case it should be smth like this: ``` from mock import patch from django.test import TestCase from django.db.models.manager import Manager from anothermodule import create_and_ge...
Python: Passing variables between functions
16,043,797
13
2013-04-16T17:54:40Z
16,043,933
13
2013-04-16T18:00:39Z
[ "python", "function", "arguments" ]
I've spent the past few hours reading around in here and elsewhere, as well as experimenting, but I'm not really understanding what I am sure is a very basic concept: passing values (as variables) between different functions. For example, I assign a whole bunch of values to a list in one function, then want to use tha...
This is what is actually happening: ``` global_list = [] def defineAList(): local_list = ['1','2','3'] print "For checking purposes: in defineAList, list is", local_list return local_list def useTheList(passed_list): print "For checking purposes: in useTheList, list is", passed_list def main(): ...
Python - re.findall returns unwanted result
16,045,643
5
2013-04-16T19:39:14Z
16,045,719
9
2013-04-16T19:43:21Z
[ "python", "regex", "findall" ]
``` re.findall("(100|[0-9][0-9]|[0-9])%", "89%") ``` This returns only result `[89]` and I need to return the whole 89%. Any ideas how to do it please?
``` >>> re.findall("(?:100|[0-9][0-9]|[0-9])%", "89%") ['89%'] ``` When there are capture groups `findall` returns only the captured parts. Use `?:` to prevent the parentheses from being a capture group.
using opencv2 write streaming video in python
16,045,654
2
2013-04-16T19:39:51Z
16,052,009
7
2013-04-17T05:12:26Z
[ "python", "opencv", "video-streaming" ]
In my project i want to save streaming video. ``` import cv2; if __name__ == "__main__": camera = cv2.VideoCapture(0); while True: f,img = camera.read(); cv2.imshow("webcam",img); if (cv2.waitKey (5) != -1): break; ``` ` using above code it is possible to strea...
You can simply save the grabbed frames into images: ``` camera = cv2.VideoCapture(0) i = 0 while True: f,img = camera.read() cv2.imshow("webcam",img) if (cv2.waitKey(5) != -1): break cv2.imwrite('{0:05d}.jpg'.format(i),img) i += 1 ``` or to a video like this: ``` camera = cv2.VideoCapture(0) vi...
How to change Tkinter Button state from disabled to normal?
16,046,743
9
2013-04-16T20:44:21Z
16,046,762
12
2013-04-16T20:45:59Z
[ "python", "button", "tkinter", "state" ]
I need to change the state from `DISABLED` to `NORMAL` of a `Button` when some event occurs. Here is the current state of my Button, which is currently disabled: ``` self.x = Button(self.dialog, text="Download", state=DISABLED, command=self.download).pack(side=LEFT) self.x(state=NORMAL) # this do...
You simply have to set the `state` of the your button `self.x` to `normal`: ``` self.x['state'] = 'normal' ``` or ``` self.x.config(state="normal") ``` This code would go in the callback for the event that will cause the Button to be enabled. --- Also, the right code should be: ``` self.x = Button(self.dialog, t...
How to set lower triangular matrix of 0-1?
16,048,233
3
2013-04-16T22:24:23Z
16,048,281
7
2013-04-16T22:28:48Z
[ "python", "arrays", "matrix", "numpy" ]
I need to make a matrix, for n dimensions, to look like this for n=4: ``` [0,0,0,0] [1,0,0,0] [1,1,0,0] [1,1,1,0] ``` because I need the positions of the 1s, ie ``` 0, 1 0, 2 0, 3 1, 2 1, 3 2, 3 ``` This is because I want to work out the distances between x points, without wasting time repeating a distance. These c...
You essentially want to increment the number of `1`s (starting from 0) in each row, while padding the rest of the row with `0`s, thereby keeping a constant length. Try something like this: ``` >>> n = 4 >>> [[1]*i + [0]*(n - i) for i in xrange(n)] [[0, 0, 0, 0], [1, 0, 0, 0], [1, 1, 0, 0], [1, 1, 1, 0]] ``` --- If y...
Pass variable between python scripts
16,048,237
4
2013-04-16T22:24:36Z
16,068,078
9
2013-04-17T19:04:01Z
[ "python" ]
I'm sure this is very simple but I've been unable to get it working correctly. I need to have my main python script call another python script and pass variables from the original script to the script that I've called So for a simplistic example my first script is, ``` first.py x = 5 import second ``` and my second ...
When you call a script, the calling script can access the namespace of the called script. (In your case, **first** can access the namespace of **second**.) However, what you are asking for is the other way around. Your variable is defined in the calling script, and you want the called script to access the caller's name...
plotting orbital trajectories in python
16,049,390
3
2013-04-17T00:19:30Z
16,049,681
8
2013-04-17T00:59:44Z
[ "python", "numpy", "matplotlib", "scipy", "differential-equations" ]
How can I setup the three body problem in python? How to I define the function to solve the ODEs? The three equations are `x'' = -mu / np.sqrt(x ** 2 + y ** 2 + z ** 2) * x`, `y'' = -mu / np.sqrt(x ** 2 + y ** 2 + z ** 2) * y`, and `z'' = -mu / np.sqrt(x ** 2 + y ** 2 + z ** 2) * z`. Written as 6 first order we...
As you've shown, you can write this as a system of six first-order ode's: ``` x' = x2 y' = y2 z' = z2 x2' = -mu / np.sqrt(x ** 2 + y ** 2 + z ** 2) * x y2' = -mu / np.sqrt(x ** 2 + y ** 2 + z ** 2) * y z2' = -mu / np.sqrt(x ** 2 + y ** 2 + z ** 2) * z ``` You can save this as a vector: ``` u = (x, y, z, x2, y2, z2) ...
What statistics module for python supports one way ANOVA with post hoc tests (Tukey, Scheffe or other)?
16,049,552
10
2013-04-17T00:41:04Z
21,177,789
18
2014-01-17T04:17:02Z
[ "python", "statistics", "scipy", "ipython", "statsmodels" ]
I have tried looking through multiple stats modules for python but can't seem to find any that support one away ANOVA post hoc tests.
one way ANOVA can be used like ``` from scipy import stats f_value, p_value = stats.f_oneway(data1, data2, data3, data4, ...) ``` This is one way ANOVA and it returns F value and P value. There is significant difference If the P value is below your setting. The Tukey-kramer HSD test can be used like ``` from sta...
Patch - Patching the class introduces an extra parameter?
16,051,422
9
2013-04-17T04:21:30Z
16,053,625
13
2013-04-17T07:03:21Z
[ "python", "unit-testing", "mocking", "patch", "typeerror" ]
First time using patch. I've tried to patch one of my classes for testing. Without the patch attempting to run gets past the test function definition, but with the patch the test function definition apparently requires another parameter and I get a ``` TypeError: testAddChannelWithNamePutsChannel() takes exactly 1 arg...
Patch passes in an instance of the patched object to your test method (or to every test method if you are patching at the class level). This is handy because it lets you set return values and side effects, or check the calls made ``` @patch('some_module.sys.stdout') def test_something_with_a_patch(self, mock_sys_stdou...
Python - finding the longest sequence with findall
16,054,705
4
2013-04-17T08:04:51Z
16,054,732
7
2013-04-17T08:05:44Z
[ "python", "regex", "findall" ]
``` found = re.findall("g+", "fggfggggfggfg", re.DOTALL) ``` I'd like to find a longest matches for a pattern using findall. I've found some solutions but only for `re.match` or `re.finditer`. Could anybody give me an advice please?
`re.DOTALL` does nothing in this case so I've just taken it out for simplicity's sake: ``` >>> import re >>> max(re.findall("g+", "fggfggggfggfg"), key=len) 'gggg' ``` If you need all of them in order of length: ``` >>> sorted(re.findall("g+", "fggfggggfggfg"), key=len, reverse=True) ['gggg', 'gg', 'gg', 'g'] ```
Changing a global variable from outside in a Flask based Python web application
16,055,024
6
2013-04-17T08:19:57Z
16,055,524
7
2013-04-17T08:45:42Z
[ "python", "global-variables", "flask" ]
I do not understand how to change a global variable when using the flask extension flask-script. To demonstrate my problem I developed the following small flask application, which will increase a global counter variable for every request call. In addition it offers a reset function to reset the global counter: ``` # -...
Python global variables like `counter` live in operating system process memory space. Each started and stopped process (application, command, etc.) gets its own pie of memory. When you run `python counter.py reset` it starts a new process with its own memory space and variables. The variable reset is run against this ...
django form dropdown list of stored models
16,055,808
9
2013-04-17T08:59:32Z
16,056,745
16
2013-04-17T09:44:22Z
[ "python", "html", "django", "forms" ]
I am trying to create a form for a library where a user can perform 2 actions: add a new book or open the stored information of an existing one. Books have 2 fields (title and author). Every time a new book is created, it is stored at the database. Any previously created book is shown as an option at a dropdown list (o...
You should use [ModelChoiceField](https://docs.djangoproject.com/en/dev/ref/forms/fields/#modelchoicefield). ``` class CronForm(forms.Form): days = forms.ModelChoiceField(queryset=Books.objects.all().order_by('name')) ``` Then your views, it should look something like this: ``` def show_book(request): form = ...
Adding dots between every char. What is the most Pythonic way?
16,057,289
2
2013-04-17T10:08:31Z
16,057,310
14
2013-04-17T10:09:47Z
[ "python" ]
I have some numbers as strings in the form of `'111'` or `'367'`. I want the output to be like `'1.1.1'` and `'3.6.7'`, respectively. I am thinking of doing this with a for loop to append each char in a list then join them with `'.'` I am just wondering is there a more *pythonic* way to achieve this ? or maybe a more p...
``` >>> '.'.join('111') '1.1.1' ``` Yes, it's that simple. Here's the [documentation](http://docs.python.org/2/library/stdtypes.html#str.join) for `str.join`.
Setting the size of the plotting canvas in Matplotlib
16,057,869
8
2013-04-17T10:39:29Z
16,061,699
9
2013-04-17T13:41:45Z
[ "python", "graph", "matplotlib", "plot" ]
I would like Matplotlib/Pyplot to generate plots with a consistent canvas size. That is, the figures can well have different sizes to accomodate the axis descriptions, but the plotting area (the rectangle within which the curves are drawn) should always have the same size. Is there a simple way to achieve that? The op...
This is one of my biggest frustrations with Matplotlib. I often work with raster data where for example i want to add a colormap, legend and some title. Any simple example from the matplotlib gallery doing so will result in a different resolution and therefore resampled data. Especially when doing image analysis you do...
Why does pyserial say I've given 12 arguments when there are 11?
16,060,188
2
2013-04-17T12:34:50Z
16,060,233
8
2013-04-17T12:36:50Z
[ "python", "pyserial" ]
I am using pyserial to open a python connection: ``` self.fpga = serial.Serial(self.fpgaport, 115200, serial.EIGHTBITS, serial.PARITY_NONE, serial.STOPBITS_ONE, self.fpgapollinterval, False, False, None, False, None) ``` This matches with the pyserial documentation found here: ``` __init__(port=None, baudrate=9600, ...
You are implicitly passing `self` as the first argument. --- I know that this answer does not *solve* your problem, but that is the reason why your interpreter tells you that you are passing 12 arguments when you are indeed only passing 11 explicit ones. And so the answer does provide exactly that, an *answer* to you...
Python: access structure field through its name in a string
16,060,625
3
2013-04-17T12:54:56Z
16,060,719
7
2013-04-17T12:59:08Z
[ "python", "ip", "structure", "field", "scapy" ]
In Scapy, I want to compare a number of header fields between any two packets `a` and `b`. This list of fields is predefined, say: ``` fieldsToCompare = ['tos', 'id', 'len', 'proto'] #IP header ``` Normally I would do it individually: ``` if a[IP].tos == b[IP].tos: ... do stuff... ``` Is there any way to access ...
You can use [`getattr()`](http://docs.python.org/2/library/functions.html#getattr). These lines are equivalent: ``` getattr(x, 'foobar') x.foobar ``` [`setattr()`](http://docs.python.org/2/library/functions.html#setattr) is its counterpart.
Patch - Why won't the relative patch target name work?
16,060,724
6
2013-04-17T12:59:16Z
16,070,660
7
2013-04-17T21:34:38Z
[ "python", "mocking", "patch" ]
I've imported a class from a module, but when I try to patch the class name without it's module as a prefix I get a type error: ``` TypeError: Need a valid target to patch. You supplied: 'MyClass' ``` For example, the following code gives me the above error: ``` import unittest from mock import Mock, MagicMock, patc...
The `patch` decorator requires the target to be a full dotted path, as stated in the [documentation](http://www.voidspace.org.uk/python/mock/patch.html): > target should be a string in the form ‘package.module.ClassName’. The target is imported and the specified object replaced with the new object, so the target m...
Alphabet range python
16,060,899
118
2013-04-17T13:06:49Z
16,060,908
214
2013-04-17T13:07:13Z
[ "python", "string", "list", "alphabet" ]
Instead of making a list of alphabet like this: ``` alpha = ['a', 'b', 'c', 'd'.........'z'] ``` Is there any way that we can group it to a range or something? For example, for numbers it can be grouped using `range()` ``` range(1, 10) ```
``` >>> import string >>> string.ascii_lowercase 'abcdefghijklmnopqrstuvwxyz' ``` If you really need a list: ``` >>> list(string.ascii_lowercase) ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] ``` And to do it with `range` ``` >>> l...
Alphabet range python
16,060,899
118
2013-04-17T13:06:49Z
37,716,814
9
2016-06-09T04:26:14Z
[ "python", "string", "list", "alphabet" ]
Instead of making a list of alphabet like this: ``` alpha = ['a', 'b', 'c', 'd'.........'z'] ``` Is there any way that we can group it to a range or something? For example, for numbers it can be grouped using `range()` ``` range(1, 10) ```
``` [chr(i) for i in range(ord('a'),ord('z')+1)] ```
tick label positions for matplotlib 3D plot
16,061,349
4
2013-04-17T13:27:30Z
16,062,306
9
2013-04-17T14:07:40Z
[ "python", "matplotlib" ]
I am trying to work out how to set/correct the position of tick labels for a 3D matplotlib plot. Tick labels do not align with the ticks. The issue seems to be especially prominent when many tick labels are required. I have modified an example (<http://matplotlib.org/examples/mplot3d/polys3d_demo.html>) from the matpl...
By using these alignments, I get much better placements: ``` ax.set_yticklabels(labels,rotation=-15, verticalalignment='baseline', horizontalalignment='left') ``` I've modified the example with less tick markers so you can see the placement: ![enter image description here](http:...
Pylint - Pylint unable to import flask.ext.wtf?
16,061,514
17
2013-04-17T13:34:07Z
16,063,076
24
2013-04-17T14:41:06Z
[ "python", "flask", "wtforms", "pylint" ]
I've got my Pylint install importing flask just fine. And with that same installation of flask, I have wtforms running just fine in my application. However, when I run Pylint on a file importing wtforms: ``` from flask.ext import wtf from flask.ext.wtf import validators class PostForm(wtf.Form): content = wtf.Tex...
So `flask.ext` is actually a custom importer written by [Armin](http://lucumr.pocoo.org/) in an awesome way. It allows people install extensions to flask in separate packages but import them in one consistent way. (Really you should go read the code for it. It is fantastic.) That said, apparently pylint doesn't appreci...
Pylint - Pylint unable to import flask.ext.wtf?
16,061,514
17
2013-04-17T13:34:07Z
31,105,330
7
2015-06-28T22:17:33Z
[ "python", "flask", "wtforms", "pylint" ]
I've got my Pylint install importing flask just fine. And with that same installation of flask, I have wtforms running just fine in my application. However, when I run Pylint on a file importing wtforms: ``` from flask.ext import wtf from flask.ext.wtf import validators class PostForm(wtf.Form): content = wtf.Tex...
Having been annoyed by this bug for a while, I created a pylint plugin to solve this issue. Code is at <https://github.com/jschaf/pylint-flask> To enable pylint to 'see' the flask.ext modules do the following: 1. `pip install pylint-flask` 2. run `pylint --load-plugins=pylint_flask <your module>`
How can I programmatically check Amazon S3 permissions with boto?
16,063,673
7
2013-04-17T15:07:02Z
16,064,836
8
2013-04-17T15:59:37Z
[ "python", "permissions", "amazon-s3", "boto" ]
We have a bushy tree in a bucket on Amazon S3 with a large number of files. I just discovered that while some files have two permissions entries, as seen if one clicks on a file in the AWS Management Console, then properties -> permissions, one line being "everyone" and the other some specific user, other files just ha...
Here is some Python code, using boto, that would look through all of the keys in a bucket. If the key does not allow "everyone" to read the contents of the key, it will add `public-read` permissions to that key: ``` import boto all_users = 'http://acs.amazonaws.com/groups/global/AllUsers' conn = boto.connect_s3() buc...
Scipy: Pearson's correlation always returning 1
16,063,839
8
2013-04-17T15:14:19Z
16,064,573
14
2013-04-17T15:47:44Z
[ "python", "statistics", "scipy", "correlation", "pearson" ]
I am using Python library scipy to calculate Pearson's correlation for two float arrays. The returned value for coefficient is always 1.0, even if the arrays are different. For example: ``` [-0.65499887 2.34644428] [-1.46049758 3.86537321] ``` I am calling the routine in this way: ``` r_row, p_value = scipy.stats....
[Pearson's correlation coefficient](http://en.wikipedia.org/wiki/Correlation_and_dependence) is a measure of how well your data would be fitted by a linear regression. If you only provide it with two points, then there is a line passing exactly through both points, hence your data perfectly fits a line, hence the corre...
How to create a code object in python?
16,064,409
6
2013-04-17T15:40:07Z
16,123,158
20
2013-04-20T17:26:21Z
[ "python", "python-3.x", "bytecode" ]
I'd like to create a new code object with the function types.CodeType() . There is almost no documentation about this and the existing one says "not for faint of heart" Tell me what i need and give me some information about each argument passed to types.CodeType , possibly posting an example. **Note**: In norm...
––––––––––– ***Disclaimer*** : Documentation in this answer is not official and may be incorrect. This answer is valid only for python version 3.x ––––––––––– In order to create a code object you have to pass to the function CodeType() the following arguments: ``` Cod...
Calling AppleScript from Python without using osascript or appscript?
16,065,162
6
2013-04-17T16:16:43Z
16,066,177
12
2013-04-17T17:16:50Z
[ "python", "osx", "applescript" ]
Is there any way to execute (and obtain the results of) AppleScript code from python without using the `osascript` command-line utility or [appscript](http://appscript.sourceforge.net/) (which I don't really want to use (I think?) because [it's no longer developed/supported/recommended](http://appscript.sourceforge.net...
You can use the PyObjC bridge: ``` >>> from Foundation import * >>> s = NSAppleScript.alloc().initWithSource_("tell app \"Finder\" to activate") >>> s.executeAndReturnError_(None) ```
Calling AppleScript from Python without using osascript or appscript?
16,065,162
6
2013-04-17T16:16:43Z
16,101,613
17
2013-04-19T09:36:14Z
[ "python", "osx", "applescript" ]
Is there any way to execute (and obtain the results of) AppleScript code from python without using the `osascript` command-line utility or [appscript](http://appscript.sourceforge.net/) (which I don't really want to use (I think?) because [it's no longer developed/supported/recommended](http://appscript.sourceforge.net...
PyPI is your friend... <http://pypi.python.org/pypi/py-applescript> Example: ``` import applescript scpt = applescript.AppleScript(''' on run {arg1, arg2} say arg1 & " " & arg2 end run on foo() return "bar" end foo on Baz(x, y) return x * y end bar ''') print(scpt....
How to format a python assert statement that complies with PEP8?
16,065,482
15
2013-04-17T16:35:17Z
16,065,512
27
2013-04-17T16:36:51Z
[ "python", "assert", "pep8" ]
How does one format a long assert statement that complies with PEP8? Please ignore the contrived nature of my example. ``` def afunc(some_param_name): assert isinstance(some_param_name, SomeClassName), 'some_param_name must be an instance of SomeClassName, silly goose!' ``` One cannot wrap it in parenthesis, beca...
It's important to remember that PEP8 is only a guideline and [even states that there are times when the rules *should* be broken](http://www.python.org/dev/peps/pep-0008/#a-foolish-consistency-is-the-hobgoblin-of-little-minds). > But most importantly: know when to be inconsistent -- sometimes the style guide just does...
Is it possible to create encodeb64 from Image object?
16,065,694
5
2013-04-17T16:46:59Z
16,066,722
7
2013-04-17T17:47:27Z
[ "python", "base64", "python-imaging-library" ]
I am looking to create base64 inline encoded data of images for display in a table using canvases. Python generates and creates the web page dynamically. As it stands python uses the Image module to create thumbnails. After all of the thumbnails are created Python then generates base64 data of each thumbnail and puts t...
You first need to save the image again in JPEG format; using the `im.tostring()` method would otherwise return raw image data that no browser would recognize: ``` from cStringIO import StringIO output = StringIO() im.save(output, format='JPEG') im_data = output.getvalue() ``` This you can then encode to base64: ```...
Python extremely puzzling regex unicode behaviour
16,067,721
7
2013-04-17T18:44:55Z
16,067,808
7
2013-04-17T18:49:54Z
[ "python", "regex", "unicode", "python-2.7" ]
I use a tokenizer to split french sentences into words and had problems with words containing the french character `â`. I tried to isolate the problem and it eventually boiled down to this simple fact: ``` >>> re.match(r"’", u'â', re.U) >>> re.match(r"[’]", u'â', re.U) <_sre.SRE_Match object at 0x21d41d0> ``` ...
Your pattern should be a unicode string too: ``` >>> re.match(ur"’", u'â', re.U) >>> re.match(ur"[’]", u'â', re.U) ``` Otherwise apparently `sre` encodes `â` to latin-1 and finds the resulting byte in the three bytes that is a utf-8 `’`. `"[’]"` is equivalent to `"[\xe2\x80\x99]"`, and `u'â'.encode('la...
Django - Site matching query does not exist
16,068,518
2
2013-04-17T19:25:57Z
16,068,551
14
2013-04-17T19:28:16Z
[ "python", "django" ]
Im trying to get the admin site of my app in Django working. Ive just sync`d the DB and then gone to the site but I get the error ... ``` Site matching query does not exist. ``` Any ideas ?
Every django app needs a `Site` to run. Here you do not seem to have it. Log into your django shell ``` $> ./manage.py shell >>> from django.contrib.sites.models import Site >>> site = Site() >>> site.domain = 'example.com' >>> site.name = 'example.com' >>> site.save() ``` or ``` $> ./manage.py shell >>> from djang...
Python - logical evaluation order in "if" statement
16,069,517
3
2013-04-17T20:19:16Z
16,069,560
11
2013-04-17T20:21:38Z
[ "python", "boolean", "short-circuiting" ]
In Python we can do this: ``` if True or blah: print("it's ok") # will be executed if blah or True: # will raise a NameError print("it's not ok") class Blah: pass blah = Blah() if blah or blah.notexist: print("it's ok") # also will be executed ``` * Can somebody point me to documentation on this fe...
The `or` and `and` *short circuit*, see the [Boolean operations](http://docs.python.org/2/reference/expressions.html#boolean-operations) documentation: > The expression `x and y` first evaluates `x`; if `x` is false, its value is returned; otherwise, `y` is evaluated and the resulting value is returned. > > The expres...
Python mock, django and requests
16,069,541
7
2013-04-17T20:20:17Z
16,072,038
11
2013-04-17T23:30:47Z
[ "python", "django", "unit-testing", "mocking", "django-testing" ]
So, I've just started using mock with a Django project. I'm trying to mock out part of a view which makes a request to a remote API to confirm a subscription request was genuine (a form of verification as per the spec I'm working to). What I have resembles: ``` class SubscriptionView(View): def post(self, request...
You're almost there. You're just calling it slightly incorrectly. ``` from mock import call, patch @patch('my_app.views.requests') def test_response_verify(self, mock_requests): # We setup the mock, this may look like magic but it works, return_value is # a special attribute on a mock, it is what is returned...
Getting Python error "from: can't read /var/mail/Bio"
16,069,816
25
2013-04-17T20:37:12Z
16,069,857
45
2013-04-17T20:39:47Z
[ "python" ]
I am running a (bio)python script which results in the following error: ``` from: can't read /var/mail/Bio ``` seeing as my script doesn't have anything to with mail, I don't understand why my script is looking in /var/mail. What seems to be the problem here? i doubt it will help as the script doesn't seem to be the...
No, it's not the script, it's the fact that your script is not executed by Python at all. If your script is stored in a file named `script.py`, you have to execute it as `python script.py`, otherwise the default shell will execute it and it will bail out at the `from` keyword. (Incidentally, `from` is the name of a com...
how to interpolate points in a specific interval on a plot formed by loading a txt file in to scipy program?
16,070,219
4
2013-04-17T21:03:24Z
16,070,341
8
2013-04-17T21:11:09Z
[ "python", "matlab", "numpy", "matplotlib", "interpolation" ]
I have a text file with two columns, x and y. I have plotted them using the below program in scipy as shown below. ``` import matplotlib.pyplot as plt with open("data.txt") as f: data = f.read() data = data.split('\n') x = [row.split(' ')[0] for row in data] y = [row.split(' ')[1] for row in data] fig = plt....
You can create a function using [`scipy.interp1d`](http://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.interp1d.html): ``` import numpy as np from scipy import interpolate data = np.genfromtxt('data.txt') x = data[:,0] #first column y = data[:,1] #second column f = interpolate.interp1d(x, y) xn...