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
How should I format a long url in a python comment and still be PEP8 compliant
10,739,843
37
2012-05-24T14:47:47Z
10,739,994
17
2012-05-24T14:55:25Z
[ "python", "pep8" ]
In a block comment, I want to reference a URL that is over 80 characters long. What is the preferred convention for displaying this URL? I know bit.ly is an option, but the URL itself is descriptive. Shortening it and then having a nested comment describing the shortened URL seems like a crappy solution.
I'd say leave it... [PEP20](http://www.python.org/dev/peps/pep-0020/): > Special cases aren't special enough to break the rules. > > Although practicality beats purity. It's more practical to be able to quickly copy/paste an url then to remove linebreaks when pasting into the browser.
How should I format a long url in a python comment and still be PEP8 compliant
10,739,843
37
2012-05-24T14:47:47Z
10,740,010
42
2012-05-24T14:56:20Z
[ "python", "pep8" ]
In a block comment, I want to reference a URL that is over 80 characters long. What is the preferred convention for displaying this URL? I know bit.ly is an option, but the URL itself is descriptive. Shortening it and then having a nested comment describing the shortened URL seems like a crappy solution.
Don't break the url: ``` # A Foolish Consistency is the Hobgoblin of Little Minds [1] # [1]: http://www.python.org/dev/peps/pep-0008/#a-foolish-consistency-is-the-hobgoblin-of-little-minds ```
How should I format a long url in a python comment and still be PEP8 compliant
10,739,843
37
2012-05-24T14:47:47Z
25,034,769
8
2014-07-30T10:43:30Z
[ "python", "pep8" ]
In a block comment, I want to reference a URL that is over 80 characters long. What is the preferred convention for displaying this URL? I know bit.ly is an option, but the URL itself is descriptive. Shortening it and then having a nested comment describing the shortened URL seems like a crappy solution.
You can use the `# noqa` at the end of the line to stop PEP8/Flake8 from running that check. This is allowed by PEP8 via: > Special cases aren't special enough to break the rules.
Why Numpy treats a+=b and a=a+b differently
10,739,978
24
2012-05-24T14:54:27Z
10,740,003
40
2012-05-24T14:55:50Z
[ "python", "numpy" ]
Is the following numpy behavior intentional or is it a bug? ``` from numpy import * a = arange(5) a = a+2.3 print 'a = ', a # Output: a = 2.3, 3.3, 4.3, 5.3, 6.3 a = arange(5) a += 2.3 print 'a = ', a # Output: a = 2, 3, 4, 5, 6 ``` Python version: 2.7.2, Numpy version: 1.6.1
That's intentional. The `+=` operator preserves the type of the array. In other words, an array of integers remains an array of integers. This enables NumPy to perform the `+=` operation using existing array storage. On the other hand, `a=a+b` creates a brand new array for the sum, and rebinds `a` to point to this ne...
Django seems to be caching datetime.now()
10,741,201
3
2012-05-24T16:05:55Z
10,741,295
11
2012-05-24T16:12:42Z
[ "python", "django", "caching", "datetime" ]
I have a model that looks like this: ``` class Item(models.Model): ... publish_date = models.DateTimeField(default=datetime.datetime.now) ... ``` And a manager that looks like this: ``` from datetime import datetime class ItemManager(Manager): def published(self): return self.get_query_set()...
I believe this is caused by your view defining `queryset = Item.objects.published()` as a class variable. This line will be executed once, when your `ItemArchive` class is initially imported. You should move that line into a method where it will be executed each time a view is called.
Do CSRF attacks apply to API's?
10,741,339
27
2012-05-24T16:14:55Z
10,741,650
27
2012-05-24T16:33:10Z
[ "python", "django", "api", "security" ]
In particular, I'm writing a Django RESTful API to back an iOS application, and I keep running into Django's CSRF protections whenever I write methods to deal with POST requests. My understanding is that cookies managed by iOS are not shared by applications, meaning that my session cookies are safe, and no other appli...
That's not the purpose of CSRF. CSRF is to prevent direct posting of data to your site. In other words, the client must actually post through an approved *path*, i.e. view the form page, fill it out, submit the data. An API pretty much precludes CSRF, because its entire purpose is generally to *allow* 3rd-party entiti...
Do CSRF attacks apply to API's?
10,741,339
27
2012-05-24T16:14:55Z
16,702,510
13
2013-05-22T22:16:10Z
[ "python", "django", "api", "security" ]
In particular, I'm writing a Django RESTful API to back an iOS application, and I keep running into Django's CSRF protections whenever I write methods to deal with POST requests. My understanding is that cookies managed by iOS are not shared by applications, meaning that my session cookies are safe, and no other appli...
They do apply if you're also using your API to support a website. In this case you still need some form of CSRF protection to prevent someone embedding requests in other sites to have drive-by effects on an authenticated user's account. Chrome seems to deny cross-origin POST requests by default (other browsers may no...
Do CSRF attacks apply to API's?
10,741,339
27
2012-05-24T16:14:55Z
20,963,698
19
2014-01-07T04:03:50Z
[ "python", "django", "api", "security" ]
In particular, I'm writing a Django RESTful API to back an iOS application, and I keep running into Django's CSRF protections whenever I write methods to deal with POST requests. My understanding is that cookies managed by iOS are not shared by applications, meaning that my session cookies are safe, and no other appli...
CSRF attacks rely on cookies being implicitly sent with all requests to a particular domain. If your API endpoints do not allow cookie-based authentication, you should be good. Even if you do use cookie-based authentication, your cookies are safe because [iOS apps do not share cookies](http://stackoverflow.com/questio...
numpy: most efficient frequency counts for unique values in an array
10,741,346
70
2012-05-24T16:15:18Z
10,741,692
53
2012-05-24T16:35:46Z
[ "python", "arrays", "performance", "numpy" ]
In **`numpy`** / **`scipy`**, is there an **efficient** way to get frequency counts for unique values in an array? Something along these lines: ``` x = array( [1,1,1,2,2,2,5,25,1,1] ) y = freq_count( x ) print y >> [[1, 5], [2,3], [5,1], [25,1]] ``` ( For you, R users out there, I'm basically looking for the `table...
Take a look at `np.bincount`: <http://docs.scipy.org/doc/numpy/reference/generated/numpy.bincount.html> ``` import numpy as np x = np.array([1,1,1,2,2,2,5,25,1,1]) y = np.bincount(x) ii = np.nonzero(y)[0] ``` And then: ``` zip(ii,y[ii]) # [(1, 5), (2, 3), (5, 1), (25, 1)] ``` or: ``` np.vstack((ii,y[ii])).T # ar...
numpy: most efficient frequency counts for unique values in an array
10,741,346
70
2012-05-24T16:15:18Z
10,742,333
11
2012-05-24T17:22:05Z
[ "python", "arrays", "performance", "numpy" ]
In **`numpy`** / **`scipy`**, is there an **efficient** way to get frequency counts for unique values in an array? Something along these lines: ``` x = array( [1,1,1,2,2,2,5,25,1,1] ) y = freq_count( x ) print y >> [[1, 5], [2,3], [5,1], [25,1]] ``` ( For you, R users out there, I'm basically looking for the `table...
`numpy.bincount` is the probably the best choice. If your array contains anything besides small dense integers it might be useful to wrap it something like this: ``` def count_unique(keys): uniq_keys = np.unique(keys) bins = uniq_keys.searchsorted(keys) return uniq_keys, np.bincount(bins) ``` For example:...
numpy: most efficient frequency counts for unique values in an array
10,741,346
70
2012-05-24T16:15:18Z
18,201,448
73
2013-08-13T05:41:20Z
[ "python", "arrays", "performance", "numpy" ]
In **`numpy`** / **`scipy`**, is there an **efficient** way to get frequency counts for unique values in an array? Something along these lines: ``` x = array( [1,1,1,2,2,2,5,25,1,1] ) y = freq_count( x ) print y >> [[1, 5], [2,3], [5,1], [25,1]] ``` ( For you, R users out there, I'm basically looking for the `table...
you can use [scipy.stats.itemfreq](http://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.itemfreq.html) ``` >>> from scipy.stats import itemfreq >>> x = [1,1,1,2,2,2,5,25,1,1] >>> itemfreq(x) array([[ 1., 5.], [ 2., 3.], [ 5., 1.], [ 25., 1.]]) ```
numpy: most efficient frequency counts for unique values in an array
10,741,346
70
2012-05-24T16:15:18Z
21,124,789
16
2014-01-14T21:53:12Z
[ "python", "arrays", "performance", "numpy" ]
In **`numpy`** / **`scipy`**, is there an **efficient** way to get frequency counts for unique values in an array? Something along these lines: ``` x = array( [1,1,1,2,2,2,5,25,1,1] ) y = freq_count( x ) print y >> [[1, 5], [2,3], [5,1], [25,1]] ``` ( For you, R users out there, I'm basically looking for the `table...
This is by far the most general and performant solution; surprised it hasn't been posted yet. ``` import numpy as np def unique_count(a): unique, inverse = np.unique(a, return_inverse=True) count = np.zeros(len(unique), np.int) np.add.at(count, inverse, 1) return np.vstack(( unique, count)).T print u...
numpy: most efficient frequency counts for unique values in an array
10,741,346
70
2012-05-24T16:15:18Z
25,943,480
151
2014-09-19T22:54:29Z
[ "python", "arrays", "performance", "numpy" ]
In **`numpy`** / **`scipy`**, is there an **efficient** way to get frequency counts for unique values in an array? Something along these lines: ``` x = array( [1,1,1,2,2,2,5,25,1,1] ) y = freq_count( x ) print y >> [[1, 5], [2,3], [5,1], [25,1]] ``` ( For you, R users out there, I'm basically looking for the `table...
As of Numpy 1.9, the easiest and fastest method is to simply use [`numpy.unique`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.unique.html), which now has a `return_counts` keyword argument: ``` import numpy as np x = np.array([1,1,1,2,2,2,5,25,1,1]) unique, counts = np.unique(x, return_counts=True) pri...
Running command lines within your Python script
10,741,600
10
2012-05-24T16:30:19Z
10,741,654
12
2012-05-24T16:33:16Z
[ "python", "windows", "cmd" ]
So I have a bunch of aliases and Command Line prompt programs, and my main program works by inputting b into the cmd.exe, followed by some filepath names and what not. How would I run those arguments in my python script? So that it mimics the action i am doing in the cmd?
You should use the [subprocess](http://docs.python.org/library/subprocess.html) module. In particular, [subprocess.call](http://docs.python.org/library/subprocess.html#subprocess.call) will run command line programs for you.
Running command lines within your Python script
10,741,600
10
2012-05-24T16:30:19Z
10,741,696
10
2012-05-24T16:36:01Z
[ "python", "windows", "cmd" ]
So I have a bunch of aliases and Command Line prompt programs, and my main program works by inputting b into the cmd.exe, followed by some filepath names and what not. How would I run those arguments in my python script? So that it mimics the action i am doing in the cmd?
or you can use ``` import os os.system('your_command') ``` for example: ``` import os os.system('notepad') ``` will launch the notepad with the command line behind. hope this helps
Python Time conversion h:m:s to seconds
10,742,296
7
2012-05-24T17:19:31Z
10,742,441
11
2012-05-24T17:28:43Z
[ "python", "datetime", "formatting" ]
I am aware that with the timedelta function you can convert seconds to h:m:s using something like: ``` >> import datetime >> str(datetime.timedelta(seconds=666)) '0:11:06' ``` But I need to convert h:m:s to seconds, or minutes. Do you know a function that can do this?
``` >>> import time, datetime >>> a = time.strptime("00:11:06", "%H:%M:%S") >>> datetime.timedelta(hours=a.tm_hour, minutes=a.tm_min, seconds=a.tm_sec).seconds 666 ``` And here's a cheeky one liner if you're really intent on splitting over ":" ``` >>> s = "00:11:06" >>> sum(int(i) * 60**index for index, i in enumerat...
Python newbie @patch decorator issue
10,742,361
10
2012-05-24T17:23:54Z
10,742,689
13
2012-05-24T17:46:38Z
[ "python", "mocking", "patch" ]
I tried patching a provider class by decorating a test method with `@patch`: ``` class TestMyUnit(unittest.TestCase): ... @patch(provider.Provider,autospec=True) def test_init(self, mock_provider): pass ``` However, when I run the test, I get the error: ``` *@patch(provider.Provider)* *File "build\bdist.win32\...
Use a string instead of the class. ``` @patch('provider.Provider', autospec=True) def test_init(self, mock_provider): pass ```
Programmatically add column names to numpy ndarray
10,742,406
9
2012-05-24T17:26:49Z
10,750,774
10
2012-05-25T08:07:36Z
[ "python", "arrays", "numpy", "multidimensional-array" ]
I'm trying to add column names to a numpy ndarray, then select columns by their names. But it doesn't work. I can't tell if the problem occurs when I add the names, or later when I try to call them. Here's my code. ``` data = np.genfromtxt(csv_file, delimiter=',', dtype=np.float, skip_header=1) #Add headers csv_name...
The problem is that you are thinking in terms of spreadsheet-like arrays, whereas NumPy does use different concepts. Here is what you must know about NumPy: 1. NumPy arrays only contain elements of a **single type**. 2. If you need spreadsheet-like "columns", this type must be some **tuple-like type**. Such arrays ar...
Ubuntu AMI not loading user-data
10,743,809
7
2012-05-24T19:08:56Z
10,746,289
10
2012-05-24T22:40:28Z
[ "python", "ubuntu", "amazon-ec2", "amazon-web-services", "user-data" ]
I am attempting to load user data into an Ubuntu 12.04 LTS AMI (ami-a29943cb, but I've tried a few others to no avail) via boto's ec2.run\_instances(..., user\_data=USER\_DATA). Similarly, I have had no success with manually supplying the user data while launching the instances via the AWS console. There are no results...
It's hard to know what happened without an error message, but there are a few places you can look: 1. The file `/var/log/cloud-init.log` will usually contain any errors (e.g. boto import failure) that occurred during instance bootstrapping. 2. The directory `/var/lib/cloud/instance` will contain the raw scripts and us...
python paramiko ssh
10,745,138
6
2012-05-24T20:55:31Z
10,758,567
7
2012-05-25T17:04:50Z
[ "python", "ssh", "paramiko" ]
i'm new on python. i wrote a script to connect to a host and execute one command ``` ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(host, username=user, password=pw) print 'running remote command' stdin, stdout, stderr = ssh.exec_command(command) stdin.close() for l...
There is extensive paramiko API documentation you can find at: <http://www.lag.net/paramiko/docs/> I use the following method to execute commands on a password protected client: ``` import paramiko import sys nbytes = 4096 hostname = 'hostname' port = 22 username = 'username' password = 'password' command = 'ls' c...
how do I check that two slices of numpy arrays are the same (or overlapping)?
10,747,748
7
2012-05-25T02:30:25Z
10,752,605
9
2012-05-25T10:17:09Z
[ "python", "numpy" ]
I would like to check if two ndarrays are overlapping views of the same underlying ndarray. To check that two slices are exactly the same, I can do something like: ``` a.base is b.base and a.shape == b.shape and a.data == b.data ``` The comparison of buffers seemed to work in one simple case -- can anyone tell me if...
`numpy.may_share_memory()` is the best heuristic that we have at the moment. It is conservatively heuristic; it may give you false positives, but it will not give you false negatives. I think there might be ways to improve the heuristic to be 100% correct. If they pan out, they will be folded into that function, so tha...
How to check if the current time is in range in python?
10,747,974
12
2012-05-25T03:05:02Z
10,748,024
18
2012-05-25T03:12:35Z
[ "python", "datetime", "range" ]
I need to check if the current time is in timerange. The most simple case time\_end > time\_start: ``` if time(6,0) <= now.time() <= time(12,00): print '1' ``` But troubles begin when user enters a time range when the end time is smaller than the start time, e.g. "23:00 - 06:00". A time like '00:00' will be in this r...
The Python solution is going to be much, much shorter. ``` def time_in_range(start, end, x): """Return true if x is in the range [start, end]""" if start <= end: return start <= x <= end else: return start <= x or x <= end ``` Use the `datetime.time` class for `start`, `end`, and `x`. ```...
Why does not the + operator change a list while .append() does?
10,748,158
7
2012-05-25T03:33:50Z
10,748,191
15
2012-05-25T03:40:29Z
[ "python", "list", "append", "concatenation" ]
I'm working through Udacity and Dave Evans introduced an exercise about list properties ``` list1 = [1,2,3,4] list2 = [1,2,3,4] list1=list1+[6] print(list1) list2.append(6) print(list2) list1 = [1,2,3,4] list2 = [1,2,3,4] def proc(mylist): mylist = mylist + [6] def proc2(mylist): mylist.append(6) # Can yo...
> So in a function the adding a 6 to the set doesn't show but it does when not in a function? No, that is not what happens. What happens is that, when you execute `mylist = mylist + [6]`, you are effectively creating an entirely new list and putting it in the local `mylist` variable. This `mylist` variable will vanis...
What does a plus sign do in front of a variable in Python?
10,748,185
14
2012-05-25T03:38:49Z
10,748,232
15
2012-05-25T03:46:58Z
[ "python", "decimal", "unary-operator" ]
There's the following bit of Python code in a project I have to maintain: ``` # If the `factor` decimal is given, compute new price and a delta factor = +factor.quantize(TWOPLACES) new_price = +Decimal(old_price * factor).quantize(TWOPLACES) delta = new_price - old_price ``` The question here is the purpose of `+` in...
What that plus sign does depends on what it's defined to do by the result of that expression (that object's `__pos__()` method is called). In this case, it's a `Decimal` object, and the unary plus is equivalent to calling the `plus()` method. Basically, it's used to apply the current context (precision, rounding, etc.)...
Can yield produce multiple consecutive generators?
10,748,331
10
2012-05-25T04:01:23Z
10,748,431
7
2012-05-25T04:21:48Z
[ "python", "iterator", "generator", "yield" ]
Here are two functions that split iterable items to sub-lists. I believe that this type of task is programmed many times. I use them to parse log files that consist of `repr` lines like ('result', 'case', 123, 4.56) and ('dump', ..) and so on. I would like to change these so that they will yield iterators rather than ...
adam's answer is good. this is just in case you're curious how to do it by hand: ``` def cleave_by_change(stream): def generator(): head = stream[0] while stream and stream[0] == head: yield stream.pop(0) while stream: yield generator() for g in cleave_by_change([1,1,1,2,2,...
img = Image.open(fp) AttributeError: class Image has no attribute 'open'
10,748,822
3
2012-05-25T05:18:07Z
10,749,029
8
2012-05-25T05:40:25Z
[ "python", "pdf", "image" ]
I want to put the pictures into a PDF file. My code follows... ``` import sys import xlrd from PIL import Image import ImageEnhance from reportlab.platypus import * from reportlab.lib.styles import getSampleStyleSheet from reportlab.rl_config import defaultPageSize PAGE_HEIGHT=defaultPageSize[1] styles = getSampleSty...
You have a namespace conflict. One of your import statements is masking `PIL.Image` (which is a module, not a class) with some class named `Image`. Instead of ... ``` from PIL import Image ``` try ... ``` import PIL.Image ``` then later in your code... ``` fp = open("/pdf-ex/downloadwin7.png","rb") img = PIL.Imag...
Set up a real timeout for loading page in Selenium WebDriver?
10,750,198
15
2012-05-25T07:24:03Z
10,753,708
9
2012-05-25T11:34:24Z
[ "python", "selenium", "webdriver", "selenium-webdriver", "wait" ]
I'm testing a site with lots of proxies, and the problem is some of those proxies are awfully slow. Therefore my code is stuck at loading pages every now and then. ``` from selenium import webdriver browser = webdriver.Firefox() browser.get("http://example.com/example-page.php") element = browser.find_element_by_id("...
You could try using the page load timeout introduced in the library. The implementation of it is not universal, but it's exposed for certain by the .NET and Java bindings, and has been implemented in and the Firefox driver now, and in the IE driver in the forthcoming 2.22. In Java, to set the page load timeout to 15 se...
Converting a latin string to unicode in python
10,750,420
3
2012-05-25T07:39:14Z
10,750,628
7
2012-05-25T07:54:31Z
[ "python", "unicode", "scrapy", "latin" ]
I am working o scrapy, I scraped some sites and stored the items from the scraped page in to json files, but some of them are containing the following format. ``` l = ["Holding it Together", "Fowler RV Trip", "S\u00e9n\u00e9gal - Mali - Niger","H\u00eatres et \u00e9tang", "Coll\u00e8ge marsan","N\u00b0o...
You have byte strings containing unicode escapes. You can convert them to unicode with the `unicode_escape` codec: ``` >>> print "H\u00eatres et \u00e9tang".decode("unicode_escape") Hêtres et étang ``` And you can encode it back to byte strings: ``` >>> s = "H\u00eatres et \u00e9tang".decode("unicode_escape") >>> ...
How do you mock patch a python class and get a new Mock object for each instantiation?
10,750,996
11
2012-05-25T08:24:10Z
10,751,818
11
2012-05-25T09:25:52Z
[ "python", "mocking", "python-unittest", "python-mock" ]
OK, I know this is mentioned in the [manual](http://www.voidspace.org.uk/python/mock/), and probably has to do with `side_effect` and/or `return_value`, but a simple, direct example will help me immensely. I have: ``` class ClassToPatch(): def __init__(self, *args): _do_some_init_stuff() def some_func...
Here's a quick'n'dirty example to get you going: ``` import mock import unittest class ClassToPatch(): def __init__(self, *args): pass def some_func(self): return id(self) class UUT(): def __init__(self, *args): resource_1 = ClassToPatch() resource_2 = ClassToPatch() ...
Returning multiple values from pandas apply on a DataFrame
10,751,127
31
2012-05-25T08:35:27Z
10,762,516
39
2012-05-25T23:48:46Z
[ "python", "pandas" ]
I'm using a Pandas DataFrame to do a row-wise t-test as per this example: ``` import numpy import pandas df = pandas.DataFrame(numpy.log2(numpy.randn(1000, 4), columns=["a", "b", "c", "d"]) df = df.dropna() ``` Now, supposing I have "a" and "b" as one group, and "c" and "d" at the other, I'm ...
Returning a Series, rather than tuple, should produce a new multi-column DataFrame. For example, ``` return pandas.Series({'pvalue': pvalue, 'mean_ratio': mean_ratio}) ```
How do I map key combinations (pressing buttons simultaneously, not sequentially) in vim?
10,751,270
4
2012-05-25T08:47:44Z
10,751,410
8
2012-05-25T08:57:06Z
[ "python", "vim", "keyboard" ]
How do I map key combinations(pressing buttons simultaneously, not sequentially) in vim? suppose I wanted to map the command `:!python % <ENTER>` to pressing the keys `j` and `k` together? I tried `:map j+k :!python % <ENTER>`, `:map j-k :!python % <ENTER>` and `:map <j-k> :!python % <ENTER>` but this doesn't work. A...
If using scripts is acceptable for you, then there is [arpeggio](http://www.vim.org/scripts/script.php?script_id=2425) script which should suit your needs.
XLRDError: Expected BOF record; found 0x4b50
10,751,330
6
2012-05-25T08:52:29Z
13,964,326
7
2012-12-20T02:19:42Z
[ "python", "excel" ]
I don't think there is something wrong with the codes. Can you help me? I need help. Thank you! ``` from xlrd import open_workbook wb = open_workbook('/pdf-ex/exc.xlsx','rb') for s in wb.sheets(): print 'Sheet:',s.name for row in range(s.nrows): values=[] for col in range(s.ncols): ...
I had the same problem and resolved it by upgrading to version 0.8.0. Prior to that version, xlsx/xlsm were not supported. Release announcement: <http://mail.python.org/pipermail/python-list/2012-August/627757.html> Latest version: <https://pypi.python.org/pypi/xlrd/>
Command line arguments in python.
10,751,948
8
2012-05-25T09:34:30Z
10,751,972
17
2012-05-25T09:36:10Z
[ "python", "argv" ]
I am familiar with C, and have started experimenting in python. My question is regarding the `sys.argv` command. I've read it is used for a command line interpreter, but when trying to execute a simple program I don't get the results I expect. Code: ``` import sys a = sys.argv[1] b = sys.argv[2] print a, b print a...
You can convert the arguments to integers using int() ``` import sys a = int(sys.argv[1]) b = int(sys.argv[2]) print a, b print a+b ``` input: `python mySum.py 100 200` output: ``` 100 200 300 ```
Command line arguments in python.
10,751,948
8
2012-05-25T09:34:30Z
10,751,981
9
2012-05-25T09:36:49Z
[ "python", "argv" ]
I am familiar with C, and have started experimenting in python. My question is regarding the `sys.argv` command. I've read it is used for a command line interpreter, but when trying to execute a simple program I don't get the results I expect. Code: ``` import sys a = sys.argv[1] b = sys.argv[2] print a, b print a...
Indeed, you have found the problem yourself, `sys.argv` is an array of strings. You can transform a string to an integer with `int()`. In this case for example: `a = int(sys.argv[1])`
numpy array creating with a sequence
10,753,528
13
2012-05-25T11:23:05Z
10,765,729
12
2012-05-26T11:11:37Z
[ "python", "arrays", "numpy", "scipy", "sequence" ]
I am on my transitional trip from MATLAB to scipy(+numpy)+matplotlib. I keep having issues when implementing some things. I want to create a simple vector array in three different parts. In MATLAB I would do something like: ``` vector=[0.2,1:60,60.8]; ``` This results in a one dimensional array of 62 positions. I'm t...
Well NumPy implements MATLAB's array-creation function, *vector*, using *two* functions instead of one--each implicitly specifies a particular axis along which *concatenation* ought to occur. These functions are: * **r\_** (row-wise concatenation) and * **c\_** (column-wise) So for your example, the NumPy equivalent ...
timeout on subprocess readline in python
10,756,383
20
2012-05-25T14:38:42Z
10,756,824
7
2012-05-25T15:04:21Z
[ "python", "timeout", "subprocess" ]
I have a small issue that I'm not quite sure how to solve. Here is a minimal example: ### What I have ``` scan_process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) while(some_criterium): line = scan_process.stdout.readline() some_criterium = do_something(line) ``` ### What I ...
I used something a bit more general in python (IIRC also pieced together from SO questions, but I cannot recall which ones). ``` import thread from threading import Timer def run_with_timeout(timeout, default, f, *args, **kwargs): if not timeout: return f(*args, **kwargs) try: timeout_timer = ...
timeout on subprocess readline in python
10,756,383
20
2012-05-25T14:38:42Z
10,759,061
12
2012-05-25T17:42:41Z
[ "python", "timeout", "subprocess" ]
I have a small issue that I'm not quite sure how to solve. Here is a minimal example: ### What I have ``` scan_process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) while(some_criterium): line = scan_process.stdout.readline() some_criterium = do_something(line) ``` ### What I ...
Thanks for all the answers! I found a way to solve my problem by simply using select.poll to peek into stdout. ``` import select ... scan_process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) poll_obj = select.poll() poll_obj.register(scan_process.stdout, select.POLLIN) while(some_cr...
Loop through all nested dictionary values?
10,756,427
27
2012-05-25T14:41:23Z
10,756,547
47
2012-05-25T14:47:57Z
[ "python", "dictionary" ]
``` for k, v in dict.iteritems(): if type(v) is dict: for t, c in v.iteritems(): print "{0} : {1}".format(t, c) ``` I'm trying to loop through a dictionary and print out all key value pairs where the value is not a nested dictionary. If the value is a dictionary I want to go into it and print o...
As said by Niklas, you need recursion, i.e. you want to define a function to print your dict, and if the value is a dict, you want to call your print function using this new dict. Something like : ``` def myprint(d): for k, v in d.iteritems(): if isinstance(v, dict): myprint(v) else: print "{0} ...
Loop through all nested dictionary values?
10,756,427
27
2012-05-25T14:41:23Z
10,756,615
14
2012-05-25T14:52:40Z
[ "python", "dictionary" ]
``` for k, v in dict.iteritems(): if type(v) is dict: for t, c in v.iteritems(): print "{0} : {1}".format(t, c) ``` I'm trying to loop through a dictionary and print out all key value pairs where the value is not a nested dictionary. If the value is a dictionary I want to go into it and print o...
Since a `dict` is iterable, you can apply the classic [nested container iterable formula](http://stackoverflow.com/a/2158532/577088) to this problem with only a couple of minor changes. ``` >>> import collections >>> def nested_dict_iter(nested): ... for key, value in nested.iteritems(): ... if isinstance(...
Loop through all nested dictionary values?
10,756,427
27
2012-05-25T14:41:23Z
10,757,107
9
2012-05-25T15:22:21Z
[ "python", "dictionary" ]
``` for k, v in dict.iteritems(): if type(v) is dict: for t, c in v.iteritems(): print "{0} : {1}".format(t, c) ``` I'm trying to loop through a dictionary and print out all key value pairs where the value is not a nested dictionary. If the value is a dictionary I want to go into it and print o...
Alternative iterative solution: ``` def myprint(d): stack = d.items() while stack: k, v = stack.pop() if isinstance(v, dict): stack.extend(v.iteritems()) else: print("%s: %s" % (k, v)) ```
import unittest error
10,756,577
3
2012-05-25T14:49:59Z
10,756,681
15
2012-05-25T14:55:58Z
[ "python", "unit-testing" ]
This is my first time doing unit testing and i'm trying to run a simple code... ``` import random import unittest class TestSequenceFunctions(unittest.TestCase): def setUp(self): self.seq = range(10) def test_shuffle(self): # make sure the shuffled sequence does not lose any elements ...
That's because your script name is called `unittest.py`. The statement `import unittest` is importing your script rather than the unittest module, hence the error with the non-existant `TestCase` attribute. For more info, see the docs for [Module Search Path](http://docs.python.org/tutorial/modules.html#the-module-sea...
Python 2.7: type object "ElementTree" has no attribute "register_namespace"
10,757,702
8
2012-05-25T15:58:23Z
10,757,887
21
2012-05-25T16:10:57Z
[ "python", "xml", "elementtree" ]
with this python 2.7.3 (or 2.7.0) code I want to change the value of the attribute "android:versionCode='2'", which has the namespace prefix "android": ``` #!/usr/bin/python from xml.etree.ElementTree import ElementTree, dump import sys, os # Problem here: ElementTree.register_namespace("android", "http://schemas.and...
[`register_namespace()` is a function contained within the ElementTree *module*](http://hg.python.org/cpython/file/2.7/Lib/xml/etree/ElementTree.py#l1030). It is *not* contained within the `ElementTree` class... An aside: Because of the confusion that is sometimes caused by doing so it is generally not recommended t...
numpy.loadtxt gives "not iterable" error
10,758,668
5
2012-05-25T17:12:32Z
10,758,854
8
2012-05-25T17:26:30Z
[ "python", "input", "numpy" ]
I'm trying to use `numpy.loadtxt` to read the data in a file that looks like this: ``` ## 14 line of header 3 0 36373.7641026 3 1 36373.7641026 3 2 36373.7641026 ... ``` And when I give it this: ``` >>> chunk, power = numpy.loadtxt(bf,skiprows=14,usecols=(1,2),unpack=True) ``` Or even this: ``` >>> power = numpy.l...
In your second example, the problem is likely `usecols=(2)`. `usecols` must be a sequence. `(2)` is the integer 2, not a one-element tuple containing 2, and is likely what the error message is complaining about: `loadtxt()` is trying to iterate over an `int`. Use `(2,)` (or `[2]` if you prefer).
Difference between object and instance in python?
10,759,099
8
2012-05-25T17:46:32Z
10,759,244
8
2012-05-25T17:59:42Z
[ "python", "oop" ]
This happens in python2.7 I am working on the idea of meta class in python, almost all the tutorial refer object as instance of a class, in python. However, when playing with the class A(): form of defining a class, I saw this: ``` class ClsDef1(): pass C1 = ClsDef1() print C1 <__main__.ClsDef1 instance at 0x2aea...
This is the difference between new-style and old-style classes, which is explained in great detail [in the documentation](http://docs.python.org/reference/datamodel.html). Basically, in Python 2.x you should ensure you always inherit from object so that you get a new-style class. In Python 3, old-style classes have gon...
Converting .jpg images to .png
10,759,117
8
2012-05-25T17:49:14Z
10,759,132
15
2012-05-25T17:51:00Z
[ "python", "python-2.7" ]
I've looked around and read the docs, and found no way or solution, so I ask here. Is there any packages available to use Python to convert a JPG image to a PNG image?
You could always use the [Python Image Library (PIL)](http://www.pythonware.com/products/pil/) for this purpose. There might be other packages/libraries too, but I've used this before to convert between formats. This works with Python 2.7 under Windows ([Python Imaging Library 1.1.7 for Python 2.7](http://effbot.org/d...
How to use gfx in pygame
10,759,608
10
2012-05-25T18:26:23Z
11,387,139
11
2012-07-08T22:09:51Z
[ "python", "pygame", "gfx" ]
I have a pygame game and I want to use pygame.gfxdraw.aacricle(), but whenever I do it gives me an error: > AttributeError: 'module' object has no attribute 'gfxdraw' How do I install gfx for python 2.7?
I had this same issue using gfxdraw in pygame as well. Once I imported the module explicitly, there were no issues. Adding this line after importing pygame fixed the issue: ``` import pygame.gfxdraw ``` Curiously, I don't need to import pygame.draw explicitly in order to use it.
Best way to print list output in python
10,760,019
4
2012-05-25T19:02:12Z
10,760,049
8
2012-05-25T19:05:09Z
[ "python", "list" ]
I have a `list` and a `list of list` like this ``` >>> list2 = [["1","2","3","4"],["5","6","7","8"],["9","10","11","12"]] >>> list1 = ["a","b","c"] ``` I zipped the above two list so that i can match their value index by index. ``` >>> mylist = zip(list1,list2) >>> mylist [('a', ['1', '2', '3', '4']), ('b', ['5', '6...
Well, you could avoid some temporary variables and use a nicer loop: ``` for label, vals in zip(list1, list2): print label print '---'.join(vals) ``` I don't think you're going to get anything fundamentally "better," though.
"Zebra Tables" in IPython Notebook?
10,760,364
8
2012-05-25T19:33:39Z
10,761,312
13
2012-05-25T21:01:21Z
[ "python", "pandas", "ipython", "ipython-notebook", "jupyter" ]
I'm building some interactive workflows in IPython using the fantastic Notebook for interactive analysis and Pandas. Some of the tables I'm displaying would be much easier to read with a little bit of formatting. I'd really like something like "zebra tables" where every other row is shaded. I [read here](http://dev.op...
You can run arbitrary javascript (with jQuery) either in markdown cells inside `<script>` tags, or via IPython's `IPython.core.display.Javascript` class. With these, you can manipulate (or ruin) the document to your heart's content, including adding stylesheets. For instance, the following will stripe appropriately cl...
"Zebra Tables" in IPython Notebook?
10,760,364
8
2012-05-25T19:33:39Z
14,050,441
7
2012-12-27T06:32:31Z
[ "python", "pandas", "ipython", "ipython-notebook", "jupyter" ]
I'm building some interactive workflows in IPython using the fantastic Notebook for interactive analysis and Pandas. Some of the tables I'm displaying would be much easier to read with a little bit of formatting. I'd really like something like "zebra tables" where every other row is shaded. I [read here](http://dev.op...
I just released a project called ipy\_table to provide an easy mechanism for creating richly formatted data tables in IPython notebooks (colors, borders, alignment, float formatting, zebra shading, etc.). The project is at <https://github.com/epmoyer/ipy_table>, and you can get a good idea of it's capabilities from <ht...
Python property does not set
10,760,937
6
2012-05-25T20:25:06Z
10,761,077
8
2012-05-25T20:39:16Z
[ "python", "properties" ]
Here is the code: ``` def Property(func): return property(**func()) class A: def __init__(self, name): self._name = name @Property def name(): doc = 'A''s name' def fget(self): return self._name def fset(self, val): self._nam...
The [documentation for `property()`](http://docs.python.org/library/functions.html#property) states: > Return a property attribute for new-style classes (classes that derive from object). Your class is not a new-style class (you didn't inherit from object). Change the class declaration to: ``` class A(object): ....
Searching a csv for hex data with python
10,760,971
4
2012-05-25T20:27:53Z
10,761,002
7
2012-05-25T20:31:23Z
[ "python", "csv" ]
I have a csv file which has 3 columns. I am trying to search through the second column for a specific value (hex values) and read the next entry over in that line (column 3). The format is similar to the below: ``` Text1, 0x04d0a053, value1 Text2, 0x04d01053, value2 Text3, 0x04d03053, value3 Text4, 0x04d05053, val...
hex(0x **0** 4413053) is "0x4413053" You should probably do the inverse, i.e. ``` int(line[clolumn1], 16) == 0x04413053 ```
How can I detect duplicate method names in a python class?
10,761,988
17
2012-05-25T22:20:05Z
10,762,022
23
2012-05-25T22:25:11Z
[ "python" ]
When writing unit tests, I sometimes cut and paste a test and don't remember to change the method name. This results in overwriting the previous test, effectively hiding it and preventing it from running. For example; ``` class WidgetTestCase(unittest.TestCase): def test_foo_should_do_some_behavior(self): self....
If you run [pylint](http://www.logilab.org/857) over your code, it will inform you when you have overwritten another method: For example, I ran this: ``` class A(object): def blah(self): print("Hello World!") def blah(self): print("I give up!") ``` In [this online pylint checker](http://anta...
How can I detect duplicate method names in a python class?
10,761,988
17
2012-05-25T22:20:05Z
10,762,966
14
2012-05-26T01:23:53Z
[ "python" ]
When writing unit tests, I sometimes cut and paste a test and don't remember to change the method name. This results in overwriting the previous test, effectively hiding it and preventing it from running. For example; ``` class WidgetTestCase(unittest.TestCase): def test_foo_should_do_some_behavior(self): self....
What follows is a horrible hack that uses undocumented, implementation-specific Python features. You should never ever *ever* do anything like this. It's been tested on Python 2.6.1 and 2.7.2; doesn't seem to work with Python 3.2 as written, but then, you can [do this right](http://stackoverflow.com/questions/10762088...
Python metaclasses: Why isn't __setattr__ called for attributes set during class definition?
10,762,088
12
2012-05-25T22:35:12Z
10,762,178
7
2012-05-25T22:47:38Z
[ "python", "metaclass" ]
I have the following python code: ``` class FooMeta(type): def __setattr__(self, name, value): print name, value return super(FooMeta, self).__setattr__(name, value) class Foo(object): __metaclass__ = FooMeta FOO = 123 def a(self): pass ``` I would have expected `__setattr__` ...
There are no assignments happening during the creation of the class. Or: they are happening, but not in the context you think they are. All class attributes are collected from class body scope and passed to metaclass' `__new__`, as the last argument: ``` class FooMeta(type): def __new__(self, name, bases, attrs): ...
Python metaclasses: Why isn't __setattr__ called for attributes set during class definition?
10,762,088
12
2012-05-25T22:35:12Z
10,763,270
18
2012-05-26T02:57:30Z
[ "python", "metaclass" ]
I have the following python code: ``` class FooMeta(type): def __setattr__(self, name, value): print name, value return super(FooMeta, self).__setattr__(name, value) class Foo(object): __metaclass__ = FooMeta FOO = 123 def a(self): pass ``` I would have expected `__setattr__` ...
A class block is roughly syntactic sugar for building a dictionary, and then invoking a metaclass to build the class object. This: ``` class Foo(object): __metaclass__ = FooMeta FOO = 123 def a(self): pass ``` Comes out pretty much as if you'd written: ``` d = {} d['__metaclass__'] = FooMeta d['...
Why accept kwargs but not use them?
10,762,780
4
2012-05-26T00:40:23Z
10,762,792
9
2012-05-26T00:43:54Z
[ "python", "django", "kwargs" ]
I was looking at the Django source code today and I noticed this: ``` class DjangoTestSuiteRunner(object): def __init__(self, verbosity=1, interactive=True, failfast=True, **kwargs): self.verbosity = verbosity self.interactive = interactive self.failfast = failfast ``` Why would they accep...
This pattern can make backwards/forwards compatibility easier. If the newer/older version of the code has more/less parameters then you won't break everything. Also, when you are inheriting this class (for example with mixins) it can be convenient to just accept everything. Imho it's not a pretty pattern to use, but ...
Is there a way to hide the csrf label while looping through form using Flask and Flask-WTForms?
10,763,139
16
2012-05-26T02:20:39Z
10,799,877
29
2012-05-29T13:10:48Z
[ "python", "flask", "jinja2" ]
I have very simple contact form and I would like to hide the label somehow so that it doesn't show `Csrf Token`. I am using Flask and Flask-WTForms and am rendering the form like this: ``` {% for field in form %} {{ field.label }} {{ field }} {% endfor %} ``` So basically this shows my inputs correctly and th...
If you want a more general solution that works for all hidden fields instead of just the CSRF token: ``` {{ form.hidden_tag() }} {% for field in form if field.widget.input_type != 'hidden' %} {{ field.label }} {{ field }} {% endfor %} ``` `form.hidden_tag()` is supplied by Flask-WTF.
Can SQLAlchemy be used with Google Cloud SQL?
10,763,171
14
2012-05-26T02:31:15Z
10,900,826
32
2012-06-05T16:07:24Z
[ "python", "google-app-engine", "sqlalchemy", "flask-sqlalchemy", "google-cloud-sql" ]
I've looked over Google Cloud SQL's documentation and various searches, but I can't find out whether it is possible to use SQLAlchemy with Google Cloud SQL, and if so, what the connection URI should be. I'm looking to use the Flask-SQLAlchemy extension and need the connection string like so: `mysql://username:password...
**Update** Google Cloud SQL now supports direct access, so the `MySQLdb` dialect can now be used. The recommended connection via the mysql dialect is using the URL format: ``` mysql+mysqldb://root@/<dbname>?unix_socket=/cloudsql/<projectid>:<instancename> ``` `mysql+gaerdbms` has been deprecated in SQLAlchemy since ...
Extract email from string instead of whole line from string
10,763,249
2
2012-05-26T02:53:51Z
10,763,260
8
2012-05-26T02:55:48Z
[ "python", "regex" ]
I am attempting to grab just the email address from a string of text using Regex. **How can I get my simple code to extract just the email address and not the whole line?** ``` demo_text = """hsds hjdsjd ksdkj Reason: 550 abc@gmail.com... No such user sdhjsdjh """ # the following code extracts the whole line "Reaso...
`.group(0)` returns the whole string. You want `.group(1)`: ``` email = re.search("Reason: 550 (.*?)... No such user", demo_text).group(1) ```
How to install python3 version of package via pip on Ubuntu?
10,763,440
225
2012-05-26T03:50:57Z
10,763,461
137
2012-05-26T03:57:28Z
[ "python", "ubuntu", "python-3.x", "ubuntu-12.04", "pip" ]
I have both `python2.7` and `python3.2` installed in `Ubuntu 12.04`. The symbolic link `python` links to `python2.7`. When I type: ``` sudo pip install package-name ``` It will default install `python2` version of `package-name`. Some package supports both `python2` and `python3`. How to install `python3` versi...
You may want to build a `virtualenv` of python3, then install packages of python3 after activating the virtualenv. So your system won't be messed up :) This could be something like: ``` virtualenv -p /usr/bin/python3 py3env source py3env/bin/activate pip install package-name ```
How to install python3 version of package via pip on Ubuntu?
10,763,440
225
2012-05-26T03:50:57Z
10,763,626
24
2012-05-26T04:39:31Z
[ "python", "ubuntu", "python-3.x", "ubuntu-12.04", "pip" ]
I have both `python2.7` and `python3.2` installed in `Ubuntu 12.04`. The symbolic link `python` links to `python2.7`. When I type: ``` sudo pip install package-name ``` It will default install `python2` version of `package-name`. Some package supports both `python2` and `python3`. How to install `python3` versi...
The easiest way to install latest `pip2`/`pip3` and corresponding packages: ``` curl https://bootstrap.pypa.io/get-pip.py | python2 pip2 install package-name curl https://bootstrap.pypa.io/get-pip.py | python3 pip3 install package-name ``` **Note:** please run these commands as `root`
How to install python3 version of package via pip on Ubuntu?
10,763,440
225
2012-05-26T03:50:57Z
10,785,555
8
2012-05-28T13:35:19Z
[ "python", "ubuntu", "python-3.x", "ubuntu-12.04", "pip" ]
I have both `python2.7` and `python3.2` installed in `Ubuntu 12.04`. The symbolic link `python` links to `python2.7`. When I type: ``` sudo pip install package-name ``` It will default install `python2` version of `package-name`. Some package supports both `python2` and `python3`. How to install `python3` versi...
If you have pip installed in both pythons, and both are in your path, just use: ``` $ pip-2.7 install PACKAGENAME $ pip-3.2 install PACKAGENAME ``` References: * <http://www.pip-installer.org/docs/pip/en/0.8.3/news.html#id4> * <https://github.com/pypa/pip/issues/200> This is a duplicate of question [#2812520](http:...
How to install python3 version of package via pip on Ubuntu?
10,763,440
225
2012-05-26T03:50:57Z
12,262,143
324
2012-09-04T11:01:30Z
[ "python", "ubuntu", "python-3.x", "ubuntu-12.04", "pip" ]
I have both `python2.7` and `python3.2` installed in `Ubuntu 12.04`. The symbolic link `python` links to `python2.7`. When I type: ``` sudo pip install package-name ``` It will default install `python2` version of `package-name`. Some package supports both `python2` and `python3`. How to install `python3` versi...
**Ubuntu 12.10+ and Fedora 13+ have a package called `python3-pip` which will install `pip-3.2` (or `pip-3.3`, `pip-3.4` or `pip3` for newer versions) without needing this jumping through hoops.** --- I came across this and fixed this without needing the likes of `wget` or virtualenvs (assuming Ubuntu 12.04): 1. Ins...
How to install python3 version of package via pip on Ubuntu?
10,763,440
225
2012-05-26T03:50:57Z
13,001,357
106
2012-10-21T19:25:36Z
[ "python", "ubuntu", "python-3.x", "ubuntu-12.04", "pip" ]
I have both `python2.7` and `python3.2` installed in `Ubuntu 12.04`. The symbolic link `python` links to `python2.7`. When I type: ``` sudo pip install package-name ``` It will default install `python2` version of `package-name`. Some package supports both `python2` and `python3`. How to install `python3` versi...
# Short Answer ``` sudo apt-get install python3-pip sudo pip3 install MODULE_NAME ``` Source: [Shashank Bharadwaj's comment](http://stackoverflow.com/questions/10763440/how-to-install-python3-version-of-package-via-pip#comment17706098_12262143) # Long Answer The short answer applies only on newer systems. On some v...
How to install python3 version of package via pip on Ubuntu?
10,763,440
225
2012-05-26T03:50:57Z
17,266,254
13
2013-06-23T23:29:08Z
[ "python", "ubuntu", "python-3.x", "ubuntu-12.04", "pip" ]
I have both `python2.7` and `python3.2` installed in `Ubuntu 12.04`. The symbolic link `python` links to `python2.7`. When I type: ``` sudo pip install package-name ``` It will default install `python2` version of `package-name`. Some package supports both `python2` and `python3`. How to install `python3` versi...
Old question, but none of the answers satisfies me. One of my systems is running Ubuntu 12.04 LTS and for some reason there's no package `python3-pip` or `python-pip` for Python 3. So here is what I've done (all commands were executed as root): * Install `setuptools` for Python3 in case you haven't. ``` apt-get i...
How to install python3 version of package via pip on Ubuntu?
10,763,440
225
2012-05-26T03:50:57Z
21,990,468
30
2014-02-24T14:22:17Z
[ "python", "ubuntu", "python-3.x", "ubuntu-12.04", "pip" ]
I have both `python2.7` and `python3.2` installed in `Ubuntu 12.04`. The symbolic link `python` links to `python2.7`. When I type: ``` sudo pip install package-name ``` It will default install `python2` version of `package-name`. Some package supports both `python2` and `python3`. How to install `python3` versi...
Well, on **ubuntu 13.10/14.04**, things are a little different. ## Install ``` $ sudo apt-get install python3-pip ``` ## Install packages ``` $ sudo pip3 install packagename ``` NOT `pip-3.3 install`
How to install python3 version of package via pip on Ubuntu?
10,763,440
225
2012-05-26T03:50:57Z
31,370,370
8
2015-07-12T17:08:06Z
[ "python", "ubuntu", "python-3.x", "ubuntu-12.04", "pip" ]
I have both `python2.7` and `python3.2` installed in `Ubuntu 12.04`. The symbolic link `python` links to `python2.7`. When I type: ``` sudo pip install package-name ``` It will default install `python2` version of `package-name`. Some package supports both `python2` and `python3`. How to install `python3` versi...
I had the same problem while trying to install pylab, and I have found this [link](https://docs.python.org/3/installing/) So what I have done to install pylab within Python 3 is: ``` python3 -m pip install SomePackage ``` It has worked properly, and as you can see in the link you can do this for every Python version...
Histogram without plotting function
10,763,697
6
2012-05-26T04:56:40Z
10,764,312
11
2012-05-26T07:02:28Z
[ "python" ]
I am trying to create a simple text based histogram using python but without importing any plotting functions such as matplot or gnuplot. I will be importing data from a csv file to create that histogram.
How about something like this ``` import random def plot(data): """ Histogram data to stdout """ largest = max(data) scale = 50. / largest for i, datum in enumerate(data): bar = "*" * int(datum * scale) print "%2d: %s (%d)" % (i, bar, datum) data = [ random.randrange(100) for ...
Python While Loop, the and (&) operator is not working
10,764,007
4
2012-05-26T05:59:49Z
10,764,020
11
2012-05-26T06:01:58Z
[ "python", "while-loop", "operator-keyword" ]
I am trying to find the greatest common factor. I wrote a bad (operation intensive) algorithm that decrements the lower value by one, checks using % to see if it evenly divides both the numerator and denominator, if it does then it exits the program. However, my while loop is not using the and operator, and thus once ...
You should be using the keyword `and` instead of the bitwise and operator `&`: ``` while (v % d != 0) and (u % d != 0): ``` This is also the same: ``` while (v % d) and (u % d): ``` Note that `&` and `and` will give the same result in the first case, but not in the second. Your problem though is that you want to u...
Python - Ubuntu install for SQLAlchemy not working
10,764,408
5
2012-05-26T07:19:23Z
10,764,439
12
2012-05-26T07:24:13Z
[ "python", "ubuntu", "sqlalchemy" ]
I'm trying to setup a ubuntu box so I can do some work, and I'm having a heck of a time trying to get SQLAlchemy installed. I have tried pretty much everything I can find on tutorials etc, and the latest position I find myself in is: `easy_install SQLAchemy` seems to work ok, and installs version 0.7.4 (as far as I c...
you could also use the version directly from the ubuntu repositories: ``` sudo apt-get install python-sqlalchemy # or python3-sqlalchemy ``` if you used `sudo easy_install`, then the packages usually get installed in `/usr/local/lib/pythonX.X/`. The problem could be that `easy_install` (and also `pip`) doesn't set th...
Python3.2 can not recognize UP/DOWN/LEFT/RIGHT keys in interpreter?
10,765,441
3
2012-05-26T10:25:08Z
10,765,461
7
2012-05-26T10:27:58Z
[ "python", "python-3.x", "ipython" ]
I am using ubuntu, linux kernel 2.6.38. I usually use python2, today, I decide to try Python3. I downloads python3 and `make install` it following the README. However,the python 3.2 interpreter can not recognize `UP/SOWN/LEFT/RIGHT` keys, these keys are available in my python 2.7 interpreter. What's wrong did I make? ...
Install the `libreadline-dev` package from Ubuntu, then recompile Python from scratch.
Build query string using urlencode python
10,765,705
4
2012-05-26T11:08:03Z
10,765,733
13
2012-05-26T11:11:55Z
[ "python", "dictionary", "urllib" ]
I am trying to build a url so that I can send a get request to it using `urllib` module. Let's suppose my `final_url` should be ``` url = "www.example.com/find.php?data=http%3A%2F%2Fwww.stackoverflow.com&search=Generate+value" ``` Now to achieve this I tried the following way: ``` >>> initial_url = "http://www.stac...
You shouldn't worry about encoding the `+` it should be restored on the server after unescaping the url. The order of named parameters shouldn't matter either. Considering OrderedDict, it is not Python's built in. You should import it from `collections`: ``` from urllib import urlencode, quote from collections import...
How to fix forward slash issue in path on windows in python?
10,766,483
5
2012-05-26T13:03:26Z
10,766,517
12
2012-05-26T13:07:57Z
[ "python", "windows", "path", "pyside" ]
I have developed an application in python and pyside. I have developed it on linux machine. Now I want to deploy it on windows machine. Here problem is path. In linux forward slash(/) used as separator but windows uses backward slash(\) as separator. So, on windows all paths not work. There are several paths in applic...
use [`os.sep`](http://docs.python.org/library/os.html#os.sep) instead of explicitly writing the slashes.
How to fix forward slash issue in path on windows in python?
10,766,483
5
2012-05-26T13:03:26Z
10,766,526
13
2012-05-26T13:09:23Z
[ "python", "windows", "path", "pyside" ]
I have developed an application in python and pyside. I have developed it on linux machine. Now I want to deploy it on windows machine. Here problem is path. In linux forward slash(/) used as separator but windows uses backward slash(\) as separator. So, on windows all paths not work. There are several paths in applic...
[`os.path.join()`](http://docs.python.org/library/os.path.html#os.path.join) will use the right kind of slash on the right platform.
Extract field list from reStructuredText
10,766,609
5
2012-05-26T13:18:54Z
10,782,270
7
2012-05-28T09:27:25Z
[ "python", "restructuredtext", "docutils" ]
Say I have the following reST input: ``` Some text ... :foo: bar Some text ... ``` What I would like to end up with is a dict like this: ``` {"foo": "bar"} ``` I tried to use this: ``` tree = docutils.core.publish_parts(text) ``` It does parse the field list, but I end up with some pseudo XML in `tree["whole"]?...
You can try to use something like the following code. Rather than using the `publish_parts` method I have used [`publish_doctree`](http://docutils.sourceforge.net/docs/api/publisher.html), to get the pseudo-XML representation of your document. I have then converted to an XML DOM in order to extract all the `field` elem...
How would you represent the following 3D data in Matplotlib or Mayavi?
10,766,698
7
2012-05-26T13:33:13Z
10,767,450
7
2012-05-26T15:23:06Z
[ "python", "matplotlib", "mayavi", "mplot3d" ]
I have a large set of data which I'm trying to represent in 3D hoping to spot a pattern. I've spent quite some time reading, researching and coding, but then I realized my main problem is NOT the programming, but actually **choosing a way to visualize the data**. Matplotlib's mplot3d offers a lot of options (wireframe...
To comment on the visualisation part of your question (not the programming), I have mocked up some example facetted graphs to suggest alternatives you may want to use to explore your data. ``` library("lubridate") library("ggplot2") library("reshape2") dates <- c("2011-01-01","2011-01-04","2011-01-05", "20...
Assigning default argument values
10,767,446
3
2012-05-26T15:22:29Z
10,767,458
9
2012-05-26T15:24:01Z
[ "python" ]
Using this script: ``` color = 'blue' def say_color(color): print 'The color is: ' + color say_color() ``` Here, I am trying to allow `say_color` to be processed without passing an argument, and the result being the default color (blue). However, if a color is specified, it will not use blue and use the string ...
``` def say_color(color='blue'): print 'The color is: ' + color say_color() ```
Is there a function in numpy to replace lower and upper diagonal values of a numpy array?
10,768,007
3
2012-05-26T16:31:55Z
10,768,105
7
2012-05-26T16:46:51Z
[ "python", "arrays", "numpy" ]
To replace the main diagonal I have used `np.fill_diagonal`: ``` matrix = np.zeros((4, 4), float) main = np.array([2,2,2,2]) np.fill_diagonal(matrix, main) ``` but I also need to replace the upper and lower diagonals that are next to the main diagonal: ``` upper=np.array([1,1,1]) lower=np.array([7,7,7]) ``` to get:...
With some smart slicing, `np.fill_diagonal` can do this too: ``` >>> np.fill_diagonal(matrix[:-1, 1:], upper) >>> np.fill_diagonal(matrix[1:, :-1], lower) >>> matrix array([[ 2., 1., 0., 0.], [ 7., 2., 1., 0.], [ 0., 7., 2., 1.], [ 0., 0., 7., 2.]]) ```
python send POST with header
10,768,522
12
2012-05-26T17:51:36Z
10,782,805
19
2012-05-28T10:06:26Z
[ "python", "post", "header" ]
I try to build a python script who sends a POST with parameters for extracting the result. Whith fiddler I have extract the post request who return that I want. The website use https only. ``` POST /Services/GetFromDataBaseVersionned HTTP/1.1 Host: www.mywbsite.fr "Connection": "keep-alive", "Content-Length": 129, "Or...
Thanks alot for your link for the requests module. It's just perfect. Below the solution at my problem. ``` import requests import json url = 'https://www.mywbsite.fr/Services/GetFromDataBaseVersionned' payload = { "Host": "www.mywbsite.fr", "Connection": "keep-alive", "Content-Length": 129, "Origin":...
Execute python commands passed as strings in command line using python -c
10,768,584
4
2012-05-26T18:01:22Z
30,690,444
7
2015-06-07T05:47:51Z
[ "python" ]
Is it possible to execute python commands passed as strings using python -c? can someone give an example.
You can use `-c` to get Python to execute a string. For example: `python3 -c "print(5)"` However, there doesn't seem to be a way to use escape characters (e.g. `\n`). So, if you need them, use a pipe from `echo -e` or `printf` instead. For example: `$ printf "import sys\nprint(sys.path)" | python3`
Why does Python return 0 for simple division calculation?
10,768,724
15
2012-05-26T18:24:22Z
10,768,737
32
2012-05-26T18:25:49Z
[ "python" ]
Why does this simple calculation return 0 ``` >>> 25/100*50 0 ``` while this actually calculates correctly? ``` >>> .25*50 12.5 >>> 10/2*2 10 ``` What is wrong with the first example?
In Python 2, `25/100` is zero when performing an integer divison. since the result is less than `1`. You can "fix" this by adding `from __future__ import division` to your script. This will always perform a float division when using the `/` operator and use `//` for integer division. Another option would be making at...
Why does Python return 0 for simple division calculation?
10,768,724
15
2012-05-26T18:24:22Z
10,768,742
7
2012-05-26T18:26:17Z
[ "python" ]
Why does this simple calculation return 0 ``` >>> 25/100*50 0 ``` while this actually calculates correctly? ``` >>> .25*50 12.5 >>> 10/2*2 10 ``` What is wrong with the first example?
This is a problem of integer **truncation** (i.e., any fractional parts of a number are discarded). So: `25 / 100` gives `0` However, as long as *at least one* of the operands in the division is a float, you'll get a float result:  `25 / 100.0` or `25.0 / 100`  or `25.0 / 100.0` all give `0.25`
Django & South: Adding new field but DatabaseError occurs "table already exists"
10,769,644
3
2012-05-26T20:48:06Z
10,769,707
12
2012-05-26T20:56:02Z
[ "python", "django", "django-south" ]
In trying to add a new field to a preexisting Model/table, I get a DatabaseError with 'table already exists.' I have run migrations before this one so I am a bit puzzled why adding a new field would pop up this error. Commands executed: ``` python manage.py schemamigration app --auto python manage.py migrate app ``` ...
You need to do `schemamigration app --initial` first *without* your new field, then `migrate app --fake 0001` (or whichever migration number it returned) to set the south database to that state (tables already created). Add your new field, *then* run `schemamigration myapp --auto`, *then* migrate.
howto create db mysql with sqlalchemy
10,770,377
13
2012-05-26T22:56:47Z
10,770,526
19
2012-05-26T23:28:03Z
[ "python", "mysql", "sqlalchemy" ]
I need to create a db in mysql using sqlalchemy, I am able to connect to a db if it already exists, but I want to be able to create it if it does not exist. this are my tables: ``` #def __init__(self): Base = declarative_base() class utente(Base): __tablename__="utente" utente_id=Column(Integer,primary_ke...
To create a `mysql` database you just connect to the server an create the database: ``` import sqlalchemy engine = sqlalchemy.create_engine('mysql://user:password@server') # connect to server engine.execute("CREATE DATABASE dbname") #create db engine.execute("USE dbname") # select new db # use the new db # continue wi...
howto create db mysql with sqlalchemy
10,770,377
13
2012-05-26T22:56:47Z
18,670,891
7
2013-09-07T07:23:50Z
[ "python", "mysql", "sqlalchemy" ]
I need to create a db in mysql using sqlalchemy, I am able to connect to a db if it already exists, but I want to be able to create it if it does not exist. this are my tables: ``` #def __init__(self): Base = declarative_base() class utente(Base): __tablename__="utente" utente_id=Column(Integer,primary_ke...
``` CREATE DATABASE IF NOT EXISTS dbName; ```
Printing Null Character ("\x00") in Python vs C
10,770,940
2
2012-05-27T01:07:21Z
10,770,953
9
2012-05-27T01:10:01Z
[ "python", "c", null, "string-formatting" ]
When I code and run the statement: ``` print "\x00\x00\x00" ``` in Python it outputs three blank spaces followed by a newline. But in C, when I code and run the statement: ``` char hex[] = "\x00\x00\x00"; printf("%s\n", hex); ``` it interprets the NULL bytes like I thought it would: it doesn't do anything....
> So why in Python are NULL bytes treated as spaces? It's not. Your terminal/console is treating them like spaces. C just happens to stop at the first NUL, whereas Python outputs them. Try writing three NULs to stdout instead.
Using metaclasses to override methods of complex builtin
10,771,010
9
2012-05-27T01:27:18Z
10,771,293
8
2012-05-27T02:47:03Z
[ "python", "metaprogramming", "metaclass", "complex-numbers" ]
As a learning exercise, I'm trying to implement a class which will emulate the behavior of python's `complex` builtin, but with different behavior of the `__str__` and `__repr__` methods: I want them to print in the format... ``` (1.0,2.0) ``` ...instead of: ``` (1+2j) ``` I first tried simply subclassing from `com...
Your current approach won't work. How you define your class isn't the issue -- the methods of `complex` are creating new instances of `complex` when you call them, rather than using the `type` of the input objects. You'll always get back instances of `complex` rather than `ComplexWrapper`, so your customized methods wo...
Python - abs vs fabs
10,772,302
61
2012-05-27T07:16:39Z
10,772,325
74
2012-05-27T07:21:00Z
[ "python" ]
I noticed that in python there are two similar looking methods for finding the absolute value of a number: First ``` abs(-5) ``` Second ``` import math math.fabs(-5) ``` How do these methods differ?
[`math.fabs()`](https://docs.python.org/2/library/math.html#math.fabs) converts its argument to float if it can (if it can't, it throws an exception). It then takes the absolute value, and returns the result as a float. In addition to floats, [`abs()`](https://docs.python.org/2/library/functions.html#abs) also works w...
Finding differences between strings
10,775,029
6
2012-05-27T15:17:43Z
10,775,310
18
2012-05-27T15:58:18Z
[ "python", "string" ]
I have the following function that gets a source and a modified strings, and bolds the changed words in it. ``` def appendBoldChanges(s1, s2): "Adds <b></b> tags to words that are changed" l1 = s1.split(' ') l2 = s2.split(' ') for i, val in enumerate(l1): if l1[i].lower() != l2[i].lower(): ...
You could use [difflib](http://docs.python.org/library/difflib.html), and do it like this: ``` from difflib import Differ def appendBoldChanges(s1, s2): "Adds <b></b> tags to words that are changed" l1 = s1.split(' ') l2 = s2.split(' ') dif = list(Differ().compare(l1, l2)) return " ".join(['<b>'+i...
Combining node.js and Python
10,775,351
91
2012-05-27T16:03:52Z
10,775,442
66
2012-05-27T16:17:28Z
[ "python", "node.js", "ipc" ]
Node.js is a perfect match for our web project, but there are few computational tasks for which we would prefer Python. We also already have a Python code for them. We are highly concerned about speed, what is the most elegant way how to call a Python "worker" from node.js in an asynchronous non-blocking way?
For communication between node.js and Python server, I would use Unix sockets if both processes run on the same server and TCP/IP sockets otherwise. For marshaling protocol I would take JSON or [protocol buffer](https://developers.google.com/protocol-buffers/docs/pythontutorial). If threaded Python shows up to be a bot...
Combining node.js and Python
10,775,351
91
2012-05-27T16:03:52Z
15,660,623
81
2013-03-27T13:54:55Z
[ "python", "node.js", "ipc" ]
Node.js is a perfect match for our web project, but there are few computational tasks for which we would prefer Python. We also already have a Python code for them. We are highly concerned about speed, what is the most elegant way how to call a Python "worker" from node.js in an asynchronous non-blocking way?
This sounds like a scenario where zeroMQ would be a good fit. It's a messaging framework that's similar to using TCP or Unix sockets, but it's much more robust (<http://zguide.zeromq.org/py:all>) There's a library that uses zeroMQ to provide a RPC framework that works pretty well. It's called zeroRPC (<http://zerorpc....
Making all variables global
10,775,411
6
2012-05-27T16:12:46Z
10,775,417
8
2012-05-27T16:14:20Z
[ "python", "variables", "global-variables" ]
I have a function in my Python script where multiple variables are created, and I want to use them in other functions. I thought of using `global` for this but I thought it would be the incorrect way to do so. So can anyone tell me what would be the best way to create variables in a function for other functions?
Organize the variables into a [class](http://docs.python.org/tutorial/classes.html). Instantiate the class in one function and then pass the instance to wherever you need it. Rule of thumb: If making something global seems like a good solution at some point, don't do it. There is always a better way.
Julia's Python performance example in pypy
10,775,510
18
2012-05-27T16:28:23Z
13,671,148
22
2012-12-02T16:21:09Z
[ "python", "numpy", "python-2.7", "pypy", "julia-lang" ]
[Julia](http://julialang.org/) is a new statistical programming language that claims significantly better performance than competing languages. I'm trying to verify this. Julia has a performance test written in Python: <https://github.com/JuliaLang/julia/blob/master/test/perf/perf.py> I can't get it to work with pypy....
![Test of python and julia performance](http://i.stack.imgur.com/Fz8H4.png) There are 4 test on Julia git (perf.py) in pure Python. Here, I run, in the same computer, **perf.py** (only the pure Python test) and **perf.pl** for a apples-to-apples comparison. I'm a little worried for Python/Pypy timing :/ And... Why `...
What does '@reify' do and when should it be used?
10,776,244
19
2012-05-27T18:25:04Z
10,776,353
29
2012-05-27T18:42:33Z
[ "python", "pyramid" ]
I saw it in the [Pyramid tutorial for UX design](http://docs.pylonsproject.org/projects/pyramid_tutorials/en/latest/humans/creatingux/step06/index.html). I couldn't make out much what this decorator is all about. Sample code where I saw its usage. ``` def __init__(self, request): self.request = request render...
From the source code documentation: > """ Put the result of a method which uses this (non-data) > descriptor decorator in the instance dict after the first call, > effectively replacing the decorator with an instance variable.""" A description from [from the fuzzy notepad blog](http://me.veekun.com/blog/2012/05/23/py...
why is xrange able to go back to beginning in Python?
10,776,250
29
2012-05-27T18:26:35Z
10,776,268
17
2012-05-27T18:29:41Z
[ "python", "iterator", "xrange" ]
I've encountered this code from [Most pythonic way of counting matching elements in something iterable](http://stackoverflow.com/questions/157039/most-pythonic-way-of-counting-matching-elements-in-something-iterable) ``` r = xrange(1, 10) print sum(1 for v in r if v % 2 == 0) # 4 print sum(1 for v in r if v % 3 == 0) ...
Because the `xrange` object produced by calling `xrange()` specifies an `__iter__` that provides a unique version of itself (actually, a separate `rangeiterator` object) each time it's iterated. ``` >>> x = xrange(3) >>> type(x) <type 'xrange'> >>> i = x.__iter__() >>> type(i) <type 'rangeiterator'> ```
why is xrange able to go back to beginning in Python?
10,776,250
29
2012-05-27T18:26:35Z
10,776,285
38
2012-05-27T18:31:16Z
[ "python", "iterator", "xrange" ]
I've encountered this code from [Most pythonic way of counting matching elements in something iterable](http://stackoverflow.com/questions/157039/most-pythonic-way-of-counting-matching-elements-in-something-iterable) ``` r = xrange(1, 10) print sum(1 for v in r if v % 2 == 0) # 4 print sum(1 for v in r if v % 3 == 0) ...
Because `xrange` does not return a generator. It returns an [xrange object](http://docs.python.org/library/functions.html#xrange). ``` >>> type(xrange(10)) <type 'xrange'> ``` In addition to repeated iteration, `xrange` objects support other things that generators don't -- like indexing: ``` >>> xrange(10)[5] 5 ``` ...
How to execute a file that requires being in the same directory?
10,776,930
3
2012-05-27T20:15:26Z
10,776,978
7
2012-05-27T20:22:25Z
[ "python" ]
I have a python script that needs to execute a `.jar` file that is located in another directory. What would be the best way to do this? So far I was thinking - ``` subprocess.call(["cd","/path/to/file"]) subprocess.call(["./file.jar"]) ``` How should I do this? **Update:** Using both of the answers below, this is w...
To run a process in a different current working directory, use `subprocess.Popen`'s `cwd` parameter: ``` import subprocess proc = subprocess.Popen(['file.jar'], cwd = '/path/to/file') ```
Python using enumerate inside list comprehension
10,777,271
62
2012-05-27T21:03:37Z
10,777,287
83
2012-05-27T21:05:15Z
[ "python", "list", "iteration", "list-comprehension" ]
Lets suppose I have a list like this: ``` mylist = ["a","b","c","d"] ``` To get the values printed along with their index I can use Python's `enumerate` function like this ``` >>> for i,j in enumerate(mylist): ... print i,j ... 0 a 1 b 2 c 3 d >>> ``` Now, when I try to use it inside a `list comprehension` it g...
Try this: ``` [(i, j) for i, j in enumerate(mylist)] ``` You need to put `i,j` inside a tuple for the list comprehension to work. Alternatively, given that `enumerate()` *already* returns a tuple, you can return it directly without unpacking it first: ``` [pair for pair in enumerate(mylist)] ``` Either way, the res...
Python using enumerate inside list comprehension
10,777,271
62
2012-05-27T21:03:37Z
10,777,288
8
2012-05-27T21:05:27Z
[ "python", "list", "iteration", "list-comprehension" ]
Lets suppose I have a list like this: ``` mylist = ["a","b","c","d"] ``` To get the values printed along with their index I can use Python's `enumerate` function like this ``` >>> for i,j in enumerate(mylist): ... print i,j ... 0 a 1 b 2 c 3 d >>> ``` Now, when I try to use it inside a `list comprehension` it g...
Here's a way to do it: ``` >>> mylist = ['a', 'b', 'c', 'd'] >>> [item for item in enumerate(mylist)] [(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd')] ``` Alternatively, you can do: ``` >>> [(i, j) for i, j in enumerate(mylist)] [(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd')] ``` The reason you got an error was that you were miss...
Python using enumerate inside list comprehension
10,777,271
62
2012-05-27T21:03:37Z
10,777,369
26
2012-05-27T21:18:27Z
[ "python", "list", "iteration", "list-comprehension" ]
Lets suppose I have a list like this: ``` mylist = ["a","b","c","d"] ``` To get the values printed along with their index I can use Python's `enumerate` function like this ``` >>> for i,j in enumerate(mylist): ... print i,j ... 0 a 1 b 2 c 3 d >>> ``` Now, when I try to use it inside a `list comprehension` it g...
Or, if you don't insist on using a list comprehension: ``` >>> mylist = ["a","b","c","d"] >>> list(enumerate(mylist)) [(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd')] ```