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 to do circular shift in numpy
15,792,465
9
2013-04-03T16:08:32Z
15,792,505
24
2013-04-03T16:10:45Z
[ "python", "arrays", "numpy", "shift" ]
I have a numpy array, for example ``` a = np.arange(10) ``` how can I move the first `n` elements to the end of the array? I found this [`roll`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.roll.html) function but it seems like it only does the opposite, which shifts the last `n` elements to the beginni...
Why not just `roll` with a negative number? ``` >>> import numpy as np >>> a = np.arange(10) >>> np.roll(a,2) array([8, 9, 0, 1, 2, 3, 4, 5, 6, 7]) >>> np.roll(a,-2) array([2, 3, 4, 5, 6, 7, 8, 9, 0, 1]) ```
Scipy: Speeding up calculation of a 2D complex integral
15,793,224
9
2013-04-03T16:43:25Z
15,794,220
11
2013-04-03T17:37:48Z
[ "python", "numpy", "scipy", "integration", "complex-numbers" ]
I want to repeatedly calculate a two-dimensional complex integral using dblquad from scipy.integrate. As the number of evaluations will be quite high I would like to increase the evaluation speed of my code. Dblquad does not seem to be able to handle complex integrands. Thus, I have split the complex integrand into a ...
You can gain a factor of about 10 in speed by using Cython, see below: ``` In [87]: %timeit cythonmodule.doit(lam=lam, y0=y0, zxp=zxp, z=z, k=k, ra=ra) 1 loops, best of 3: 501 ms per loop In [85]: %timeit doit() 1 loops, best of 3: 4.97 s per loop ``` This is probably not enough, and the bad news is that this is prob...
Why can't I rig SciPy's constrained optimization for integer programming?
15,793,381
5
2013-04-03T16:50:48Z
15,793,619
11
2013-04-03T17:02:39Z
[ "python", "numpy", "scipy", "mathematical-optimization" ]
[I've read that integer programming is either very tricky or not possible with SciPy](http://stackoverflow.com/questions/12180822/integer-step-size-in-scipy-optimize-minimize) and that I probably need to use something like zibopt to do it in Python . But I really thought I could do it by creating one "is binary" constr...
The problem is that, as unintuitive as it may seem, [Integer Programming](http://en.wikipedia.org/wiki/Linear_programming#Integer_unknowns) is a fundamentally more difficult problem than Linear Programming with real numbers. Someone in the SO thread you linked to mentions that SciPy uses the [Simplex](http://en.wikiped...
How to avoid a Broken Pipe error when printing a large amount of formatted data?
15,793,886
6
2013-04-03T17:18:08Z
15,794,022
9
2013-04-03T17:26:00Z
[ "python", "format", "string-formatting", "ioerror", "broken-pipe" ]
I am trying to print a list of tuples formatted in my `stdout`. For this, I use the [str.format](http://docs.python.org/2/library/string.html#string-formatting) method. Everything works fine, but when I pipe the output to see the first lines using the `head` command a `IOError` occurs. Here is my code: ``` # creating...
`head` reads from `stdout` then *closes* it. This causes `print` to fail, internally it writes to `sys.stdout`, now closed. You can simply *catch* the `IOError` and exit silently: ``` try: for pid, uid, pname in data: print template.format(pid, uid, pname) except IOError: # stdout is closed, no point ...
decorator to set attributes of function
15,794,419
4
2013-04-03T17:48:36Z
15,794,454
9
2013-04-03T17:51:04Z
[ "python", "attributes", "decorator", "function-attributes" ]
I want different functions to be executable only if the logged in user has the required permission level. To make my life more complexly simply I want to use decorators. Below I attempy to set attribute `permission` on 'decorated' functions - as shown below. ``` def permission(permission_required): def wrapper(fu...
You are setting the attribute in the inner (wrapper) function. You don't need a wrapper function *at all*: ``` def permission(permission_required): def decorator(func): func.permission_required = permission_required return func return decorator ``` Your decorator needs to return *something* th...
How to make an action happen every minute in Python
15,795,404
5
2013-04-03T18:42:23Z
15,795,496
7
2013-04-03T18:46:39Z
[ "python", "loops", "time", "count" ]
I would like to add 1 to a variable every minute without interfering with the code that's already running. It is a game so I want in the background for wood+1, rock+1, fish+1 to happen every minute without the user knowing. the time.sleep won't work in this situation because it pauses the whole program. ``` start=ti...
You need to import the *thread* module and the *itertools* (in addition to [svks' comment](http://stackoverflow.com/questions/15795404/how-to-make-an-action-happen-every-minute-in-python#comment22460224_15795496)) in python ``` import thread, time, itertools ``` initialize your threadsafe counter like ``` wood = ite...
Disable pagination in Django tastypie?
15,795,416
8
2013-04-03T18:43:00Z
15,928,594
9
2013-04-10T14:24:28Z
[ "python", "django", "pagination", "tastypie" ]
I have a tastypie api that I'm working on and in the list views for my api resources I'd like to get the entire list of data without pagination applied, regardless of the number of objects in the list. I don't need a custom paginator with a high limit, I'd like to disable pagination entirely. I could potentially modif...
To do this you need to set at least two different things. In the site settings file, set ``` API_LIMIT_PER_PAGE = 0 ``` In the resource Meta class that you want to disable pagination for, set: ``` class MyResource(ModelResource): ... class Meta: ... max_limit = None ``` Then if you navigate...
creating multiple generators inside a list comprehension
15,795,799
5
2013-04-03T19:02:14Z
15,795,914
7
2013-04-03T19:09:31Z
[ "python", "generator", "list-comprehension" ]
I am trying to group cards of the same suit (color) and rank inside generators and store those generators inside a list comprehension. The solution I came up with does that except for the fact that all the generators contain exactly the same cards. Any idea why? Here is the code ``` deck=range(52) gens=[(i for i in...
The problem is that the name `v` in your generator expression refers to that variable `v` in the list comprehension. So, when the code your generator expression actually runs (when you call `next`), it looks at the variable `v` and sees the value `12`, no matter what the value of `v` was when you created the generator....
Django ModelForm to have a hidden input
15,795,869
30
2013-04-03T19:06:39Z
15,795,924
50
2013-04-03T19:10:11Z
[ "python", "django", "django-models", "django-forms" ]
So I have my TagStatus model. I'm trying to make a ModelForm for it. However, my form requires that the hidden input be populated with the {{ tag.name }}. I've been looking through the docs and I don't know how to make the tag field a hidden input. Perhaps a ModelForm isn't the way to go? **models.py:** ``` class Tag...
There are 2 ways that I know of to render hidden fields in Django - You could declare a field normally in `forms.py` but in your templates html file use `{{ form.field.as_hidden }}` Or, in `forms.py` directly use hidden input widget. ``` class MyForm(forms.Form): hidden_field = forms.CharField(widget=forms.Hidde...
Django ModelForm to have a hidden input
15,795,869
30
2013-04-03T19:06:39Z
23,463,004
61
2014-05-05T00:04:53Z
[ "python", "django", "django-models", "django-forms" ]
So I have my TagStatus model. I'm trying to make a ModelForm for it. However, my form requires that the hidden input be populated with the {{ tag.name }}. I've been looking through the docs and I don't know how to make the tag field a hidden input. Perhaps a ModelForm isn't the way to go? **models.py:** ``` class Tag...
To make a field in a ModelField a hidden field, use a HiddenInput widget. The ModelForm uses a sensible default widget for all the fields, you just need to override it when the object is constructed. ``` class TagStatusForm(forms.ModelForm): class Meta: model = TagStatus widgets = {'tag': forms.Hid...
Removing all div tags from HTML string
15,796,994
2
2013-04-03T20:04:15Z
15,797,247
7
2013-04-03T20:18:34Z
[ "python", "regex" ]
I am trying to strip all divs. Input: ``` <p>111</p> <div class="1334">bla</div> <p>333</p> <p>333</p> <div some unkown stuff>bla2</div> ``` Desired Output: ``` <p>111</p> <p>333</p> <p>333</p> ``` I tried this but it isn't working: ``` release_content = re.sub("/<div>.*<\/div>/s", "", release_co...
[Do not use regex for this problem](http://stackoverflow.com/a/1732454/1253312). Use an html parser. Here is a solution in python with BeautifulSoup: ``` from BeautifulSoup import BeautifulSoup with open('Path/to/file', 'r') as content_file: content = content_file.read() soup = BeautifulSoup(content) [div.extrac...
How to print string version of backspace in python?
15,797,587
2
2013-04-03T20:36:19Z
15,797,629
8
2013-04-03T20:38:13Z
[ "python", "string" ]
How would I print '\x08' as '\x08' in python? If I enter the command ``` print '\x08' ``` the output is blank instead of ``` \x08 ```
Please use `r` before string, it means *raw string*, in which you don't need to escape special chars. For more details about string literal prefixes please read the [documentation](http://docs.python.org/2/reference/lexical_analysis.html#strings). ``` print r'\x08' ```
Pandas "Group By" Query on Large Data in HDFStore?
15,798,209
15
2013-04-03T21:11:03Z
15,800,314
13
2013-04-04T00:00:19Z
[ "python", "pandas", "pytables" ]
I have about 7 million rows in an `HDFStore` with more than 60 columns. The data is more than I can fit into memory. I'm looking to aggregate the data into groups based on the value of a column "A". The documentation for pandas [splitting/aggregating/combining](http://pandas.pydata.org/pandas-docs/stable/groupby.html) ...
Heres a complete example. ``` import numpy as np import pandas as pd import os fname = 'groupby.h5' # create a frame df = pd.DataFrame({'A': ['foo', 'foo', 'foo', 'foo', 'bar', 'bar', 'bar', 'bar', 'foo', 'foo', 'foo'], 'B': ['one', 'one', 'one', '...
Diffing Binary Files In Python
15,798,411
2
2013-04-03T21:24:03Z
15,798,718
8
2013-04-03T21:43:19Z
[ "python", "diff" ]
I've got two binary files. They look something like this, but the data is more random: File A: ``` FF FF FF FF 00 00 00 00 FF FF 44 43 42 41 FF FF ... ``` File B: ``` 41 42 43 44 00 00 00 00 44 43 42 41 40 39 38 37 ... ``` What I'd like is to call something like: ``` >>> someDiffLib.diff(file_a_data, file_b_data)...
You can use [`itertools.groupby()`](http://docs.python.org/3.3/library/itertools.html#itertools.groupby) for this, here is an example: ``` from itertools import groupby # this just sets up some byte strings to use, Python 2.x version is below # instead of this you would use f1 = open('some_file', 'rb').read() f1 = by...
Python MySQL escape special characters
15,798,969
4
2013-04-03T22:00:02Z
15,799,022
7
2013-04-03T22:03:08Z
[ "python", "mysql" ]
I am using python to insert a string into MySQL with special characters. The string to insert looks like so: ``` macaddress_eth0;00:1E:68:C6:09:A0;macaddress_eth1;00:1E:68:C6:09:A1 ``` Here is the SQL: ``` UPGRADE inventory_server set server_mac = macaddress\_eth0\;00\:1E\:68\:C6\:09\:A0\;macaddress\_eth1\;00\:1E\...
This is one of the reasons you're supposed to use [parameter binding](http://www.python.org/dev/peps/pep-0249/#id15) instead of formatting the parameters in Python. Just do this: ``` sql = 'UPGRADE inventory_server set server_mac = %s where server_name = %s' ``` Then: ``` cur.execute(sql, macs, host) ``` That way,...
Resampling Within a Pandas MultiIndex
15,799,162
14
2013-04-03T22:12:51Z
15,799,355
14
2013-04-03T22:28:18Z
[ "python", "pandas", "time-series", "hierarchical-data" ]
I have some hierarchical data which bottoms out into time series data which looks something like this: ``` df = pandas.DataFrame( {'value_a': values_a, 'value_b': values_b}, index=[states, cities, dates]) df.index.names = ['State', 'City', 'Date'] df value_a value_b State Cit...
[`pd.Grouper`](http://pandas.pydata.org/pandas-docs/version/0.14.1/generated/pandas.Grouper.html) allows you to specify a "groupby instruction for a target object". In particular, you can use it to group by dates even if `df.index` is not a `DatetimeIndex`: ``` df.groupby(pd.Grouper(freq='2D', level=-1)) ``` The `lev...
Resampling Within a Pandas MultiIndex
15,799,162
14
2013-04-03T22:12:51Z
15,813,787
7
2013-04-04T14:16:04Z
[ "python", "pandas", "time-series", "hierarchical-data" ]
I have some hierarchical data which bottoms out into time series data which looks something like this: ``` df = pandas.DataFrame( {'value_a': values_a, 'value_b': values_b}, index=[states, cities, dates]) df.index.names = ['State', 'City', 'Date'] df value_a value_b State Cit...
An alternative using stack/unstack ``` df.unstack(level=[0,1]).resample('2D', how='sum').stack(level=[2,1]).swaplevel(2,0) value_a value_b State City Date Georgia Atlanta 2012-01-01 1 21 Alabama Mobile 2012-01-01 17 37 Montgomery 2012-01-...
Library to build URLs in Python
15,799,696
17
2013-04-03T22:56:11Z
15,799,706
15
2013-04-03T22:57:35Z
[ "python" ]
I need to find a library to build URLs in python like: ``` http://subdomain.domain.com?arg1=someargument&arg2someotherargument ``` What library would you recommend to use and why? Is there a "best" choice for this kind of library?
[`urlparse`](http://docs.python.org/2/library/urlparse.html) in the python standard library is all about building valid urls. Check the documentation of urlparse
Library to build URLs in Python
15,799,696
17
2013-04-03T22:56:11Z
28,011,983
10
2015-01-18T16:23:50Z
[ "python" ]
I need to find a library to build URLs in python like: ``` http://subdomain.domain.com?arg1=someargument&arg2someotherargument ``` What library would you recommend to use and why? Is there a "best" choice for this kind of library?
I would go for Python's `urllib`, it's a built-in library. ``` # Python 2: import urllib # Python 3: # import urllib.parse getVars = {'var1': 'some_data', 'var2': 1337} url = 'http://domain.com/somepage/?' # Python 2: print(url + urllib.urlencode(getVars)) # Python 3: # print(url + urllib.parse.urlencode(getVars))...
How to call a method with spaces in the name?
15,800,123
3
2013-04-03T23:38:23Z
15,800,140
11
2013-04-03T23:40:16Z
[ "python", "syntax", "identifier" ]
I have the following class: ``` Help on class A in module a: class A(__builtin__.object) | Methods defined here: | | any vegetable(self) | TODO document this | | getHeight(self) | uses the chicken to measure it ``` Calling `any vegetable` doesn't work: ``` >>> a.A().any vegetable() File "<...
Use `getattr`: ``` >>> a = A() >>> getattr(a, 'any vegetable')() ``` Note that having names with weird characters such as spaces in them is a ***very, very bad idea***. No sane person would ever do this.
Python: Get Image size WITHOUT loading image into memory
15,800,704
34
2013-04-04T00:42:43Z
19,034,942
21
2013-09-26T17:37:46Z
[ "python", "image", "image-processing" ]
I understand that you can get the image size using PIL in the following fashion ``` from PIL import Image im = Image.open(image_filename) width, height = im.size ``` However, I would like to get the image width and height *without* having to load the image in memory. Is that possible? I am only doing statistics on im...
As the comments allude, PIL does not load the image into memory when calling `.open`. Looking at the docs of `PIL 1.1.7`, the docstring for `.open` says: ``` def open(fp, mode="r"): "Open an image file, without loading the raster data" ``` There are a few file operations in the source like: ``` ... prefix = fp...
Python: Get Image size WITHOUT loading image into memory
15,800,704
34
2013-04-04T00:42:43Z
19,035,508
31
2013-09-26T18:06:55Z
[ "python", "image", "image-processing" ]
I understand that you can get the image size using PIL in the following fashion ``` from PIL import Image im = Image.open(image_filename) width, height = im.size ``` However, I would like to get the image width and height *without* having to load the image in memory. Is that possible? I am only doing statistics on im...
If you don't care about the image contents, PIL is probably an overkill. I suggest parsing the output of the python magic module: ``` >>> t = magic.from_file('teste.png') >>> t 'PNG image data, 782 x 602, 8-bit/color RGBA, non-interlaced' >>> re.search('(\d+) x (\d+)', t).groups() ('782', '602') ``` This is a wrappe...
how to understand appengine ndb.tasklet?
15,801,523
5
2013-04-04T02:27:35Z
15,854,543
12
2013-04-06T18:32:49Z
[ "python", "google-app-engine", "tasklet" ]
From [documentation](https://developers.google.com/appengine/docs/python/ndb/async#tasklets): > An NDB tasklet is a piece of code that might run concurrently with > other code. If you write a tasklet, your application can use it much > like it uses an async NDB function: it calls the tasklet, which > returns a Future;...
If you look at the implementation of a Future, its very comparable to what a generator is in python. In fact, it uses the same `yield` keyword to achieve what it says it does. Read the [intro comments on the tasklets.py](https://github.com/GoogleCloudPlatform/datastore-ndb-python/blob/master/ndb/tasklets.py) for some c...
how to correctly pass a json object to flask server using jquery ajax
15,801,782
4
2013-04-04T02:58:03Z
15,801,873
7
2013-04-04T03:10:29Z
[ "javascript", "python", "ajax", "json", "flask" ]
i want to pass a json object which contains nested objects from my client to my server. on the client side, my data structure looks like this: ``` var response = {}; response['screening'] = '1'; response['assistance'] = 'wheelchair access'; response['guests'] = {}; response['guests']['1'] = {} response['guests']['1']...
You could send your object as a JSON string: ``` var data = { screening: '1', assistance: 'wheelchair access', guests: [ { first: 'John', last: 'Smith' }, { first: 'Dave', last: 'Smith' } ] }; $.ajax({ type: 'POST', ...
Python 3.3 function to merge unique values form multiple lists to one list
15,802,637
12
2013-04-04T04:39:51Z
15,802,669
16
2013-04-04T04:42:43Z
[ "python", "list", "function", "merge", "python-3.3" ]
I am pretty new to Python..I am trying to write a function that will merge unique values in separate lists into one list. I keep getting a result of a tuple of lists. Ultimately I would like to have one list of unique values from my three lists -a,b,c. Can anyone give me a hand with this? ``` def merge(*lists): ne...
You may just need sets: ``` >>> a = [1,2,3,4] >>> b = [3,4,5,6] >>> c = [5,6,7,8] >>> >>> uniques = set( a + b + c ) >>> uniques set([1, 2, 3, 4, 5, 6, 7, 8]) >>> ```
Django setting : psycopg2.OperationalError: FATAL: Peer authentication failed for user "indivo"
15,805,561
35
2013-04-04T07:58:20Z
15,889,545
22
2013-04-08T21:42:52Z
[ "python", "django", "postgresql", "psycopg2", "django-settings" ]
I am getting problem in Django project setting with POSTGRESQL. Here is my setting.py database setting ``` DATABASES = { 'default':{ 'ENGINE':'django.db.backends.postgresql_psycopg2', # '.postgresql_psycopg2', '.mysql', or '.oracle' 'NAME':'indivo', # Required to be non-empty string 'USER'...
By default in many Linux distros, client authentication is set to "peer" for Unix socket connections to the DB. This is set in the `pg_hba.conf` config file for postgresql. The psycopg2 python library documentation states: > - \*host\*: database host address (defaults to UNIX socket if not provided) So if you leave t...
Django setting : psycopg2.OperationalError: FATAL: Peer authentication failed for user "indivo"
15,805,561
35
2013-04-04T07:58:20Z
19,617,516
35
2013-10-27T11:26:09Z
[ "python", "django", "postgresql", "psycopg2", "django-settings" ]
I am getting problem in Django project setting with POSTGRESQL. Here is my setting.py database setting ``` DATABASES = { 'default':{ 'ENGINE':'django.db.backends.postgresql_psycopg2', # '.postgresql_psycopg2', '.mysql', or '.oracle' 'NAME':'indivo', # Required to be non-empty string 'USER'...
I have similar problem and solved it with [this answer](http://stackoverflow.com/a/8232004/2343488) by adding `localhost` to the database `HOST` settings in settings.py, so your database settings should look like this: ``` DATABASES = { 'default':{ 'ENGINE':'django.db.backends.postgresql_psycopg2', # '.pos...
Django can't find my custom template filter
15,806,254
4
2013-04-04T08:35:29Z
15,806,505
8
2013-04-04T08:48:44Z
[ "python", "django", "filter", "django-templates" ]
I'm trying to create a custom template filter in my Django app. I've created a templatetags folder under my app, added an `__init__.py` file and a filters.py file with my filters, like so: ``` import os from django import template from django.template.defaultfilters import stringfilter register = template.Library() ...
You need to use `{% load name_of_file_tags_are_in %}` inside your template. <https://docs.djangoproject.com/en/1.5/howto/custom-template-tags/>
Python SyntaxError: ("'return' with argument inside generator",)
15,809,296
12
2013-04-04T11:01:02Z
15,809,390
19
2013-04-04T11:05:26Z
[ "python", "return", "generator", "tornado" ]
I have this function in my Python program: ``` @tornado.gen.engine def check_status_changes(netid, sensid): como_url = "".join(['http://131.114.52:44444/ztc?netid=', str(netid), '&sensid=', str(sensid), '&start=-5s&end=-1s']) http_client = AsyncHTTPClient() response = yield tornado.gen.Task(http_c...
You cannot use `return` with a value to exit a generator. You need to use `yield` plus a `return` *without* an expression: ``` if response.error: self.error("Error while retrieving the status") self.finish() yield error return ``` In the loop itself, use `yield` again: ``` for line in response.body.s...
Keep duplicates in a list in Python
15,812,547
7
2013-04-04T13:23:38Z
15,812,664
7
2013-04-04T13:27:45Z
[ "python", "duplicates" ]
I know this is probably an easy answer but I can't figure it out. What is the best way in Python to keep the duplicates in a list: ``` x = [1,2,2,2,3,4,5,6,6,7] ``` The output should be: ``` [2,6] ``` I found this link: [Find (and keep) duplicates of sublist in python](http://stackoverflow.com/questions/1723072/fin...
This is a short way to do it if the list is sorted already: ``` x = [1,2,2,2,3,4,5,6,6,7] from itertools import groupby print [key for key,group in groupby(x) if len(list(group)) > 1] ```
Keep duplicates in a list in Python
15,812,547
7
2013-04-04T13:23:38Z
15,812,667
10
2013-04-04T13:27:53Z
[ "python", "duplicates" ]
I know this is probably an easy answer but I can't figure it out. What is the best way in Python to keep the duplicates in a list: ``` x = [1,2,2,2,3,4,5,6,6,7] ``` The output should be: ``` [2,6] ``` I found this link: [Find (and keep) duplicates of sublist in python](http://stackoverflow.com/questions/1723072/fin...
I'd use a `collections.Counter`: ``` from collections import Counter x = [1, 2, 2, 2, 3, 4, 5, 6, 6, 7] counts = Counter(x) output = [value for value, count in counts.items() if count > 1] ``` Here's another version which keeps the order of when the item was first duplicated that only assumes that the sequence passed...
Python list comprehension - want to avoid repeated evaluation
15,812,779
34
2013-04-04T13:32:08Z
15,812,850
9
2013-04-04T13:34:54Z
[ "python", "list-comprehension", "code-readability" ]
I have a list comprehension which approximates to: ``` [f(x) for x in l if f(x)] ``` Where l is a list and f(x) is an expensive function which returns a list. I want to avoid evaluating f(x) twice for every non-empty occurance of f(x). Is there some way to save its output within the list comprehension? I could remo...
``` [y for y in [f(x) for x in l] if y] ``` For your updated problem, this might be useful: ``` [g(x,y) for x in l for y in [f(x)] if y] ```
Python list comprehension - want to avoid repeated evaluation
15,812,779
34
2013-04-04T13:32:08Z
15,812,866
27
2013-04-04T13:35:32Z
[ "python", "list-comprehension", "code-readability" ]
I have a list comprehension which approximates to: ``` [f(x) for x in l if f(x)] ``` Where l is a list and f(x) is an expensive function which returns a list. I want to avoid evaluating f(x) twice for every non-empty occurance of f(x). Is there some way to save its output within the list comprehension? I could remo...
`[y for y in (f(x) for x in l) if y]` will do
Python list comprehension - want to avoid repeated evaluation
15,812,779
34
2013-04-04T13:32:08Z
15,812,933
11
2013-04-04T13:38:33Z
[ "python", "list-comprehension", "code-readability" ]
I have a list comprehension which approximates to: ``` [f(x) for x in l if f(x)] ``` Where l is a list and f(x) is an expensive function which returns a list. I want to avoid evaluating f(x) twice for every non-empty occurance of f(x). Is there some way to save its output within the list comprehension? I could remo...
You should use a memoize decorator. Here is an interesting [link](http://code.activestate.com/recipes/578231-probably-the-fastest-memoization-decorator-in-the-/). --- Using memoization from the link and your 'code': ``` def memoize(f): """ Memoization decorator for functions taking one or more arguments. """ ...
Python list comprehension - want to avoid repeated evaluation
15,812,779
34
2013-04-04T13:32:08Z
15,812,973
10
2013-04-04T13:40:01Z
[ "python", "list-comprehension", "code-readability" ]
I have a list comprehension which approximates to: ``` [f(x) for x in l if f(x)] ``` Where l is a list and f(x) is an expensive function which returns a list. I want to avoid evaluating f(x) twice for every non-empty occurance of f(x). Is there some way to save its output within the list comprehension? I could remo...
A solution (the best if you have repeated value of x) would be to **memoize** the function f, i.e. to create a wrapper function that saves the argument by which the function is called and save it, than return it if the same value is asked. a really simple implementation is the following: ``` storage = {} def memoized...
Python list comprehension - want to avoid repeated evaluation
15,812,779
34
2013-04-04T13:32:08Z
15,814,283
7
2013-04-04T14:36:48Z
[ "python", "list-comprehension", "code-readability" ]
I have a list comprehension which approximates to: ``` [f(x) for x in l if f(x)] ``` Where l is a list and f(x) is an expensive function which returns a list. I want to avoid evaluating f(x) twice for every non-empty occurance of f(x). Is there some way to save its output within the list comprehension? I could remo...
As the previous answers have shown, you can use a double comprehension or use memoization. For reasonably-sized problems it's a matter of taste (and I agree that memoization looks cleaner, since it hides the optimization). But if you're examining a very large list, **there's a huge difference:** Memoization will store ...
python: in ""?
15,813,041
9
2013-04-04T13:43:26Z
15,813,062
7
2013-04-04T13:44:18Z
[ "python" ]
I stumbled upon [this](https://raw.github.com/jackjack-jj/pywallet/278c6e08d29958be78c0586d9457d602b9296274/pywallet.py) apparently horrific piece of code: ``` def determine_db_name(): if wallet_name in "": return "wallet.dat" else: return wallet_name ``` What is supposed `if xx in "":` to mea...
That expression is true if `wallet_name` is the empty string. It would probably be clearer if the code had been written as follows: ``` if wallet_name == '': ``` Or just: ``` if not wallet_name: ```
python: in ""?
15,813,041
9
2013-04-04T13:43:26Z
15,813,078
13
2013-04-04T13:44:53Z
[ "python" ]
I stumbled upon [this](https://raw.github.com/jackjack-jj/pywallet/278c6e08d29958be78c0586d9457d602b9296274/pywallet.py) apparently horrific piece of code: ``` def determine_db_name(): if wallet_name in "": return "wallet.dat" else: return wallet_name ``` What is supposed `if xx in "":` to mea...
It'll return `True` if `wallet_name` is itself empty: ``` >>> foo = '' >>> foo in '' True ``` It is *horrific* though. Just use `if not wallet_name:` instead, or use `or` and do away with the `if` statement altogether: ``` def determine_db_name(): return wallet_name or "wallet.dat" ``` which works because `or` ...
Prettier default plot colors in matplotlib
15,814,635
29
2013-04-04T14:51:31Z
15,814,926
45
2013-04-04T15:04:21Z
[ "python", "matplotlib" ]
The default colors used in matplotlib (example here: <http://matplotlib.org/examples/pylab_examples/pie_demo.html>) are kind of plain and ugly. I've also noticed that if you plot more than 5-6 different series in a single plot, matplotlib starts repeating colors. I've seen some gorgeous graphs coming out of other visu...
You can use [Matplotlib's style sheets](http://matplotlib.org/users/style_sheets.html). It has been ported from the [mpltools library](http://tonysyu.github.com/mpltools/index.html) which has a [style](http://tonysyu.github.com/mpltools/api/mpltools.style.html) module that redefine matplotlib rc parameters. As an exam...
Prettier default plot colors in matplotlib
15,814,635
29
2013-04-04T14:51:31Z
19,591,929
19
2013-10-25T14:00:22Z
[ "python", "matplotlib" ]
The default colors used in matplotlib (example here: <http://matplotlib.org/examples/pylab_examples/pie_demo.html>) are kind of plain and ugly. I've also noticed that if you plot more than 5-6 different series in a single plot, matplotlib starts repeating colors. I've seen some gorgeous graphs coming out of other visu...
Have a look at [prettyplotlib](http://olgabot.github.io/prettyplotlib/) a library — just pointed out to me recently by friends — that modifies matplotlib to be better aligned with the ideas of [Edward Tufte](http://www.edwardtufte.com/tufte/), as well as some very carefully studied work by [Cynthia Brewer](http://w...
Prettier default plot colors in matplotlib
15,814,635
29
2013-04-04T14:51:31Z
32,950,553
8
2015-10-05T14:03:45Z
[ "python", "matplotlib" ]
The default colors used in matplotlib (example here: <http://matplotlib.org/examples/pylab_examples/pie_demo.html>) are kind of plain and ugly. I've also noticed that if you plot more than 5-6 different series in a single plot, matplotlib starts repeating colors. I've seen some gorgeous graphs coming out of other visu...
The [Seaborn](http://stanford.edu/~mwaskom/software/seaborn/) package (based on Matplotlib) has nice default graph styles, and I've found that it's a nice way to create an appealing color-cycle. They have a nice discussion of the colorpalettes here: <https://stanford.edu/~mwaskom/software/seaborn/tutorial/color_palett...
Prettier default plot colors in matplotlib
15,814,635
29
2013-04-04T14:51:31Z
34,577,275
8
2016-01-03T13:57:11Z
[ "python", "matplotlib" ]
The default colors used in matplotlib (example here: <http://matplotlib.org/examples/pylab_examples/pie_demo.html>) are kind of plain and ugly. I've also noticed that if you plot more than 5-6 different series in a single plot, matplotlib starts repeating colors. I've seen some gorgeous graphs coming out of other visu...
The question was asked 2 years ago, and today it's much easier to get better style for your plot. You don't even need external packages for that. As @asmaier mentioned in his comment, mpltools.style functionality has been integrated into Matplotlib 1.4, so you can switch styles with: ``` plt.style.use(style_name) ``` ...
How to add column to numpy array
15,815,854
8
2013-04-04T15:47:10Z
15,816,887
27
2013-04-04T16:37:57Z
[ "python", "numpy" ]
I am trying to add one column to the array created from `recfromcsv`. In this case it's an array: `[210,8]` (rows, cols). I want to add a ninth column. Empty or with zeroes doesn't matter. ``` from numpy import genfromtxt from numpy import recfromcsv import numpy as np import time if __name__ == '__main__': print("...
I think that your problem is that you are expecting `np.append` to add the column in-place, but what it does, because of how numpy data is stored, is create a copy of the joined arrays ``` Returns ------- append : ndarray A copy of `arr` with `values` appended to `axis`. Note that `append` does not occur in-p...
Group/Count list of dictionaries based on value
15,815,976
2
2013-04-04T15:54:21Z
15,816,111
8
2013-04-04T16:00:45Z
[ "python", "list", "aggregate-functions" ]
I've got a list of Tokens which looks something like: ``` [{ Value: "Blah", StartOffset: 0, EndOffset: 4 }, ... ] ``` What I want to do is get a count of how many times each value occurs in the list of tokens. In VB.Net I'd do something like... ``` Tokens = Tokens. GroupBy(Function(x) x.Value). Select(F...
IIUC, you can use `collections.Counter`: ``` >>> from collections import Counter >>> tokens = [{"Value": "Blah", "SO": 0}, {"Value": "zoom", "SO": 5}, {"Value": "Blah", "SO": 2}, {"Value": "Blah", "SO": 3}] >>> Counter(tok['Value'] for tok in tokens) Counter({'Blah': 3, 'zoom': 1}) ``` if you only need a count. If yo...
In Python cProfile, what is the difference between calls count and primitive calls count?
15,816,415
12
2013-04-04T16:14:59Z
15,816,524
10
2013-04-04T16:21:30Z
[ "python", "profiling" ]
When I display profiling data using `pstats`, the first column is the number of calls for each function. However, when I sort data, I have choice between `calls`, `ncalls` and `pcalls` keys. Documentation says that `calls` and `ncalls` are *call count*, when `pcalls` is *primitive call count*. Is sorting by `calls` or...
<http://docs.python.org/2/library/profile.html#module-cProfile> > We define primitive to mean that the call was not induced via recursion. > > ...when the function does not recurse, these two values are the same Sorting by `calls` or `ncalls` is the same. --- > When there are two numbers in the first column (for ex...
Can a developed Ansible module include or extend an Ansible Core module?
15,816,952
8
2013-04-04T16:41:31Z
15,903,451
9
2013-04-09T13:36:22Z
[ "python", "ansible" ]
I am developing an Ansible module that generates a url, fetches (like get\_url) the tarball at that url from my internal artifactory and then extracts it. I am wondering if there is a way to include or extend the get\_url Ansible core module in my module. I can't have this in multiple steps because the url being used i...
To quote Michael DeHaan's post [here](https://groups.google.com/d/msg/ansible-project/7SByPqJxa7Q/YAopBmA-4_8J): > Generally speaking, Ansible allows sharing code through > "lib/ansible/module\_common.py" to make writing functionality easier. > > It does not, however, make it possible for one module to call another, >...
subprocess and Type Str doesnt support the buffer API
15,817,420
16
2013-04-04T17:07:19Z
15,817,457
16
2013-04-04T17:09:24Z
[ "python", "subprocess", "python-3.3" ]
I have ``` cmd = subprocess.Popen('dir',shell=True,stdout=subprocess.PIPE) for line in cmd.stdout: columns = line.split(' ') print (columns[3]) ``` have error in line 3 Type Str doesnt support the buffer API. What am i doing wrong i am on Python 3.3
You are reading binary data, not `str`, so you need to decode the output first: ``` import locale encoding = locale.getdefaultlocale()[1] cmd = subprocess.Popen('dir',shell=True,stdout=subprocess.PIPE) for line in cmd.stdout: columns = line.decode(encoding).split() if columns: print(columns[-1]) ``` ...
Pandas DataFrame concat vs append
15,819,050
15
2013-04-04T18:37:25Z
15,822,811
19
2013-04-04T22:25:29Z
[ "python", "pandas" ]
I have a list of 4 pandas dataframe containing a day of tick data that I want to merge into a single data frame. I find can't seem to understand the behavior of concat on my timestamps. See details below: ``` data [<class 'pandas.core.frame.DataFrame'> DatetimeIndex: 35228 entries, 2013-03-28 00:00:07.089000+02:00 to...
So what are you doing is with append and concat is *almost* equivalent. The difference is the empty DataFrame. For some reason this causes a big slowdown, not sure exactly why, will have to look at some point. Below is a recreation of basically what you did. I almost always use concat (though in this case they are equ...
DBSCAN with python and scikit-learn: What exactly are the integer labes returned by make_blobs?
15,819,103
7
2013-04-04T18:39:31Z
15,819,240
11
2013-04-04T18:45:01Z
[ "python", "scikit-learn", "dbscan" ]
I'm trying to comprehend the example for the DBSCAN algorithm implemented by scikit (<http://scikit-learn.org/0.13/auto_examples/cluster/plot_dbscan.html>). I changed the line ``` X, labels_true = make_blobs(n_samples=750, centers=centers, cluster_std=0.4) ``` with `X = my_own_data`, so I can use my own data for the...
`labels_true` is the "true" assignment of points to labels: which cluster they should actually belong on. This is available because [`make_blobs`](http://scikit-learn.org/dev/modules/generated/sklearn.datasets.make_blobs.html) knows which "blob" it generated the point from. You can't get that for your own arbitrary da...
How to initialize nested dictionaries in Python
15,819,428
6
2013-04-04T18:55:01Z
15,819,459
10
2013-04-04T18:56:53Z
[ "python", "dictionary", "python-2.7", "initialization", "nested" ]
I'm using Python v2.7 dictionaries, nested one inside another like this: ``` def example(format_str, year, value): format_to_year_to_value_dict = {} # In the actual code there are many format_str and year values, # not just the one inserted here. if not format_str in format_to_year_to_value_dict: format_to...
Use [`setdefault`](http://docs.python.org/2/library/stdtypes.html#dict.setdefault): > If key is in the dictionary, return its value. If not, insert key with a value of default and return default. ``` format_to_year_to_value_dict.setdefault(format_str, {})[year] = value ``` Or [`collections.defaultdict`](http://docs....
Calculate mean across dimension in a 2D array
15,819,980
17
2013-04-04T19:25:25Z
15,820,007
29
2013-04-04T19:26:57Z
[ "python", "arrays", "multidimensional-array", "numpy", "mean" ]
I have an array `a` like this: ``` a=[] a.append([40,10]) a.append([50,11]) ``` so it looks like this: ``` >>> a [[40, 10], [50, 11]] ``` I need to calculate the mean for each dimension separately, the result should be this: ``` [45,10.5] ``` `45` being the mean of `a[*][0]` and `10.5` the mean of `a[\*][1]. Wh...
`a.mean()` takes an `axis` argument: ``` In [1]: import numpy as np In [2]: a = np.array([[40, 10], [50, 11]]) In [3]: a.mean(axis=1) # to take the mean of each row Out[3]: array([ 25. , 30.5]) In [4]: a.mean(axis=0) # to take the mean of each col Out[4]: array([ 45. , 10.5]) ``` Or, as a standalone func...
How do I print a fibonacci sequence to the nth number in Python?
15,820,601
4
2013-04-04T19:59:22Z
15,820,864
12
2013-04-04T20:14:39Z
[ "python", "parameter-passing", "fibonacci" ]
I have a homework assignment that I'm stumped on. I'm trying to write a program that outputs the fibonacci sequence up the nth number. Here's what I have so far: ``` def fib(): n = int(input("Please Enter a number: ")) if n == 1: return(1) elif n == 0: return(0) else: ...
Non-recursive solution ``` def fib(n): cur = 1 old = 1 i = 1 while (i < n): cur, old, i = cur+old, cur, i+1 return cur for i in range(10): print(fib(i)) ``` Generator solution: ``` def fib(n): old = 0 cur = 1 i = 1 yield cur while (i < n): cur, old, i = cu...
Using Twitter Bootstrap radio buttons with Flask
15,820,788
8
2013-04-04T20:09:59Z
15,955,816
10
2013-04-11T18:08:06Z
[ "python", "twitter-bootstrap", "flask", "jinja2" ]
I am building a web-based dashboard, and I would like to use radio-buttons from [Twitter Bootstrap](http://en.wikipedia.org/wiki/Twitter_Bootstrap) to help create queries that are then run against [MongoDB](http://en.wikipedia.org/wiki/MongoDB) (via [Flask](http://en.wikipedia.org/wiki/Flask_%28programming%29)), which ...
If you have big sets of similar controls — best way to use loops for them. Let's imagine we use list for storing all button names, and other list of buttons that are acive. This will give us some controller: ``` from flask import render_template @app.route('/form/') def hello(name=None): return render_template(...
Using Twitter Bootstrap radio buttons with Flask
15,820,788
8
2013-04-04T20:09:59Z
15,996,432
7
2013-04-14T06:34:09Z
[ "python", "twitter-bootstrap", "flask", "jinja2" ]
I am building a web-based dashboard, and I would like to use radio-buttons from [Twitter Bootstrap](http://en.wikipedia.org/wiki/Twitter_Bootstrap) to help create queries that are then run against [MongoDB](http://en.wikipedia.org/wiki/MongoDB) (via [Flask](http://en.wikipedia.org/wiki/Flask_%28programming%29)), which ...
As for setting the active box, I'm not sure what you mean, but the button tag attribute [autofocus](http://www.w3schools.com/tags/att_button_autofocus.asp) may be helpful. And it might be a good idea to just leave the fields blank initially. You can pass the selected box to Flask without JavaScript using the following...
What's the working directory when using IDLE?
15,821,121
16
2013-04-04T20:30:55Z
15,821,159
20
2013-04-04T20:33:34Z
[ "python", "python-idle" ]
So, I'm learning Python and would like to create a simple script to download a file from the internet and then write it to a file. However, I am using IDLE and have no idea what the working directory is in IDLE or how to change it. How can I do file system stuff in IDLE if I don't know the working directory or how to c...
You can easily check that yourself using [`os.getcwd`](http://docs.python.org/3/library/os.html#os.getcwd): ``` >>> import os >>> os.getcwd() 'C:\\Program Files\\Python33' ``` That’s on my Windows machine, so it’s probably the installation directory of Python itself. You can change that directory at runtime usin...
How to properly use mock in python with unittest setUp
15,821,465
23
2013-04-04T20:51:47Z
23,618,258
23
2014-05-12T20:29:04Z
[ "python", "unit-testing", "mocking" ]
In my attempt to learn TDD, trying to learn unit testing and using mock with python. Slowly getting the hang of it, but unsure if I'm doing this correctly. Forewarned: I'm stucking using python 2.4 because the vendor API's come as pre-compiled 2.4 pyc files, so I'm using mock 0.8.0 and unittest ( not unittest2 ) Given...
See: [26.5.3.4. Applying the same patch to every test method](https://docs.python.org/3.5/library/unittest.mock-examples.html#applying-the-same-patch-to-every-test-method) It makes more sense to set up the patcher this way on setUp if you want the patching to be done for all the test methods.
Python 3.3 - urllib.request - import error
15,821,480
2
2013-04-04T20:52:25Z
15,821,508
9
2013-04-04T20:54:21Z
[ "python", "urllib", "pycharm", "python-3.3" ]
When I try to run the following Python 3.3 code on OS X 10.8 in PyCharm 2.7 (or run the .py file with the Python 3.3/2.7.3 launcher): ``` import urllib.request f = urllib.request.urlopen('http://www.python.org/') print(f.read(300)) ``` I get the following error message: ``` /System/Library/Frameworks/Python.framewor...
You named your file `urllib`, it is shadowing the standard library package. Rename your file.
How to round Python Decimal instance
15,824,726
4
2013-04-05T02:00:51Z
15,824,803
7
2013-04-05T02:12:31Z
[ "python" ]
How do I round a Python Decimal instance to a specific number of digits while rounding to the nearest decimal? I've tried using the `.quantize(Decimal('.01'))` method outlined in the [docs](http://docs.python.org/release/3.1.5/library/decimal.html#decimal.Context), and suggested in [previous answers](http://stackoverf...
I think you need to use the `decimal.ROUND_HALF_UP` option to `quantize` to get what you want. ``` >>> for x in ('3.605', '29342398479823.605', '3.604', '3.606'): print x, repr(Decimal(x).quantize(Decimal('.01'), decimal.ROUND_HALF_UP)) 3.605 Decimal('3.61') 29342398479823.605 Decimal('29342398479823.61') 3.604 D...
Django: I want to recognize a hash url
15,828,765
5
2013-04-05T07:59:56Z
15,828,863
7
2013-04-05T08:06:04Z
[ "python", "django", "web-services" ]
I have a url like `http://localhost/user/?hash={hash value generated}` i need to configure urls.py so that any url of this form is recognized and does not give an error. I currently wrote urls.py as `url(r'^user/(?P<hash>\w+)/$', 'Myapp.views.createnewpass'),` and this is giving a 404 error for a valid hash. How c...
Well, it should be clear to you that the regex does not match the URL: it's looking for URLs in the form /user/hash/, whereas you have /user/?hash=hash. In any case, query parameters (those after the ?) do not get processed by urls.py, they are passed in request.GET. So your URLconf should just be `r'^user/$`.
Bluetooth server with Python 3.3
15,828,916
8
2013-04-05T08:09:55Z
16,289,711
8
2013-04-29T23:08:52Z
[ "python", "python-3.x", "bluetooth" ]
Python 3.3 came with native support for bluetooth sockets. Unfortunately, it's not too well documented yet (there is only one mention of it in the [documentation](http://docs.python.org/3.4/library/socket.html?highlight=af_bluetooth)). Googling it there is [a blog post](http://bitsofpy.blogspot.com.ar/2012/09/bluetoot...
*Bad news*: Python doesn't appear to support what you want to do out of the box. (At least not in [socketmodule.c](http://hg.python.org/cpython/file/84cef4f1999a/Modules/socketmodule.c#l1)). Most of the python/bluetooth users I've seen use [`pybluez`](https://code.google.com/p/pybluez/) although it hasn't been updated...
Python: How to import information from a .csv file to python as a list with tuples inside?
15,830,298
2
2013-04-05T09:26:42Z
15,830,375
11
2013-04-05T09:29:59Z
[ "python", "function", "import" ]
I am new to programming so please excuse my shallow knowledge with coding. I have a .csv file that I can open with excel. Each row represents a person's name and their details (like address, phone number and age) with each detail in different columns. Whenever I move onto a new row it is another person's detail. I wan...
With the [`csv` module](http://docs.python.org/2/library/csv.html) it is quite simple: ``` import csv with open('friends.csv', 'Ur') as f: data = list(tuple(rec) for rec in csv.reader(f, delimiter=',')) ``` `data` is a list of tuples. The `csv` module reads the files correctly: ``` "Smith, John",123 ``` will ...
XML Unicode strings with encoding declaration are not supported
15,830,421
10
2013-04-05T09:31:54Z
15,830,619
19
2013-04-05T09:41:30Z
[ "python", "xml", "django" ]
Trying to do the following... ``` from lxml import etree from lxml.etree import fromstring if request.POST: parser = etree.XMLParser(ns_clean=True, recover=True) h = fromstring(request.POST['xml'], parser=parser) return HttpResponse(h.cssselect('itagg_delivery_receipt status').text_content()) ``` but it ...
You'll have to encode it and then force the same encoding in the parser: ``` from lxml import etree from lxml.etree import fromstring if request.POST: xml = request.POST['xml'].encode('utf-8') parser = etree.XMLParser(ns_clean=True, recover=True, encoding='utf-8') h = fromstring(xml, parser=parser) r...
Create a list of empty dictionaries
15,835,268
5
2013-04-05T13:30:19Z
15,835,286
13
2013-04-05T13:31:06Z
[ "python", "list", "dictionary" ]
I want to create a list of variable length containing empty directories. ``` n = 10 # size of list foo = [] for _ in range(n) foo.append({}) ``` Would you do this the same way, or is there something like? ``` a = [{}*n] ```
List comprehensions to the rescue! ``` foo = [{} for _ in range(n)] ``` There is no shorter notation, I am afraid. In Python 2 you use `xrange(n)` instead of `range(n)` to avoid materializing a useless list. The alternative, `[{}] * n` creates a list of length `n` with only *one* dictionary, referenced `n` times. Th...
Matplotlib: Change math font size
15,836,050
10
2013-04-05T14:06:37Z
15,838,395
8
2013-04-05T15:58:53Z
[ "python", "numpy", "matplotlib" ]
I am making some plots with matplotlib, and I've come across a problem with the TeX rendering. It seems that the mathtext x-height is is a bit smaller than the normal Bitstream Vera Sans. See the following example: ``` x = linspace(0, 30, 300); y = 0.5*rand(300)+20/(numpy.power(x-15, 2)+4); xlabel(r'$\omega$ (rad$\cdo...
From the [matplotlib docs](http://matplotlib.org/users/mathtext.html#fonts): > Additionally, you can use `\mathdefault{...}` or its alias > `\mathregular{...}` to use the font used for regular text outside of > mathtext. There are a number of limitations to this approach, most > notably that far fewer symbols will be ...
Scrapy CrawlSpider doesn't crawl the first landing page
15,836,062
10
2013-04-05T14:07:17Z
15,839,394
10
2013-04-05T16:55:10Z
[ "python", "scrapy", "web-crawler" ]
I am new to Scrapy and I am working on a scraping exercise and I am using the CrawlSpider. Although the Scrapy framework works beautifully and it follows the relevant links, I can't seem to make the CrawlSpider to scrape the very first link (the home page / landing page). Instead it goes directly to scrape the links de...
There's a number of ways of doing this, but one of the simplest is to implement `parse_start_url` and then modify `start_urls` ``` from scrapy.contrib.spiders import CrawlSpider, Rule from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor from scrapy.selector import HtmlXPathSelector class DownloadSpider(Cr...
Scrapy CrawlSpider doesn't crawl the first landing page
15,836,062
10
2013-04-05T14:07:17Z
15,839,428
12
2013-04-05T16:57:09Z
[ "python", "scrapy", "web-crawler" ]
I am new to Scrapy and I am working on a scraping exercise and I am using the CrawlSpider. Although the Scrapy framework works beautifully and it follows the relevant links, I can't seem to make the CrawlSpider to scrape the very first link (the home page / landing page). Instead it goes directly to scrape the links de...
Just change your callback to `parse_start_url` and override it: ``` from scrapy.contrib.spiders import CrawlSpider, Rule from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor class DownloadSpider(CrawlSpider): name = 'downloader' allowed_domains = ['bnt-chemicals.de'] start_urls = [ "ht...
Allowing a specific value for an Argparse argument
15,836,713
5
2013-04-05T14:37:42Z
15,836,714
8
2013-04-05T14:37:42Z
[ "python", "python-2.7", "argparse" ]
Is it possible to require that an `argparse` argument be one of a few preset values? My current approach is would be to examine the argument manually and if it's not one of the allowed values call `print_help()` and exit. Here's the current implementation: ``` ... parser.add_argument('--val', dest='val', action='sto...
This can be done by passing in the additional `choices` option: ``` ... parser.add_argument('--val', dest='val', action='store', choices=['a','b','c'], help='Special testing value') args = parser.parse_args(sys.argv[1:]) ``` See the [docs](http://docs.python.org/2.7/librar...
random.choice from set? python
15,837,729
22
2013-04-05T15:26:03Z
15,837,796
33
2013-04-05T15:29:10Z
[ "python", "list", "set" ]
I'm working on an AI portion of a guessing game. I want the AI to select a random letter from this list. I'm doing it as a set so I can easily remove letters from the list as they are guessed in the game and are therefore no longer available to be guessed again. it says "set" object isn't indexable. How do I work arou...
``` >>> random.sample(set('abcdefghijklmnopqrstuvwxyz'), 1) ['f'] ```
random.choice from set? python
15,837,729
22
2013-04-05T15:26:03Z
24,949,742
20
2014-07-25T06:53:27Z
[ "python", "list", "set" ]
I'm working on an AI portion of a guessing game. I want the AI to select a random letter from this list. I'm doing it as a set so I can easily remove letters from the list as they are guessed in the game and are therefore no longer available to be guessed again. it says "set" object isn't indexable. How do I work arou...
You should use random.choice(tuple(myset)), because it's faster and arguably cleaner looking than random.sample. I wrote the following to test: ``` import random import timeit bigset = set(random.uniform(0,10000) for x in range(10000)) def choose(): random.choice(tuple(bigset)) def sample(): random.sample(b...
How to clear Tkinter Canvas?
15,839,491
16
2013-04-05T17:02:07Z
15,840,231
22
2013-04-05T17:46:31Z
[ "python", "python-3.x", "tkinter", "tkinter-canvas" ]
When I draw a shape using: ``` canvas.create_rectangle(10, 10, 50, 50, color="green") ``` Does Tkinter keep track of the fact that it was created? In a simple game I'm making, my code has one `Frame` create a bunch of rectangles, and then draw a big black rectangle to clear the screen, and then draw another set of u...
Every canvas item is an object that Tkinter keeps track of. If you are clearing the screen by just drawing a black rectangle, then you effectively have created a memory leak -- eventually your program will crash due to the millions of items that have been drawn. To clear a canvas, use the [delete](http://effbot.org/tk...
When are .pyc files refreshed?
15,839,555
45
2013-04-05T17:05:59Z
15,839,646
38
2013-04-05T17:11:18Z
[ "python", "python-internals", "pyc" ]
I understand that ".pyc" files are compiled versions of the plain-text ".py" files, created at runtime to make programs run faster. However I have observed a few things: 1. Upon modification of "py" files, program behavior changes. This indicates that the "py" files are compiled or at least go though some sort of hash...
The `.pyc` files are created (and possibly overwritten) only when that python file is imported by some other script. If the import is called, Python checks to see if the `.pyc` file's internal timestamp matches the corresponding `.py` file. If it does, it loads the `.pyc`; if it does not or if the `.pyc` does not yet e...
When are .pyc files refreshed?
15,839,555
45
2013-04-05T17:05:59Z
19,353,631
13
2013-10-14T04:41:22Z
[ "python", "python-internals", "pyc" ]
I understand that ".pyc" files are compiled versions of the plain-text ".py" files, created at runtime to make programs run faster. However I have observed a few things: 1. Upon modification of "py" files, program behavior changes. This indicates that the "py" files are compiled or at least go though some sort of hash...
.pyc files generated whenever the corresponding code elements are imported, and updated if the corresponding code files have been updated. If the .pyc files are deleted, they will be automatically regenerated. However, they are **not** automatically deleted when the corresponding code files are deleted. This can cause...
How to check a variable is class object or not
15,841,417
4
2013-04-05T18:55:34Z
15,841,486
11
2013-04-05T19:00:07Z
[ "python", "class", "python-2.7" ]
Assume a simple class: ``` class MyClass(object): pass . . . m = MyClass print type(m) # gets: <type 'classobj'> # if m is classobj, how can i check a variable is class object? ``` My question is: how can i check a variable is a class object? a simple solution: ``` if str(type(m)) == "<type 'classobj'>": #...
In 2.x, a class object can be be a `type` (new-style classes) or a `classobj` (classic classes). The `type` type is a builtin, but the `classobj` type is not. So, how do you get it? That's what the [`types`](http://docs.python.org/2/library/types.html) module is for. ``` isinstance(MyClass, (types.TypeType, types.Clas...
How to check a variable is class object or not
15,841,417
4
2013-04-05T18:55:34Z
15,841,614
17
2013-04-05T19:07:15Z
[ "python", "class", "python-2.7" ]
Assume a simple class: ``` class MyClass(object): pass . . . m = MyClass print type(m) # gets: <type 'classobj'> # if m is classobj, how can i check a variable is class object? ``` My question is: how can i check a variable is a class object? a simple solution: ``` if str(type(m)) == "<type 'classobj'>": #...
Use [inspect](http://docs.python.org/2/library/inspect.html#inspect.isclass): ``` import inspect print inspect.isclass(obj) ```
'int' object is not callable error python
15,841,910
2
2013-04-05T19:23:07Z
15,841,930
13
2013-04-05T19:24:28Z
[ "python", "int" ]
Hey guys so I am getting this "TypeError: 'int' object is not callable" error when I run this code, I did some research and I think it's something with my variable naming? Could someone please explain to me what is wrong? ``` class account(object): def set(self, bal): self.balance = bal def balance(sel...
You are masking your method `balance` with a instance attribute `balance`. Rename one or the other. You could rename the instance attribute by pre-pending it with an underscore for example: ``` def set(self, bal): self._balance = bal def balance(self): return self._balance ``` Attributes on the instance trum...
Reading Multiple CSV Files into Python Pandas Dataframe
15,843,123
6
2013-04-05T20:40:03Z
15,843,942
10
2013-04-05T21:30:46Z
[ "python", "pandas" ]
The general use case behind the question is to read multiple CSV log files from a target directory into a single Python Pandas DataFrame for quick turnaround statistical analysis & charting. The idea for utilizing Pandas vs MySQL is to conduct this data import or append + stat analysis periodically throughout the day. ...
The `append` method on an instance of a DataFrame does not function the same as the `append` method on an instance of a list. `Dataframe.append()` does not occur in-place and instead returns a new object. ``` years = range(1880, 2011) names = pd.DataFrame() for year in years: path ='C:\\Documents and Settings\\Fo...
Comparing Exception Objects in Python
15,844,131
6
2013-04-05T21:45:34Z
15,844,248
10
2013-04-05T21:53:43Z
[ "python", "exception", "comparison" ]
I am new at Python and I'm stuck at this problem. I am trying to compare two "exception objects", example: ``` try: 0/0 except Exception as e: print e >> integer division or modulo by zero try: 0/0 except Exception as e2: print e2 >> integer division or modulo by zero e == e2 >> False e is e2 >> Fal...
With most exception classes, you can test for functional equality with ``` type(e) is type(e2) and e.args == e2.args ``` This tests that their classes are exactly identical, and that they contain the same exception arguments. This may not work for exception classes that don't use `args`, but to my knowledge, all stan...
Django-crispy-forms AttributeError when using built in AuthenticationForm
15,845,023
3
2013-04-05T23:04:19Z
15,862,269
7
2013-04-07T12:16:31Z
[ "python", "django", "django-crispy-forms" ]
I'm trying to use django-crispy-forms to display the built-in `AuthenticationForm` with the login view in django. I'm having issues subclassing AuthenticationForm - I'm getting an AttributeError. The error says `'WSGIrequest' object has no attribute 'get'.` Here is my form: ``` class LoginForm(AuthenticationForm): ...
It looks like you've got an error in your form: ``` class LoginForm(AuthenticationForm): def __init__(self, *args, **kwargs): super(LoginForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_tag = False self.helper.layout = Layout( Field('user...
How to set the Python 2 Preference in PyCharm?
15,845,929
9
2013-04-06T01:08:51Z
15,846,659
8
2013-04-06T03:18:30Z
[ "python", "pycharm" ]
**PyCharm** is a good IDE, but its code hinting is not so intelligent. For example, when I use it to write Python2 code (the setting of my *interpreter path* can tell PyCharm this), I type ***prin***, which I want PyCharm to give me a hint of ***print***, however, the first prompt is ***print()***, which is a Python3 s...
Perhaps, you should select python 2.x interpreter for the project (File - Settings - Project Interpreter).
How do I download a file using urllib.request in Python 3?
15,846,017
8
2013-04-06T01:25:28Z
15,846,062
7
2013-04-06T01:32:28Z
[ "python", "http", "python-3.x", "urllib" ]
So, I'm messing around with `urllib.request` in Python 3 and am wondering how to write the result of getting an internet file to a file on the local machine. I tried this: ``` g = urllib.request.urlopen('http://media-mcw.cursecdn.com/3/3f/Beta.png') with open('test.png', 'b+w') as f: f.write(g) ``` But I got this...
change ``` f.write(g) ``` to ``` f.write(g.read()) ```
Python: why do functions in math module accept Decimal objects as arguments?
15,846,510
8
2013-04-06T02:52:49Z
15,846,787
7
2013-04-06T03:44:08Z
[ "python", "math", "decimal" ]
Bizzarely, every function from Python's math module seems to work just fine with Decimal objects. For example: frexp, exp, cos. When I type `print(math.frexp(decimal.Decimal('2341.12412')))`, Python prints the correct answer, which is `(0.57156... , 12)`, and doesn't throw any exceptions. I would assume that the math...
Well looking at the `math module.c` I got this: ``` static PyObject * math_frexp(PyObject *self, PyObject *arg) { int i; double x = PyFloat_AsDouble(arg); if (x == -1.0 && PyErr_Occurred()) return NULL; /* deal with special cases directly, to sidestep platform differences */ if (Py_I...
How to ConfigParse a file keeping multiple values for identical keys?
15,848,674
9
2013-04-06T08:28:10Z
15,848,928
9
2013-04-06T08:57:48Z
[ "python", "python-2.7", "configparser" ]
I need to be able to use the `ConfigParser` to read multiple values for the same key. Example config file: ``` [test] foo = value1 foo = value2 xxx = yyy ``` With the 'standard' use of `ConfigParser` there will be one key `foo` with the value `value2`. But I need the parser to read in both values. Following an [entr...
After a small modification, I was able to achieve what you want: ``` class MultiOrderedDict(OrderedDict): def __setitem__(self, key, value): if isinstance(value, list) and key in self: self[key].extend(value) else: super(OrderedDict, self).__setitem__(key, value) config = C...
How to get rid of extenstions from file basename using python
15,849,521
9
2013-04-06T10:01:31Z
15,849,561
25
2013-04-06T10:06:55Z
[ "python", "regex" ]
I have got the complete path of files in a list like this: ``` a = ['home/robert/Documents/Workspace/datafile.xlsx', 'home/robert/Documents/Workspace/datafile2.xls', 'home/robert/Documents/Workspace/datafile3.xlsx'] ``` what I want is to get just the file NAMES without their extensions, like: ``` b = ['datafile', 'd...
1. The regex you've used is wrong. `(\.xls)+` matches strings of the form `.xls`, `.xls.xls`, etc. This is why there is a remaining `x` in the `.xlsx` items. What you want is `\.xls.*`, i.e. a `.xls` followed by zero or more of any characters. 2. You don't really need to use regex. There are specialized methods in [os....
How to use winapi SetWinEventHook in python?
15,849,564
5
2013-04-06T10:07:09Z
15,898,768
7
2013-04-09T09:51:20Z
[ "python", "winapi" ]
I want to get the handle of every new Dialog which pops up from a specific application. I understand I should set a hook with [SetWinEventHook](http://msdn.microsoft.com/en-us/library/windows/desktop/dd373640%28v=vs.85%29.aspx) which is in `user32.dll` in windows, but I don't know how to do that in python. Would you ...
Here's a very simple example that prints to the console the window text for each dialog that is opened: ``` import sys import time import ctypes import ctypes.wintypes EVENT_SYSTEM_DIALOGSTART = 0x0010 WINEVENT_OUTOFCONTEXT = 0x0000 user32 = ctypes.windll.user32 ole32 = ctypes.windll.ole32 ole32.CoInitialize(0) Wi...
Redis: How to parse a list result
15,850,112
11
2013-04-06T11:05:43Z
15,850,347
11
2013-04-06T11:27:58Z
[ "python", "redis" ]
I am storing a list in Redis like this: ``` redis.lpush('foo', [1,2,3,4,5,6,7,8,9]) ``` And then I get the list back like this: ``` redis.lrange('foo', 0, -1) ``` and I get something like this: ``` [b'[1, 2, 3, 4, 5, 6, 7, 8, 9]'] ``` How can I convert this to actual Python list? Also, I don't see anything defin...
I think you're bumping into semantics which are similar to the distinction between *list.append()* and **list.extend()**. I know that this works for me: ``` myredis.lpush('foo', *[1,2,3,4]) ``` ... note the \* (map-over) operator prefixing the list!
Need Help in switching values in a list in python
15,850,242
3
2013-04-06T11:18:01Z
15,850,251
9
2013-04-06T11:19:04Z
[ "python" ]
I have a list of numbers, such as: ``` [1, 2, 3, 4, 5, 6] ``` I'm having trouble figuring out how to switch the first 2 items of the list with the last 2, or the first 3 with the last 3, and so on. When i assign the values of the 1st two numbers to the last 2 items of the list, i then cannot assign the last 2 values...
``` >>> nums = [1, 2, 3, 4, 5, 6] >>> nums[:2], nums[-2:] = nums[-2:], nums[:2] >>> nums [5, 6, 3, 4, 1, 2] ``` This modifies the original list but if you want a separate new list you should use the following: ``` >>> nums = [1, 2, 3, 4, 5, 6] >>> swapped_nums = nums[-2:] + nums[2:-2] + nums[:2] >>> swapped_nums [5, ...
how to get the last part of a string before a certain character?
15,851,568
29
2013-04-06T13:32:20Z
15,851,721
49
2013-04-06T13:47:57Z
[ "python", "string", "python-2.7", "split", "slice" ]
I am trying to print the last part of a string before a certain character. I'm not quite sure whether to use the string .split() method or string slicing or maybe something else. Here is some code that doesn't work but I think shows the logic: ``` x = 'http://test.com/lalala-134' print x['-':0] # beginning at the en...
You are looking for [`str.rsplit()`](http://docs.python.org/2/library/stdtypes.html#str.rsplit), with a limit: ``` print x.rsplit('-', 1)[0] ``` `.rsplit()` searches for the splitting string from the end of input string, and the second argument limits how many times it'll split to just once. Another option is to use...
What does adding '=' do to bit operators in Python? (ie '<<=' instead of '<<')
15,851,609
4
2013-04-06T13:35:51Z
15,851,622
8
2013-04-06T13:36:49Z
[ "python", "bitwise-operators" ]
What do the `<<=`and the `|=` operators mean Python? I guess they are bitwise operators. I know the operators `|` (bitwise or) and `<<` (bit shifting), but I don't know them in combination with the `=`. I found it in [this](http://learn.adafruit.com/reading-a-analog-in-and-controlling-audio-volume-with-the-raspberry-p...
Both are *in-place* assignments; they effectively give you `name = name op right-hand-expression` in the space of just `name op= right-hand-expression`. So for your example, you could read that as: ``` commandout = commandout | 0x18 commandout = commandout << 3 ``` That is oversimplifying it a little, because with d...
list of ints into a list of tuples python
15,852,295
6
2013-04-06T14:49:08Z
15,852,349
9
2013-04-06T14:54:11Z
[ "python", "list" ]
`[1, 109, 2, 109, 2, 130, 2, 131, 2, 132, 3, 28, 3, 127]` I have this array and I want to turn it into a list of tuples, each tuple has 2 values in. so this list becomes `[(1, 109), (2, 109), (2, 130), (2, 131), (2, 132), (3, 28), (3, 127)]`
``` >>> it = iter(L) >>> zip(*[it]*2) [(1, 109), (2, 109), (2, 130), (2, 131), (2, 132), (3, 28), (3, 127)] ``` --- ### Explanation `it = iter(L)` creates iterator on the initial list `[it]*2` crates the list consisting of the same iterator twice. `*` used at the first place in the parameter is used to unpack the ...
list of ints into a list of tuples python
15,852,295
6
2013-04-06T14:49:08Z
15,852,357
12
2013-04-06T14:55:21Z
[ "python", "list" ]
`[1, 109, 2, 109, 2, 130, 2, 131, 2, 132, 3, 28, 3, 127]` I have this array and I want to turn it into a list of tuples, each tuple has 2 values in. so this list becomes `[(1, 109), (2, 109), (2, 130), (2, 131), (2, 132), (3, 28), (3, 127)]`
You can use [zip](http://docs.python.org/2/library/functions.html#zip) combined with [slicing](http://techearth.net/python/index.php5?title=Python%3aBasics%3aSlices) to create a new [list](http://docs.python.org/release/1.5.1p1/tut/lists.html) of [tuples](http://docs.python.org/release/1.5.1p1/tut/tuples.html). ``` my...
How to find the 2nd max of a Counter - Python
15,852,436
2
2013-04-06T15:02:41Z
15,852,488
7
2013-04-06T15:07:07Z
[ "python", "collections", "dictionary", "counter", "multiset" ]
The max of a counter can be accessed as such: ``` c = Counter() c['foo'] = 124123 c['bar'] = 43 c['foofro'] =5676 c['barbar'] = 234 # This only prints the max key print max(c), src_sense[max(c)] # print the max key of the value x = max(src_sense.iteritems(), key=operator.itemgetter(1))[0] print x, src_sense[x] ``` *...
``` most_common(self, n=None) method of collections.Counter instance List the n most common elements and their counts from the most common to the least. If n is None, then list all element counts. >>> Counter('abcdeabcdabcaba').most_common(3) [('a', 5), ('b', 4), ('c', 3)] ``` and so: ``` >>> c.most...
Correlation between columns in DataFrame
15,854,878
18
2013-04-06T19:05:50Z
15,855,998
43
2013-04-06T21:03:04Z
[ "python", "pandas" ]
I'm pretty new to pandas, so I guess I'm doing something wrong - I have a DataFrame: ``` a b 0 0.5 0.75 1 0.5 0.75 2 0.5 0.75 3 0.5 0.75 4 0.5 0.75 ``` `df.corr()` gives me: ``` a b a NaN NaN b NaN NaN ``` but `np.correlate(df["a"], df["b"])` gives: `1.875` Why is that? I want to have the...
[np.correlate](http://docs.scipy.org/doc/numpy/reference/generated/numpy.correlate.html) calculates the (unnormalized) [cross-correlation](http://en.wikipedia.org/wiki/Cross-correlation) between two 1-dimensional sequences: ``` z[k] = sum_n a[n] * conj(v[n+k]) ``` while [df.corr](http://pandas.pydata.org/pandas-docs/...
python: what is the purpose of using ( ) in python imports?
15,855,248
13
2013-04-06T19:43:03Z
15,855,259
15
2013-04-06T19:43:50Z
[ "python" ]
I just saw the following ``` from flask_login import (LoginManager, login_required, login_user, current_user, logout_user, UserMixin) ``` in [here](http://blog.thecircuitnerd.com/flask-login-tokens/) What is the purpose of using parenthesis `()` in import statement? Why shall someone use p...
So the statement can wrap onto the next line. See sections: [2.1.5. Explicit line joining and 2.1.6. Implicit line joining](http://docs.python.org/2/reference/lexical_analysis.html#explicit-line-joining).
python: what is the purpose of using ( ) in python imports?
15,855,248
13
2013-04-06T19:43:03Z
15,855,260
7
2013-04-06T19:43:57Z
[ "python" ]
I just saw the following ``` from flask_login import (LoginManager, login_required, login_user, current_user, logout_user, UserMixin) ``` in [here](http://blog.thecircuitnerd.com/flask-login-tokens/) What is the purpose of using parenthesis `()` in import statement? Why shall someone use p...
The parentheses allow the import to span multiple lines. Without the parentheses, you would get a syntax error. If the imports are all on one line, the parentheses don't change anything.
How do I compare 2D lists for equality in Python?
15,855,792
3
2013-04-06T20:40:26Z
15,855,811
9
2013-04-06T20:42:18Z
[ "python", "arrays", "list" ]
Given two lists: ``` a = [[1,2],[3,4]] b = [[1,2],[3,4]] ``` How would I write `compare` such that: ``` compare(a,b) => true ```
Do you want this: ``` >>> a = [[1,2],[3,4]] >>> b = [[1,2],[3,4]] >>> a == b True ``` Note: `==` not useful when List are unordered e.g (*notice order in `a`, and in `b`*) ``` >>> a = [[3,4],[1,2]] >>> b = [[1,2],[3,4]] >>> a == b False ``` See this question for further reference: [How to compare a list of lists/se...
How to Sum Two List N-Element
15,856,407
3
2013-04-06T21:47:15Z
15,856,444
7
2013-04-06T21:50:55Z
[ "python", "python-2.7" ]
I need to add two lists of numbers. When one list is greater than the other I get the error "IndexError: list index out of range". The error occurs in line `resultado = v1[i] + v2[i]`, but I don't know how to solve it. My code is: ``` def suma(A, B): if len(A) > len(B): v1 = A v2 = B else: ...
``` >>> import itertools >>> A = [1, 2, 3] >>> B = [10, 11] >>> [a + b for a, b in itertools.izip_longest(A, B, fillvalue=0)] [11, 13, 3] ``` * [itertools.izip\_longest](http://docs.python.org/2/library/itertools.html#itertools.izip_longest) So, ``` def suma(A, B): return [a + b for a, b in itertools.izip_longes...
How to export plots from matplotlib with transparent background?
15,857,647
35
2013-04-07T00:47:01Z
15,858,047
59
2013-04-07T01:51:44Z
[ "python", "matplotlib", "plot", "transparency" ]
I am using matplotlib to make some graphs and unfortunately I cannot export them without the white background. ![sample plot with solid white background](http://i.stack.imgur.com/wfysS.png) In other words, when I export a plot like this and position it on top of another image, the white background hides what is behin...
Use the matplotlib `savefig` function with the keyword argument `transparent=True` to save the image as a png file. ``` In [30]: x = np.linspace(0,6,31) In [31]: y = np.exp(-0.5*x) * np.sin(x) In [32]: plot(x, y, 'bo-') Out[32]: [<matplotlib.lines.Line2D at 0x3f29750>] In [33]: savefig('demo.png', trans...
How to construct a TarFile object in memory from byte buffer in Python 3?
15,857,792
7
2013-04-07T01:08:44Z
15,858,237
10
2013-04-07T02:30:36Z
[ "python", "file", "python-3.x", "tar", "tarfile" ]
Is it possible to create a TarFile object in memory using a buffer containing the tar data without having to write the TarFile to disk and open it up again? We get the bytes sent over a socket. Something like this: ``` import tarfile byte_array = client.read_bytes() tar = tarfile.open(byte_array) # how to do this? # ...
BytesIO() from [IO module](http://docs.python.org/3/library/io.html) does exactly what you need. ``` import tarfile, io byte_array = client.read_bytes() file_like_object = io.BytesIO(byte_array) tar = tarfile.open(fileobj=file_like_object) # use "tar" as a regular TarFile object for member in tar.getmembers(): f =...
Python SVG parser
15,857,818
10
2013-04-07T01:12:36Z
15,857,847
16
2013-04-07T01:17:26Z
[ "python", "xml", "svg", "xml-parsing", "cnc" ]
I want to parse an SVG file using python to extract coordinates/paths (I believe this is listed under the "path" ID, specifically the d="..."/>). This data will eventually be used to drive a 2 axis CNC. I've searched on SO and Google for libraries that can return the string of such paths so I can further parse it, but...
Ignoring transforms, you can extract the path strings from an SVG like so: ``` from xml.dom import minidom doc = minidom.parse(svg_file) # parseString also exists path_strings = [path.getAttribute('d') for path in doc.getElementsByTagName('path')] doc.unlink() ```
How to include one positional argument into argparse mutually exclusive group?
15,857,953
5
2013-04-07T01:35:06Z
15,864,328
8
2013-04-07T15:49:50Z
[ "python", "argparse" ]
I know that does not make sense multiple positional arguments into a mutually exclusive group because you can't say who is who. But I need to include ONE positional argument into that. What I need: ``` $ myprogram -h usage: myprogram [-h] [--delete value | --update value | value] ``` Where positional `value` is the ...
I'd do this a little bit differently: ``` parser = ArgumentParser() group = parser.add_mutually_exclusive_group() group.set_defaults(mode='insert') group.add_argument('--delete', action='store_const', dest='mode', const='delete') group.add_argument('--update', action='store_const', dest='mode', const='update') group.a...