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
Publish a post using XML-RPC WordPress API and Python with category
12,585,307
4
2012-09-25T14:37:36Z
14,372,862
7
2013-01-17T05:44:26Z
[ "python", "wordpress", "xml-rpc", "categories" ]
I'm doing a migration from a website to another one which use Wordpress. I created new custom types for my needs (with the plugin Custom Post Types), and I created categories for each custom type. I then wrote down a script in Python (adapted from [this article](http://www.jansipke.nl/using-python-to-add-new-posts-in...
[XML-RPC WordPress API Document](http://codex.wordpress.org/XML-RPC_WordPress_API/Posts#wp.newPost) says: ``` struct terms: Taxonomy names as keys, array of term IDs as values. struct terms_names: Taxonomy names as keys, array of term names as values. ``` This means terms and terms\_names are directory, the key name ...
Requests, bind to an ip
12,585,317
8
2012-09-25T14:38:44Z
12,590,625
13
2012-09-25T20:35:34Z
[ "python", "urllib2", "python-requests" ]
I have a script that makes some requests with `urllib2`. I use the trick [suggested elsewhere on Stack Overflow](http://stackoverflow.com/questions/1150332/source-interface-with-python-and-urllib2) to bind another ip to the application, where my my computer has two ip addresses (IP A and IP B). I would like to switch...
Looking into the `requests` module, it looks like it uses `httplib` to send the http requests. `httplib` uses `socket.create_connection()` to connect to the www host. Knowing that and following the monkey patching method in the link you provided: ``` import socket real_create_conn = socket.create_connection def set...
remove last STDOUT line in Python
12,586,601
20
2012-09-25T15:50:50Z
12,586,667
27
2012-09-25T15:54:57Z
[ "python", "stdout", "command-prompt" ]
I am trying to figure out how to suppress the display of user input on stdout. `raw_input()` followed by any print statement preserves what the user typed in. `getpass()` does not show what the user typed, but it does preserve the "Password:" prompt. To fix this, I would like to only remove the last line (which would...
You might be able to do what you want with [VT100 control codes](http://www.termsys.demon.co.uk/vtansi.htm#cursor). Something like this maybe: ``` CURSOR_UP_ONE = '\x1b[1A' ERASE_LINE = '\x1b[2K' print(CURSOR_UP_ONE + ERASE_LINE) ```
How do I link to a static image inside a css file?
12,587,144
7
2012-09-25T16:24:40Z
12,587,180
11
2012-09-25T16:26:16Z
[ "python", "pylons", "pyramid" ]
newb to pyramid and python. I've been able to link to my static files successfully in any of my jinja2 templates, ie: ``` <link rel="stylesheet" type="text/css" href="{{'myproject:static/mycss.css'|static_url}}"></link> ``` The .css file loads fine and I can link to any images that are inside my static folder as long...
Your CSS file is a static file, and thus is *not* treated as a template. All static resources are served as-is, without any processing. All non-absolute URLs in a CSS file are relative to the location from where the CSS file has been loaded; if you use `background-image:url("myimage.gif")`, the browser loads the image...
Python set with the ability to pop a random element
12,587,352
20
2012-09-25T16:37:51Z
12,588,050
14
2012-09-25T17:25:46Z
[ "python", "random", "set" ]
I am in need of a Python (2.7) object that functions like a set (fast insertion, deletion, and membership checking) but has the ability to return a random value. Previous questions asked on stackoverflow have answers that are things like: ``` import random random.sample(mySet, 1) ``` But this is quite slow for large ...
I think the best way to do this would be to use the [`MutableSet`](http://docs.python.org/library/collections.html#collections-abstract-base-classes) abstract base class in `collections`. Inherit from `MutableSet`, and then define `add`, `discard`, `__len__,` `__iter__`, and `__contains__`; also rewrite `__init__` to o...
Python Pandas: Multiple aggregations of the same column
12,589,481
17
2012-09-25T19:05:26Z
13,592,901
13
2012-11-27T20:57:33Z
[ "python", "aggregate", "pandas" ]
Given the following (totally overkill) data frame example ``` df = pandas.DataFrame({ "date":[datetime.date(2012,x,1) for x in range(1,11)], "returns":0.05*np.random.randn(10), "dummy":np.repeat(1,10) }) ``` is there an exis...
You can simply pass the functions as a list: ``` In [20]: df.groupby("dummy").agg({"returns": [np.mean, np.sum]}) Out[20]: returns sum mean dummy 1 0.285833 0.028583 ``` or as a dictionary: ``` In [21]: df.groupby('dummy').agg({'returns': ...
os.path.getsize reports a filesize with an L at the end, why?
12,589,976
5
2012-09-25T19:43:24Z
12,590,165
7
2012-09-25T19:57:05Z
[ "python", "dictionary", "filesize", "directory" ]
``` import os, sys def crawlLocalDirectories(directoryToCrawl): crawledDirectory = [os.path.join(path, subname) for path, dirnames, filenames in os.walk(directoryToCrawl) for subname in dirnames + filenames] return crawledDirectory print crawlLocalDirectories('.') dictionarySize = {} def getSizeOfFiles(files...
The trailing `L` means you have a [`long`](http://docs.python.org/library/stdtypes.html#typesnumeric). You actually always have it, but `print`ing a `dict` will show printable representations of the values, including the `L` notation; however, printing a `long` itself shows only the number. You almost certainly don't ...
os.path.getsize reports a filesize with an L at the end, why?
12,589,976
5
2012-09-25T19:43:24Z
12,590,797
8
2012-09-25T20:47:47Z
[ "python", "dictionary", "filesize", "directory" ]
``` import os, sys def crawlLocalDirectories(directoryToCrawl): crawledDirectory = [os.path.join(path, subname) for path, dirnames, filenames in os.walk(directoryToCrawl) for subname in dirnames + filenames] return crawledDirectory print crawlLocalDirectories('.') dictionarySize = {} def getSizeOfFiles(files...
This is only displayed or in interactive mode or when you get the string representation via `repr()`. As zigg wrote, you can simply ignore it. Consider this an implementation detail. It was probably usefull in time when it was important to make a difference between normal int and long int. In Python 3, there is no `L`,...
Python - performance with global variables vs local
12,590,058
11
2012-09-25T19:49:48Z
12,590,177
11
2012-09-25T19:58:00Z
[ "python", "performance" ]
I am still new to Python, and I have been trying to improve the performance of my Python script, so I tested it with and without global variables. I timed it, and to my surprise, it ran faster with global variables declared rather than passing local vars to functions. What's going on? I thought execution speed was fast...
The time that you are not including is the programmer time spent tracking down the bugs created when using a global has a side effect somewhere else in your program. That time is many times greater than the time spent creating and freeing local variables,
Python - performance with global variables vs local
12,590,058
11
2012-09-25T19:49:48Z
12,590,209
23
2012-09-25T20:00:51Z
[ "python", "performance" ]
I am still new to Python, and I have been trying to improve the performance of my Python script, so I tested it with and without global variables. I timed it, and to my surprise, it ran faster with global variables declared rather than passing local vars to functions. What's going on? I thought execution speed was fast...
## Locals should be faster According to [this page on locals and globals](http://www.diveintopython.net/html_processing/locals_and_globals.html): > When a line of code asks for the value of a variable x, Python will search for that variable in all the available namespaces, in order: > > * **local namespace** - specif...
mapping multiple lists to dictionary
12,590,358
3
2012-09-25T20:13:25Z
12,590,568
8
2012-09-25T20:30:39Z
[ "python", "list", "dictionary", "mapping" ]
I have 5 lists and I want to map them to a hierarchical dictionary. let's say i have: ``` temp = [25, 25, 25, 25] volt = [3.8,3.8,3.8,3.8] chan = [1,1,6,6] rate = [12,14,12,14] power = [13.2,15.3,13.8,15.1] ``` and what I want as my dictionary is this: ``` {25:{3.8:{1:{12:13.2,14:15.3},6:{12:13.8,14:15.1}}}} ``` B...
This is only slightly tested, but it seems to do the trick. Basically, what `f` does, is to create a `defaultdict` of `defaultdicts`. ``` f = lambda: collections.defaultdict(f) d = f() for i in range(len(temp)): d[temp[i]][volt[i]][chan[i]][rate[i]] = power[i] ``` Example: ``` >>> print d[25][3.8][6][14] 15.1 ``...
Links between IPython notebooks
12,590,611
26
2012-09-25T20:34:32Z
19,447,566
21
2013-10-18T10:36:46Z
[ "python", "ipython" ]
Is it possible to link one IPython notebook to another with a hyperlink in a Markdown cell? If I try ``` Link to [Notebook 2](files/notebook2.ipynb) ``` or ``` Link to <a href="files/notebook2.ipynb">Notebook 2</a> ``` A new tab is opened with raw unformatted contents of the ipynb file. Is there a way to get IPytho...
It is now possible to do this with Ipython 1.0+ at least. Just do: localhost:8888/My Notebook.ipynb Here is the documentation for this feature. <https://github.com/ipython/ipython/pull/3058>
Links between IPython notebooks
12,590,611
26
2012-09-25T20:34:32Z
23,934,226
37
2014-05-29T13:14:00Z
[ "python", "ipython" ]
Is it possible to link one IPython notebook to another with a hyperlink in a Markdown cell? If I try ``` Link to [Notebook 2](files/notebook2.ipynb) ``` or ``` Link to <a href="files/notebook2.ipynb">Notebook 2</a> ``` A new tab is opened with raw unformatted contents of the ipynb file. Is there a way to get IPytho...
At least with IPython 2 you may now use exactly the syntax you first tried: ``` Link to [Notebook 2](notebook2.ipynb) ```
List instances in auto scaling group with boto
12,590,646
6
2012-09-25T20:37:30Z
12,592,543
9
2012-09-25T23:26:59Z
[ "python", "amazon-web-services", "boto", "autoscaling" ]
I want to list all instances that are currently running within a auto scaling group. Can that be accomplished with boto? There must be some relation between the ASG and the instances as boto has the `shutdown_instances` method within the `boto.ec2.autoscale.group.AutoScalingGroup` class. Any pointers in the right dir...
Something like this should work: ``` >>> import boto >>> autoscale = boto.connect_autoscale() >>> ec2 = boto.connect_ec2() >>> group = autoscale.get_all_groups(['mygroupname'])[0] >>> instance_ids = [i.instance_id for i in group.instances] >>> reservations = ec2.get_all_instances(instance_ids) >>> instances = [i for r...
Flask broken pipe with requests
12,591,760
23
2012-09-25T22:04:36Z
12,591,943
56
2012-09-25T22:19:58Z
[ "python", "ubuntu", "python-2.7", "flask" ]
I'd like to send a local REST request in a flask app, like this: ``` from flask import Flask, url_for, request import requests app = Flask(__name__) @app.route("/<name>/hi", methods=["POST"]) def hi_person(name): form = {"name": name} return requests.post(url_for("hi", _external=True), data=form) @app.route...
Run your flask app under a proper WSGI server capable of handling concurrent requests (perhaps [gunicorn](http://gunicorn.org/) or [uWSGI](http://projects.unbit.it/uwsgi/)) and it'll work. While developing, enable threads in the Flask-supplied server with: ``` app.run(threaded=True) ``` but note that the Flask server...
Flask broken pipe with requests
12,591,760
23
2012-09-25T22:04:36Z
12,592,000
11
2012-09-25T22:25:17Z
[ "python", "ubuntu", "python-2.7", "flask" ]
I'd like to send a local REST request in a flask app, like this: ``` from flask import Flask, url_for, request import requests app = Flask(__name__) @app.route("/<name>/hi", methods=["POST"]) def hi_person(name): form = {"name": name} return requests.post(url_for("hi", _external=True), data=form) @app.route...
There are several things at play here, and I'll try to address them one-at-a-time. First, you're probably using the toy development server. This server has many limitations; chiefly among these limitations is that it can only handle one request at a time. When you create a second request during your first request, you...
TypeError: expected a character buffer object
12,592,544
6
2012-09-25T23:27:03Z
12,592,856
11
2012-09-26T00:10:28Z
[ "python", "csv", "python-2.x" ]
I am trying to write a list of a list to a new file, but I am getting this error: > Traceback (most recent call last): File "", line 1, in > dowork() File "C:\Python27\work\accounting\formatting quickbooks file\sdf.py", line 11, in dowork > WriteFile() File "C:\Python27\work\accounting\formatting quickbooks file\sdf.p...
What the error message is saying is that you can't write a list to a file, only "a character buffer object", meaning a string or something else that acts a lot like a string. If you just want to write the list to the file in the same way you'd print them to the console, you can write `str(thefile)` or `repr(thefile)` ...
Python Requests Multipart HTTP POST
12,592,553
5
2012-09-25T23:27:57Z
12,592,684
8
2012-09-25T23:45:49Z
[ "python", "urllib2", "multipartform-data", "python-requests" ]
I was wondering how do you translate something like this using Python Requests? In urllib2, you can manually manipulate the data that is being sent over the wire to the API service, but Requests claims multipart file uploads are easy. However, when trying to send over the same request using the Requests library, I beli...
with `requests`, I believe that you don't have to be so manual, simply: ``` import requests # ... url = self._resolve_url('/a/creative/uploadcreative') files = {'file': ('userfile', open(filepath, 'rb'))} data = {'account_id': account_id} headers = {'content-type': 'multipart/form-data'} res = requests.post(url, file...
How do I parse json-object using python?
12,593,411
2
2012-09-26T01:39:22Z
12,593,444
8
2012-09-26T01:44:53Z
[ "python", "json" ]
I am trying to parse a json object and having problems. ``` import json record= '{"shirt":{"red":{"quanitity":100},"blue":{"quantity":10}},"pants":{"black":{"quantity":50}}}' inventory = json.loads(record) #HELP NEEDED HERE for item in inventory: print item ``` I can figure out how to obtain the values. I can ge...
You no longer have a JSON object, you have a Python [**dictionary**](http://docs.python.org/tutorial/datastructures.html#dictionaries). Iterating over a dictionary produces its keys. ``` >>> for k in {'foo': 42, 'bar': None}: ... print k ... foo bar ``` If you want to access the values then either index the origin...
SqlAlchemy and Flask, how to query many-to-many relationship
12,593,421
19
2012-09-26T01:41:00Z
12,594,203
29
2012-09-26T03:37:48Z
[ "python", "sql", "sqlalchemy", "many-to-many", "flask" ]
I need help creating SqlAlchemy query. I'm doing a Flask project where I'm using SqlAlchemy. I have created 3 tables: Restaurant, Dish and restaurant\_dish in my models.py file. ``` restaurant_dish = db.Table('restaurant_dish', db.Column('dish_id', db.Integer, db.ForeignKey('dish.id')), db.Column('restaurant_...
The semantic of the relationship doesn't look right. I think it should be something like: ``` class Restaurant(db.Model): ... dishes = db.relationship('Dish', secondary=restaurant_dish, backref=db.backref('restaurants')) ``` Then, to retrieve all the dishes for a restaurant, you can do: ``` x = Dish...
where can i check tornado's log file?
12,593,460
9
2012-09-26T01:47:03Z
12,596,852
16
2012-09-26T07:41:28Z
[ "python", "tornado" ]
i think there was a default log file,but i didn't find them yet. sometimes the http request process would throw an exception on the screen, but i suggest it also go somewhere on the disk,or i wouldn't know what was wrong during a long run test. p.s. write an exception handler is another topic.first i'd like to know m...
It uses standard python logging module by default. Here is [definition](https://github.com/facebook/tornado/blob/master/tornado/log.py#L45): ``` access_log = logging.getLogger("tornado.access") app_log = logging.getLogger("tornado.application") gen_log = logging.getLogger("tornado.general") ``` It doesn't write to f...
Python regex uppercase unicode word
12,593,509
3
2012-09-26T01:54:19Z
12,593,595
8
2012-09-26T02:05:57Z
[ "python", "regex" ]
I need to find abbreviations text in many languages. Current [regex](http://pypi.python.org/pypi/regex) is: ``` import regex as re pattern = re.compile('(?:[\w]\.)+', re.UNICODE | re.MULTILINE | re.DOTALL | re.VERSION1) pattern.findall("U.S.A. u.s.a.") ``` I don't need **u.s.a** in the result, i need only uppercase t...
You need to use a Unicode character property in order to match them. `re` does not support character properties, but [`regex`](http://pypi.python.org/pypi/regex) does. ``` >>> regex.findall(ur'\p{Lu}', u'ÜìÑ') [u'\xdc', u'\xd1'] ```
Adapt an iterator to behave like a file-like object in Python
12,593,576
10
2012-09-26T02:04:12Z
12,593,795
10
2012-09-26T02:35:10Z
[ "python" ]
I have a generator producing a list of strings. Is there a utility/adapter in Python that could make it look like a file? For example, ``` >>> def str_fn(): ... for c in 'a', 'b', 'c': ... yield c * 3 ... >>> for s in str_fn(): ... print s ... aaa bbb ccc >>> stream = some_magic_adaptor(str_fn()) >>...
Here's a solution that should read from your iterator in chunks. ``` class some_magic_adaptor: def __init__( self, it ): self.it = it self.next_chunk = "" def growChunk( self ): self.next_chunk = self.next_chunk + self.it.next() def read( self, n ): if self.next_chunk == None: return None ...
How to start TLS on an active connection in python?
12,593,944
6
2012-09-26T02:55:03Z
12,594,010
10
2012-09-26T03:03:46Z
[ "python", "sockets", "smtp", "ssl" ]
The following is my current code for connecting to gmail's smtp server on port 587. After issuing the STARTTLS command how would I finish negotiating the TLS session and begin issuing commands such as AUTH LOGIN and MAIL FROM? I have ommitted my Base64 encoded gmail username and replaced it with xxxxxxxx near the botto...
You can ssl wrap a connected socket. This will give you the idea: ``` import ssl import base64 from socket import * cc = socket(AF_INET, SOCK_STREAM) cc.connect(("smtp.gmail.com", 587)) # cc.read(..) cc.send('helo tester.com\r\n') cc.send('starttls\r\n') # cc.read(..) If the server responds ok to starttls # ...
Skipping execution of -with- block
12,594,148
6
2012-09-26T03:28:32Z
12,594,323
8
2012-09-26T03:54:27Z
[ "python", "with-statement", "skip" ]
I am defining a context manager class and I would like to be able to skip the block of code without raising an exception if certain conditions are met during instantiation. For example, ``` class My_Context(object): def __init__(self,mode=0): """ if mode = 0, proceed as normal if mode = 1, ...
According to [PEP-343](http://www.python.org/dev/peps/pep-0343/), a `with` statement translates from: ``` with EXPR as VAR: BLOCK ``` to: ``` mgr = (EXPR) exit = type(mgr).__exit__ # Not calling it yet value = type(mgr).__enter__(mgr) exc = True try: try: VAR = value # Only if "as VAR" is present ...
Check if string matches pattern
12,595,051
69
2012-09-26T05:27:36Z
12,595,082
122
2012-09-26T05:30:57Z
[ "python", "regex", "string-matching" ]
How do I check if a string matches this pattern? Uppercase letter, number(s), uppercase letter, number(s)... Example, These would match: ``` A1B2 B10L1 C1N200J1 ``` These wouldn't ('^' points to problem) ``` a1B2 ^ A10B ^ AB400 ^ ```
``` import re pattern = re.compile("^([A-Z][0-9]+)+$") pattern.match(string) ```
Check if string matches pattern
12,595,051
69
2012-09-26T05:27:36Z
12,595,098
16
2012-09-26T05:31:58Z
[ "python", "regex", "string-matching" ]
How do I check if a string matches this pattern? Uppercase letter, number(s), uppercase letter, number(s)... Example, These would match: ``` A1B2 B10L1 C1N200J1 ``` These wouldn't ('^' points to problem) ``` a1B2 ^ A10B ^ AB400 ^ ```
``` import re import sys prog = re.compile('([A-Z]\d+)+') while True: line = sys.stdin.readline() if not line: break if prog.match(line): print 'matched' else: print 'not matched' ```
How do I make the x-coordinates letters?
12,595,174
4
2012-09-26T05:39:48Z
12,595,210
8
2012-09-26T05:42:50Z
[ "python", "matplotlib" ]
I have made a line graph in python with pyplot/matplotlib: ``` import matplotlib.pyplot as plt import math import numpy as np alphabet = range(0, 25) firstLine = [letter + 65 for letter in alphabet] secondLine = [letter + 97 for letter in alphabet] plt.plot(alphabet, firstLine, '-b', label='ASCII value of capital.')...
Use the `xticks` function. If you do `pyplot.xticks([0, 1, 2, 3], ['a', 'b', 'c', 'd'])` then it will have axis marks at 0, 1, 2, and 3, and they will be labeled a, b, c, and d. You can also use `np.arange` to quickly create the range of numbers you want.
Why can't I iterate over an object which delegates via __getattr__ to an iterable?
12,595,506
4
2012-09-26T06:07:58Z
12,596,052
10
2012-09-26T06:47:59Z
[ "python", "python-2.7" ]
An example from the book [Core Python Programming](http://cpp.wesc.webfactional.com/cpp1e/) on the topic `Delegation` doesn't seem to be working.. Or may be I didn't understand the topic clearly.. Below is the code, in which the class `CapOpen` wraps a `file` object and defines a modified behaviour of `file` when open...
This is a non-intuitive consequence of a Python [implementation decision for new-style classes](http://docs.python.org/reference/datamodel.html#new-style-special-lookup): > In addition to bypassing any instance attributes in the interest of > correctness, implicit special method lookup generally also bypasses > the `_...
arguments for / against `raise Exception(message)` in Python
12,596,557
2
2012-09-26T07:20:42Z
12,596,677
7
2012-09-26T07:27:37Z
[ "python", "coding-style" ]
I'm working with a framework and the source code is raising exceptions using the `Exception` class (and not a subclass, either framework specific or from the stdlib) in a few places, which is is not a good idea in my opinion. The main argument against this idiom is that it forces the caller to use `except Exception:` ...
From [PEP 8](http://www.python.org/dev/peps/pep-0008/#programming-recommendations): > Modules or packages should define their own domain-specific base exception class, which should be subclassed from the built-in Exception class.
Force python interpreter to reload a code module
12,597,164
18
2012-09-26T08:01:41Z
12,597,338
12
2012-09-26T08:12:35Z
[ "python", "openerp" ]
The OpenERP python code development cycle is to edit your code, restart the server and test it. Restarting the server is necessary, because it's what makes your source code to be reloaded into memory, but it adds an annoying delay in your work pace. Since python is such a dynamic language, I wonder if there is a way t...
The [`reload`](http://docs.python.org/library/functions.html#reload) built-in function will reload a single module. There are various solutions to recursively reload updated packages; see [How to re import an updated package while in Python Interpreter?](http://stackoverflow.com/questions/684171/how-to-re-import-an-upd...
Python replace string pattern with output of function
12,597,370
18
2012-09-26T08:14:50Z
12,597,709
28
2012-09-26T08:36:33Z
[ "python", "regex" ]
I have a string in Python, say `The quick @red fox jumps over the @lame brown dog.` I'm trying to replace each of the words that begin with `@` with the output of a function that takes the word as an argument. ``` def my_replace(match): return match + str(match.index('e')) #Psuedo-code string = "The quick @red ...
You can pass a function to [`re.sub`](http://docs.python.org/library/re.html#re.sub). The function will receive a match object as the argument, use `.group()` to extract the match as a string. ``` >>> def my_replace(match): ... match = match.group() ... return match + str(match.index('e')) ... >>> re.sub(r'@\w...
How can I hide a django label in a custom django form?
12,597,780
5
2012-09-26T08:41:15Z
12,599,168
12
2012-09-26T09:58:20Z
[ "python", "django", "forms", "widget" ]
I have a custom form that creates a hidden input of a field: ``` class MPForm( forms.ModelForm ): def __init__( self, *args, **kwargs ): super(MPForm, self).__init__( *args, **kwargs ) self.fields['mp_e'].label = "" #the trick :) class Meta: model = MeasurementPoint widgets = { 'mp_e': for...
I wouldn't recommend removing the label as it makes the form inaccessible. You could [add a custom CSS class](http://djangosnippets.org/snippets/2487/) to the field, and in your CSS [make that class invisible](http://xhtml.com/en/css/reference/visibility/). **EDIT** I missed that the input was hidden so accessibility...
Pandas hierarchical dataframe
12,597,926
5
2012-09-26T08:50:48Z
12,598,379
12
2012-09-26T09:16:28Z
[ "python", "dataframe", "pandas" ]
I have a dataframe: ``` Form nr Element Type Text Options 1 Name1 select text1 op1 1 Name1 select text op2 1 Name1 select text op3 1 Name2 input text2 NaN 2 Name1 input text2 NaN ``` Is there a way to greate a "nested" hierarchical index like this: ```...
Assuming there is a typo in the Text column, text <-> text1? I`ll go from your first DataFrame. ``` In [11]: df Out[11]: Form nr Element Type Test Options 0 1 Name1 select text1 op1 1 1 Name1 select text op2 2 1 Name1 select text op3 3 1 Name2 input t...
Z3/Python getting python values from model
12,598,408
9
2012-09-26T09:17:57Z
12,600,208
11
2012-09-26T10:59:33Z
[ "python", "z3", "z3py" ]
How can I get real python values from a Z3 model? E.g. ``` p = Bool('p') x = Real('x') s = Solver() s.add(Or(x < 5, x > 10), Or(p, x**2 == 2), Not(p)) s.check() print s.model()[x] print s.model()[p] ``` prints ``` -1.4142135623? False ``` but those are Z3 objects and not python float/bool objects. I know that I c...
For Boolean values, you can use the functions `is_true` and `is_false`. Numerical values can be integer, rational or algebraic. We can use the functions `is_int_value`, `is_rational_value` and `is_algebraic_value` to test each case. The integer case is the simplest, we can use the method `as_long()` to convert the Z3 i...
Descriptors as instance attributes in python
12,599,972
15
2012-09-26T10:45:42Z
12,645,197
12
2012-09-28T18:09:51Z
[ "python", "descriptor" ]
To the question: > Why can't descriptors be instance attributes? it has been [answered](http://stackoverflow.com/questions/2954331/dynamically-adding-property-in-python) that: > descriptor objects needs to live in the class, not in the instance because that is the way that the `__getattribute__` is implemented. A ...
This exact question was [raised on Python-list](https://mail.python.org/pipermail/python-list/2012-January/631338.html) earlier this year. I'm just going to quote [Ian G. Kelly's response](https://mail.python.org/pipermail/python-list/2012-January/631340.html): > The behavior is by design. First, keeping object behavi...
Descriptors as instance attributes in python
12,599,972
15
2012-09-26T10:45:42Z
12,645,321
8
2012-09-28T18:19:58Z
[ "python", "descriptor" ]
To the question: > Why can't descriptors be instance attributes? it has been [answered](http://stackoverflow.com/questions/2954331/dynamically-adding-property-in-python) that: > descriptor objects needs to live in the class, not in the instance because that is the way that the `__getattribute__` is implemented. A ...
Plenty of advanced functionality only works when defined on a class rather than an instance; all of the special methods, for example. As well as making code evaluation more efficient, this makes clear the separation between instances and types which otherwise would tend to collapse (because of course all types are obje...
How to make python Requests work via socks proxy
12,601,316
22
2012-09-26T12:02:26Z
15,661,226
38
2013-03-27T14:20:07Z
[ "python", "proxy", "socks", "python-requests" ]
I'm using the great [Requests](http://docs.python-requests.org/en/latest/index.html) library in my Python script: ``` import requests r = requests.get("some-site.com") print r.text ``` I would like to use socks proxy. But Requests only supports HTTP proxy now. How can I do that?
The modern way: ``` pip install -U requests[socks] ``` then ``` import requests resp = requests.get('http://go.to', proxies=dict(http='socks5://user:pass@host:port', https='socks5://user:pass@host:port')) ```
How to make python Requests work via socks proxy
12,601,316
22
2012-09-26T12:02:26Z
36,954,255
11
2016-04-30T11:24:19Z
[ "python", "proxy", "socks", "python-requests" ]
I'm using the great [Requests](http://docs.python-requests.org/en/latest/index.html) library in my Python script: ``` import requests r = requests.get("some-site.com") print r.text ``` I would like to use socks proxy. But Requests only supports HTTP proxy now. How can I do that?
As of `requests` version [2.10.0](https://github.com/kennethreitz/requests/blob/master/HISTORY.rst#2100-2016-04-29), released on 2016-04-29, `requests` supports SOCKS. It requires [PySocks](https://pypi.python.org/pypi/PySocks), which can be installed with `pip install pysocks`. Example usage: ``` import requests pr...
Pandas: how to change all the values of a column?
12,604,909
18
2012-09-26T15:12:25Z
12,605,055
36
2012-09-26T15:20:01Z
[ "python", "database", "pandas" ]
I have a data frame with a column called `"Date"` and want all the values from this column to have the same value (the year only). Example: ``` City Date Paris 01/04/2004 Lisbon 01/09/2004 Madrid 2004 Pekin 31/2004 ``` What I want is: ``` City Date Paris 2004 Lisbon 2004 Madrid 2004 Pekin ...
As @DSM points out, you can do this more directly using the [vectorised string methods](http://pandas.pydata.org/pandas-docs/stable/basics.html#vectorized-string-methods): ``` df['Date'].str[-4:].astype(int) ``` Or using extract (assuming there is only one set of digits of length 4 somewhere in each string): ``` df[...
How to use subprocess popen Python
12,605,498
34
2012-09-26T15:42:45Z
12,605,520
52
2012-09-26T15:44:05Z
[ "python", "subprocess", "popen" ]
Since os.popen is being replaced by subprocess.popen, I was wondering how would I convert ``` os.popen('swfdump /tmp/filename.swf/ -d') ``` to subprocess.popen() I tried: ``` subprocess.Popen("swfdump /tmp/filename.swf -d") subprocess.Popen("swfdump %s -d" % (filename)) # NOTE: filename is a variable ...
`subprocess.Popen` takes a list of arguments: ``` from subprocess import Popen, PIPE process = Popen(['swfdump', '/tmp/filename.swf', '-d'], stdout=PIPE, stderr=PIPE) stdout, stderr = process.communicate() ``` There's even a [section of the documentation](http://docs.python.org/library/subprocess.html#replacing-os-p...
Formating date in Web2py Python
12,605,934
4
2012-09-26T16:08:04Z
12,606,625
10
2012-09-26T16:50:54Z
[ "python", "database", "date", "web2py" ]
Im looking for a function to format a date in order to get day, month and year. Dates are being stored in my database in the following format 2012-09-26. Thanks!
If your goal is to display on web2py template, so you have to use pure Python to format ``` {{=row.datetime_field.strftime("%d/%m/%Y")}} ``` The above will generate `25/09/2012` Tale a look at Python strftime documentations. If you want to show only the day. ``` {{=row.datetime_field.date}} ``` Also you can set i...
python pip: no distributions at all found for an existing package
12,607,241
13
2012-09-26T17:32:08Z
13,662,333
11
2012-12-01T18:22:23Z
[ "python", "pip" ]
I am trying to install the `ScientificPython` package into a newly installed distribution of Python on a Fedora 14 x64 system. Pip finds `ScientificPython` in the repository but does not want to install it ``` [bin]$ sudo ./python2.7 ./pip search ScientificPython ScientificPython - Various Python modules for ...
Have a look at the [ScientificPython entry on pypi](http://pypi.python.org/pypi/ScientificPython) and you will find that it only contains a link to their project page, no downloadable package or egg (which pip would need to install from). That's why pip told you `Could not find any downloads`. You will have to install ...
Python UDP Broadcast not sending
12,607,516
10
2012-09-26T17:49:56Z
12,607,646
23
2012-09-26T17:57:52Z
[ "python", "udp", "broadcast", "labview" ]
I am trying to UDP broadcast from a Python program to two LabView programs. I cannot seem to get the broadcast to send and I am not sure where my socket initialization is wrong, broadcasting seems simple enough?? As far as I can see, there is no data being received by the other PC's. Also, I will need this program to r...
You need not `connect()` to a UDP socket, you need to: ``` cs.sendto(data, ('255.255.255.255', 5455)) ``` EDIT: This seems to work for me: ``` from socket import * cs = socket(AF_INET, SOCK_DGRAM) cs.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1) cs.setsockopt(SOL_SOCKET, SO_BROADCAST, 1) cs.sendto('This is a test', ('255....
Changing the "tick frequency" on x or y axis in matplotlib?
12,608,788
131
2012-09-26T19:12:53Z
12,608,937
162
2012-09-26T19:24:08Z
[ "python", "matplotlib" ]
I am trying to fix how python plots my data. Say ``` x = [0,5,9,10,15] ``` and ``` y = [0,1,2,3,4] ``` Then I would do: ``` matplotlib.pyplot.plot(x,y) matplotlib.pyplot.show() ``` and the x axis' ticks are plotted in intervals of 5. Is there a way to make it show intervals of 1?
You could explicitly set where you want to tick marks with `plt.xticks`: ``` plt.xticks(np.arange(min(x), max(x)+1, 1.0)) ``` --- For example, ``` import numpy as np import matplotlib.pyplot as plt x = [0,5,9,10,15] y = [0,1,2,3,4] plt.plot(x,y) plt.xticks(np.arange(min(x), max(x)+1, 1.0)) plt.show() ``` --- (`n...
Changing the "tick frequency" on x or y axis in matplotlib?
12,608,788
131
2012-09-26T19:12:53Z
19,972,993
50
2013-11-14T08:38:42Z
[ "python", "matplotlib" ]
I am trying to fix how python plots my data. Say ``` x = [0,5,9,10,15] ``` and ``` y = [0,1,2,3,4] ``` Then I would do: ``` matplotlib.pyplot.plot(x,y) matplotlib.pyplot.show() ``` and the x axis' ticks are plotted in intervals of 5. Is there a way to make it show intervals of 1?
Another approach is to set the axis locator: ``` import matplotlib.ticker as plticker loc = plticker.MultipleLocator(base=1.0) # this locator puts ticks at regular intervals ax.xaxis.set_major_locator(loc) ``` There are several different types of locator depending upon your needs.
Changing the "tick frequency" on x or y axis in matplotlib?
12,608,788
131
2012-09-26T19:12:53Z
27,533,166
10
2014-12-17T19:18:45Z
[ "python", "matplotlib" ]
I am trying to fix how python plots my data. Say ``` x = [0,5,9,10,15] ``` and ``` y = [0,1,2,3,4] ``` Then I would do: ``` matplotlib.pyplot.plot(x,y) matplotlib.pyplot.show() ``` and the x axis' ticks are plotted in intervals of 5. Is there a way to make it show intervals of 1?
This is an old topic, but I stumble over this every now and then and made this function. It's very convenient: ``` import matplotlib.pyplot as pp import numpy as np def resadjust(ax, xres=None, yres=None): """ Send in an axis and I fix the resolution as desired. """ if xres: start, stop = ax....
Changing the "tick frequency" on x or y axis in matplotlib?
12,608,788
131
2012-09-26T19:12:53Z
31,997,618
12
2015-08-13T20:15:58Z
[ "python", "matplotlib" ]
I am trying to fix how python plots my data. Say ``` x = [0,5,9,10,15] ``` and ``` y = [0,1,2,3,4] ``` Then I would do: ``` matplotlib.pyplot.plot(x,y) matplotlib.pyplot.show() ``` and the x axis' ticks are plotted in intervals of 5. Is there a way to make it show intervals of 1?
This is a bit hacky, but by far the cleanest/easiest to understand example that I've found to do this. It's from an answer on SO here: [Cleanest way to hide every nth tick label in matplotlib colorbar?](http://stackoverflow.com/questions/20337664/cleanest-way-to-hide-every-nth-tick-label-in-matplotlib-colorbar) ``` f...
Changing the "tick frequency" on x or y axis in matplotlib?
12,608,788
131
2012-09-26T19:12:53Z
36,229,671
11
2016-03-25T23:24:37Z
[ "python", "matplotlib" ]
I am trying to fix how python plots my data. Say ``` x = [0,5,9,10,15] ``` and ``` y = [0,1,2,3,4] ``` Then I would do: ``` matplotlib.pyplot.plot(x,y) matplotlib.pyplot.show() ``` and the x axis' ticks are plotted in intervals of 5. Is there a way to make it show intervals of 1?
I like this solution (from the [Matplotlib Plotting Cookbook](https://www.safaribooksonline.com/library/view/matplotlib-plotting-cookbook/9781849513265/ch03s11.html)): ``` import matplotlib.pyplot as plt import matplotlib.ticker as ticker x = [0,5,9,10,15] y = [0,1,2,3,4] tick_spacing = 1 fig, ax = plt.subplots(1,1...
Changing the "tick frequency" on x or y axis in matplotlib?
12,608,788
131
2012-09-26T19:12:53Z
36,646,298
8
2016-04-15T11:46:09Z
[ "python", "matplotlib" ]
I am trying to fix how python plots my data. Say ``` x = [0,5,9,10,15] ``` and ``` y = [0,1,2,3,4] ``` Then I would do: ``` matplotlib.pyplot.plot(x,y) matplotlib.pyplot.show() ``` and the x axis' ticks are plotted in intervals of 5. Is there a way to make it show intervals of 1?
In case anyone is interested in a general one-liner, simply get the current ticks and use it to set the new ticks by sampling every other tick. ``` ax.set_xticks(ax.get_xticks()[::2]) ```
Why does os.path.join throw away arguments?
12,609,075
11
2012-09-26T19:33:46Z
12,609,156
14
2012-09-26T19:38:44Z
[ "python", "language-design" ]
I'm learning Python and I noticed something strange with one of my scripts. Doing a little testing I discovered the problem stemmed from this behavior: ``` >>> import os >>> os.path.join('a','b') 'a/b' >>> os.path.join('a','/b') '/b' ``` Checking the [documentation](http://docs.python.org/library/os.path.html#module-...
One case where it is useful for `os.path.join('a', '/b')` to return `/b` would be if you ask a user for a filename. The user can enter either a path relative to the current directory, or a full path, and your program could handle both cases like this: ``` os.path.join(os.getcwd(), filename) ``` --- ``` In [54]: os....
printing every 2 elements in a tuple
12,609,983
3
2012-09-26T20:37:16Z
12,610,048
8
2012-09-26T20:40:40Z
[ "python", "iteration", "tuples" ]
I have looked at several questions [Iterating over every two elements in a list](http://stackoverflow.com/questions/5389507/iterating-over-every-two-elements-in-a-list) and [Python "Every Other Element" Idiom](http://stackoverflow.com/questions/2631189/python-every-other-element-idiom?lq=1), they have yielded an answer...
To print every other element: ``` for elem in Gun_rack[::2]: print elem ``` and every other element, starting with the second one: ``` for elem in Gun_rack[1::2]: print elem ``` Of course, to do every fourth element, just change the 2 to a 4. The reason this works is because `slice` objects (which are created...
count the number of a certain triplet in a file (DNA codon analysis)
12,610,184
2
2012-09-26T20:50:30Z
12,610,245
7
2012-09-26T20:55:31Z
[ "python", "shell", "bioinformatics" ]
This question is actually for DNA codon analysis, to put it in a simple way, let's say I have a file like this: atgaaaccaaag... and I want to count the number of 'aaa' triplet present in this file. Importantly, the triplets start from the very beginning (which means atg,aaa,cca,aag,...) So the result should be 1 in...
first readin the file ``` with open("some.txt") as f: file_data = f.read() ``` then split it into 3's ``` codons = [file_data[i:i+3] for i in range(0,len(file_data),3)] ``` then count em ``` print codons.count('aaa') ``` like so ``` >>> my_codons = 'atgaaaccaaag' >>> codons = [my_codons[i:i+3] for i in range...
What does placing \ at the end of a line do in python?
12,612,065
7
2012-09-26T23:41:27Z
12,612,073
17
2012-09-26T23:42:27Z
[ "python" ]
I'm looking at the following piece of code: ``` totalDistance += \ GetDistance(xCoords[i], yCoords[i], xCoords[i+1], yCoords[i+1]) ``` and can't understand what `+= \` means?
`\` at the end of a line just indicates it will be continued on the next line as otherwise that (`totalDist +=`) would raise an error... (also important to note that there can be nothing after the slash ... not even whitespace) `+=` just adds and assigns back ``` x = 1 x += 1 # x is now 2 (same as x = x + 1) ```
What does placing \ at the end of a line do in python?
12,612,065
7
2012-09-26T23:41:27Z
12,612,168
7
2012-09-26T23:56:28Z
[ "python" ]
I'm looking at the following piece of code: ``` totalDistance += \ GetDistance(xCoords[i], yCoords[i], xCoords[i+1], yCoords[i+1]) ``` and can't understand what `+= \` means?
The `\` escapes the line return immediately following it (there should not be any character between the `\` and the implicit `\n`). There are also a few other exceptions; new lines are ignored when enclosed in the matching pairs of the following: * `[]` * `()` * `{}` In other words, the following are equivalent: ``...
Python - Element Tree is removing the XML declaration
12,612,648
6
2012-09-27T01:06:23Z
12,612,740
16
2012-09-27T01:18:14Z
[ "python", "xml", "elementtree" ]
I'm writing some XML with element tree. I'm giving the code an empty template file that starts with the XML declaration:`<?xml version= "1.0"?>` when ET has finished making its changes and writes the completed XML its stripping out the declarion and starting with the root tag. How can I stop this? Write call: `ET.El...
According to [the documentation](http://docs.python.org/library/xml.etree.elementtree.html#xml.etree.ElementTree.ElementTree.write): > write(file, encoding="us-ascii", xml\_declaration=None, method="xml") > > Writes the element tree to a file, as XML. file is a file name, or a file object opened for writing. encoding ...
Python Script Uploading files via FTP
12,613,797
15
2012-09-27T03:48:42Z
12,613,970
64
2012-09-27T04:11:43Z
[ "python", "image", "upload", "ftp", "screenshot" ]
I would like to make a script to upload a file to FTP. How would the login system work? I'm looking for something like this: ``` ftp.login=(mylogin) ftp.pass=(mypass) ``` And any other sign in credentials.
Use [`ftplib`](http://docs.python.org/library/ftplib.html), you can write it like this: ``` import ftplib session = ftplib.FTP('server.address.com','USERNAME','PASSWORD') file = open('kitten.jpg','rb') # file to send session.storbinary('STOR kitten.jpg', file) # send the file file.close() ...
Identifying "sensitive" code in your application
12,614,131
20
2012-09-27T04:32:04Z
12,663,047
10
2012-09-30T16:45:34Z
[ "python", "code-analysis" ]
Looking to improve quality of a fairly large Python project. I am happy with the types of warnings PyLint gives me. However, they are just too numerous and hard to enforce across a large organization. Also I believe that some code is more critical/sensitive than others with respect to where the next bug may come. For e...
I'm afraid you are mostly on your own. If you have decent set of tests, look at code coverage and dead code. If you have a decent profiling setup, use that to get a glimpse of what's used more. In the end, it seems you are more interested in fan-in/fan-out analysis, I'm not aware of any good tools for Python, primar...
Identifying "sensitive" code in your application
12,614,131
20
2012-09-27T04:32:04Z
13,008,605
15
2012-10-22T09:39:33Z
[ "python", "code-analysis" ]
Looking to improve quality of a fairly large Python project. I am happy with the types of warnings PyLint gives me. However, they are just too numerous and hard to enforce across a large organization. Also I believe that some code is more critical/sensitive than others with respect to where the next bug may come. For e...
You problem is similar to the one I answered over at SQA <http://sqa.stackexchange.com/a/3082>. This problem was associated with Java which made the tooling a bit easier, but I have a number of suggestions below. A number of other answers suggest that there is no good runtime tools for Python. I disagree on this in se...
Custom sorting on a namedtuple class
12,614,213
6
2012-09-27T04:42:33Z
12,614,638
10
2012-09-27T05:27:27Z
[ "python", "sorting", "namedtuple", "functools" ]
I use [namedtuple](http://docs.python.org/library/collections.html#collections.namedtuple) classes a lot. I have been thinking today if there is a nice way to implement custom sorting for such a class, i.e. make the default sort key not the first element (then second, third, etc) of the namedtuple. My first instinct w...
OPTION 1. Use a [mixin](http://stackoverflow.com/questions/533631/what-is-a-mixin-and-why-are-they-useful) and apply the total\_ordering to that ``` @total_ordering class B_ordering(object): __slots__ = () # see Raymond's comment def __lt__(self, other): return self.y < other.y class B...
TypeError: 'bool' object is not callable
12,614,334
9
2012-09-27T04:56:39Z
12,614,376
22
2012-09-27T05:01:04Z
[ "python" ]
I am brand new to python. I got a error ``` while not cls.isFilled(row,col,myMap): TypeError: 'bool' object is not callable ``` Would you please instruct how to solve this issue? The first "if" check is fine, but "while not" has this error. ``` def main(cls, args): ... if cls.isFilled(row,col,myMap):...
You do `cls.isFilled = True`. That overwrites the method called `isFilled` and replaces it with the value True. That method is now gone and you can't call it anymore. So when you try to call it again you get an error, since it's not there anymore. The solution is use a different name for the variable than you do for t...
Getting exactly one element or raising exception with lxml xpath
12,615,366
4
2012-09-27T06:28:10Z
12,615,497
14
2012-09-27T06:37:49Z
[ "python", "xpath", "lxml" ]
The xpath() function in lxml normally returns a list of elements. If I have an XPath which I expect to return exactly one element, what's the nicest way to: * Check that one element is returned or else raise an exception, and: * Get that element (as opposed to a one-element list)? I'm really looking for the analogue...
``` try: (element,) = tree.xpath('//xpath/selector') except ValueError: raise InvalidSelector() # happened because the list was either empty or contained multiple elements ```
What are the different use cases of joblib versus pickle?
12,615,525
9
2012-09-27T06:39:45Z
12,617,603
11
2012-09-27T08:56:34Z
[ "python", "pickle", "scikit-learn" ]
Background: I'm just getting started with scikit-learn, and read at the bottom of the page about [joblib, versus pickle](http://scikit-learn.org/stable/tutorial/basic/tutorial.html). > it may be more interesting to use joblib’s replacement of pickle (joblib.dump & joblib.load), which is more efficient on big data, b...
joblib is usually significantly faster on large numpy arrays because it has a special handling for the array buffers of the numpy datastructure. To find about the implementation details you can have a look at the [source code](https://github.com/joblib/joblib/blob/master/joblib/numpy_pickle.py). It can also compress th...
Numpy slicing from variable
12,616,821
4
2012-09-27T08:11:11Z
12,616,901
10
2012-09-27T08:16:51Z
[ "python", "numpy", "slice" ]
I'm trying to slice a numpy array using a slice that is predefined in a variable. This works: ``` b = fromfunction(lambda x,y: 10*x+y, (5,4),dtype=int) # Just some matrix b[1:3,1:3] # Output: # array([[11, 12], # [21, 22]]) ``` But what I want to do is somthing like this: ``` slice = "1:3,1:3" b[slice] # Outp...
You can use the built-in `slice` function ``` s = slice(1,3) b[s,s] ds = (s,s) b[ds] ```
how to replace back slash character with empty string in python
12,618,030
4
2012-09-27T09:18:36Z
12,618,060
8
2012-09-27T09:20:13Z
[ "python", "replace" ]
I am trying replace a backslash '\' in a string with the following code ``` string = "<P style='TEXT-INDENT'>\B7 </P>" result = string.replace("\",'') ``` result: ``` ------------------------------------------------------------ File "<ipython console>", line 1 result = string.replace("\",'') ...
``` result = string.replace("\\","") ```
Problems running beautifulsoup4 within Apache/mod_python/Django
12,618,567
4
2012-09-27T09:48:12Z
12,705,170
14
2012-10-03T09:05:41Z
[ "python", "django", "apache", "beautifulsoup", "mod-python" ]
I'm was trying to render an HTML-page on the fly using BeautifulSoup version 4 in Django (using Apache2 with mod\_python). However, as soon as I pass any HTML-string to the BeautifulSoup constructor (see code below), the browser just hangs waiting for the webserver. I tried equivalent code in CLI and it works like a ch...
I'm using Apache2 with mod\_python. I solved the hang problem by explicitly passing the 'html.parser' to get a soup. ``` s = bs4.BeautifulSoup('<b>asdf</b>', 'html.parser') ```
Create a Python list filled with the same string over and over and a number that increases based on a variable.
12,620,974
5
2012-09-27T12:05:42Z
12,621,009
8
2012-09-27T12:07:40Z
[ "python", "python-2.7" ]
I'm trying to create a list that is populated by a reoccurring string and a number that marks which one in a row it is. The number that marks how many strings there will be is gotten from an int variable. So something like this: ``` b = 5 a = range(2, b + 1) c = [] c.append('Adi_' + str(a)) ``` I was hoping this wou...
You almost got it: ``` for i in a: c.append('Adi_' + str(i)) ``` Your initial line was transforming the *whole* list `a` as a string. Note that you could get rid of the loop with a list comprehension and some [string formatting](http://docs.python.org/library/string.html#formatstrings): ``` c = ['Adi_%s' % s fo...
two lists into one multidimensional list
12,624,623
2
2012-09-27T15:13:32Z
12,624,645
9
2012-09-27T15:14:23Z
[ "python", "list" ]
I would like to merge two lists into one 2d list. ``` list1=["Peter", "Mark", "John"] list2=[1,2,3] ``` into ``` list3=[["Peter",1],["Mark",2],["John",3]] ```
``` list3 = [list(a) for a in zip(list1, list2)] ```
Python requests - saving cookie for later url usage
12,624,980
4
2012-09-27T15:33:21Z
12,625,032
11
2012-09-27T15:36:40Z
[ "python", "python-2.7", "python-requests" ]
I been trying to get a cookie and post it to a url in later use in the program, but I cant seem to get the cookie parameters to work. Right now I have ``` response = requests.get("url") ``` But how exactly do I retrive cookies from this url and post them to a new url (the same cookies). The tutorial in requests is s...
You want to use a [session](http://docs.python-requests.org/en/latest/user/advanced/#session-objects): ``` s = requests.session() response = s.get('url') ``` You use the session just like the `requests` module (it has the same methods), but it'll retain cookies for you and send them along on future requests.
pytz and astimezone() cannot be applied to a naive datetime
12,626,045
23
2012-09-27T16:34:02Z
12,626,106
22
2012-09-27T16:37:38Z
[ "python", "datetime", "pytz" ]
I have a date and I need to make it time zone aware. ``` local_tz = timezone('Asia/Tokyo') start_date = '2012-09-27' start_date = datetime.strptime(start_date, "%Y-%m-%d") start_date = start_date.astimezone(local_tz) now_utc = datetime.now(timezone('UTC')) local_now = now_utc.astimezone(local_tz) ``` I need to f...
For `pytz` timezones, use their `.localize()` method to turn a naive `datetime` object into one with a timezone: ``` start_date = local_tz.localize(start_date) ``` For timezones without a DST transition, the [`.replace()` method](http://docs.python.org/library/datetime.html#datetime.datetime.replace) to attach a time...
pytz and astimezone() cannot be applied to a naive datetime
12,626,045
23
2012-09-27T16:34:02Z
12,713,155
10
2012-10-03T16:51:54Z
[ "python", "datetime", "pytz" ]
I have a date and I need to make it time zone aware. ``` local_tz = timezone('Asia/Tokyo') start_date = '2012-09-27' start_date = datetime.strptime(start_date, "%Y-%m-%d") start_date = start_date.astimezone(local_tz) now_utc = datetime.now(timezone('UTC')) local_now = now_utc.astimezone(local_tz) ``` I need to f...
You could use `local_tz.localize(naive_dt, is_dst=None)` to convert a naive datetime object to timezone-aware one. ``` from datetime import datetime import pytz local_tz = pytz.timezone('Asia/Tokyo') start_date = local_tz.localize(datetime(2012, 9, 27), is_dst=None) now_utc = datetime.utcnow().replace(tzinfo=pytz.ut...
Virtualenv shell errors
12,626,370
16
2012-09-27T16:52:34Z
12,626,756
17
2012-09-27T17:16:15Z
[ "python", "virtualenv", "pip" ]
I've just installed virtualenv (with Python 2.7.2) on my Mac, and I followed the guide here: <http://virtualenvwrapper.readthedocs.org/en/latest/install.html> But I now get the following errors when I start up my shell every time: ``` stevedore.extension Could not load 'user_scripts': distribute stevedore.extension d...
Based on the error you are getting, it looks like you are having the following error: [install glitch when using pip + virtualenv](https://bitbucket.org/tarek/distribute/issue/91/install-glitch-when-using-pip-virtualenv). The issue is created when using the -distribute switch. The fix is (without re-running virtualenv...
Virtualenv shell errors
12,626,370
16
2012-09-27T16:52:34Z
13,702,964
19
2012-12-04T12:31:08Z
[ "python", "virtualenv", "pip" ]
I've just installed virtualenv (with Python 2.7.2) on my Mac, and I followed the guide here: <http://virtualenvwrapper.readthedocs.org/en/latest/install.html> But I now get the following errors when I start up my shell every time: ``` stevedore.extension Could not load 'user_scripts': distribute stevedore.extension d...
I also use zsh and had a similar problem. I solved with this: ``` sudo pip install virtualenv virtualenvwrapper ``` I have the package `python-pip` installed in my Ubuntu 12.04.
Virtualenv shell errors
12,626,370
16
2012-09-27T16:52:34Z
21,353,601
7
2014-01-25T17:17:34Z
[ "python", "virtualenv", "pip" ]
I've just installed virtualenv (with Python 2.7.2) on my Mac, and I followed the guide here: <http://virtualenvwrapper.readthedocs.org/en/latest/install.html> But I now get the following errors when I start up my shell every time: ``` stevedore.extension Could not load 'user_scripts': distribute stevedore.extension d...
Had the same error message, upgrading the setuptools resolved the issue for me. ``` pip install --upgrade setuptools ``` I've found the information in this thread: <http://blog.gmane.org/gmane.comp.python.virtualenv/month=20131001>
Python Image Library convert from Jpeg to PDF
12,626,654
3
2012-09-27T17:09:40Z
12,627,790
9
2012-09-27T18:23:57Z
[ "python", "pdf", "image-processing", "python-imaging-library", "resolution" ]
I'm attempting to convert a Jpeg file with, 200 dpi, to a PDF file, however, when I save the file as a PDF I think it's changing the dpi to 72, and thus making the image larger. I had a similar problem when initially trying to scale my jpeg image to a smaller size, and was able to solve that by specifying the dpi when ...
In the CHANGES file of `PIL 1.1.7` sources one can read: > * Added resolution save option for PDF files. > > Andreas Kostyrka writes: I've included a patched PdfImagePlugin.py > based on 1.1.6 as included in Ubuntu, that supports a "resolution" > save option. Not great, but it makes the PDF saving more usefu...
Get a function argument's default value?
12,627,118
18
2012-09-27T17:40:07Z
12,627,202
40
2012-09-27T17:46:14Z
[ "python" ]
For this function ``` def eat_dog(name, should_digest=True): print "ate dog named %s. Digested, too? %" % (name, str(should_digest)) ``` I want to, external to the function, read its arguments and any default values attached. So for this specific example, I want to know that `name` has no default value (i.e. that...
The args/defaults can be combined as: ``` import inspect a = inspect.getargspec(eat_dog) zip(a.args[-len(a.defaults):],a.defaults) ``` Here `a.args[-len(a.defaults):]` are the arguments with defaults values and obviously `a.defaults` are the corresponding default values. You could even pass the output of `zip` to th...
Why does one file object flush, but the other one doesn't?
12,627,297
4
2012-09-27T17:52:10Z
12,628,024
9
2012-09-27T18:40:34Z
[ "python", "file", "flush" ]
I wanted a file object that flushes out straight to file as data is being written, and wrote this: ``` class FlushingFileObject(file): def write(self,*args,**kwargs): return_val= file.write(self,*args,**kwargs) self.flush() return return_val def writelines(self,*args,**kwargs): ...
Great question. This happens because Python optimizes calls to `write` on `file` objects by bypassing the Python-level `write` method and calling `fputs` directly. To see this in action, consider: ``` $ cat file_subclass.py import sys class FileSubclass(file): def write(self, *a, **kw): raise Exception("...
Python, override__getstate__() __setstate__()
12,627,949
13
2012-09-27T18:35:17Z
12,628,702
15
2012-09-27T19:27:24Z
[ "python" ]
I have this classes: ``` class Family(object): __slot__ = ['father', 'var1'] def __init__(self, father, var1 = 1): self.father, self.var1 = father var1 class Father(object): __slots__ = ['var2'] def __init__(self, var2 = ''): self.var2 = var2 father = Father() family = Family(father =...
[`__getstate__`](http://docs.python.org/library/pickle.html#object.__getstate__) should return a picklable object (such as a tuple) with enough information to reconstruct the instance. [`__setstate__`](http://docs.python.org/library/pickle.html#object.__setstate__) should expect to receive the same object, and use it ...
Trouble installing SciPy on windows
12,628,164
16
2012-09-27T18:49:03Z
12,629,074
12
2012-09-27T19:55:00Z
[ "python", "windows", "install", "scipy" ]
I have Python 2.7 and NumPy installed. I have downloaded pre-built binaries for SciPy, but the install script fails with this error: Blas `(http://www.netlib.org/blas/)` libraries not found. Directories to search for the libraries can be specified in the `numpy/distutils/site.cfg` file (section `[blas]`) or by setting...
To install SciPy on Windows you have to have a fortran compiler installed. The SciPy project recommends MinGW. See [Building and installing SciPy](http://projects.scipy.org/scipy/wiki/GetCode#windows). To install MinGW follow these instructions: [HOWTO Install the MinGW (GCC) Compiler Suite](http://www.mingw.org/wiki/I...
How to send oauth request with python-oauth2
12,628,246
6
2012-09-27T18:54:29Z
12,642,195
10
2012-09-28T14:42:26Z
[ "python", "oauth" ]
I have been pounding my head against the wall over figuring out how to send authenticated requests with oauth. I was able to get access tokens, but wasn't entirely sure how to submit a request with them. I found this on twitter's developer's information: <https://dev.twitter.com/docs/auth/oauth/single-user-with-examp...
Twitter's documentation is out of date -- the version of `oauth2` they link to is a 3-year-old fork. There is no keyword argument `force_auth_header` anymore for `oauth2.Client.request` The reason why you still get errors even after removing the offending line is because your default value for `post_body` is `None` wh...
Remove small words using Python
12,628,958
14
2012-09-27T19:46:30Z
12,628,978
38
2012-09-27T19:47:28Z
[ "python", "regex" ]
Is it possible use regex to remove small words in a text? For example, I have the following string (text): ``` anytext = " in the echo chamber from Ontario duo " ``` I would like remove all words that is 3 characters or less. The Result should be: ``` "echo chamber from Ontario" ``` Is it possible do that using reg...
I don't think you need a regex for this simple example anyway ... ``` ' '.join(word for word in anytext.split() if len(word)>3) ```
Remove small words using Python
12,628,958
14
2012-09-27T19:46:30Z
12,629,012
23
2012-09-27T19:49:50Z
[ "python", "regex" ]
Is it possible use regex to remove small words in a text? For example, I have the following string (text): ``` anytext = " in the echo chamber from Ontario duo " ``` I would like remove all words that is 3 characters or less. The Result should be: ``` "echo chamber from Ontario" ``` Is it possible do that using reg...
Certainly, it's not that hard either: ``` shortword = re.compile(r'\W*\b\w{1,3}\b') ``` The above expression selects any word that is preceded by some non-word characters (essentially whitespace or the start), is between 1 and 3 characters short, and ends on a word boundary. ``` >>> shortword.sub('', anytext) ' echo...
Returning API Error Messages with Python and Flask
12,630,224
18
2012-09-27T21:23:07Z
12,630,466
16
2012-09-27T21:43:55Z
[ "python", "api", "error-handling", "flask" ]
I am designing a RESTful API using Python and Flask. As expected, the API needs to receive an API request and return data if all goes well, but in the instance of an error, it needs to fail softly and return the proper error. I typically raise exceptions when an error results, but in this case I need to return the erro...
You could use [`abort(http_code)`](http://flask.pocoo.org/docs/api/#flask.abort) to return an appropriate http code to the client or just raise a non-http exception. And use `@app.errorhandler()` decorator to provide a custom handler for http errors and arbitrary exceptions. You could also use an ordinary try/except bl...
How to sort dict by value, when keys are fractions represented by strings?
12,630,988
2
2012-09-27T22:30:39Z
12,631,035
12
2012-09-27T22:34:28Z
[ "python", "dictionary" ]
I need to sort a dict, where keys are fractions represented by strings and need to be sorted by its numerical values: i.e.: ``` exp_time = {"2":10, "1/2":5:, "2.5":11, "1/200":9, "15":3, "1/30":6} ``` result should be like this(descending order): ``` 15 2.5 2 1/2 1/30 1/200 ```
``` >>> import fractions >>> exp_time = {"2":10, "1/2":5, "2.5":11, "1/200":9, "15":3, "1/30":6} >>> sorted(exp_time, key=fractions.Fraction, reverse=True) ['15', '2.5', '2', '1/2', '1/30', '1/200'] ```
python Socket server with real ip adress
12,631,791
2
2012-09-27T23:58:26Z
12,631,967
8
2012-09-28T00:23:24Z
[ "python", "sockets", "ip" ]
So I am playing with my python server, but I'm through with using localhost and I want to go over the internet. My code thus-far is: ``` import socket import threading import socketserver class ThreadedTCPRequestHandler(socketserver.BaseRequestHandler): def handle(self): data = self.request.recv(1024) ...
> ip = '12.34.56.789' #Not my real ip address, its the one i got from whatismyip.org The first problem is that '12.34.56.789' isn't a valid IP address at all. Each component has to fit in 8 bits (0-255); 789 is impossible. But I assume that isn't the actual code you're running, because the output shows 12.45.29.122. ...
GridSearch for an estimator inside a OneVsRestClassifier
12,632,992
13
2012-09-28T02:55:04Z
12,637,528
16
2012-09-28T09:44:20Z
[ "python", "machine-learning", "scikit-learn" ]
I want to perform GridSearchCV in a SVC model, but that uses the one-vs-all strategy. For the latter part, I can just do this: ``` model_to_set = OneVsRestClassifier(SVC(kernel="poly")) ``` My problem is with the parameters. Let's say I want to try the following values: ``` parameters = {"C":[1,2,4,8], "kernel":["po...
When you use nested estimators with grid search you can scope the parameters with `__` as a separator. In this case the SVC model is stored as an attribute named `estimator` inside the `OneVsRestClassifier` model: ``` from sklearn.datasets import load_iris from sklearn.multiclass import OneVsRestClassifier from sklear...
Python concatenate string & list
12,633,024
7
2012-09-28T02:59:41Z
12,633,040
11
2012-09-28T03:01:56Z
[ "python" ]
I have a list and string: ``` fruits = ['banana', 'apple', 'plum'] mystr = 'i like the following fruits: ' ``` How can I concatenate them so I get (keeping in mind that the enum may change size) 'i like the following fruits: banana, apple, plum'
Join the list, then add the strings. ``` print mystr + ', '.join(fruits) ``` And don't use the name of a built-in type (`str`) as a variable name.
Nesting string format
12,633,179
8
2012-09-28T03:23:22Z
12,633,191
8
2012-09-28T03:25:52Z
[ "python", "python-3.x", "string-formatting" ]
I'm writing some reports, and I'd like to know if there's a simpler way to obtain the following behavior. ``` >>> '{:-^60}'.format('Percentage used: {:.2%}'.format(.4)) '------------------Percentage used: 40.00%-------------------' ``` As you can see I'm centering the text and then printing a number formated to perce...
A more readable option might be `str.center` ``` >>> 'Percentage used: {:.2%}'.format(.4).center(60, '-') '------------------Percentage used: 40.00%-------------------' ```
Method return value to call another form in OpenERP
12,634,031
3
2012-09-28T05:23:24Z
12,634,259
7
2012-09-28T05:47:47Z
[ "python", "openerp" ]
Currently, you can set to return value of an OpenERP to the following, to get the current form to be closed: ``` return {'type':'ir.actions.act_window_close' } ``` Is there a return value that would open another form instead? For example, in the Product form, buttons can call a sales form or a wizard form.
Following is an example function.Maybe helpful for you ``` def open_popup(self, cr, uid, ids, context=None): mod_obj = self.pool.get('ir.model.data') if move.parent_production_id: res = mod_obj.get_object_reference(cr, uid, 'module_name', 'id_specified_for_the_view') return { 'name'...
Is it possible to get full URL(include domain) within Django template
12,636,329
5
2012-09-28T08:26:53Z
12,636,369
11
2012-09-28T08:29:58Z
[ "python", "django", "django-templates" ]
I found the tag `{% url path.to.view %}` can only return the path of URL, how can I get the full URL with domain name? Actually, what I want to do is, adding a link which point to **another** view of my site. But `{% url path.to.view %}` can only get the path of my view. In result, the link cannot point to what I want...
That's in the docs [here](https://docs.djangoproject.com/en/dev/ref/request-response/): Use the method `build_absolute_uri()` on the request object.
Python, convert 4-byte char to avoid MySQL error "Incorrect string value:"
12,636,489
6
2012-09-28T08:38:02Z
12,636,588
12
2012-09-28T08:44:18Z
[ "python", "mysql", "utf-8", "character-encoding", "python-unicode" ]
I need to convert (in Python) a 4-byte char into some other character. This is to insert it into my utf-8 mysql database without getting an error such as: "Incorrect string value: '\xF0\x9F\x94\x8E' for column 'line' at row 1" [Warning raised by inserting 4-byte unicode to mysql](http://stackoverflow.com/questions/107...
In a UCS-2 build, python uses 2 code units internally for each unicode character over the `\U0000ffff` code point. Regular expressions need to work with those, so you'd need to use the following regular expression to match these: ``` highpoints = re.compile(u'[\uD800-\uDBFF][\uDC00-\uDFFF]') ``` This regular expressi...
How to delete some characters from a string by matching certain character in python
12,636,788
2
2012-09-28T08:59:35Z
12,636,809
7
2012-09-28T09:00:32Z
[ "python" ]
i am trying to delete certain portion of a string if a match found in the string as below ``` string = 'Newyork, NY' ``` I want to delete all the characters after the comma from the string including `comma`, if comma is present in the string Can anyone let me now how to do this .
Use [`.split()`](http://docs.python.org/library/stdtypes.html#str.split): ``` string = string.split(',', 1)[0] ``` We split the string on the comma *once*, to save python the work of splitting on more commas. Alternatively, you can use [`.partition()`](http://docs.python.org/library/stdtypes.html#str.partition): ``...
Python 3: send method of generators
12,637,768
14
2012-09-28T09:58:12Z
12,638,313
34
2012-09-28T10:32:09Z
[ "python", "python-3.x", "generator" ]
I can't understand the `send` method. I understand that it is used to operate the generator. But the syntax is here: `generator.send(value)`. I somehow can't catch why the value should become the result of the current `yield` expression. I prepared an example: ``` def gen(): for i in range(10): X = yield ...
When you use `send` and expression `yield` in a generator, you're treating it as a coroutine; a separate thread of execution that can run sequentially interleaved but not in parallel with its caller. When the caller executes `R = m.send(a)`, it puts the object `a` into the generator's input slot, transfers control to ...
Decorating Hex function to pad zeros
12,638,408
23
2012-09-28T10:38:25Z
12,638,449
14
2012-09-28T10:40:55Z
[ "python", "hex", "built-in", "pad" ]
I wrote this simple function: ``` def padded_hex(i, l): given_int = i given_len = l hex_result = hex(given_int)[2:] # remove '0x' from beginning of str num_hex_chars = len(hex_result) extra_zeros = '0' * (given_len - num_hex_chars) # may not get used.. return ('0x' + hex_result if num_hex_cha...
How about this: ``` print '0x%04x' % 42 ```
Decorating Hex function to pad zeros
12,638,408
23
2012-09-28T10:38:25Z
12,638,477
47
2012-09-28T10:43:09Z
[ "python", "hex", "built-in", "pad" ]
I wrote this simple function: ``` def padded_hex(i, l): given_int = i given_len = l hex_result = hex(given_int)[2:] # remove '0x' from beginning of str num_hex_chars = len(hex_result) extra_zeros = '0' * (given_len - num_hex_chars) # may not get used.. return ('0x' + hex_result if num_hex_cha...
Use the new [`.format()`](http://docs.python.org/library/string.html#format-string-syntax) string method: ``` >>> "{0:#0{1}x}".format(42,6) 0x002a ``` **Explanation:** ``` { # Format identifier 0: # first parameter # # use "0x" prefix 0 # fill with zeroes {1} # to a length of n characters (including 0x), defi...
switch to different user using fabric
12,641,514
9
2012-09-28T14:00:43Z
12,648,391
8
2012-09-28T22:58:29Z
[ "python", "deployment", "fabric" ]
I recently started looking at fabric for remote deployment. I need to switch to a diff user (from the one that I login as) and am not able to figure it out. Is it even possible, if so how? My current user doesnt have `sudo` permissions. I tried changing following environment variables ``` env.sudo_prefix = "su newUse...
Thanks [J F Sebastian](http://stackoverflow.com/users/4279/j-f-sebastian), There were couple of catches. 1. Fabric makes connections lazily, so I had to make a dummy connection before invoking su to avoid context switch. 2. Pwd need to be stored in global scope and so that it can be reused. Fabric doesnt put it in cac...
Python: find area of polygon from xyz coordinates
12,642,256
4
2012-09-28T14:45:51Z
12,643,315
11
2012-09-28T15:53:07Z
[ "python", "3d", "polygon", "area" ]
I'm trying to use the `shapely.geometry.Polygon` module to find the area of polygons but it performs all calculations on the `xy` plane. This is fine for some of my polygons but others have a `z` dimension too so it's not quite doing what I'd like. Is there a package which will either give me the area of a planar poly...
[Here is the derivation of a formula for calculating the area of a 3D planar polygon](http://softsurfer.com/Archive/algorithm_0101/algorithm_0101.htm#3D%20Polygons) Here is Python code that implements it: ``` #determinant of matrix a def det(a): return a[0][0]*a[1][1]*a[2][2] + a[0][1]*a[1][2]*a[2][0] + a[0][2]*a...
Frequency of global variables in python?
12,642,624
9
2012-09-28T15:07:33Z
12,642,889
7
2012-09-28T15:24:51Z
[ "python" ]
Stack Overflow has a lot of questions regarding global variables in python, and it seems to generate some amount of confusion for people coming from other languages. Scoping rules don't exactly work the way a lot of people from other backgrounds expect them to. At the same time, code is meant to be organized not so mu...
I highly recommend you read this blog post titled [Singletons and their Problems in Python](http://lucumr.pocoo.org/2009/7/24/singletons-and-their-problems-in-python/). It has caused me to rethink my use of global variables. Some choice quotes: > But beware. Just because you do not implement the singleton design patte...
Bézier curve fitting with SciPy
12,643,079
5
2012-09-28T15:37:25Z
12,644,499
8
2012-09-28T17:14:47Z
[ "python", "scipy" ]
I have a set of points which approximate a 2D curve. I would like to use Python with numpy and scipy to find a cubic Bézier path which approximately fits the points, where I specify the exact coordinates of two endpoints, and it returns the coordinates of the other two control points. I initially thought `scipy.inter...
Here's a way to do Bezier curves with numpy: ``` import numpy as np from scipy.misc import comb def bernstein_poly(i, n, t): """ The Bernstein polynomial of n, i as a function of t """ return comb(n, i) * ( t**(n-i) ) * (1 - t)**i def bezier_curve(points, nTimes=1000): """ Given a set o...
sqlalchemy postgresql where int = string
12,643,646
6
2012-09-28T16:14:24Z
12,643,842
12
2012-09-28T16:26:31Z
[ "python", "sqlite", "postgresql", "sqlalchemy" ]
I have 0 experience with postgresql and am deploying an app written in python using sqlalchemy to a server with postgres. For development, I used an sqlite server. Things are going pretty smoothly, but I hit a bump I don't know how to resolve. I have three tables that look like that ``` class Car(db.Model): id...
Simply cast to a string: ``` db.session.query(Vehicle).filter(str(Car.id) == Vehicle.value) ``` if `Car.id` is a local variable that is an int. If you need to use this in a join, have the database cast it to a string: ``` from sqlalchemy.sql.expression import cast db.session.query(Vehicle).filter(cast(Car.id, sqla...