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 delete a symbolic link in python?
11,700,545
12
2012-07-28T11:18:26Z
11,704,965
17
2012-07-28T21:56:30Z
[ "python", "symlink" ]
I have been trying to delete some symbolic links in my working directory, but I am facing some issues. `os.remove` also removes the actual contents of the original folder of the link `os.shutil` throws up an error in case of symbolic links. Is there a way to remove a symbolic link using python commands without destr...
`os.unlink()` works for me. It removes the symlink without removing the directory that it links to.
Creating files and directories via Python
11,700,593
9
2012-07-28T11:25:22Z
11,700,649
35
2012-07-28T11:33:08Z
[ "python", "file", "directory" ]
I'm having trouble creating a directory and then opening/creating/writing into a file in the specified directory. The reason seems unclear to me. I'm using os.mkdir() and ``` path=chap_name print "Path : "+chap_path #For debugging purposes if not os.path.exists(path): os.mkdir(path) temp_file...
``` import os path = chap_name if not os.path.exists(path): os.makedirs(path) filename = img_alt + '.jpg' with open(os.path.join(path, filename), 'wb') as temp_file: temp_file.write(buff) ``` Key point is to use `os.makedirs` in place of `os.mkdir`. It is recursive, i.e. it generates all intermediate direct...
Python recursively replace character in keys of nested dictionary?
11,700,705
11
2012-07-28T11:41:51Z
11,700,817
10
2012-07-28T11:58:01Z
[ "python", "dictionary", "replace", "nested", "character" ]
I'm trying to create a generic function that replaces dots in keys of a nested dictionary. I have a non-generic function that goes 3 levels deep, but there must be a way to do this generic. Any help is appreciated! My code so far: ``` output = {'key1': {'key2': 'value2', 'key3': {'key4 with a .': 'value4', 'key5 with ...
Yes, there exists better way: ``` def print_dict(d): new = {} for k, v in d.iteritems(): if isinstance(v, dict): v = print_dict(v) new[k.replace('.', '-')] = v return new ``` (Edit: It's recursion, more on [Wikipedia](http://en.wikipedia.org/wiki/Recursion_%28computer_science%2...
Python - accessing values nested within dictionaries
11,700,798
5
2012-07-28T11:55:25Z
11,700,851
10
2012-07-28T12:03:51Z
[ "python", "dictionary", "nested" ]
I have a dictionary which contains dictionaries, which may also contain dictionaries, e.g. ``` dictionary = {'ID': 0001, 'Name': 'made up name', 'Transactions': {'Transaction Ref': 'a1', 'Transaction Details': {'Bill To': 'abc', 'Ship To': 'def', 'Product': 'Widget A' ...
``` bill_to = transactions['Transaction Details']['Bill To'] ``` actually works. `transactions['Transaction Details']` is an expression denoting a `dict`, so you can do lookup in it. For practical programs, I would prefer an OO approach to nested dicts, though. `collections.namedtuple` is particularly useful for quick...
Python - accessing values nested within dictionaries
11,700,798
5
2012-07-28T11:55:25Z
11,701,539
16
2012-07-28T13:43:05Z
[ "python", "dictionary", "nested" ]
I have a dictionary which contains dictionaries, which may also contain dictionaries, e.g. ``` dictionary = {'ID': 0001, 'Name': 'made up name', 'Transactions': {'Transaction Ref': 'a1', 'Transaction Details': {'Bill To': 'abc', 'Ship To': 'def', 'Product': 'Widget A' ...
You can use something like this: ``` >>> def lookup(dic, key, *keys): ... if keys: ... return lookup(dic.get(key, {}), *keys) ... return dic.get(key) ... >>> d = {'a':{'b':{'c':5}}} >>> print lookup(d, 'a', 'b', 'c') 5 >>> print lookup(d, 'a', 'c') None ``` Additionally, if you don't want to define yo...
Pyramid subrequests
11,701,920
4
2012-07-28T14:35:00Z
11,702,530
8
2012-07-28T15:59:17Z
[ "python", "pyramid" ]
I need to call GET, POST, PUT, etc. requests to another URI because of search, but I cannot find a way to do that internally with pyramid. Is there any way to do it at the moment?
Simply use the existing python libraries for calling other webservers. On python 2.x, use [`urllib2`](http://docs.python.org/library/urllib2.html), for python 3.x, use [`urllib.request`](http://docs.python.org/py3k/library/urllib.request.html) instead. Alternatively, you could install [`requests`](http://docs.python-r...
pydev debugger: unable to find real location for python 2.7 after OS 10.8 upgrade
11,702,139
10
2012-07-28T15:06:33Z
11,753,554
12
2012-08-01T06:17:18Z
[ "python", "python-2.7", "aptana", "osx-mountain-lion" ]
I just upgraded to OS X 10.8 Mountain Lion and having troubles understanding how the pydev debugger should work on Aptana 3.0. In Aptana's preferences I have the python interpreter setup with a location of "/usr/bin/python". It states that the System libs are coming from "/System/Library/Frameworks/Python.framework/Ve...
I had a very similar problem. It turned out that after upgrading to Mountain Lion, all the Python source files disappeared. The solution was to install the "Command Line Tools" from Apple. Try this link: <https://developer.apple.com/downloads/index.action?=command%20line%20tools> Or go to <https://developer.apple.co...
How do i add two lists' elements into one list?
11,703,064
11
2012-07-28T17:11:25Z
11,703,083
18
2012-07-28T17:14:21Z
[ "python", "list" ]
For example, I have a list like this: ``` list1 = [good, bad, tall, big] list2 = [boy, girl, guy, man] ``` and I want to make a list like this: ``` list3 = [goodboy, badgirl, tallguy, bigman] ``` I tried something like these: ``` list3=[] list3 = list1 + list2 ``` but this would only contain the value of `list1`...
You can use list comprehensions with `zip`: ``` list3 = [a + b for a, b in zip(list1, list2)] ``` `zip` produces a list of tuples by combining elements from iterables you give it. So in your case, it will return pairs of elements from `list1` and `list2`, up to whichever is exhausted first.
Python: 'import *' vs execfile
11,703,327
9
2012-07-28T17:46:43Z
11,703,875
12
2012-07-28T19:12:09Z
[ "python", "django", "django-settings", "python-import", "execfile" ]
In some of my Django apps I'm using a `settings_local.py` file to override settings that are different on various environments (e.g. development, test and production). I have originally used the following code to include its contents in the `settings.py`: ``` try: from settings_local import * except ImportError: ...
Using `execfile` function will result in the evaluation of the Python source file (.py) every time the settings file is evaluated. You are executing the Python parser each time. Using `import` wouldn't necessarily do this (might use the .pyc file). Generally the first time you run a project in Python (at least, cPython...
Python Drawing ASCII Map
11,703,727
5
2012-07-28T18:49:33Z
11,704,363
10
2012-07-28T20:20:54Z
[ "python", "python-2.7", "mud", "online-game" ]
I need to have a 2 radius map drawn off the player's current room in a MUD I'm building in python (or more, if possible). Rooms are set up as containers with a `self.exits = {'west':1, 'north':2}` where the key is the direction that the value (UID of the adjacent room) is located. Rooms are linked only in this way. A p...
This code is in serious trouble. Let's start designing from scratch. This will hopefully serve as a good lesson in how to design and build classes and data structures. To start with, you should organize your code around a `Map` class, which then represents your rooms as a grid. You shouldn't think about "room 1", "roo...
Split requirements files in pip
11,704,287
27
2012-07-28T20:09:41Z
11,704,396
43
2012-07-28T20:26:20Z
[ "python", "syntax", "install", "pip", "package-management" ]
To create Python virtual environments I use virtualenv and pip. The workflow is very simple: ``` $ virtualenv project $ cd project $ . bin/activate $ pip install -r /path/to/requirements/req1.txt $ pip install -r /path/to/requirements/req2.txt ``` The number of different requirement files can grow enough to make hand...
The `-r` flag isn't restricted to command-line use only, it can also be used inside requirements files. So running `pip install -r req-1-and-2.txt` when req-1-and-2.txt contains this: ``` -r req-1.txt -r req-2.txt ``` will install everything specified in req-1.txt and req-2.txt.
Python pip broken after OS X 10.8 upgrade
11,704,379
64
2012-07-28T20:23:37Z
11,704,409
121
2012-07-28T20:28:14Z
[ "python", "osx", "pip" ]
Made the upgrade to Mac OS X 10.8 (Mountain Lion) and get now the following error when trying to call `$ pip`: ``` Traceback (most recent call last): File "/usr/local/bin/pip", line 5, in <module> from pkg_resources import load_entry_point File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/l...
Use `easy_install` to update your `pip` to the latest version: `sudo easy_install -U pip` Also make sure you have the lastest `XCode` installed (ver 4.4) with `Command Line Tools`.
Python - get full package module name
11,705,055
14
2012-07-28T22:10:25Z
11,705,103
21
2012-07-28T22:18:24Z
[ "python", "inspect" ]
For verbose debug messages in my application I'm using a function that returns a helpful prefix. Consider the following example: ``` import inspect def get_verbose_prefix(): """Returns an informative prefix for verbose debug output messages""" s = inspect.stack() module_name = inspect.getmodulename(s[1][1...
`__name__` always contains the full name of the module. (Other than `__main__` on main, of course.)
Python: Sort custom class without use of `key` argument?
11,705,371
8
2012-07-28T23:06:42Z
11,705,400
13
2012-07-28T23:12:55Z
[ "python" ]
You can sort an array of `myclass` by using the `key` argument to the `sorted` function: ``` sortedlist = sorted(myclasses, key=lambda obj: obj.myproperty) ``` Is there a way to define a natural ordering for our class? Perhaps some magic method so that we don't have to pass in a key each time? e.g., ``` class mycla...
In addition to `__cmp__`, you can also do it with the so-called "rich comparison operators" `__eq__`, `__le__`, `__lt__`, `__gt__`, and `__ge__`. Rather than defining all of them, you can use the [`functools.total_ordering`](http://docs.python.org/library/functools.html#functools.total_ordering) class decorator in 2.7+...
eliminating redundant tuples
11,705,436
5
2012-07-28T23:20:38Z
11,705,501
7
2012-07-28T23:32:44Z
[ "python", "tuples" ]
If I have a list of tuples, where each tuple represents variables, `a`, `b` and `c`, how can I eliminate redundant tuples? Redundant tuples are those where `a` and `b` are simply interchanged, but `c` is the same. So for this example: ``` tups = [(30, 40, 50), (40, 30, 50), (20, 48, 52), (48, 20, 52)] ``` my final l...
``` set([(a,b,c) if a<b else (b,a,c) for a,b,c in tups]) ```
Process functions from a list of strings in Python
11,705,546
5
2012-07-28T23:43:27Z
11,705,568
11
2012-07-28T23:46:33Z
[ "python", "string", "function", "exec" ]
I have a module that I import to my main application called pageprocs.py with a collection of functions in it that generate different content and return it in a string. pageprocs is supposed to be a way of allowing authenticated users to create plugins for the different content type. I then have a list of strings: ['c...
``` for i in list_of_stats: getattr(pageprocs, i, lambda: None)() ``` The `lambda: None` part is optional, but will prevent `AttributeError` being raised if the specified function doesn't exist (it's an anonymous do-nothing function).
How can I check the value of a DNS TXT record for a host?
11,705,946
5
2012-07-29T01:32:31Z
11,706,378
9
2012-07-29T03:17:37Z
[ "python", "dns" ]
I'm looking to verify domain ownership via a script, specifically a Python script, and would like know how to lookup the value of a DNS TXT entry. I know there are services and websites out there for this, but I would like to do it with a script.
This is easy using [dnspython](http://www.dnspython.org/). Here is an example: ``` import dns.resolver for txtrecord in dns.resolver.query('google.com', 'TXT').answer.response: print txtrecord.to_text() ``` This gives the following output: ``` 'google.com. 1700 IN TXT "v=spf1 include:_netblocks.google.com ip4:21...
Fix first element, shuffle the rest of a list/array
11,706,287
5
2012-07-29T02:56:15Z
11,706,317
9
2012-07-29T03:03:24Z
[ "python", "shuffle" ]
Is it possible to shuffle only a (continuous) part of a given list (or array in numpy)? If this is not generally possible, how about the special case where the first element is fixed while the rest of the list/array need to be shuffled? For example, I have a list/array: ``` to_be_shuffled = [None, 'a', 'b', 'c', 'd',...
Why not just ``` import random rest = to_be_shuffled[1:] random.shuffle(rest) shuffled_lst = [to_be_shuffled[0]] + rest ```
python usage of percentage sign- doesn't appear to be modulo or string formatting
11,707,046
2
2012-07-29T05:59:14Z
11,707,060
7
2012-07-29T06:01:56Z
[ "python" ]
What does a `%` sign mean in python when it is not a modulo or a string formatter? I came across it in this baffling block of code in the `timeit` module: ``` # Don't change the indentation of the template; the reindent() calls # in Timer.__init__() depend on setup being indented 4 spaces and stmt # being indented 8 s...
That is also string formatting. The `%(var)` syntax is used when you pass a dictionary of format replacers, and each is replaced by name: ``` >>> "%(foo)s is replaced" % {'foo': 'THIS'} 'THIS is replaced' ``` This is the "mapping key" usage described in [the documentation](http://docs.python.org/library/stdtypes.html...
Printing a list of list without brackets in python
11,707,150
2
2012-07-29T06:20:48Z
11,707,163
7
2012-07-29T06:22:46Z
[ "python", "list" ]
I have a list of list that I want to display as a string. This list: ``` my_list = [[7, 'd'], [3, 's']] ``` I want to display without the brackets and commas like this: ``` 7d 3s ``` How?
``` >>> my_list = [[7, 'd'], [3, 's']] >>> ' '.join('{0}{1}'.format(x, y) for x, y in my_list) 7d 3s ``` The above solution is best for the specific case of any two elements but here is a more general solution which works for any number of elements in the sublist: ``` >>> ' '.join(''.join(map(str, sublist)) for subli...
Python pandas, how to widen output display to see more columns?
11,707,586
96
2012-07-29T07:44:51Z
11,707,706
10
2012-07-29T08:03:35Z
[ "python", "pandas", "options", "display", "column-width" ]
Is there a way to widen the display of output in either interactive or script-execution mode? Specifically, I am using the describe() function on a Pandas dataframe. When the dataframe is 5 columns (labels) wide, I get the descriptive statistics that I want. However, if the dataframe has any more columns, the statisti...
You can use `print df.describe().to_string()` to force it to show the whole table. (You can use `to_string()` like this for any DataFrame. The result of `describe` is just a DataFrame itself.) The 8 is the number of rows in the DataFrame holding the "description" (because `describe` computes 8 statistics, min, max, me...
Python pandas, how to widen output display to see more columns?
11,707,586
96
2012-07-29T07:44:51Z
11,708,664
18
2012-07-29T10:56:01Z
[ "python", "pandas", "options", "display", "column-width" ]
Is there a way to widen the display of output in either interactive or script-execution mode? Specifically, I am using the describe() function on a Pandas dataframe. When the dataframe is 5 columns (labels) wide, I get the descriptive statistics that I want. However, if the dataframe has any more columns, the statisti...
You can adjust pandas print options with `set_printoptions`. ``` In [3]: df.describe() Out[3]: <class 'pandas.core.frame.DataFrame'> Index: 8 entries, count to max Data columns: x1 8 non-null values x2 8 non-null values x3 8 non-null values x4 8 non-null values x5 8 non-null values x6 8 non-nu...
Python pandas, how to widen output display to see more columns?
11,707,586
96
2012-07-29T07:44:51Z
11,711,637
155
2012-07-29T18:02:02Z
[ "python", "pandas", "options", "display", "column-width" ]
Is there a way to widen the display of output in either interactive or script-execution mode? Specifically, I am using the describe() function on a Pandas dataframe. When the dataframe is 5 columns (labels) wide, I get the descriptive statistics that I want. However, if the dataframe has any more columns, the statisti...
As @bmu [mentioned](http://stackoverflow.com/a/11708664/623735), pandas auto detects (by default) the size of the display area, a summary view will be used when an object repr does not fit on the display. You mentioned resizing the IDLE window, to no effect. If you do `print df.describe().to_string()` does it fit on th...
Python pandas, how to widen output display to see more columns?
11,707,586
96
2012-07-29T07:44:51Z
25,415,404
26
2014-08-20T22:19:24Z
[ "python", "pandas", "options", "display", "column-width" ]
Is there a way to widen the display of output in either interactive or script-execution mode? Specifically, I am using the describe() function on a Pandas dataframe. When the dataframe is 5 columns (labels) wide, I get the descriptive statistics that I want. However, if the dataframe has any more columns, the statisti...
Try this: ``` pd.set_option('display.expand_frame_repr', False) ``` From the documentation: > display.expand\_frame\_repr : boolean > > Whether to print out the full DataFrame repr for wide DataFrames across multiple lines, max\_columns is still respected, but the output will wrap-around across multiple “pages” ...
Python pandas, how to widen output display to see more columns?
11,707,586
96
2012-07-29T07:44:51Z
29,074,073
8
2015-03-16T10:04:56Z
[ "python", "pandas", "options", "display", "column-width" ]
Is there a way to widen the display of output in either interactive or script-execution mode? Specifically, I am using the describe() function on a Pandas dataframe. When the dataframe is 5 columns (labels) wide, I get the descriptive statistics that I want. However, if the dataframe has any more columns, the statisti...
You can set the output display to match your current terminal width: ``` pd.set_option('display.width', pd.util.terminal.get_terminal_size()[0]) ```
Python pandas, how to widen output display to see more columns?
11,707,586
96
2012-07-29T07:44:51Z
33,375,383
9
2015-10-27T18:04:34Z
[ "python", "pandas", "options", "display", "column-width" ]
Is there a way to widen the display of output in either interactive or script-execution mode? Specifically, I am using the describe() function on a Pandas dataframe. When the dataframe is 5 columns (labels) wide, I get the descriptive statistics that I want. However, if the dataframe has any more columns, the statisti...
If you want to set options temporarily for display one large df, you can use [option\_context](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.option_context.html): ``` with pd.option_context('display.max_rows', 999, 'display.max_columns', 5): print df ``` Option values are restored automatically whe...
Parsing HTML using Python
11,709,079
69
2012-07-29T12:00:42Z
11,709,123
25
2012-07-29T12:07:25Z
[ "python", "xml-parsing", "html-parsing" ]
I'm looking for an HTML Parser module for Python that can help me get the tags in the form of Python lists/dictionaries/objects. If I have a document of the form: ``` <html> <head>Heading</head> <body attr1='val1'> <div class='container'> <div id='class'>Something here</div> <div>Something else</d...
Here you can read more about different HTML parsers in Python and their performance. Even though the article is a bit dated it still gives you a good overview. [Python HTML parser performance](http://blog.ianbicking.org/2008/03/30/python-html-parser-performance/) I'd recommend BeautifulSoup even though it isn't built...
Parsing HTML using Python
11,709,079
69
2012-07-29T12:00:42Z
11,709,155
85
2012-07-29T12:12:15Z
[ "python", "xml-parsing", "html-parsing" ]
I'm looking for an HTML Parser module for Python that can help me get the tags in the form of Python lists/dictionaries/objects. If I have a document of the form: ``` <html> <head>Heading</head> <body attr1='val1'> <div class='container'> <div id='class'>Something here</div> <div>Something else</d...
> So that I can basically ask it to get me the content/text in the div tag with class='container' contained within the body tag, Or something similar. ``` try: from BeautifulSoup import BeautifulSoup except ImportError: from bs4 import BeautifulSoup html = #the HTML code you've written above parsed_html = Bea...
Parsing HTML using Python
11,709,079
69
2012-07-29T12:00:42Z
11,709,361
29
2012-07-29T12:47:39Z
[ "python", "xml-parsing", "html-parsing" ]
I'm looking for an HTML Parser module for Python that can help me get the tags in the form of Python lists/dictionaries/objects. If I have a document of the form: ``` <html> <head>Heading</head> <body attr1='val1'> <div class='container'> <div id='class'>Something here</div> <div>Something else</d...
I guess what you're looking for is [pyquery](http://pypi.python.org/pypi/pyquery): > pyquery: a jquery-like library for python. An example of what you want may be like: ``` from pyquery import PyQuery html = # Your HTML CODE pq = PyQuery(html) tag = pq('div#class') print tag.text() ``` And it uses the same sele...
Parsing HTML using Python
11,709,079
69
2012-07-29T12:00:42Z
26,812,589
8
2014-11-08T01:08:26Z
[ "python", "xml-parsing", "html-parsing" ]
I'm looking for an HTML Parser module for Python that can help me get the tags in the form of Python lists/dictionaries/objects. If I have a document of the form: ``` <html> <head>Heading</head> <body attr1='val1'> <div class='container'> <div id='class'>Something here</div> <div>Something else</d...
Compared to the other parser libraries `lxml` is extremely fast: * <http://blog.dispatched.ch/2010/08/16/beautifulsoup-vs-lxml-performance/> * <http://www.ianbicking.org/blog/2008/03/python-html-parser-performance.html> And with `cssselect` it’s quite easy to use for scraping HTML pages too: ``` from lxml.html imp...
How to not redefine url for static files in flask everytime
11,709,746
6
2012-07-29T13:48:41Z
11,717,984
16
2012-07-30T08:41:59Z
[ "python", "flask" ]
My app has a lot of routes that use the same set of static files. I have to define them for every route like this: ``` css_reset = url_for("static", filename="reset.css") css_main = url_for("static", filename="main.css") css_fonts = url_for("static", filename="fonts.css") js_jquery = url_for("static", filename="jque...
Instead of passing these variables to your templates every time you can register them as globals in Jinja: ``` app.jinja_env.globals.update( css_reset=url_for("static", filename="reset.css"), css_main=url_for("static", filename="main.css"), ... ) ``` Or, better yet, register a helper function: ``` app.ji...
How to not redefine url for static files in flask everytime
11,709,746
6
2012-07-29T13:48:41Z
11,718,637
11
2012-07-30T09:25:56Z
[ "python", "flask" ]
My app has a lot of routes that use the same set of static files. I have to define them for every route like this: ``` css_reset = url_for("static", filename="reset.css") css_main = url_for("static", filename="main.css") css_fonts = url_for("static", filename="fonts.css") js_jquery = url_for("static", filename="jque...
The simplest way is to use [Flask-Assets](http://elsdoerfer.name/docs/flask-assets/) extension. ``` from flask.ext.assets import Environment, Bundle assets = Environment(app) css_all = Bundle('reset.css','main.css','fonts.css') assets.register('css_all',css_all) ``` In template: ``` {% assets %} ...
Python dictionary "copy value"
11,711,245
2
2012-07-29T17:14:42Z
11,711,262
8
2012-07-29T17:16:22Z
[ "python", "docutils" ]
I was looking at the docutil source code (which is in python), when I saw this (redacted) : ``` def __init__(self, **attributes): for att, value in attributes.items(): att = att.lower() if att in self.list_attributes: # mutable list; make a copy for this node self.attributes...
It makes a copy of the list (it's not a dictionary) The notation is called "slicing". You can also specify where to start and end copying, if you don't specify anything - as in your code extract - it will copy from the first to the last element. For instance, `mylist[1:]` will copy the entire list omitting the first ...
Opening a Python thread in a new console window
11,712,629
6
2012-07-29T20:24:56Z
11,724,655
7
2012-07-30T15:32:52Z
[ "python", "windows", "linux", "multithreading", "python-multithreading" ]
I am trying to make a program that will launch both a view window (console) and a command line. In the view window, it would show **constant** updates, while the command line window would use `raw_input()` to accept commands that affect the view window. I am thinking about using threads for this, but I have no idea how...
I agree with @stark a GUI is the way. Purely for illustration here's a *not recommended non-GUI* way that shows how to do it using a thread, a subprocess, and a named pipe as IPC. There are two scripts: * `entry.py`: accept commands from a user, do something with the command, pass it to the named pipe given at the c...
Designing an extensible pipeline with Python
11,712,767
12
2012-07-29T20:41:00Z
11,718,113
9
2012-07-30T08:50:57Z
[ "python", "pipeline" ]
**Context:** I'm currently using Python to a code a data-reduction pipeline for a large astronomical imaging system. The main pipeline class passes experimental data through a number of discrete processing 'stages'. The stages are written in separate .py files which constitute a package. A list of available stages is ...
I've built a similar system; it's called [`collective.transmogrifier`](https://github.com/mjpieters/collective.transmogrifier). One of these days I'll make it more generic (it is currently tied to the CMF, one of the underpinnings of Plone). ### Decoupling What you need, is a way to decouple the component registratio...
How to remove strange space in LaTeX-style maths in matplotlib plot
11,712,899
8
2012-07-29T20:59:50Z
11,713,079
13
2012-07-29T21:23:22Z
[ "python", "latex", "matplotlib" ]
I am using the following as an axis label in matplotlib: ``` "Pixel Radiance ($W/m^2/\mu m$)" ``` But when I produce a graph with this as the y-axis label I get the image below, which has a strange space between the m^2 and the \mu which makes it look rather strange. How can I remove this strange space? ![example gr...
You can use a negative space, `\!`: ``` r"Pixel Radiance ($W/m^2\!/\mu m$)" ``` Incidentally, I'd recommend using raw-strings with LaTeX formulae, as that will prevent LaTeX commands (or parts of them) being interpreted as backslash-escapes: you probably wouldn't want `\tau` ending up as a tab followed by `au`.
How to debug C extensions for Python on Windows
11,713,701
9
2012-07-29T22:59:43Z
11,768,458
11
2012-08-01T22:23:46Z
[ "python", "c", "windows", "debugging", "gdb" ]
I have a [problem](http://stackoverflow.com/questions/11657958/catching-a-segfault-in-python-pyodbc-cursor-fetch-causes-python-to-crash) with a segfault in pyodbc and would like to debug it in Windows XP x86. However, the information online seems primarily Linux-centric. What is the best way to go about this?
So I was able to successfully resolve my issue by using Visual Studio 2008. I loosely followed the steps listed here - <http://www.velocityreviews.com/forums/t329214-debugging-python-extensions.html> And some tips on workarounds here - [Compiling python modules whith DEBUG defined on MSVC](http://stackoverflow.com/q...
Python weird string processing issue with strip
11,713,838
2
2012-07-29T23:24:31Z
11,713,846
10
2012-07-29T23:26:04Z
[ "python", "string", "strip" ]
Can anyone explain the following behavior to me? This doesn't make any sense. I have a string: ``` In [170]: t = "c:\\website\\site-env\\scripts" ``` I try to strip "c:\website" from the front, and it doesn't work: ``` In [171]: t.strip("c:\\website") Out[171]: '-env\\scrip' ``` I back up a little to see where it ...
`strip` uses the *characters*, not the string. For example, `"abcdefg".strip("facedb")` would result in `"g"`. Use a slice instead: ``` t[len(r'c:\website'):] if t.startswith(r'c:\website') else t ```
Homework - Python Proxy Server
11,713,933
5
2012-07-29T23:47:41Z
11,714,931
7
2012-07-30T03:01:03Z
[ "python", "sockets", "proxy-server" ]
For a programming exercise (**from Computer Networking: A Top-Down Approach (6th Edition) by Kurose and Ross**), we're trying to develop a simple proxy server in python. We were given the following code, wherever it says `#Fill in start. ... #Fill in end.` that is where we need to write code. My specific question and ...
This seems to be my potential solution. The pdf from the homework mentions I need to do something at the end, not sure what it is. But the cache and proxy seems to function with this. I hope it helps someone else. ``` from socket import * import sys if len(sys.argv) <= 1: print 'Usage: "python ProxyServer.py serv...
Check if an object exists
11,714,536
19
2012-07-30T01:45:09Z
11,714,635
27
2012-07-30T02:04:20Z
[ "python", "database", "django", "view", "model" ]
I need to check if `Model.objects.filter(...)` turned up anything, but do not need to insert anything. My code so far is: ``` user_pass = log_in(request.POST) # form class if user_pass.is_valid(): cleaned_info = user_pass.cleaned_data user_object = User.objects.filter(email = cleaned_info['username']) ```
Since `filter` returns a `QuerySet`, you can use [count](https://docs.djangoproject.com/en/dev/ref/models/querysets/#count) to check how many results were returned. This is assuming you don't actually need the results. ``` num_results = User.objects.filter(email = cleaned_info['username']).count() ``` After looking a...
Check if an object exists
11,714,536
19
2012-07-30T01:45:09Z
21,750,566
29
2014-02-13T09:48:41Z
[ "python", "database", "django", "view", "model" ]
I need to check if `Model.objects.filter(...)` turned up anything, but do not need to insert anything. My code so far is: ``` user_pass = log_in(request.POST) # form class if user_pass.is_valid(): cleaned_info = user_pass.cleaned_data user_object = User.objects.filter(email = cleaned_info['username']) ```
I think the easiest from a logical and efficiency point of view is using the queryset's **exists()** function, documented here: <https://docs.djangoproject.com/en/dev/ref/models/querysets/#django.db.models.query.QuerySet.exists> So in your example above I would simply write: ``` if User.objects.filter(email = cleane...
How to pluralize a name in a template with jinja2?
11,714,614
8
2012-07-30T02:01:22Z
22,336,061
16
2014-03-11T20:35:10Z
[ "python", "templates", "jinja2", "pluralize" ]
If I have a template variable called num\_countries, to pluralize with Django I could just write something like this: ``` countr{{ num_countries|pluralize:"y,ies" }} ``` Is there a way to do something like this with jinja2? (I do know this doesn't work in jinja2) What's the jinja2 alternative to this? Thanks for any...
Guy Adini's reply is definitely the way to go, though I think (or maybe I misused it) it is not exactly the same as *pluralize* filter in Django. Hence this was my implementation (using decorator to register) ``` @app.template_filter('pluralize') def pluralize(number, singular = '', plural = 's'): if number == 1:...
How to display the first few characters of a string in Python?
11,714,859
27
2012-07-30T02:44:52Z
11,714,936
62
2012-07-30T03:01:51Z
[ "python", "python-2.7" ]
Hi I just started learning Python but I'm sort of stuck right now. I have `hash.txt` file containing thousands of malware hashes in MD5, Sha1 and Sha5 respectively separated by delimiters in each line. Below are 2 examples lines I extracted from the .txt file. > 416d76b8811b0ddae2fdad8f4721ddbe|d4f656ee006e248f2f3a8a...
You can 'slice' a `string` very easily, just like you'd pull items from a `list`: ``` a_string = 'This is a string' ``` To get the first 4 letters: ``` first_four_letters = a_string[:4] >>> 'This' ``` Or the last 5: ``` last_five_letters = a_string[-5:] >>> 'string' ``` So applying that logic to your problem: ``...
How to display the first few characters of a string in Python?
11,714,859
27
2012-07-30T02:44:52Z
11,715,226
8
2012-07-30T03:56:18Z
[ "python", "python-2.7" ]
Hi I just started learning Python but I'm sort of stuck right now. I have `hash.txt` file containing thousands of malware hashes in MD5, Sha1 and Sha5 respectively separated by delimiters in each line. Below are 2 examples lines I extracted from the .txt file. > 416d76b8811b0ddae2fdad8f4721ddbe|d4f656ee006e248f2f3a8a...
Since there is a delimiter, you should use that instead of worrying about how long the md5 is. ``` >>> s = "416d76b8811b0ddae2fdad8f4721ddbe|d4f656ee006e248f2f3a8a93a8aec5868788b927|12a5f648928f8e0b5376d2cc07de8e4cbf9f7ccbadb97d898373f85f0a75c47f" >>> md5sum, delim, rest = s.partition('|') >>> md5sum '416d76b8811b0dda...
GCC-4.2 error on Mac OS-X Mountain Lion, unable to install some packages with pip / virtualenv
11,716,107
11
2012-07-30T06:02:06Z
11,796,279
14
2012-08-03T13:03:09Z
[ "python", "osx", "gcc", "pip", "osx-mountain-lion" ]
I'm seeing a very annoying bug that I don't really know how to deal with. It seems to be pretty common, and I've tried nearly every solution that I could find to no avail. I'm trying to install libraries using pip. This problem was encountered with gevent, with psycopg2, and with greenlet. The issue seems to be that m...
Same problem with pycrypto install failing to compile in a virtualenv. Found the solution in this thread by poster jiaaro: <https://gist.github.com/3179227#gistcomment-379913> > You need to install Xcode 4.4 (from the app store) and then, within > xcode open Xcode > Preferences (or press Cmd + ,) > then open the downl...
Python: BeautifulSoup extract text from anchor tag
11,716,380
8
2012-07-30T06:32:24Z
11,721,115
18
2012-07-30T12:00:42Z
[ "python", "html", "beautifulsoup", "scraper" ]
I want to extract text from following src of the image tag and text of the anchor tag which is inside the div class data. I successfully manage to extract the img src but I am having trouble on extracting the text from the anchor tag. ``` <a class="title" href="http://rads.stackoverflow.com/amzn/click/B0073HSK0K">Nik...
This will help: ``` from BeautifulSoup import BeautifulSoup data = '''<div class="image"> <a href="http://www.example.com/eg1">Content1<img src="http://image.example.com/img1.jpg" /></a> </div> <div class="image"> <a href="http://www.example.com/eg2">Content2<img sr...
Why does str.split not take keyword arguments?
11,716,687
24
2012-07-30T06:58:59Z
11,716,790
13
2012-07-30T07:07:05Z
[ "python", "standard-library", "cpython", "string-split" ]
I came across this - in my view - strange behaviour: ``` "a b c".split(maxsplit=1) TypeError: split() takes no keyword arguments ``` Why does str.split() not take keyword arguments, even though it would make sense? I found this behavior both in Python2 and Python3.
`str.split` is a builtin method implemented in C. Unfortunately some builtin functions/methods do not accept keyword arguments. See [this bug report](http://bugs.python.org/issue1176).
Why does str.split not take keyword arguments?
11,716,687
24
2012-07-30T06:58:59Z
11,716,792
27
2012-07-30T07:07:14Z
[ "python", "standard-library", "cpython", "string-split" ]
I came across this - in my view - strange behaviour: ``` "a b c".split(maxsplit=1) TypeError: split() takes no keyword arguments ``` Why does str.split() not take keyword arguments, even though it would make sense? I found this behavior both in Python2 and Python3.
See [this bug](http://bugs.python.org/issue8626) and [its superseder](http://bugs.python.org/issue8350). `str.split()` is a native function in CPython, and as such exhibits the behavior described [here](http://docs.python.org/dev/reference/expressions.html#calls): > **CPython implementation detail:** An implementatio...
sum over values in python dict except one
11,718,852
3
2012-07-30T09:39:30Z
11,718,879
7
2012-07-30T09:41:03Z
[ "python", "dictionary", "numpy", "sum" ]
Is there a way to sum over all values in a python dict except one by using a selector in ``` >>> x = dict(a=1, b=2, c=3) >>> np.sum(x.values()) 6 ``` ? My current solution is a loop based one: ``` >>> x = dict(a=1, b=2, c=3) >>> y = 0 >>> for i in x: ... if 'a' != i: ... y += x[i] ... >>> y 5 ``` E...
You could loop over the dict to create a generator for the `sum` method: ``` np.sum(value for key, value in x.iteritems() if key != 'a') ```
should chained calls be used in favor of more explicit assignments?
11,720,449
3
2012-07-30T11:19:22Z
11,720,559
11
2012-07-30T11:26:08Z
[ "python", "python-2.7", "stringio" ]
our team have to snippet like below: this: ``` buf = StringIO.StringIO() gzip.GzipFile(fileobj=buf, mode='wb').write(foo) ... ``` and this one: ``` buf = StringIO.StringIO() tmp = gzip.GzipFile(fileobj=buf, mode='wb') tmp.write(foo) ... ``` which one is more pythonic? EDITED: I have try/catch to do the error hand...
You need to close the `GzipFile` object after you are finished with it, so the one-line will not work. Instead, use a context manager expression: ``` buf = StringIO.StringIO() with gzip.GzipFile(fileobj=buf, mode='wb') as tmp: tmp.write(foo) ``` The one-liner `gzip.GzipFile(fileobj=buf, mode='wb').write(foo)` is ...
Django Many-to-Many (m2m) Relation to same model
11,721,157
17
2012-07-30T12:03:24Z
11,721,204
12
2012-07-30T12:06:43Z
[ "python", "django", "django-models", "many-to-many" ]
I'd like to create a many-to-many relationship from and to a user class object. I have something like this: ``` class MyUser(models.Model): ... blocked_users = models.ManyToManyField(MyUser, blank=True, null=True) ``` The question is if I can use the class reference inside itself. Or do I have to use `"self"...
``` class MyUser(models.Model): ... blocked_users = models.ManyToManyField("self", blank=True) ```
Django Many-to-Many (m2m) Relation to same model
11,721,157
17
2012-07-30T12:03:24Z
11,723,808
28
2012-07-30T14:43:06Z
[ "python", "django", "django-models", "many-to-many" ]
I'd like to create a many-to-many relationship from and to a user class object. I have something like this: ``` class MyUser(models.Model): ... blocked_users = models.ManyToManyField(MyUser, blank=True, null=True) ``` The question is if I can use the class reference inside itself. Or do I have to use `"self"...
Technically, I'm pretty sure "MyUser" or "self" will work, as long as it's a string in either case. You just can't pass `MyUser`, the actual class. However, the docs always use "self". Using "self" is not only more explicit about what's actually happening, but it's impervious to class name changes. For example, if you...
duckduckgo API not returning results
11,722,465
10
2012-07-30T13:20:46Z
11,923,803
20
2012-08-12T16:27:57Z
[ "python", "api", "parsing", "search" ]
**Edit** I now realize the API is simply inadequate and is not even working. I would like to redirect my question, I want to be able to auto-magically search duckduckgo using their "I'm feeling ducky". So that I can search for "stackoverflow" for instance and get the main page ("<http://stackoverflow.com/>") as my resu...
If you visit [DuckDuck Go API Page](http://duckduckgo.com/api.html), you will find some notes about using the API. The first notes says clearly that: > As this is a Zero-click Info API, most deep queries (non topic names) > will be blank. An here's the list of those fields: ``` Abstract: "" AbstractText: "" Abstract...
Split long conditional expressions to lines
11,723,018
5
2012-07-30T13:55:38Z
11,723,044
10
2012-07-30T13:57:28Z
[ "python", "if-statement", "python-2.6" ]
I have some if statements like: ``` def is_valid(self): if (self.expires is None or datetime.now() < self.expires) and (self.remains is None or self.remains > 0): return True return False ``` When I type this expressions my Vim automatically moves `and` to new line with this same indent as `if` li...
Add an additional level of brackets around the whole condition. This will allow you to insert line breaks as you wish. ``` if (1+1==2 and 2 < 5 < 7 and 2 != 3): print 'yay' ``` <http://ideone.com/lcV3a>
P-value from Chi sq test statistic in Python
11,725,115
18
2012-07-30T15:59:09Z
11,728,072
21
2012-07-30T19:14:30Z
[ "python", "statistics", "scipy", "chi-squared" ]
I have computed a test statistic that is distributed as a chi square with 1 degree of freedom, and want to find out what P-value this corresponds to using python. I'm a python and maths/stats newbie so I think what I want here is the probability denisty function for the chi2 distribution from SciPy. However, when I us...
Quick refresher here: Probability Density Function: think of it as a point value; how dense is the probability at a given point? Cumulative Distribution Function: this is the mass of probability of the function up to a given point; what percentage of the distribution lies on one side of this point? In your case, you...
P-value from Chi sq test statistic in Python
11,725,115
18
2012-07-30T15:59:09Z
20,165,482
13
2013-11-23T17:25:02Z
[ "python", "statistics", "scipy", "chi-squared" ]
I have computed a test statistic that is distributed as a chi square with 1 degree of freedom, and want to find out what P-value this corresponds to using python. I'm a python and maths/stats newbie so I think what I want here is the probability denisty function for the chi2 distribution from SciPy. However, when I us...
To calculate probability of null hypothesis given chisquared sum, and degrees of freedom you can also call `chisqprob`: ``` >>> from scipy.stats import chisqprob >>> chisqprob(3.84, 1) 0.050043521248705189 ```
P-value from Chi sq test statistic in Python
11,725,115
18
2012-07-30T15:59:09Z
30,401,469
11
2015-05-22T16:15:33Z
[ "python", "statistics", "scipy", "chi-squared" ]
I have computed a test statistic that is distributed as a chi square with 1 degree of freedom, and want to find out what P-value this corresponds to using python. I'm a python and maths/stats newbie so I think what I want here is the probability denisty function for the chi2 distribution from SciPy. However, when I us...
While stats.chisqprob() and 1-stats.chi2.cdf() appear comparable for small chi-square values, for large chi-square values the former is preferable. The latter cannot provide a p-value smaller than machine epsilon,and will give very inaccurate answers close to machine epsilon. As shown by others, comparable values resul...
PyCharm shows unresolved references error for valid code
11,725,519
118
2012-07-30T16:23:10Z
11,773,462
195
2012-08-02T08:12:08Z
[ "python", "pycharm" ]
I am using PyCharm to work on a project. The project is opened and configured with an interpreter, and can run successfully. The remote interpreter paths are mapped properly. This seems to be the correct configuration, but PyCharm is highlighting my valid code with "unresolved reference" errors, even for built-in Pytho...
File | Invalidate Caches... and restarting PyCharm helps.
PyCharm shows unresolved references error for valid code
11,725,519
118
2012-07-30T16:23:10Z
20,022,329
75
2013-11-16T18:50:34Z
[ "python", "pycharm" ]
I am using PyCharm to work on a project. The project is opened and configured with an interpreter, and can run successfully. The remote interpreter paths are mapped properly. This seems to be the correct configuration, but PyCharm is highlighting my valid code with "unresolved reference" errors, even for built-in Pytho...
Dmitry's response didn't work for me. I got mine working by going to Project Interpreters, Selecting the "Paths" tab, and hitting the refresh button in that submenu. It auto-populated with something called "python-skeletons". **edit**: screenshot using PyCharm 3.4.1 (it's quite well hidden) ![enter image description...
PyCharm shows unresolved references error for valid code
11,725,519
118
2012-07-30T16:23:10Z
22,563,427
10
2014-03-21T15:51:41Z
[ "python", "pycharm" ]
I am using PyCharm to work on a project. The project is opened and configured with an interpreter, and can run successfully. The remote interpreter paths are mapped properly. This seems to be the correct configuration, but PyCharm is highlighting my valid code with "unresolved reference" errors, even for built-in Pytho...
I find myself removing and re-adding the remote interpreter to fix this problem when Invalidating Caches or Refreshing Paths does not work. I use vagrant and every once and awhile if I add a new VM to my multi-vm setup, the forwarded port changes and this seems to confuse PyCharm when it tries to use the wrong port fo...
PyCharm shows unresolved references error for valid code
11,725,519
118
2012-07-30T16:23:10Z
29,665,019
9
2015-04-16T03:51:15Z
[ "python", "pycharm" ]
I am using PyCharm to work on a project. The project is opened and configured with an interpreter, and can run successfully. The remote interpreter paths are mapped properly. This seems to be the correct configuration, but PyCharm is highlighting my valid code with "unresolved reference" errors, even for built-in Pytho...
If none of the other solutions work for you, try (backing up) and deleting your ~/.PyCharm40 folder, then reopening PyCharm. This will kill all your preferences as well. On Mac you want to delete ~/Library/Caches/Pycharm40 and ~/Library/Preferences/PyCharm40. And on Windows: C:\Users\$USER.PyCharm40.
PyCharm shows unresolved references error for valid code
11,725,519
118
2012-07-30T16:23:10Z
30,163,990
8
2015-05-11T09:27:56Z
[ "python", "pycharm" ]
I am using PyCharm to work on a project. The project is opened and configured with an interpreter, and can run successfully. The remote interpreter paths are mapped properly. This seems to be the correct configuration, but PyCharm is highlighting my valid code with "unresolved reference" errors, even for built-in Pytho...
Tested with PyCharm 4.0.6 (OSX 10.10.3) following this steps: 1. Click PyCharm menu. 2. Select Project Interpreter. 3. Select Gear icon. 4. Select More button. 5. Select Project Interpreter you are in. 6. Select Directory Tree button. 7. Select Reload list of paths. Problem solved!
python looping through input file
11,726,349
6
2012-07-30T17:17:36Z
11,726,405
14
2012-07-30T17:21:31Z
[ "python", "for-loop", "file-io" ]
My question is related to file-input in Python, using `open()`. I have a text file `mytext.txt` with 3 lines. I am trying to do two things with this file: print the lines, and print the number of lines. I tried the following code: ``` input_file = open('mytext.txt', 'r') count_lines = 0 for line in input_file: pr...
The file handle is an iterator. After iterating over the file it will be positioned at EOF. You can rewind the file pointer with `input_file.seek(0)` without reopening it. That said, counting lines in the same loop is more I/O efficient, otherwise you have to read the whole file from disk a second time just to count t...
Fast 2-D interpolation in Python with SciPy regular grid to scattered / irregular evaluation
11,726,484
8
2012-07-30T17:27:44Z
11,729,709
8
2012-07-30T21:16:02Z
[ "python", "numpy", "scipy", "interpolation", "mesh" ]
I have a regular grid of training values (vectors x and y with respective grids xmesh and ymesh and known values of zmesh) but an scattered / ragged / irregular group of values to be interpolated (vectors xI and yI, where we are interested in zI[0] = f(xI[0],yI[0]) ... zI[N-1] = f(xI[N-1],yI[N-1]). This interpolation w...
This: <http://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.RectBivariateSpline.ev.html> I.e. `myspline.ev(xI, yI)`
Shouldn't the imports be absolute by default in python27?
11,726,633
17
2012-07-30T17:36:43Z
11,741,846
25
2012-07-31T13:58:38Z
[ "python", "import" ]
Imagine the directory structure: ``` / a/ __init__.py b.py c.py c.py ``` File `/a/b.py` looks like: ``` import c should_be_absolute = c ``` All the other files (including `__init__`) are empty. When running a test script (using python 2.7): ``` import a.b print a.b.should_be_absolu...
you need to add `from __future__ import absolute_import` or use `importlib.import_module('c')` on Python 2.7 It is default on Python 3. There was a bug in Python: [`__future__.py` and its documentation claim absolute imports became mandatory in 2.7, but they didn't](http://bugs.python.org/issue14494).
Multiple return values in python
11,726,758
5
2012-07-30T17:45:21Z
11,726,792
12
2012-07-30T17:47:35Z
[ "python" ]
I want to change a python function to return two values. How do I achieve that without affecting any of the previous function calls which only expect one return value? For eg. Original Definition: ``` def foo(): x = 2 y = 2 return (x+y) ``` sum = foo() Ne Definition: ``` def foo(): x = 2 y = 2...
``` def foo(return_2nd=False): x = 2 y = 2 return (x+y) if not return_2nd else (x+y),(x-y) ``` then call new version ``` sum, diff = foo(True) sum = foo() #old calls still just get sum ```
How to set an HTTP proxy in Python 2.7?
11,726,881
43
2012-07-30T17:53:31Z
11,727,032
79
2012-07-30T18:03:53Z
[ "python" ]
I am trying to run a script that installs pip: get-pip.py and am getting a connection timeout due to my network being behind an HTTP proxy. Is there some way I could configure an HTTP proxy in my Python 2.7 installation to be able to install what I am trying to install? Note: I am using Windows. Below is the error I a...
It looks like `get-pip.py` has been updated to use the environment variables `http_proxy` and `https_proxy`. Windows: ``` set http_proxy=http://proxy.myproxy.com set https_proxy=https://proxy.myproxy.com python get-pip.py ``` Linux/OS X: ``` export http_proxy=http://proxy.myproxy.com export https_proxy=https://prox...
Check if each element in a list match with a string in Python?
11,727,351
3
2012-07-30T18:26:53Z
11,727,388
8
2012-07-30T18:29:26Z
[ "python", "list" ]
I am writing a simple if else loop to check if a string match with multiple words like this: ``` if "word1" in data or "word2" in data or "word3" in data: .... ``` I am not sure if we have a more comprehensive way to process this kind of comparison ? Thank you very much
You can do: ``` if any(x in data for x in ('word1', 'word2', 'word3')): ```
Check if each element in a list match with a string in Python?
11,727,351
3
2012-07-30T18:26:53Z
11,727,390
8
2012-07-30T18:29:34Z
[ "python", "list" ]
I am writing a simple if else loop to check if a string match with multiple words like this: ``` if "word1" in data or "word2" in data or "word3" in data: .... ``` I am not sure if we have a more comprehensive way to process this kind of comparison ? Thank you very much
``` if any(word in data for word in ('word1', 'word2', 'word3')): ... ``` If you run into performance issues, you may want to convert `data` to a `set` before running the comparisons.
Reading a .vtk file with python
11,727,822
9
2012-07-30T18:56:45Z
11,942,424
11
2012-08-13T21:15:04Z
[ "python", "vtk" ]
I've been given a legacy format vtk file (I think its an unstructured grid) and I'd like to read it in with python and output a .npy file instead, since I know how to deal with that. The file is a dump from ATHENA and so has density, velocity, magnetic field along with the coordinates. I'm very much a procedural prog...
Here is the solution that I came up with, the trick was turning on ReadAllVectorsOn(). ``` import numpy from vtk import vtkStructuredPointsReader from vtk.util import numpy_support as VN reader = vtkStructuredPointsReader() reader.SetFileName(filename) reader.ReadAllVectorsOn() reader.ReadAllScalarsOn() reader.Update...
Python: determining whether any item in sequence is equal to any other
11,728,662
9
2012-07-30T19:56:53Z
11,728,700
18
2012-07-30T19:59:23Z
[ "python", "comparison" ]
I'd like to compare multiple objects and return `True` only if all objects are not equal among themselves. I tried using the code below, but it doesn't work. If obj1 and obj3 are equal and obj2 and obj3 are not equal, the result is `True`. ``` obj1 != obj2 != obj3 ``` I have more than 3 objects to compare. Using the ...
If the objects are all hashable, then you can see whether a `frozenset` of the sequence of objects has the same length as the sequence itself: ``` def all_different(objs): return len(frozenset(objs)) == len(objs) ``` Example: ``` >>> all_different([3, 4, 5]) True >>> all_different([3, 4, 5, 3]) False ```
Python: determining whether any item in sequence is equal to any other
11,728,662
9
2012-07-30T19:56:53Z
11,728,734
20
2012-07-30T20:01:24Z
[ "python", "comparison" ]
I'd like to compare multiple objects and return `True` only if all objects are not equal among themselves. I tried using the code below, but it doesn't work. If obj1 and obj3 are equal and obj2 and obj3 are not equal, the result is `True`. ``` obj1 != obj2 != obj3 ``` I have more than 3 objects to compare. Using the ...
@Michael Hoffman's answer is good if the objects are all hashable. If not, you can use [itertools.combinations](http://docs.python.org/library/itertools.html#itertools.combinations): ``` >>> all(a != b for a, b in itertools.combinations(['a', 'b', 'c', 'd', 'a'], 2)) False >>> all(a != b for a, b in itertools.combinat...
Use Python xmlrpclib with unix domain sockets?
11,729,159
9
2012-07-30T20:34:22Z
11,746,051
10
2012-07-31T17:47:48Z
[ "python", "xml-rpc", "xmlrpclib", "unix-socket", "unix-domain-sockets" ]
I'm trying to interact with `supervisord`, and I'd like to talk with it over a unix socket (it's a shared hosting environment). What I've tried so far is: ``` import xmlrpclib server = xmlrpclib.ServerProxy('unix:///path/to/supervisor.sock/RPC2') Traceback (most recent call last): File "<stdin>", line 1, in <module...
`xmlrpclib` requires that the url passed start with `http` or `https`. The way around this is to define a custom transport which ignores that url. Here's some code using the transport from supervisor: ``` import supervisor.xmlrpc import xmlrpclib proxy = xmlrpclib.ServerProxy('http://127.0.0.1', ...
Build systems in Sublime Text
11,729,368
22
2012-07-30T20:51:50Z
11,729,762
35
2012-07-30T21:19:16Z
[ "c++", "python", "build", "sublimetext2" ]
I'm just beginning to learn programming (on C++ and Python), and by beginning I mean total beginning ("hello world" beginning...). Not wanting to use multiple IDE's, I would like to be able to code and build–simple–programs with my text editor, Sublime Text 2. Could someone indicate me, with a step-by-step tutorial...
Sublime Text 2 already comes with scripts for building and running Python and C++ programs. Simply press `Cmd`+`B` (or `Ctrl`+`B` on Windows & Linux) when a .py or .cpp file is open. The Python file will automatically execute and show the result in the built in console. For C++, you need to press `Cmd`+`Shift`+`B` (`...
Adding data to QTableWidget using PyQt4 in Python
11,729,472
10
2012-07-30T20:58:39Z
11,731,883
15
2012-07-31T01:22:33Z
[ "python", "pyqt" ]
I want to add my data to a table using pyqt in python. I found that I should use `setItem()` function to add data to a `QTableWidget` and give it the row and column number and a `QTableWidgetItem`. I did it but when I want to display the table, it's completely empty. Maybe I made a silly mistake but please help me. Her...
What you are looking for are the `setRowCount()` and `setColumnCount()` methods. Call these on the `QTableWidget` to specify the number of rows/columns. E.g. ``` ... self.table = QtGui.QTableWidget() self.table.setRowCount(5) self.table.setColumnCount(5) layout.addWidget(self.led, 0, 0) layout.addWidget(self.table, 1,...
Disable 'pause' in windows bat script
11,729,562
6
2012-07-30T21:04:55Z
11,729,668
11
2012-07-30T21:13:07Z
[ "python", "windows", "batch-file", "cmd" ]
In windows, I am running a bat script that currently ends with a 'pause' and prompts for the user to 'Press any key to continue...' I am unable to edit the file in this scenario and I need the script to terminate instead of hang waiting for input that will never come. Is there a way I can run this that will disable or...
Try to execute `cmd.exe /c YourCmdFile < nul` `YourCmdFile` - full path to your batch script
Python class method decorator w/ self arguments?
11,731,136
31
2012-07-30T23:30:39Z
11,731,208
58
2012-07-30T23:38:53Z
[ "python" ]
How do I pass a class field to a decorator on a class method as an argument? What I want to do is something like: ``` class Client(object): def __init__(self, url): self.url = url @check_authorization("some_attr", self.url) def get(self): do_work() ``` It complains that self doesn't exist...
Yes. Instead of passing in the instance attribute at class definition time, check it at runtime: ``` def check_authorization(f): def wrapper(*args): print args[0].url return f(*args) return wrapper class Client(object): def __init__(self, url): self.url = url @check_authorizat...
Boolean testing a list in Python
11,732,329
7
2012-07-31T02:35:54Z
11,732,347
11
2012-07-31T02:38:11Z
[ "python", "list", "boolean" ]
I was testing a list to see if it's empty or not. Normally I use len(list) == 0 and I vaguely remembered reading a little while ago that the correct way to test if a list is empty was whether it was True or false. So I tried list is False, and that returned False. Maybe I'm suppose to be using == ? Nope, that also ret...
An empty list is not False, but when you convert it to a boolean, it converts to False. Likewise for dicts, tuples, strings, etc.: ``` >>> [] == False False >>> bool([]) == False True >>> {} == False False >>> bool({}) == False True ``` When you put something in the condition of an `if` clause, it is its boolean valu...
How can I delete all zeros except for x of them in every run of consecutive zeros within a list?
11,732,554
4
2012-07-31T03:09:54Z
11,732,610
8
2012-07-31T03:17:58Z
[ "python", "list", "del" ]
For every run of `x` or more consecutive zeros in a list in Python, I would like to del all zeros in the run except for `x` of them. If `x = 0`, then delete all zeros. I was thinking of a Python function that took a list, `L`, and a number, `x`, as inputs. For example, let `L = [7, 0, 12, 0, 0, 2, 0, 0, 0, 27, 10, 0,...
This is easy to do as a generator. Wrap your call to it in a `list` constructor if you want a fresh list with the zero-runs removed. ``` def compact_zero_runs(iterable, max_zeros): zeros = 0 for i in iterable: if i == 0: zeros += 1 if zeros <= max_zeros: yield i ...
Mechanize in Python - Redirect is not working after submit
11,732,792
4
2012-07-31T03:48:27Z
11,734,485
7
2012-07-31T06:40:39Z
[ "python", "mechanize", "mechanize-python" ]
I just started using mechanize in Python and I'm having some problems with it already. I've looked around on StackOverflow and on Google and I've seen people say that the documentation is great and that it should be easy to get it working, but I think I don't know how to look for that documentation since all I can find...
<http://wwwsearch.sourceforge.net/mechanize/documentation.html> Avoid using "\_http" directly. The first underscore in a name tells us that the developer was thinking on it as something private, and you probably don't need it. ``` In [20]: mechanize.HTTPRefreshProcessor is mechanize._http.HTTPRefreshProcessor Out[20]...
In python, is there an easy way to turn numbers with commas into an integer, and then back to numbers with commas?
11,735,037
4
2012-07-31T07:18:08Z
11,735,233
11
2012-07-31T07:30:11Z
[ "python", "string", "math" ]
Let's say I have a number like this: **8,741** or **8,741,291** How can I use python to multiply that number by 2, and then put commas back into it? I want the python function to return **17,482 and 17,482,582**, in a string format.
``` my_str = '1,255,000' my_num = int(my_str.replace(',','')) #replace commas with nothing ``` this will return my\_num = 1255000 ``` result = my_num * 2 import locale locale.setlocale(locale.LC_ALL, 'en_US') my_str = locale.format("%d", result, grouping=True) ``` this will return->my\_str='2,510,000'
Python3: UnicodeEncodeError only when run from crontab
11,735,363
5
2012-07-31T07:38:13Z
11,735,666
9
2012-07-31T08:03:32Z
[ "python", "python-3.x", "python-unicode" ]
first post so be kind please, I have searched a lot around but most things I found are relevant to Python 2. I have a Python3 script that builds a zip file from a file list; it fails with UnicodeEncodeError only when the script is run from crontab, but it works flawlessly when run from interactive console. I guess the...
A team member found the resolution in a [Python bug thread](http://bugs.python.org/issue13643#msg149941). The issue was fixed by prepending a LANG directive to the script command: ``` * * * * * LANG=it_IT.UTF-8 /home/vte/vtebackup/vte41/scripts/runbackup.sh >/dev/null 2>&1 ``` I hope this is useful for others becaus...
Apply list of functions on an object in Python
11,736,407
8
2012-07-31T08:51:06Z
11,736,719
7
2012-07-31T09:11:30Z
[ "python", "functional-programming" ]
Is there any clean way to apply a list of functions on an object in Python without lambda or list comprehensions? Like the Haskell expression: ``` map ($ obj) [foo1,foo2] ``` Example with lambda in Python: ``` response = map(lambda foo:foo(obj),[foo1,foo2]) #fooX:object->Bool ``` Is it extendable to class functions...
You could always just create a function to take care of it for you: ``` def map_funcs(obj, func_list): return [func(obj) for func in func_list] # I was under the impression that the OP wanted to compose the functions, # i.e. f3(f2(f1(f0(obj))), for which the line below is applicable: # return reduce(l...
why PyObject* can point to any object in python?
11,736,762
4
2012-07-31T09:13:20Z
11,737,139
7
2012-07-31T09:33:59Z
[ "python", "c" ]
In python's source code, there are some macro definitions like this: ``` #define PyObject_HEAD \ int ob_refcnt; \ struct _typeobject *ob_type; #define PyObject_VAR_HEAD \ PyObject_HEAD \ int ob_size; typedef struct _object { PyObject_HEAD } PyObject; typedef struct ...
Each struct for the different types of Python object has an instance of `PyObject_HEAD` as its first member (or the first member of its first member, and so on). This member sub-object is guaranteed to be located at the same address as the full object. The `PyObject_HEAD*` points at that member sub-object, but could ...
Django get_models with models/__init.py__
11,739,011
8
2012-07-31T11:23:23Z
11,739,122
11
2012-07-31T11:30:11Z
[ "python", "django" ]
I'm having a problem using get\_model and get\_models in django I have several models under models/ ``` models/blog.py models/tags.py models/users.py models/comments.py models/category.py ``` And a `models/__init.py__` ``` from myapp.models.blog import * from myapp.models.tags import * from myapp.models.users ...
Because you haven't defined your models in the app's `models.py`, you must explicitly set the [`app_label`](https://docs.djangoproject.com/en/dev/ref/models/options/#django.db.models.Options.app_label) option for each model. ``` class Blog(models.Model): title = models.CharField(max_length=30) ... class M...
How to create a dictionary with certain specific behaviour of values
11,739,170
4
2012-07-31T11:33:01Z
11,739,350
8
2012-07-31T11:43:57Z
[ "python", "dictionary" ]
Suppose I have two lists: ``` l1 = [['b', (1, 1)], ['b', (1, 2)], ['b', (1, 3)], ['a', (1, 5)], ['b', (2, 1)], ['b',(3, 1)]] l2 = ['A','B','C'] ``` How can I create a dictionary into this format? ``` dct = {'A': len(sublist1), 'B': len(sublist2), 'C' : len(sublist3)} ``` where ``` sublist1 = [['b', (1, 1)],...
This seems to work: ``` from itertools import groupby key = lambda x: x[1][0] lens = [len(list(g)) for k, g in groupby(sorted(l1, key=key), key=key)] dct = dict(zip(l2, lens)) ``` I hope I've inferred correctly when I've assumed A match with 1, B with 2, and so on. **Re: OP edit** I don't know where the `(2, 3)` i...
Django Tastypie - Prepend URLs does not work
11,739,774
4
2012-07-31T12:09:01Z
11,739,775
7
2012-07-31T12:09:01Z
[ "python", "django", "api", "tastypie" ]
I tried to use the `prepend_url()` function similar to the search example in the [tastypie cookbook](http://django-tastypie.readthedocs.org/en/latest/cookbook.html). For some reason the browser returned just a 404 and nothing else happens...
The cookbook refers to the 0.9.12 version which is just an alpha version. The `prepend_urls()` function is not implemented in the older versions. Therefore the function is simply not called and does not trigger an error message. So you have to install the alpha or use the `override_urls()` function ([documentation](ht...
Python 3.2 installation on Ubuntu 12.04
11,740,218
6
2012-07-31T12:37:21Z
11,740,498
11
2012-07-31T12:50:38Z
[ "python", "ubuntu-12.04", "failed-installation", "python-3.2" ]
I am trying to install python 3.2.3 on my ubuntu machine, which is 12.04, but I do not want to disturb the current 2.7 installation. After searching on the internet, I found a reference [here](http://www.unixmen.com/howto-install-python-3-x-in-ubuntu-debian-fedora-centos/). I followed the instructions, but when trying ...
You can install as many Python versions as needed. A call to `python` from the shell will execute `python2.7` (you can check that by executing `ls -l /usr/bin/python`), python 3.2 can be called also as `python3`. If you have even more versions, these can be accessed directly with their numbers as `python2.6` etc. I pe...
Can a method be a decorator of another method of the same class?
11,740,626
10
2012-07-31T12:56:27Z
11,740,716
8
2012-07-31T13:01:46Z
[ "python", "instance", "decorator" ]
I have a class with a dull repeating pattern on their functions and I wanted to turn this pattern into a decorator. But the thing is that this decorator must access some attributes of the current instance, so I wanted to turn it into a method in this class. I'm having some problems with that. So, this is similar to wh...
The decorator gets only one parameter – the function or method it decorates. It does not get passed an instance as `self` parameter – at the moment the decorator is called, not even the class has been created, let alone an instance of the class. The instance will be passed as first argument to the decorated functio...
Is there a way to use two if conditions in list comprehensions in python
11,740,814
10
2012-07-31T13:06:53Z
11,740,834
12
2012-07-31T13:07:54Z
[ "python", "list" ]
Suppose i had a list ``` my_list = ['91 9925479326','18002561245','All the best','good'] ``` Now i want to ignore the strings in the list starting with `91` and `18` like below ``` result = [] for i in my_list: if not '91' in i: if not '18' in i: result.append(i) ``` So here i want to achieve this...
``` [i for i in my_list if '91' not in i and '18' not in i] ``` Note you shouldn't use `list` as a variable name, it shadows the built-in function.
Where is the source code for pypi, the Python package index?
11,741,069
10
2012-07-31T13:20:44Z
11,741,215
9
2012-07-31T13:27:37Z
[ "python", "pypi" ]
I'm having a hard time finding the source code for pypi. Where is it?
The PyPI source can be found [here](https://bitbucket.org/pypa/pypi). More technical documents about PyPI's architecture are: * [CheeseShop](http://wiki.python.org/moin/CheeseShop) (general overview with various links) * [CheeseShopDev](http://wiki.python.org/moin/CheeseShopDev) (technical documentation) The name *Ch...
How to print UTF-8 encoded text to the console in Python < 3?
11,741,574
31
2012-07-31T13:45:08Z
11,742,574
24
2012-07-31T14:35:58Z
[ "python", "shell", "encoding", "utf-8", "ascii" ]
I'm running a recent Linux system where all my locales are UTF-8: ``` LANG=de_DE.UTF-8 LANGUAGE= LC_CTYPE="de_DE.UTF-8" LC_NUMERIC="de_DE.UTF-8" LC_TIME="de_DE.UTF-8" ... LC_IDENTIFICATION="de_DE.UTF-8" LC_ALL= ``` **Now I want to write UTF-8 encoded content to the console.** Right now Python uses UTF-8 for the FS e...
This is how I do it: ``` #!/usr/bin/python2.7 -S import sys sys.setdefaultencoding("utf-8") import site ``` Note the `-S` in the bangline. That tells Python to not automatically import the `site` module. The `site` module is what sets the default encoding and the removes the method so it can't be set again. But will...
How to print UTF-8 encoded text to the console in Python < 3?
11,741,574
31
2012-07-31T13:45:08Z
11,742,928
25
2012-07-31T14:54:56Z
[ "python", "shell", "encoding", "utf-8", "ascii" ]
I'm running a recent Linux system where all my locales are UTF-8: ``` LANG=de_DE.UTF-8 LANGUAGE= LC_CTYPE="de_DE.UTF-8" LC_NUMERIC="de_DE.UTF-8" LC_TIME="de_DE.UTF-8" ... LC_IDENTIFICATION="de_DE.UTF-8" LC_ALL= ``` **Now I want to write UTF-8 encoded content to the console.** Right now Python uses UTF-8 for the FS e...
It seems accomplishing this is not recommended. Fedora suggested [using the system locale as the default](https://fedoraproject.org/wiki/Features/PythonEncodingUsesSystemLocale), but apparently this breaks other things. Here's a quote from the [mailing-list discussion](http://thread.gmane.org/gmane.comp.python.devel/...
Python SOAP client, WSDL call with suds gives Transport Error 401 Unauthorized for HTTP basic authentication
11,742,494
8
2012-07-31T14:31:42Z
12,163,179
9
2012-08-28T16:00:56Z
[ "python", "soap", "wsdl", "basic-authentication", "suds" ]
### Background I'm building a SOAP client with python 2.7.3 and using the suds 0.4.1 library provided by Canonical. The server is using basic authentication over HTTPS. ### Problem Can't pass authentication on the server, even to get at the WSDL. I get the following error: `suds.transport.TransportError: HTTP Erro...
suds wasn't adding the authorization header to the request, so I set it manually: ``` import base64 # code excluded for brevity base64string = base64.encodestring('%s:%s' % (username, password)).replace('\n', '') authenticationHeader = { "SOAPAction" : "ActionName", "Authorization" : "Basic %s" % base64strin...
Convert python datetime to epoch with strftime
11,743,019
62
2012-07-31T14:59:57Z
11,743,111
43
2012-07-31T15:04:33Z
[ "python", "datetime", "utc", "epoch", "strftime" ]
I have a time in UTC from which I want the number of seconds since epoch. I am using strftime to convert it to the number of seconds. Taking 1st April 2012 as an example. ``` >>>datetime.datetime(2012,04,01,0,0).strftime('%s') '1333234800' ``` 1st of April 2012 UTC from epoch is 1333238400 but this above returns 133...
I had serious issues with Timezones and such. The way Python handles all that happen to be pretty confusing (to me). Things seem to be working fine using the calendar module (see links [1](http://stackoverflow.com/questions/2956886/python-calendar-timegm-vs-time-mktime), [2](http://docs.python.org/library/calendar.html...
Convert python datetime to epoch with strftime
11,743,019
62
2012-07-31T14:59:57Z
11,743,262
121
2012-07-31T15:10:58Z
[ "python", "datetime", "utc", "epoch", "strftime" ]
I have a time in UTC from which I want the number of seconds since epoch. I am using strftime to convert it to the number of seconds. Taking 1st April 2012 as an example. ``` >>>datetime.datetime(2012,04,01,0,0).strftime('%s') '1333234800' ``` 1st of April 2012 UTC from epoch is 1333238400 but this above returns 133...
Python doesn't actually support %s as an argument to strftime (if you check at <http://docs.python.org/library/datetime.html#strftime-and-strptime-behavior> it's not in the list), the only reason it's working is because Python is passing the information to your system's strftime, which uses your local timezone. If you...
Convert python datetime to epoch with strftime
11,743,019
62
2012-07-31T14:59:57Z
17,203,956
18
2013-06-20T01:31:43Z
[ "python", "datetime", "utc", "epoch", "strftime" ]
I have a time in UTC from which I want the number of seconds since epoch. I am using strftime to convert it to the number of seconds. Taking 1st April 2012 as an example. ``` >>>datetime.datetime(2012,04,01,0,0).strftime('%s') '1333234800' ``` 1st of April 2012 UTC from epoch is 1333238400 but this above returns 133...
``` import time from datetime import datetime now = datetime.now() time.mktime(now.timetuple()) ```
Convert python datetime to epoch with strftime
11,743,019
62
2012-07-31T14:59:57Z
18,967,102
13
2013-09-23T19:20:00Z
[ "python", "datetime", "utc", "epoch", "strftime" ]
I have a time in UTC from which I want the number of seconds since epoch. I am using strftime to convert it to the number of seconds. Taking 1st April 2012 as an example. ``` >>>datetime.datetime(2012,04,01,0,0).strftime('%s') '1333234800' ``` 1st of April 2012 UTC from epoch is 1333238400 but this above returns 133...
``` import time from datetime import datetime now = datetime.now() # same as above except keeps microseconds time.mktime(now.timetuple()) + now.microsecond * 1e-6 ``` (Sorry, it wouldn't let me comment on existing answer)
Remove Commas from Large CSV (1GB)
11,744,136
6
2012-07-31T15:53:14Z
11,744,671
8
2012-07-31T16:21:03Z
[ "python", "matlab", "csv", "comma" ]
I have a large CSV file (1GB) that I would like to remove commas from. The data are all positive integers. Methods I have tried include dlmwrite with a space as the delimiter, but the output is then output in decimal format. I have also tried to use the fprintf command, but then I lose the shape of the matrix (i.e. all...
In Python, if the format is really that simple (and there already is a space after each comma): ``` with open("infile.csv") as infile, open("outfile.csv", "w") as outfile: for line in infile: outfile.write(line.replace(",", "")) ``` If you can't be sure about whitespace: ``` import re with open("infile.c...
Running python script inside ipython
11,744,181
53
2012-07-31T15:55:55Z
11,744,336
14
2012-07-31T16:02:39Z
[ "python", "path", "ipython" ]
Is it possible to run a python script (not module) from inside ipython without indicating its path? I tried to set PYTHONPATH but it seems to work only for modules. I would like to execute ``` %run my_script.py ``` without being in the directory containing the file.
In python there is no difference between modules and scripts; You can execute both scripts and modules. The file must be on the pythonpath AFAIK because python must be able to find the file in question. If python is executed from a directory, then the directory is automatically added to the pythonpath. Refer to [What ...