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 |
|---|---|---|---|---|---|---|---|---|---|
Extract Google Scholar results using Python (or R) | 13,200,709 | 9 | 2012-11-02T18:02:29Z | 22,916,617 | 8 | 2014-04-07T15:22:13Z | [
"python",
"google-scholar"
] | I'd like to use python to scrape google scholar search results. I found two different script to do that, one is [gscholar.py](https://github.com/venthur/gscholar) and the other is `scholar.py` (can that one be used as a python library?).
Now, I should maybe say that I'm totally new to python, so sorry if I miss the ob... | I suggest you not to use specific libraries for crawling specific websites, but to use general purpose HTML libraries that are well tested and has well formed documentation such as BeautifulSoup.
For accessing websites with a browser information, you could use an url opener class with a custom user agent:
```
from ur... |
Beautiful Soup find children for particular div | 13,202,087 | 12 | 2012-11-02T19:49:20Z | 13,202,203 | 22 | 2012-11-02T19:58:47Z | [
"python",
"parsing",
"beautifulsoup"
] | I have am trying to parse a webpage that looks like this with Python->Beautiful Soup:
I am trying to extract the contents of the highlighted td div. Currently I can get all the divs by
```
alltd = soup.findAll('td')
for td in alltd:
print td
```... | It is useful to know that whatever elements BeautifulSoup finds within one element still have the same type as that parent element - that is, various methods can be called.
So this is somewhat of a working code for your example:
```
soup = BeautifulSoup(html)
divTag = soup.find_all("div", {"class":"tablebox"}
for ta... |
Python Code: Geometric Brownian Motion - what's wrong? | 13,202,799 | 5 | 2012-11-02T20:44:51Z | 13,203,189 | 9 | 2012-11-02T21:19:40Z | [
"python",
"finance",
"random-walk",
"stochastic"
] | I'm pretty new to Python, but for a paper in University I need to apply some models, using preferably Python. I spent a couple of days with the code I attached, but I can't really help, what's wrong, it's not creating a random process which looks like standard brownian motions with drift. My parameters like mu and sigm... | According to [Wikipedia](http://en.wikipedia.org/wiki/Geometric_Brownian_motion#Solving_the_SDE),

So it appears that
```
X=(mu-0.5*sigma**2)*t+(sigma*W) ###geometric brownian motion####
```
rather than
```
X=(mu-0.5*sigma**2)*dt+(sigma*sqrt(dt)*W)... |
Removing help_text from Django UserCreateForm | 13,202,845 | 8 | 2012-11-02T20:49:02Z | 13,203,077 | 12 | 2012-11-02T21:08:34Z | [
"python",
"django",
"django-models",
"django-registration"
] | Probably a poor question, but I'm using Django's UserCreationForm (slightly modified to include email), and I would like to remove the help\_text that Django automatically displays on the HTML page.
On the Register portion of my HTML page, it has the Username, Email, Password1 & Password 2 fields. But underneath Usern... | You can set `help_text` of fields to None in `__init__`
```
from django.contrib.auth.forms import UserCreationForm
from django import forms
class UserCreateForm(UserCreationForm):
email = forms.EmailField(required=True)
def __init__(self, *args, **kwargs):
super(UserCreateForm, self).__init__(*args, ... |
Trouble querying ListField with mongoengine | 13,204,573 | 4 | 2012-11-02T23:47:11Z | 13,252,040 | 8 | 2012-11-06T13:26:46Z | [
"python",
"django",
"mongodb",
"mongoengine"
] | I'm using mongoengine, and I've got the following situation,
My model:
```
class Item(Document):
...
tags = ListField(StringField(max_length=30))
```
The query:
```
filters = {
'tags__contains': query
}
tags_with_counter = Item.objects.filter(**filters).item_frequencies('tags')
```
This returns a list of... | Having this similar MongoEngine model and documents:
```
class Post(Document):
title = StringField()
tags = ListField(StringField())
post1 = Post(title='Fun with MongoEngine', tags=['mongodb', 'mongoengine']).save()
post2 = Post(title='Loving Mongo', tags=['mongodb']).save()
```
You'll store this:
```
{
"... |
just one row from sqlalchemy | 13,205,157 | 5 | 2012-11-03T01:35:18Z | 13,213,416 | 7 | 2012-11-03T20:55:29Z | [
"python",
"sqlalchemy"
] | ```
import re
from sqlalchemy import *
db = create_engine('sqlite:///code.db')
db.echo = True
metadata = MetaData(db)
halo4 = Table('emblem_codes', metadata, autoload=True)
#########################
## Get One Unused Code ##
#########################
s = select([halo4.c.code, halo4.c.status=='None'])
result = s.e... | If you want to get just one row from a [ResultProxy](http://docs.sqlalchemy.org/en/rel_0_7/core/connections.html#sqlalchemy.engine.base.ResultProxy) object (which is the result of your `s.execute()` statement, you need to use the [`fetchone()`](http://docs.sqlalchemy.org/en/rel_0_7/core/connections.html#sqlalchemy.engi... |
Code to detect all words that start with a capital letter in a string | 13,205,343 | 4 | 2012-11-03T02:14:32Z | 13,205,353 | 8 | 2012-11-03T02:17:01Z | [
"python"
] | I'm writing out a small snippet that grabs all letters that start with a capital letter in python . Here's my code
```
def WordSplitter(n):
list1=[]
words=n.split()
print words
#print all([word[0].isupper() for word in words])
if ([word[0].isupper() for word in words]):
list1.append(word)
... | You're only evaluating it once, so you get a list of True and it only appends the last item.
```
print [word for word in words if word[0].isupper() ]
```
or
```
for word in words:
if word[0].isupper():
list1.append(word)
``` |
somethig like cron (timer) in gevent | 13,206,798 | 5 | 2012-11-03T06:51:25Z | 13,869,310 | 8 | 2012-12-13T22:05:25Z | [
"python",
"timer",
"gevent"
] | How can I make classical timer in gevent?
I'm currently using gevent.spawn\_later but is there a way to use core.timer like saying "do callback on interval" just like cron does?
```
def callback():
# do something
print '!'
timer = core.timer(10, callback)
timer.start()
outpout:
0s
10s !
20s !
30s !
``` | On the top of my head, you can use gevent.sleep in a loop:
```
import gevent
import gevent.monkey
gevent.monkey.patch_all()
INTERVAL = 10
def callback():
# do something
print "!"
def loop():
while True:
gevent.sleep(INTERVAL)
callback()
gevent.Greenlet.spawn(loop)
```
Of course, you m... |
virtualenv Env not creating bin directory in Windows 7 | 13,206,990 | 13 | 2012-11-03T07:22:44Z | 13,206,997 | 26 | 2012-11-03T07:24:10Z | [
"python",
"windows",
"virtualenv"
] | I'm a newbie to Python and I've spent hours on this. I can't seem to figure out why when I run a simple command to setup my Python environment: `virtualenv --distribute env`
This doesn't create a bin file in the `env` directory.
It only creates:
```
-- env
-- Include
-- Lib
-- Scripts
```
My impressions wa... | On Windows, this is entirely correct. A `bin` directory is created on POSIX systems only. From the [Windows Notes](https://virtualenv.pypa.io/en/latest/virtualenv.html?highlight=windows#windows-notes) section of the documentation:
> Some paths within the virtualenv are slightly different on Windows: scripts and execut... |
PermissionError: [Errno 13] in python | 13,207,450 | 7 | 2012-11-03T08:32:07Z | 13,207,548 | 8 | 2012-11-03T08:49:56Z | [
"python",
"python-3.x"
] | Just starting to learn some python and I'm having an issue as stated below:
```
a_file = open('E:\Python Win7-64-AMD 3.3\Test', encoding='utf-8')
Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
a_file = open('E:\Python Win7-64-AMD 3.3\Test', encoding='utf-8')
PermissionError: [Errno 1... | When doing;
```
a_file = open('E:\Python Win7-64-AMD 3.3\Test', encoding='utf-8')
```
...you're trying to open a *directory* as a file, which may (and on most non UNIX file systems will) fail.
Your other example though;
```
a_file = open('E:\Python Win7-64-AMD 3.3\Test\a.txt', encoding='utf-8')
```
should work wel... |
What's the simplest way of detecting keyboard input in python from the terminal? | 13,207,678 | 9 | 2012-11-03T09:07:36Z | 31,736,883 | 12 | 2015-07-31T01:47:49Z | [
"python",
"keyboard",
"terminal"
] | I have a simple python script, that has some functions that run in a loop (I'm taking sensor readings).
```
while True:
print "Doing a function"
```
If the keyboard is pressed I'd like to print "key pressed".
What's the simplest way of doing this in Python? I've searched high and low. I've found out how to do it... | # Edit:
I've thought about this problem a lot, and there are a few different behaviors one could want. I've been implementing most of them for Unix and Windows, and will post them here once they are done.
### Syncronous/Blocking key capture:
1. A simple `input` or `raw_input`, a blocking function which returns text ... |
Python Variable in an HTML email in Python | 13,208,212 | 3 | 2012-11-03T10:21:08Z | 13,208,233 | 12 | 2012-11-03T10:23:38Z | [
"python",
"email",
"html-email",
"smtplib"
] | How do I insert a variable into an html email I'm sending with python? The variable I'm trying to send is `code`. Below is what I have so far.
```
text = "We Says Thanks!"
html = """\
<html>
<head></head>
<body>
<p>Thank you for being a loyal customer.<br>
Here is your unique code to unlock exclusive co... | Use [`"formatstring".format`](http://docs.python.org/2/library/string.html#string-formatting):
```
code = "We Says Thanks!"
html = """\
<html>
<head></head>
<body>
<p>Thank you for being a loyal customer.<br>
Here is your unique code to unlock exclusive content:<br>
<br><br><h1>{code}</h1><br>
... |
Functional python programming and conditionals | 13,209,119 | 3 | 2012-11-03T12:20:18Z | 13,209,268 | 9 | 2012-11-03T12:40:10Z | [
"python",
"lambda",
"functional-programming",
"conditional-statements"
] | I'm trying to write a python function in a functional way. The problem is I don't know, how to transform an if conditional into a functional style. I have two variables: `A` and `C`, which I want to check for the following conditions:
```
def function():
if(A==0): return 0
elif(C!=0): return 0
elif(A > 4):... | From the [link you posted](http://www.ibm.com/developerworks/linux/library/l-prog/index.html):
> FP either discourages or outright disallows statements,
> and instead works with the evaluation of expressions
So instead of `if`-statements, you could use a [conditional expression](http://docs.python.org/reference/expre... |
Python split string based on regex | 13,209,288 | 24 | 2012-11-03T12:41:57Z | 13,209,313 | 13 | 2012-11-03T12:45:44Z | [
"python",
"regex",
"split"
] | What is the best way to split a string like `"HELLO there HOW are YOU"` by upper case words (in Python)?
So I'd end up with an array like such: `results = ['HELLO there', 'HOW are', 'YOU']`
---
EDIT:
I have tried:
```
p = re.compile("\b[A-Z]{2,}\b")
print p.split(page_text)
```
It doesn't seem to work, though. | You could use a lookahead:
```
re.split(r'[ ](?=[A-Z]+\b)', input)
```
This will split at every space that is followed by a string of upper-case letters which end in a word-boundary.
Note that the square brackets are only for readability and could as well be omitted.
If it is enough that the first letter of a word ... |
Python split string based on regex | 13,209,288 | 24 | 2012-11-03T12:41:57Z | 13,209,453 | 27 | 2012-11-03T13:02:14Z | [
"python",
"regex",
"split"
] | What is the best way to split a string like `"HELLO there HOW are YOU"` by upper case words (in Python)?
So I'd end up with an array like such: `results = ['HELLO there', 'HOW are', 'YOU']`
---
EDIT:
I have tried:
```
p = re.compile("\b[A-Z]{2,}\b")
print p.split(page_text)
```
It doesn't seem to work, though. | I suggest
```
l = re.compile("(?<!^)\s+(?=[A-Z])(?!.\s)").split(s)
```
Check **[this demo](http://ideone.com/qoaTqr)**. |
Get full traceback | 13,210,436 | 18 | 2012-11-03T15:13:28Z | 13,210,518 | 26 | 2012-11-03T15:22:53Z | [
"python",
"traceback"
] | How can i get full traceback in the following case, including the calls of `func2` and `func` functions?
```
import traceback
def func():
try:
raise Exception('Dummy')
except:
traceback.print_exc()
def func2():
func()
func2()
```
When i run this, i get:
```
Traceback (most recent call... | As mechmind answered, the stack trace consists only of frames between the site where the exception was raised and the site of the `try` block. If you need the full stack trace, apparently you're out of luck.
Except that it's obviously possible to extract the stack entries from top-level to the current frameâ`traceba... |
Get only NEW Emails imaplib and python | 13,210,737 | 12 | 2012-11-03T15:46:12Z | 13,210,800 | 18 | 2012-11-03T15:53:01Z | [
"python",
"imaplib"
] | This is a smaller portion of a bigger project. I need to only get unread emails and a parse their headers. How can I modify the following script to only get unread emails?
```
conn = imaplib.IMAP4_SSL(imap_server)
conn.login(imap_user, imap_password)
status, messages = conn.select('INBOX')
if status != "OK":
... | Something like this will do the trick.
```
conn = imaplib.IMAP4_SSL(imap_server)
try:
(retcode, capabilities) = conn.login(imap_user, imap_password)
except:
print sys.exc_info()[1]
sys.exit(1)
conn.select(readonly=1) # Select inbox or default namespace
(retcode, messages) = conn.search(None, '(UNSEEN)')
... |
Detect face then autocrop pictures | 13,211,745 | 27 | 2012-11-01T18:13:43Z | 13,243,712 | 50 | 2012-11-06T03:01:53Z | [
"python",
"linux",
"opencv",
"crop",
"face-detection"
] | I am trying to find an app that can detect faces in my pictures, make the detected face centered and crop 720 x 720 pixels of the picture. It is rather very time consuming & meticulous to edit around hundreds of pictures I plan to do that.
I have tried doing this using [python opencv mentioned here](http://creatingwit... | I have managed to grab bits of code from various sources and stitch this together. It is still a work in progress. Also, do you have any example images?
```
'''
Sources:
http://pythonpath.wordpress.com/2012/05/08/pil-to-opencv-image/
http://www.lucaamore.com/?p=638
'''
#Python 2.7.2
#Opencv 2.4.2
#PIL 1.1.7
import c... |
How to reconfigure tkinter canvas items? | 13,212,300 | 2 | 2012-11-03T18:42:41Z | 13,212,501 | 7 | 2012-11-03T19:06:03Z | [
"python",
"user-interface",
"tkinter"
] | I don't know if this question has duplicates , but i haven't found one yet.
when using python you can create GUI fastly , but sometimes you cannot find a method to do what you want. for example i have the following problem:
let's suppose that there is a canvas called K with a rectangle with ID=1(canvas item id , not ... | You can use [`Canvas.itemconfig`](http://effbot.org/tkinterbook/canvas.htm):
```
item = K.create_rectangle(x1,y1,x2,y2,options...)
K.itemconfig(item,options)
```
To move the item, you can use [`Canvas.move`](http://effbot.org/tkinterbook/canvas.htm#Tkinter.Canvas.move-method)
---
```
import Tkinter as tk
root = tk... |
How Do I Handle Ampersands in Django URLs? | 13,212,960 | 2 | 2012-11-03T20:01:06Z | 13,213,330 | 8 | 2012-11-03T20:44:28Z | [
"python",
"django",
"url",
"django-urls"
] | I have a Django site that uses item names to create viewer-friendly URLs. For instance:
```
/item/DeluxeWidget/
```
I have an item that has an ampersand in the name:
```
/item/Red & Blue Widget/
```
The ampersand throws things off. If I use {{ widget.name|fix\_ampersands }}, the ampersand will be escaped as `&`... | Consider using a [SlugField](https://docs.djangoproject.com/en/dev/ref/models/fields/#slugfield) which can automatically be filled with a cleaned up version of another field suitable for use in URLs. |
Cannot import scikits-learn even though it seems to be installed | 13,212,987 | 10 | 2012-11-03T20:03:47Z | 13,214,159 | 8 | 2012-11-03T22:34:06Z | [
"python",
"scikit-learn",
"scikits"
] | Per the scikit-learn user guide, I installed scikit-learn using `pip install -U scikit-learn`.
So using `pip search scikit-learn`, I get this search result:
```
scikit-learn - A set of python modules for machine learning and data mining
INSTALLED: 0.12.1 (latest)
```
But when I go into Python and try to `import skle... | Thanks folks (see comment thread under the question)! It turns out that I have two versions of Python under my Mac's /Library/Frameworks/Python.framework directory tree: 2.7 (came with OSX) and 7.3 (installed by EPD Free).
It turns out `pip` put scikit-learn under 2.7 when I really wanted it under 7.3.
Changing direc... |
Cannot import scikits-learn even though it seems to be installed | 13,212,987 | 10 | 2012-11-03T20:03:47Z | 28,062,904 | 13 | 2015-01-21T08:46:31Z | [
"python",
"scikit-learn",
"scikits"
] | Per the scikit-learn user guide, I installed scikit-learn using `pip install -U scikit-learn`.
So using `pip search scikit-learn`, I get this search result:
```
scikit-learn - A set of python modules for machine learning and data mining
INSTALLED: 0.12.1 (latest)
```
But when I go into Python and try to `import skle... | Got same problem, @Alan gave correct solution but hard way.
Here are easy steps to resolve issue, as i am on mac osx, giving steps for same.
```
Ameys-Mac-mini:~ amey$ python --version
Python 2.7.2
Ameys-Mac-mini:~ amey$ cd /Library/Python/2.7/site-packages/
Ameys-Mac-mini:site-packages amey$ brew install gcc
Ameys-Ma... |
How to query BigQuery programmatically from Python without end-user interaction? | 13,212,991 | 8 | 2012-11-03T20:04:16Z | 13,214,592 | 12 | 2012-11-03T23:37:01Z | [
"python",
"google-bigquery"
] | This question seems like it should be so simple to answer, but after days of research and several dead ends, I can't seem to get query results out of `BigQuery` without it insisting on user-based OAuth. Has anyone had any luck with this? I am not using `Google AppEngine` for my app, it is hosted in `EC2`. Here is the e... | Sorry this is being so challenging to find info on. You're looking for what's called [Service Accounts](https://developers.google.com/bigquery/docs/authorization#service-accounts-server) which are documented in our [Authorizing Access to the BigQuery API using OAuth 2.0](https://developers.google.com/bigquery/docs/auth... |
urllib2 HTTP error 429 | 13,213,048 | 7 | 2012-11-03T20:10:26Z | 13,214,012 | 15 | 2012-11-03T22:13:41Z | [
"python",
"urllib2",
"reddit"
] | So I have a list of sub-reddits and I'm using urllib to open them. As I go through them eventually urllib fails with:
```
urllib2.HTTPError: HTTP Error 429: Unknown
```
Doing some research I found that reddit limits the ammount of requests to their servers by IP:
> Make no more than one request every two seconds. Th... | From <https://github.com/reddit/reddit/wiki/API>:
> Many default User-Agents (like "Python/urllib" or "Java") are drastically limited to encourage unique and descriptive user-agent strings.
This applies to regular requests as well. You need to supply your own user agent header when making the request.
```
#TODO: cha... |
What does 'depending on rounding' exactly mean? | 13,213,496 | 6 | 2012-11-03T21:07:30Z | 13,213,524 | 7 | 2012-11-03T21:10:43Z | [
"python",
"random",
"floating-point",
"rounding"
] | About `random.uniform`, docstring says:
> Get a random number in the range [a, b) or [a, b] depending on rounding.
But I do not know what does 'depending on rounding' exactly mean. | The [current documentation for `random.uniform()`](http://docs.python.org/2/library/random.html#random.uniform) reads:
> Return a random floating point number `N` such that `a <= N <= b` for `a <= b` and `b <= N <= a` for `b < a`.
>
> The end-point value `b` may or may not be included in the range depending on floatin... |
md5 to integer bits in python | 13,213,538 | 2 | 2012-11-03T21:12:33Z | 13,213,664 | 11 | 2012-11-03T21:27:18Z | [
"python",
"hash"
] | I'm trying to convert an MD5 hashed value into a a bit integer in python. Does anyone have any idea how I would go about doing this?
I currently go through several ngrams applying a hash to each ngram:
```
for sentence in range(0,len(doc)):
for i in range(len(doc[sentence]) - 4 + 1):
ngram = doc[s... | If by "into bits", you mean a bit string for instance, then something like:
```
import hashlib
a = hashlib.md5('alsdkfjasldfjkasdlf')
b = a.hexdigest()
as_int = int(b, 16)
print bin(as_int)[2:]
# 11110000110010001100111010111001011010101011110001010000011010010010100111100
``` |
Grouping in a list with sequence re-read | 13,214,153 | 5 | 2012-11-03T22:33:19Z | 13,214,200 | 7 | 2012-11-03T22:38:53Z | [
"python",
"list"
] | I have a string (Ex: BCVDBCVCBCBD) which i have converted into a list using the
```
seq_split = [string[i:i+1] for i in range (0, len(string),1)]
```
This resulted in a list like ['B' ,'C','V'.........,'D']
Now considering I take a user input, in the form of a number (say for example 2). I need to read every 2nd ele... | You can get the desired list with
```
[x + y for x, y in zip(string, string[i:])]
```
where `i` is the number chosen by the user. Example:
```
>>> string = "BCVDBCVCBCBD"
>>> i = 2
>>> [x + y for x, y in zip(string, string[i:])]
['BV', 'CD', 'VB', 'DC', 'BV', 'CC', 'VB', 'CC', 'BB', 'CD']
``` |
Pretty print 2D Python list | 13,214,809 | 19 | 2012-11-04T00:12:56Z | 13,214,945 | 30 | 2012-11-04T00:36:01Z | [
"python",
"matrix"
] | Is there a simple, built-in way to print a 2D Python list as a 2D matrix?
So this:
```
[["A", "B"], ["C", "D"]]
```
would become something like
```
A B
C D
```
I found the pprint module, but it doesn't seem to do what I want. | To make things interesting, let's try with a bigger matrix:
```
matrix = [
["Ah!", "We do have some Camembert", "sir"],
["It's a bit", "runny", "sir"],
["Well,", "as a matter of fact it's", "very runny, sir"],
["I think it's runnier", "than you", "like it, sir"]
]
s = [[str(e) for e in row] for row in... |
How do I make Python, QT, and Webkit work on a headless server? | 13,215,120 | 4 | 2012-11-04T01:06:39Z | 13,215,192 | 12 | 2012-11-04T01:23:31Z | [
"python",
"qt",
"webkit",
"headless",
"headless-browser"
] | I have Debian Linux server that I use for a variety of things. I want it to be able to do some web-scraping jobs I need done regularly.
This code can be [found here](http://bit.ly/QeqvzX).
```
import sys
from PyQt4.QtGui import *
from PyQt4.QtCore import *
from PyQt4.QtWebKit import *
class Render(QWebPage):... | One of the constructors of `QApplication` takes a boolean argument [`GUIenabled`](http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/html/qapplication.html#QApplication-2).
If you use that, you can instantiante QAppliaction without an X server, but you can't create QWidgets.
So in this case the only option is to... |
creating python packages | 13,215,386 | 2 | 2012-11-04T02:05:15Z | 13,215,392 | 7 | 2012-11-04T02:06:24Z | [
"python"
] | I wrote some code in python as a class, but now I'm trying to prepare it for distribution as a package and I was having some trouble with figuring out how the different pieces should fit together.
So, as I originally wrote the code I had a class with a few functions in it, including an `__init__` function. I've now sp... | You can't split a class across multiple files. A package should contain multiple modules, which are files containing code (complete classes, functions, etc...).
The `__init__.py` file is run when the package is imported (although it's rare it is used to actually execute much code) and tells Python the directory is a p... |
How to extend an array in-place in Numpy? | 13,215,525 | 7 | 2012-11-04T02:35:45Z | 13,215,559 | 11 | 2012-11-04T02:43:10Z | [
"python",
"arrays",
"numpy",
"scipy"
] | Currently, I have some codes like this
```
import numpy as np
ret = np.array([])
for i in range(100000):
tmp = get_input(i)
ret = np.append(ret, np.zeros(len(tmp)))
ret = np.append(ret, np.ones(fixed_length))
```
I think these codes are **not efficient** as `np.append` need to return a copy of the array instea... | Imagine a numpy array as occupying one contiguous block of memory. Now imagine other objects, say other numpy arrays, which are occupying the memory just to the left and right of our numpy array. There would be no room to append to or extend our numpy array. The underlying data in a numpy array always occupies a *conti... |
How to extend an array in-place in Numpy? | 13,215,525 | 7 | 2012-11-04T02:35:45Z | 13,215,670 | 7 | 2012-11-04T03:01:30Z | [
"python",
"arrays",
"numpy",
"scipy"
] | Currently, I have some codes like this
```
import numpy as np
ret = np.array([])
for i in range(100000):
tmp = get_input(i)
ret = np.append(ret, np.zeros(len(tmp)))
ret = np.append(ret, np.ones(fixed_length))
```
I think these codes are **not efficient** as `np.append` need to return a copy of the array instea... | You can use the `.resize()` method of ndarrays. It requires that the memory is not referred to by other arrays/variables.
```
import numpy as np
ret = np.array([])
for i in range(100):
tmp = np.random.rand(np.random.randint(1, 100))
ret.resize(len(ret) + len(tmp)) # <- ret is not referred to by anything else,
... |
List of numbers whose squares are the sum of two squares | 13,215,629 | 7 | 2012-11-04T02:55:26Z | 13,215,664 | 7 | 2012-11-04T03:00:22Z | [
"python",
"python-2.7",
"numbers",
"sum",
"square"
] | I've just started learning Python and have started doing some problems just to help buid my skills however I am pretty stuck on this question.
Make a list containing all positive integers up to 1000 whose squares can be expressed as a sum of two squares, (i,e., integers p for which p^2=m^2+n^2, where m and n are integ... | First of all, you aren't solving the problem. You need to do a check to make sure `(x+b)**.5` is actually an integer.
Secondly, if you are printing numbers, you have already calculated out all the numbers. Doing the above will decrease the time required for this step. |
IOError: [Errno 13] Permission denied when trying to open hidden file in "w" mode | 13,215,716 | 17 | 2012-11-04T03:08:58Z | 13,215,998 | 22 | 2012-11-04T04:11:03Z | [
"python",
"windows",
"winapi",
"file-io",
"hidden-files"
] | I want to replace the contents of a hidden file, so I attempted to open it in `w` mode so it would be erased/truncated:
```
>>> import os
>>> ini_path = '.picasa.ini'
>>> os.path.exists(ini_path)
True
>>> os.access(ini_path, os.W_OK)
True
>>> ini_handle = open(ini_path, 'w')
```
But this resulted in a traceback:
```... | It's just how the Win32 API works. Under the hood, Python's `open` function is calling the [`CreateFile`](http://msdn.microsoft.com/en-us/library/windows/desktop/aa363858%28v=vs.85%29.aspx) function, and if that fails, it translates the Windows error code into a Python `IOError`.
The `r+` open mode corresponds to a `d... |
Mac OSX - AttributeError: 'FigureCanvasMac' object has no attribute 'restore_region' | 13,216,520 | 25 | 2012-11-04T06:17:58Z | 17,513,914 | 17 | 2013-07-07T16:22:32Z | [
"python",
"osx",
"matplotlib"
] | Walking through matplotlib's animation example on my Mac OSX machine - <http://matplotlib.org/examples/animation/simple_anim.html> - I am getting this error:-
```
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/matplotlib/animation.py", line 248, in _blit_clear
a.figure.canvas.r... | You can avoid the problem by switching to a different backend:
```
import matplotlib
matplotlib.use('TkAgg')
``` |
Mac OSX - AttributeError: 'FigureCanvasMac' object has no attribute 'restore_region' | 13,216,520 | 25 | 2012-11-04T06:17:58Z | 18,767,394 | 37 | 2013-09-12T14:43:47Z | [
"python",
"osx",
"matplotlib"
] | Walking through matplotlib's animation example on my Mac OSX machine - <http://matplotlib.org/examples/animation/simple_anim.html> - I am getting this error:-
```
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/matplotlib/animation.py", line 248, in _blit_clear
a.figure.canvas.r... | Just set
```
blit=False
```
when [animation.FuncAnimation()](http://matplotlib.org/api/animation_api.html#matplotlib.animation.FuncAnimation) is called and it will work.
For instance ([from double\_pendulum\_animated](http://matplotlib.org/examples/animation/double_pendulum_animated.html)):
```
ani = animation.Func... |
python 3 unable to write to file | 13,216,907 | 2 | 2012-11-04T07:34:03Z | 13,216,925 | 9 | 2012-11-04T07:37:11Z | [
"python",
"file",
"python-3.x",
"attributeerror"
] | My code is:
```
from random import randrange, choice
from string import ascii_lowercase as lc
from sys import maxsize
from time import ctime
tlds = ('com', 'edu', 'net', 'org', 'gov')
for i in range(randrange(5, 11)):
dtint = randrange(maxsize)
dtstr = ctime() ... | `file` should be a file object, not a file name. File objects have `write` method, `str` objects don't.
From the doc on [`print`](http://docs.python.org/3/library/functions.html#print):
> The *file* argument must be an object with a `write(string)` method; if it
> is not present or `None`, `sys.stdout` will be used.
... |
Python 3 os.urandom | 13,217,016 | 4 | 2012-11-04T07:55:21Z | 13,217,038 | 10 | 2012-11-04T07:59:44Z | [
"python",
"random",
"python-3.x"
] | where can i find a complete tutorial or doc on os.urandom? i need to get get a random int to choose a char from a string of 80 char
im runing Ubuntu 12.04
on an aser aspire 5920 | If you just need a random integer, you can use [`random.randint(a, b)` from the random module](http://docs.python.org/3/library/random.html#random.randint).
If you need it for crypto purposes, use `random.SystemRandom().randint(a, b)`, which makes use of `os.urandom()`.
### [Example](http://ideone.com/Nqgq0D)
```
im... |
Python accepts keyword arguments in CPython functions? | 13,217,056 | 6 | 2012-11-04T08:03:04Z | 13,217,089 | 10 | 2012-11-04T08:11:59Z | [
"python",
"keyword-argument",
"python-3.3"
] | I use python3.3 and just found out that it accepts keyword arguments in *some* of its CPython functions:
```
>>> "I like python!".split(maxsplit=1)
['I', 'like python!']
```
But some other functions **don't** accept keyword arguments:
```
>>> sum([1,2,3,4], start = 10)
Traceback (most recent call last):
File "<pys... | CPython functions that use [PyArg\_ParseTuple()](http://docs.python.org/dev/c-api/arg.html#PyArg_ParseTuple) to parse their arguments do not support keyword arguments (mostly because `PyArg_ParseTuple()` only supports positional parameters, e.g. a simple sequence).
This is explained in the `CPython implementation deta... |
Insert to cassandra from python using cql | 13,217,434 | 11 | 2012-11-04T09:28:17Z | 13,223,488 | 15 | 2012-11-04T22:15:04Z | [
"python",
"cassandra",
"cql"
] | I'm planning to insert data to bellow CF that has compound keys.
```
CREATE TABLE event_attend (
event_id int,
event_type varchar,
event_user_id int,
PRIMARY KEY (event_id, event_type) #compound keys...
);
```
But I can't insert data to this CF from python using cql.
(http://code.google.com/a/apach... | It looks like you are trying to follow the example in:
<http://pypi.python.org/pypi/cql/1.4.0>
```
import cql
con = cql.connect(host, port, keyspace)
cursor = con.cursor()
cursor.execute("CQL QUERY", dict(kw='Foo', kw2='Bar', kwn='etc...'))
```
However, if you only need to insert one row (like in your question), just... |
Turning a string into a list with specifications | 13,218,290 | 2 | 2012-11-04T11:56:03Z | 13,218,349 | 8 | 2012-11-04T12:04:04Z | [
"python",
"string",
"list"
] | I want to create a list out of my string in python that would show me how many times a letter is shown in a row inside the string.
for example:
```
my_string= "google"
```
i want to create a list that looks like this:
```
[['g', 1], ['o', 2], ['g', 1], ['l', 1], ['e', 1]]
```
Thanks! | You could use [groupby](http://docs.python.org/2/library/itertools.html#itertools.groupby) from [itertools](http://docs.python.org/2/library/itertools.html):
```
from itertools import groupby
my_string= "google"
[(c, len(list(i))) for c, i in groupby(my_string)]
``` |
Predicting values using an OLS model with statsmodels | 13,218,461 | 6 | 2012-11-04T12:21:07Z | 13,218,891 | 9 | 2012-11-04T13:23:20Z | [
"python",
"pandas",
"linear-regression",
"statsmodels"
] | I calculated a model using OLS (multiple linear regression). I divided my data to train and test (half each), and then I would like to predict values for the 2nd half of the labels.
```
model = OLS(labels[:half], data[:half])
predictions = model.predict(data[half:])
```
The problem is that I get and error:
File "/usr... | For statsmodels >=0.4, if I remember correctly
`model.predict` doesn't know about the parameters, and requires them in the call
see <http://statsmodels.sourceforge.net/stable/generated/statsmodels.regression.linear_model.OLS.predict.html>
What should work in your case is to fit the model and then use the predict meth... |
How to get system timezone setting and pass it to pytz.timezone? | 13,218,506 | 28 | 2012-11-04T12:27:56Z | 13,218,525 | 21 | 2012-11-04T12:30:29Z | [
"python",
"timezone",
"pytz"
] | We can use `time.tzname` get a local timezone name, but that name is not compatible with `pytz.timezone`.
In fact, the name returned by `time.tzname` is ambiguous. This method returns `('CST', 'CST')` in my system, but 'CST' can indicate four timezones:
* Central Time Zone (North America) - observed in North America'... | Use the [`tzlocal` function](http://labix.org/python-dateutil#head-5fb12f4538c5a2fd83f87eea8e6c0ddd47f8b4b0) from the [`python-dateutil` package](http://pypi.python.org/pypi/python-dateutil):
```
from dateutil.tz import tzlocal
localtimezone = tzlocal()
```
Internally, this is a class that uses `time.timezone` and `... |
How to get system timezone setting and pass it to pytz.timezone? | 13,218,506 | 28 | 2012-11-04T12:27:56Z | 13,218,990 | 11 | 2012-11-04T13:35:07Z | [
"python",
"timezone",
"pytz"
] | We can use `time.tzname` get a local timezone name, but that name is not compatible with `pytz.timezone`.
In fact, the name returned by `time.tzname` is ambiguous. This method returns `('CST', 'CST')` in my system, but 'CST' can indicate four timezones:
* Central Time Zone (North America) - observed in North America'... | A very simple method to solve this question:
```
import time
def localTzname():
offsetHour = time.timezone / 3600
return 'Etc/GMT%+d' % offsetHour
```
**Update**: @MartijnPieters said 'This won't work with DST / summertime.' So how about this version?
```
import time
def localTzname():
if time.daylight... |
How to get system timezone setting and pass it to pytz.timezone? | 13,218,506 | 28 | 2012-11-04T12:27:56Z | 17,365,806 | 29 | 2013-06-28T13:26:26Z | [
"python",
"timezone",
"pytz"
] | We can use `time.tzname` get a local timezone name, but that name is not compatible with `pytz.timezone`.
In fact, the name returned by `time.tzname` is ambiguous. This method returns `('CST', 'CST')` in my system, but 'CST' can indicate four timezones:
* Central Time Zone (North America) - observed in North America'... | [`tzlocal` module](https://github.com/regebro/tzlocal) returns pytz tzinfo's object corresponding to the local timezone:
```
import time
from datetime import datetime
import pytz # $ pip install pytz
from tzlocal import get_localzone # $ pip install tzlocal
# get local timezone
local_tz = get_localzone()
# tes... |
How can I speed up transition matrix creation in Numpy? | 13,219,041 | 11 | 2012-11-04T13:41:54Z | 13,221,622 | 8 | 2012-11-04T18:41:51Z | [
"python",
"numpy",
"scipy"
] | The following is the most basic way I know of to count transitions in a markov chain and use it to populate a transition matrix:
```
def increment_counts_in_matrix_from_chain(markov_chain, transition_counts_matrix):
for i in xrange(1, len(markov_chain)):
old_state = markov_chain[i - 1]
new_state = ... | Just for kicks, and because I've been wanting to try it out, I applied [Numba](http://numba.pydata.org/) to your problem. In code, that involves just adding a decorator (although I've made a direct call so I could test the jit variants that numba provides here):
```
import numpy as np
import numba
def increment_count... |
How to embed python expression into :s command in vim? | 13,219,111 | 5 | 2012-11-04T13:50:55Z | 13,220,941 | 7 | 2012-11-04T17:20:04Z | [
"python",
"vim"
] | I can use `\=expr` in `:s` command. For example, to convert timestamps format inplace:
```
:%s/\v<\d{10}>/\=strftime('%c', submatch(0))/g
```
---
But the functionality of built-in functions are so limited. To parse a timestamp, I'd like to use python script like this:
```
$ python
>>> import datetime
>>> d = 'Apr 1... | If you have at least vim-7.3.569 then you may do the following:
```
:python import datetime
:%s/\v\w+\ \d{2}\ \d{4}/\=pyeval('datetime.datetime.strptime(vim.eval("submatch(0)"), "%b %d %Y").isoformat()')/g
```
. If you donât you have recent vim you can emulate pyeval in this case:
```
function Pyeval(expr)
pyt... |
argparse: Get undefined number of arguments | 13,219,910 | 7 | 2012-11-04T15:25:48Z | 13,220,006 | 17 | 2012-11-04T15:37:05Z | [
"python",
"argparse"
] | I'm building a script which uses arguments to configure the behavior and shall read an undefined number of files. Using the following code allows me to read one single file. Is there any way to accomplish that without having to set another argument, telling how many files the script should read?
```
parser = argparse.... | Yes, change your `"FILE"` line to:
```
parser.add_argument("FILE", help="File to store as Gist", nargs="+")
```
This will gather all the positional arguments in a list instead. It will also generate an error if there's not at least one to operate on.
Check out the [nargs documentation](http://docs.python.org/dev/lib... |
Getting Error: redirect_uri_mismatch The redirect URI in the request: http://localhost:8080/oauth2callback did not match a registered redirect URI | 13,221,978 | 9 | 2012-11-04T19:22:17Z | 13,222,012 | 11 | 2012-11-04T19:25:24Z | [
"python",
"google-app-engine",
"oauth-2.0",
"google-bigquery"
] | I'm getting this error while trying to run my application...
```
The redirect URI in the request: http://localhost:8080/oauth2callback did not match a registered redirect URI
```
In google API console i have registered my redirect urls
```
Redirect URIs: http://localhost:8080/
```
And in the client\_secrets.json a... | You will actually need to add the following to your redirect URIs:
```
http://localhost:8080/oauth2callback
```
Also, you may need to append a trailing `/` if the above doesn't match:
```
http://localhost:8080/oauth2callback/
``` |
Setting a property doesn't work - dumb syntax error? | 13,222,360 | 3 | 2012-11-04T18:57:27Z | 13,222,366 | 7 | 2012-11-04T20:06:24Z | [
"python",
"properties"
] | I'm probably making some elementary mistake...
When I initialize and look at a property of an object, fine. But if I try to set it, the object doesn't update itself. I'm trying to define a property which I can set and get. To make it interesting, this rectangle stores twice its width instead of the width, so the gette... | ```
class Rect:
"""simple rectangle (size only) which remembers double its w,h
as demo of properties
"""
```
Should be:
```
class Rect(object):
"""simple rectangle (size only) which remembers double its w,h
as demo of properties
"""
```
In python 2.x, `property` only works properly if y... |
how to read a file in other directory in python | 13,223,737 | 6 | 2012-11-04T22:46:02Z | 13,223,867 | 7 | 2012-11-04T23:01:15Z | [
"python"
] | > I have a file its name is 5\_1.txt in a directory I named it direct ,
> how can I read that file using the instruction read.
i verified the path using :
```
import os
os.getcwd()
os.path.exists(direct)
```
the result was
True
```
x_file=open(direct,'r')
```
and i got this error :
```
Traceback (most recent ... | Looks like you are trying to open a *directory* for reading as if it's a regular file. Many OSs won't let you do that. You don't need to anyway, because what you want (judging from your description) is
```
x_file = open(os.path.join(direct, "5_1.txt"), "r")
```
or simply
```
x_file = open(direct+"/5_1.txt", "r")
``` |
Principal Component Analysis (PCA) in Python | 13,224,362 | 24 | 2012-11-05T00:10:11Z | 13,224,444 | 10 | 2012-11-05T00:24:49Z | [
"python",
"numpy",
"machine-learning",
"pca"
] | I have a (26424 x 144) array and I want to perform PCA over it using Python. However, there is no particular place on the web that explains about how to achieve this task (There are some sites which just do PCA according to their own - there is no generalized way of doing so that I can find). Anybody with any sort of h... | This is a job for `numpy`.
And here's a tutorial demonstrating how pincipal component analysis can be done using `numpy`'s built-in modules like `mean,cov,double,cumsum,dot,linalg,array,rank`.
<http://glowingpython.blogspot.sg/2011/07/principal-component-analysis-with-numpy.html>
Notice that `scipy` also has a long ... |
Principal Component Analysis (PCA) in Python | 13,224,362 | 24 | 2012-11-05T00:10:11Z | 13,224,566 | 24 | 2012-11-05T00:42:25Z | [
"python",
"numpy",
"machine-learning",
"pca"
] | I have a (26424 x 144) array and I want to perform PCA over it using Python. However, there is no particular place on the web that explains about how to achieve this task (There are some sites which just do PCA according to their own - there is no generalized way of doing so that I can find). Anybody with any sort of h... | You can find a PCA function in the matplotlib module:
```
from matplotlib.mlab import PCA
data = array(randint(10,size=(10,3)))
results = PCA(data)
```
results will store the various parameters of the PCA.
It is from the mlab part of matplotlib, which is the compatibility layer with the MATLAB syntax
EDIT:
on the bl... |
Principal Component Analysis (PCA) in Python | 13,224,362 | 24 | 2012-11-05T00:10:11Z | 13,224,592 | 33 | 2012-11-05T00:48:03Z | [
"python",
"numpy",
"machine-learning",
"pca"
] | I have a (26424 x 144) array and I want to perform PCA over it using Python. However, there is no particular place on the web that explains about how to achieve this task (There are some sites which just do PCA according to their own - there is no generalized way of doing so that I can find). Anybody with any sort of h... | I posted my answer even though another answer has already been accepted; the accepted answer relies on a [deprecated function](http://matplotlib.org/api/mlab_api.html?highlight=mlab#deprecated-functions); additionally, this deprecated function is based on *Singular Value Decomposition* (SVD), which (although perfectly ... |
Principal Component Analysis (PCA) in Python | 13,224,362 | 24 | 2012-11-05T00:10:11Z | 27,933,271 | 7 | 2015-01-13T23:16:36Z | [
"python",
"numpy",
"machine-learning",
"pca"
] | I have a (26424 x 144) array and I want to perform PCA over it using Python. However, there is no particular place on the web that explains about how to achieve this task (There are some sites which just do PCA according to their own - there is no generalized way of doing so that I can find). Anybody with any sort of h... | Another Python PCA using numpy. The same idea as @doug but that one didn't run.
```
from numpy import array, dot, mean, std, empty, argsort
from numpy.linalg import eigh, solve
from numpy.random import randn
from matplotlib.pyplot import subplots, show
def cov(data):
"""
covariance matrix
note: sp... |
Preserving python dictionary order - (Continuation of python dict ) | 13,225,254 | 2 | 2012-11-05T02:33:38Z | 13,225,265 | 8 | 2012-11-05T02:35:13Z | [
"python",
"list",
"dictionary",
"python-2.7"
] | [List duplicate data concatenation in python](http://stackoverflow.com/questions/13218865/list-duplicate-data-concatenation-in-python/13220621)
This is in continuation of list issue but here i want to preserver the order of the dict
```
listData=[('audioVerify', '091;0'), ('imageVerify', 'icon091.gif'), ('bufferVerif... | I have just what the doctor `ordered`: [OrderedDict](http://docs.python.org/2/library/collections.html#collections.OrderedDict)
From the [examples](http://docs.python.org/2/library/collections.html#ordereddict-examples-and-recipes):
```
>>> from collections import OrderedDict
>>> # regular unsorted dictionary
>>> d =... |
"System error: new style getargs format but argument is not a tuple" when using cv2.blur | 13,225,525 | 11 | 2012-11-05T03:22:21Z | 13,226,938 | 12 | 2012-11-05T06:20:13Z | [
"python",
"image-processing",
"opencv"
] | I am just trying to apply a filter to an image using cv2, the opencv python bindings. Here is what my code look like:
```
im = cv2.imread('./test_imgs/zzzyj.jpg')
cv2.imshow('Image', cv2.blur(im, 2)
cv2.waitKey(0)
```
It's almost copy-and-paste from the [documentation](http://docs.opencv.org/modules/imgproc/doc/filte... | For cv2.blur, you need to give ksize as a tuple of two elements , like (2,2). But for medianBlur, ksize = 3 is sufficient. It will deduct a square kernel from it.
So make code like this :
```
im = cv2.imread('./test_imgs/zzzyj.jpg')
cv2.imshow('Image', cv2.blur(im, (3,3)))
cv2.waitKey(0)
cv2.destroyAllWindows()
```
... |
Convert list of keys and list of values to a dictionary | 13,225,755 | 3 | 2012-11-05T04:03:43Z | 13,225,794 | 11 | 2012-11-05T04:09:24Z | [
"python",
"dictionary"
] | I have these lists:
```
list1 = ["a","b","c"]
list2 = ["1","2","3"]
```
I need to add them to a dictionary, where list1 is the key and list2 is the value.
I wrote this code:
```
d = {}
for i in list1:
for j in list2:
d[i] = j
print d
```
The output is this:
```
{'a':'3','b':'3','c':'3'}
```
What's wr... | Zip the lists and use a dict comprehension :
```
{i: j for i, j in zip(a, b)}
```
Or, even easier, just use `dict()` :
```
dict(zip(a, b))
```
You should keep it simple, so the last solution is the best, but I kept the dict comprehension example to show how it could be done. |
Django default=timezone.now() saves records using "old" time | 13,225,890 | 10 | 2012-11-05T04:23:14Z | 13,226,368 | 35 | 2012-11-05T05:23:47Z | [
"python",
"django",
"django-timezone"
] | This issue has been occurring on and off for a few weeks now, and it's unlike any that has come up with my project.
Two of the models that are used have a timestamp field, which is by default set to `timezone.now()`.
This is the sequence that raises error flags:
---
* Model one is created at time 7:30 PM
* Model tw... | Just ran into this last week for a field that had `default=date.today()`. If you remove the parentheses (in this case, try `default=timezone.now`) then you're passing a callable to the model and it will be called each time a new instance is saved. With the parentheses, it's only being called once when `models.py` loads... |
Benefits of panda's multiindex? | 13,226,029 | 22 | 2012-11-05T04:43:47Z | 13,226,352 | 47 | 2012-11-05T05:22:05Z | [
"python",
"pandas",
"multi-index"
] | So I learned that I can use DataFrame.groupby without having a MultiIndex to do subsampling/cross-sections.
On the other hand, when I have a MultiIndex on a DataFrame, I still need to use DataFrame.groupby to do sub-sampling/cross-sections.
So what is a MultiIndex good for apart from the quite helpful and pretty disp... | Hierarchical indexing (also referred to as âmulti-levelâ indexing) was introduced in the pandas 0.4 release.
This opens the door to some quite sophisticated data analysis and manipulation, especially for working with higher dimensional data. In essence, it enables you to effectively store and manipulate arbitraril... |
calculating angle between two lines in python | 13,226,038 | 3 | 2012-11-05T04:45:28Z | 13,226,141 | 14 | 2012-11-05T04:56:23Z | [
"python",
"math"
] | I am trying to calculate the angle between two lines in python.
I searched the internet and found the equation on how to do it. But I don't always get accurate result. Some of the results are clearly false when other seems correct.
My code is given below:
```
def angle(pt1,pt2):
m1 = (pt1.getY() - pt1.getY())/1
... | Your angle formula will fail if
```
pt2.getX() == pt1.getX()
```
(that is, if pt1 and pt2 lie on a vertical line) because you can not divide by zero. (`m2`, the slope, would be infinite.)
Also
```
m1 = (pt1.getY() - pt1.getY())/1
```
will always be zero. So at the very least, your formula could be simplified to th... |
Boto script to download latest file from s3 bucket | 13,226,940 | 5 | 2012-11-05T06:20:21Z | 13,239,898 | 9 | 2012-11-05T20:31:16Z | [
"python",
"amazon-s3",
"boto"
] | I like to write a boto python script to download the recent most file from the s3 bucket i.e. for eg I have 100 files in a s3 bucket I need to download the recent most uploaded file in it.
Is there a way to download the recent most modified file from S3 using python boto
THanks in advance | You could list all of the files in the bucket and find the one with the most recent one (using the last\_modified attribute).
```
>>> import boto
>>> c = boto.connect_s3()
>>> bucket = c.lookup('mybucketname')
>>> l = [(k.last_modified, k) for k in bucket]
>>> key_to_download = sorted(l, cmp=lambda x,y: cmp(x[0], y[0]... |
set chrome options with remote driver | 13,227,346 | 7 | 2012-11-05T06:55:40Z | 13,227,591 | 8 | 2012-11-05T07:14:50Z | [
"python",
"selenium",
"webdriver",
"selenium-chromedriver"
] | So there's a nice [long list of switches](http://peter.sh/experiments/chromium-command-line-switches/) that can be passed to the chromedriver.
I would like to use some of them, specifically `--disable-logging`.
I do no want to (only) use chromedriver locally though, I'd like to write all my code to use `webdriver.Rem... | This should give you the flags available:
```
from selenium import webdriver
options = webdriver.ChromeOptions()
# set some options
# for example:
# options.add_argument('--disable-logging')
driver = webdriver.Remote(desired_capabilities=options.to_capabilities())
``` |
Scrapy crawls first page but does not follow links | 13,227,546 | 4 | 2012-11-05T07:10:17Z | 13,227,933 | 8 | 2012-11-05T07:44:28Z | [
"python",
"scrapy"
] | I can't figure out why Scrapy is crawling the first page but not following the links to crawl the subsequent pages. It must be something to do with the Rules. Much appreciated. Thank you!
```
from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
from scra... | Craig uses `index100`,`index200`,`index300`... for next pages, max is `index900`.
```
rules = (Rule (SgmlLinkExtractor(allow=("index\d00\.html", ),restrict_xpaths=('//p[@id="nextpage"]',))
, callback="parse_items", follow= True),
)
```
works for me. |
How to compare dates only (and not the time) in python | 13,227,597 | 3 | 2012-11-05T07:15:30Z | 13,227,661 | 10 | 2012-11-05T07:20:35Z | [
"python",
"date",
"datetime"
] | I have 2 datetime objects. One only has the date and the other one has date & time. I want to compare the dates only (and not the time).
This is what I have:
```
d2=datetime.date(d1.year,d1.month,d1.day)
print d2 == d1.date
```
It prints out false. Any idea why?
Thank you! | ```
d1.date() == d2.date()
```
From the Python [doc](http://docs.python.org/3.3/library/datetime.html#datetime.datetime.date):
> `datetime.date()` Return date object with same year, month and day. |
Convert mongodb return object to dictionary | 13,230,284 | 13 | 2012-11-05T10:35:14Z | 13,230,510 | 21 | 2012-11-05T10:47:45Z | [
"python",
"mongodb",
"python-2.7",
"bottle",
"mongoengine"
] | I'm using the bottle framework together with mongoengine.
I have an orders model :
```
class OrderDetail(Option):
orderDetailsQty = FloatField()
def to_dict(self):
return mongo_to_dict_helper(self)
class Order(Document):
userName = StringField(required=True)
orderDate = DateTimeField()
o... | What about just using `to_mongo` method of an object to convert it to a dict?
```
object.to_mongo()
``` |
How do I call a specific Method from a Python Script in C#? | 13,231,913 | 7 | 2012-11-05T12:14:38Z | 13,241,517 | 14 | 2012-11-05T22:36:01Z | [
"c#",
"python",
"methods",
"arguments",
"ironpython"
] | I'm wondering if there is a possibility to call a specific Method from a Python script over a C# project.
I have no code... but my idea is:
Python Code:
```
def SetHostInfos(Host,IP,Password):
Work to do...
def CalcAdd(Numb1,Numb2):
Work to do...
```
C# Code:
```
SetHostInfos("test","0.0.0.0","PWD")
result ... | You can host IronPython, execute the script and access the functions defined within the script through the created scope.
The following sample shows the basic concept and two ways of using the function from C#.
```
var pySrc =
@"def CalcAdd(Numb1, Numb2):
return Numb1 + Numb2";
// host python and execute script
... |
Python Cubes OLAP Framework - how to work with joins? | 13,233,809 | 4 | 2012-11-05T14:09:04Z | 13,241,799 | 11 | 2012-11-05T23:03:50Z | [
"python",
"database",
"olap",
"star-schema"
] | I'm trying to use python's olap framework [cubes](http://packages.python.org/cubes/) on a very simple database, but I am having some trouble joining tables.
My schema looks like this:
```
Users table
ID | name
Products table
ID | name | price
Purchases table
ID | user_id | product_id | date
```
And the cubes model... | First let's fix the model a bit. In your schema you have more attributes per dimension: id and name, you might end up having more details in the future. You can add them by specifying attributes as a list: `"attriubtes": ["id", "name"]`. Note also that the dimension is named as entity `product` not as a key `id_product... |
openerp context in act_window | 13,235,220 | 6 | 2012-11-05T15:29:25Z | 13,238,243 | 15 | 2012-11-05T18:38:28Z | [
"python",
"openerp"
] | In OpenERP 6.1 this act\_window:
```
<act_window
domain="[('id', '=', student)]"
id="act_schedule_student"
name="Student"
res_model="school.student"
src_model="school.schedule"/>
```
creates a **Student** button in the **Schedule** form which opens the student tree view showing only the appro... | The magical (and probably undocumented) way to have an OpenERP action directly open the form view of a given record, is to set an extra `res_id` attribute on the action.
Unfortunately in OpenERP 6.1[1] the `res_id` attribute is not part of the `act_window` data model, so it is not possible to directly set it in an XML... |
Check if a string is valid absolute path address format | 13,235,853 | 6 | 2012-11-05T16:05:39Z | 13,235,910 | 16 | 2012-11-05T16:08:29Z | [
"python"
] | I have a string which contains user input for a directory address on a linux system. I need to check if it is properly formatted and *could* be an address in Python 2.6. It's important to note that this is not on the current system so I can't check if it is there using os.path nor can I try to create the directories as... | Sure the question has been edited since writing this but:
There is the `os.path.isabs(PATH)` which will tell you if the path is absolute or not.
> Return True if path is an absolute pathname. On Unix, that means it begins with a slash, on Windows that it begins with a (back)slash after chopping off a potential drive ... |
Unicode in ipython notebook | 13,236,086 | 3 | 2012-11-05T16:20:19Z | 13,236,220 | 10 | 2012-11-05T16:27:54Z | [
"python",
"unicode",
"matplotlib",
"ipython",
"ipython-notebook"
] | I'm trying to get a "degree" sign (°) in a matplotlib plot from ipython notebook.
When I run
```
ax = plt.gca()
ax.set_xlabel("something at 55" + unicode("\xc2", errors='replace'))
ax.plot([0.,1.,], [0.,1.])
```
I get a plot, but instead of the degree sign, I have a strange black square with a question mark. This a... | The error message is telling you what to do:
```
ValueError: matplotlib display text must have all code points < 128
or use Unicode strings
```
Make your `xlabel` a unicode string:
```
ax.set_xlabel(u"something at 55°")
``` |
PDF bleed detection | 13,236,370 | 3 | 2012-11-05T16:36:28Z | 13,240,546 | 15 | 2012-11-05T21:17:57Z | [
"python",
"pdf",
"typography",
"pypdf"
] | I'm currently writing a little tool (Python + pyPdf) to test PDFs for printer conformity.
Alas I already get confused at the first task: Detecting if the PDF has at least 3mm 'bleed' (border around the pages where nothing is printed). I already got that I can't detect the bleed for the complete document, since there d... | Quoting from the PDF specification [ISO 32000-1:2008](http://www.adobe.com/content/dam/Adobe/en/devnet/acrobat/pdfs/PDF32000_2008.pdf) as published by Adobe:
> 14.11.2 Page Boundaries
>
> 14.11.2.1 General
>
> A PDF page may be prepared either for a finished medium, such as a
> sheet of paper, or as part of a prepress... |
No module named numpy | 13,237,522 | 11 | 2012-11-05T17:47:53Z | 13,238,028 | 22 | 2012-11-05T18:21:40Z | [
"python",
"numpy"
] | I have the following programs installed
1. python 2.7 installed
2. Numpy-1.6.2-python2.7
3. Matplotlib-1.1.1-py2.7
I believe numpy has been installed properly because when I type import numpy in python interpreter, it doesn't give me an error. I can also check the version of the numpy installed.
I am getting the fol... | in terminal:
sudo apt-get install python-numpy |
sorting list of nested dictionaries in python | 13,237,941 | 7 | 2012-11-05T18:15:20Z | 13,237,991 | 11 | 2012-11-05T18:19:23Z | [
"python",
"sorting",
"dictionary"
] | I have something like
```
[
{
"key": { "subkey1":1, "subkey2":"a" }
},
{
"key": { "subkey1":10, "subkey2":"b" }
},
{
"key": { "subkey1":5, "subkey2":"c" }
}
]
```
And would need to have :
```
[
{
"key": { "subkey1":10, "subkey2":"b" }
},
{
... | Use the `key` keyword to the [`sorted()` function](http://docs.python.org/2/library/functions.html#sorted) and [`sort()` method](http://docs.python.org/2/library/stdtypes.html#mutable-sequence-types):
```
yourdata.sort(key=lambda e: e['key']['subkey'], reverse=True)
```
Demo:
```
>>> yourdata = [{'key': {'subkey': 1... |
Is it possible to turn a list into a nested dict of keys *without* recursion? | 13,238,255 | 6 | 2012-11-05T18:39:03Z | 13,238,323 | 10 | 2012-11-05T18:44:11Z | [
"python",
"list",
"recursion",
"dictionary",
"iteration"
] | Supposing I had a list as follows:
```
mylist = ['a','b','c','d']
```
Is it possible to create, from this list, the following dict **without** using recursion/a recursive function?
```
{
'a': {
'b': {
'c': {
'd': { }
}
}
}
}
``` | For the simple case, simply iterate and build, either from the end or the start:
```
result = {}
for name in reversed(mylist):
result = {name: result}
```
or
```
result = current = {}
for name in mylist:
current[name] = {}
current = current[name]
```
The first solution can also be expressed as a one-lin... |
ignoring directories in os.walk()? | 13,239,002 | 4 | 2012-11-05T19:29:58Z | 13,239,030 | 13 | 2012-11-05T19:32:09Z | [
"python"
] | I wish to ignore some directories in my os.walk().
I do:
```
folders_to_ignore = ['C:\\Users\\me\\AppData\\'];
def find_files(directory, pattern):
for root, dirs, files in os.walk(directory):
dir[:] = [d for d in dirs if not is_folder_to_ignore(d)];
for basename in files:
if fnmatch.fnmatch(basename, ... | You're using [`dir`](http://docs.python.org/2/library/functions.html#dir) which is a built-in, probably you mean `dirs`
change this
```
dir[:] = [d for d in dirs if not is_folder_to_ignore(d)]
```
to this
```
dirs[:] = [d for d in dirs if not is_folder_to_ignore(d)]
``` |
Is it possible to add <key, value> pair at the end of the dictionary in python | 13,239,279 | 3 | 2012-11-05T19:49:18Z | 13,239,305 | 10 | 2012-11-05T19:51:39Z | [
"python",
"dictionary"
] | When I introduce new pair it is inserted at the beginning of dictionary. Is it possible to append it at the end? | Dictionaries have no order, and thus have no beginning or end. The display order is arbitrary.
If you need order, you can use a `list` of `tuple`s instead of a `dict`:
```
In [1]: mylist = []
In [2]: mylist.append(('key', 'value'))
In [3]: mylist.insert(0, ('foo', 'bar'))
```
You'll be able to easily convert it int... |
Reverse an arbitrary dimension in an ndarray | 13,240,117 | 7 | 2012-11-05T20:47:56Z | 13,240,248 | 9 | 2012-11-05T20:57:20Z | [
"python",
"multidimensional-array",
"numpy"
] | I'm working with an n-dimensional array, and I'd like a way to reverse a numbered dimension. So rather than
```
rev = a[:,:,::-1]
```
I'd like to be able to write
```
rev = a.reverse(dimension=2)
```
or something similar. I can't seem to find examples that don't rely on the former syntax. | If you browse the numpy (python) source code you'll find a trick they use to write functions that operate on a particular axis is to use `np.swapaxes` to put the target axis in the `axis = 0` position. Then they write code that operates on the `0-axis`, and then they use `np.swapaxes` again to put the `0-axis` back in ... |
Matplotlib plot pulse propagation in 3d | 13,240,633 | 5 | 2012-11-05T21:25:02Z | 13,244,026 | 8 | 2012-11-06T03:41:14Z | [
"python",
"3d",
"matplotlib"
] | I'd like to plot pulse propagation in such a way at each step, it plots the pulse shape. In other words, I want a serie of x-z plots, for each values of y. Something like this (without color):

How can I do this using matplotlib (or Mayavi)? Here is what I did so... | Change to:
```
ax.plot_wireframe(T, z, abs(U), cstride=1000)
```
and call:
```
drawPropagation(1.0, 1.0, numpy.linspace(-2, 2, 10))
```
will create the following graph:

If you need the curve been filled with white color:
```
import numpy
from mp... |
python/beautifulsoup to find all <a href> with specific anchor text | 13,240,700 | 2 | 2012-11-05T21:30:19Z | 13,240,775 | 13 | 2012-11-05T21:35:30Z | [
"python",
"beautifulsoup"
] | I am trying to use beautiful soup to parse html and find all href with a specific anchor tag
```
<a href="http://example.com">TEXT</a>
<a href="http://example.com/link">TEXT</a>
<a href="http://example.com/page">TEXT</a>
```
all the links I am looking for have the exact same anchor text, in this case TEXT. I am NOT l... | Would something like this work?
```
In [39]: from bs4 import BeautifulSoup
In [40]: s = """\
....: <a href="http://example.com">TEXT</a>
....: <a href="http://example.com/link">TEXT</a>
....: <a href="http://example.com/page">TEXT</a>
....: <a href="http://dontmatchme.com/page">WRONGTEXT</a>"""
In [41]: ... |
Check string indentation? | 13,241,399 | 2 | 2012-11-05T22:25:45Z | 13,241,465 | 8 | 2012-11-05T22:30:33Z | [
"python",
"indentation",
"analysis",
"lint"
] | I'm building an analyzer for a series of strings.
I need to check how much each line is indented (either by tabs or by spaces).
Each line is just a string in a text editor.
How do I check by how much a string is indented?
Or rather, maybe I could check how much whitespace or \t are before a string, but I'm unsure of ... | To count the number of spaces at the beginning of a string you could do a comparison between the left stripped (whitespace removed) string and the original:
```
a = " indented string"
leading_spaces = len(a) - len(a.lstrip())
print leading_spaces
```
Ran in the interpreter you get:
```
>>> a = " indented strin... |
Resampling a numpy array representing an image | 13,242,382 | 28 | 2012-11-05T23:56:27Z | 13,251,340 | 7 | 2012-11-06T12:43:42Z | [
"python",
"image-processing",
"numpy",
"scipy",
"python-imaging-library"
] | I am looking for how to resample a numpy array representing image data at a new size, preferably having a choice of the interpolation method (nearest, bilinear, etc.). I know there is
```
scipy.misc.imresize
```
which does exactly this by wrapping PIL's resize function. The only problem is that since it uses PIL, the... | Have you looked at [Scikit-image](http://scikit-image.org/docs/dev/api/api.html)? Its `transform.pyramid_*` functions might be useful for you. |
Resampling a numpy array representing an image | 13,242,382 | 28 | 2012-11-05T23:56:27Z | 16,510,074 | 45 | 2013-05-12T17:19:54Z | [
"python",
"image-processing",
"numpy",
"scipy",
"python-imaging-library"
] | I am looking for how to resample a numpy array representing image data at a new size, preferably having a choice of the interpolation method (nearest, bilinear, etc.). I know there is
```
scipy.misc.imresize
```
which does exactly this by wrapping PIL's resize function. The only problem is that since it uses PIL, the... | Based on your description, you want [`scipy.ndimage.zoom`](http://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.interpolation.zoom.html#scipy.ndimage.interpolation.zoom).
Bilinear interpolation would be `order=1`, nearest is `order=0`, and cubic is the default (`order=3`).
`zoom` is specifically for regu... |
How to Take Checkboxes in Python | 13,242,412 | 4 | 2012-11-06T00:00:39Z | 13,242,681 | 7 | 2012-11-06T00:33:47Z | [
"python",
"html",
"google-app-engine",
"checkbox",
"webapp2"
] | I am trying to use checkboxes in my HTML, return these checkboxes to my python backend, and then increment three counters if the box is clicked.
Right now my HTML is as follows and works fine:
```
<form method="post">
<input type="checkbox inline" name="adjective" value="entertaining">Entertaining
<input type... | When your form has multiple checkboxes with the same `name` attribute, the request when the form is submitted will have multiple values for that name.
Your current code uses `Request.get` to get a value, but this will only retrieve the first value if there is more than one. Instead, you can get all the values using `R... |
how to replace %s with one variable in python | 13,243,163 | 2 | 2012-11-06T01:36:25Z | 13,243,180 | 7 | 2012-11-06T01:38:42Z | [
"python"
] | I have a string like
```
strTemp='i don\'t want %s repeat the %s variable again %s and again %s'%('aa','aa','aa','aa')
```
I want to replace all the %s with 'aa', so I have to repeat the 'aa' for many times, how can I tell the program that I want to replace all the %s just with the same variable, so I needn't type th... | The % operator is discouraged. Use `str.format` instead.
```
strTemp='i don\'t want {0} repeat the {0} variable again {0} and again {0}'.format('aa')
``` |
Python Empty Generator Function | 13,243,766 | 41 | 2012-11-06T03:08:13Z | 13,243,870 | 58 | 2012-11-06T03:22:44Z | [
"python",
"generator"
] | In python, one can easily define an iterator function, by putting the yield keyword in the function's body, such as:
```
def gen():
for i in range(100):
yield i
```
How can I define a generator function that yields no value (generates 0 values), the following code doesn't work, since python cannot know th... | You can use `return` once in a generator; it stops iteration without yielding anything, and thus provides an explicit alternative to letting the function run out of scope. So use `yield` to turn the function into a generator, but precede it with `return` to terminate the generator before yielding anything.
```
>>> def... |
Python Empty Generator Function | 13,243,766 | 41 | 2012-11-06T03:08:13Z | 13,243,920 | 26 | 2012-11-06T03:28:54Z | [
"python",
"generator"
] | In python, one can easily define an iterator function, by putting the yield keyword in the function's body, such as:
```
def gen():
for i in range(100):
yield i
```
How can I define a generator function that yields no value (generates 0 values), the following code doesn't work, since python cannot know th... | Python 3.3 (because I'm on a `yield from` kick, and because @senderle stole my first thought):
```
>>> def f():
... yield from ()
...
>>> list(f())
[]
```
But I have to admit, I'm having a hard time coming up with a use case for this for which `iter([])` or `(x)range(0)` wouldn't work equally well. |
Python Empty Generator Function | 13,243,766 | 41 | 2012-11-06T03:08:13Z | 17,288,868 | 9 | 2013-06-25T03:52:37Z | [
"python",
"generator"
] | In python, one can easily define an iterator function, by putting the yield keyword in the function's body, such as:
```
def gen():
for i in range(100):
yield i
```
How can I define a generator function that yields no value (generates 0 values), the following code doesn't work, since python cannot know th... | And another option is:
> (\_ for \_ in ()) |
Python Empty Generator Function | 13,243,766 | 41 | 2012-11-06T03:08:13Z | 26,271,684 | 22 | 2014-10-09T06:26:25Z | [
"python",
"generator"
] | In python, one can easily define an iterator function, by putting the yield keyword in the function's body, such as:
```
def gen():
for i in range(100):
yield i
```
How can I define a generator function that yields no value (generates 0 values), the following code doesn't work, since python cannot know th... | ```
iter(())
```
You don't *require* a generator. C'mon guys! |
Popen waiting for child process even when the immediate child has terminated | 13,243,807 | 8 | 2012-11-06T03:12:51Z | 13,256,908 | 7 | 2012-11-06T18:17:02Z | [
"python",
"subprocess",
"popen"
] | I'm working with Python 2.7 on Windows 8/XP.
I have a program A that runs another program B using the following code:
```
p = Popen(["B"], stdout=PIPE, stderr=PIPE)
stdout, stderr = p.communicate()
return
```
B runs a batch script C. C is a long running script and I want B to exit even though C has not finished. I h... | You could provide `start_new_session` analog for the `C` subprocess:
```
#!/usr/bin/env python
import os
import sys
import platform
from subprocess import Popen, PIPE
# set system/version dependent "start_new_session" analogs
kwargs = {}
if platform.system() == 'Windows':
# from msdn [1]
CREATE_NEW_PROCESS_GR... |
Redis Connection pool in python what am I doing wrong? | 13,245,889 | 2 | 2012-11-06T06:52:53Z | 13,665,251 | 17 | 2012-12-02T00:32:36Z | [
"python",
"redis"
] | Here is what I am doing. redis-py blows up when i do this.
```
Python 2.7.3 (default, Aug 1 2012, 05:16:07)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import redis
>>> p = redis.ConnectionPool()
>>> r = redis.Redis(connection_pool=p)
>>> p.release(r)
Traceback (mo... | OK since nobody responded to this question, I took some time and went through the redis-py source code (use the source luke!) and here is what I found. I will share it here in case someone else faces the same issue in the future.
The Redis() object returned by
```
r = redis.Redis(connection_pool=p)
```
does not repr... |
django database delete specific number of entries | 13,248,593 | 4 | 2012-11-06T09:59:45Z | 13,250,685 | 9 | 2012-11-06T12:05:38Z | [
"python",
"django",
"django-database"
] | How to delete specific number of entries from the database?
I did something like this
```
EntriesToDelete=Statusmessages.objects.filter(time__lt=date)[:30000]
EntriesToDelete.delete()
```
But I get an error which says:
`AssertionError. Cannot use 'limit' or 'offset' with delete`.
How can I specify the number of entr... | You could do it like this:
```
Statusmessages.objects.filter(pk__in=Statusmessages.objects.filter(time__lt=date).values_list('pk')[:30000]).delete()
``` |
Efficient & pythonic check for singular matrix | 13,249,108 | 7 | 2012-11-06T10:31:43Z | 13,264,934 | 9 | 2012-11-07T07:20:51Z | [
"python",
"numpy",
"linear-algebra"
] | Working on some matrix algebra here. Sometimes I need to invert a matrix that may be singular or ill-conditioned. I understand it is pythonic to simply do this:
```
try:
i = linalg.inv(x)
except LinAlgErr as err:
#handle it
```
but am not sure how efficient that is. Wouldn't this be better?
```
if linalg.con... | Your first solution catches the case where your matrix is so singular that numpy cannot cope at all - potentially quite an extreme case. Your second solution is better, because it catches the case where numpy gives an answer, but that answer is potentially corrupted by rounding error - this seems much more sensible.
I... |
Installing Pandas on Mac OSX | 13,249,135 | 8 | 2012-11-06T10:33:34Z | 13,252,767 | 8 | 2012-11-06T14:09:43Z | [
"python",
"pandas"
] | I'm having trouble installing the Python Pandas library on my Mac OSX computer.
I type the following in Terminal:
```
$ sudo easy_install pandas
```
But then I get the following:
```
Searching for pandas
Reading http://pypi.python.org/simple/pandas/
Reading http://pandas.pydata.org
Reading http://pandas.sourceforge... | You need to install XCode AND you need to make sure you install the **command line tools** for XCode so you can get gcc. |
Installing Pandas on Mac OSX | 13,249,135 | 8 | 2012-11-06T10:33:34Z | 21,649,359 | 9 | 2014-02-08T17:30:51Z | [
"python",
"pandas"
] | I'm having trouble installing the Python Pandas library on my Mac OSX computer.
I type the following in Terminal:
```
$ sudo easy_install pandas
```
But then I get the following:
```
Searching for pandas
Reading http://pypi.python.org/simple/pandas/
Reading http://pandas.pydata.org
Reading http://pandas.sourceforge... | Install `pip`.
Then install `pandas` with `pip`:
```
pip install pandas
``` |
Installing Pandas on Mac OSX | 13,249,135 | 8 | 2012-11-06T10:33:34Z | 22,848,472 | 7 | 2014-04-03T20:36:36Z | [
"python",
"pandas"
] | I'm having trouble installing the Python Pandas library on my Mac OSX computer.
I type the following in Terminal:
```
$ sudo easy_install pandas
```
But then I get the following:
```
Searching for pandas
Reading http://pypi.python.org/simple/pandas/
Reading http://pandas.pydata.org
Reading http://pandas.sourceforge... | You can install python with homebrew:
```
brew install python
```
Make sure that OSX uses the correct path:
```
which python
```
Then you can use the pip tool to install pandas:
```
pip install pandas
```
Make sure that all dependencies are installed. I followed this tutorial: <http://penandpants.com/2013/04/04/i... |
surpress scapy warning message when importing the module | 13,249,341 | 10 | 2012-11-06T10:45:44Z | 13,249,436 | 24 | 2012-11-06T10:52:17Z | [
"python",
"hide",
"stderr",
"scapy",
"output"
] | I'm writing a small script, that gathers some information using scapy and then returns some xml code, that I'll pass on to the xmlrpc interface of metasploit. I'd like it that my script only returns xml, and no additional warnings etc.
I can surpress most scapy output, with adding the option `verbose=0` to my sr1 comm... | You can get rid of warnings by scapy by adding:
```
logging.getLogger("scapy.runtime").setLevel(logging.ERROR)
```
**before** importing Scapy. This will suppress all messages that have a lower level of seriousness than error messages.
---
**for example:**
```
import logging
logging.getLogger("scapy.runtime").setLe... |
Dynamic import of several names from a module | 13,249,481 | 3 | 2012-11-06T10:54:54Z | 13,249,552 | 7 | 2012-11-06T10:59:58Z | [
"python"
] | I am trying to import some symbols from one package into another. I have tried the following, with no luck as both are syntax errors.
```
from signal import SIG*
```
or
```
import _signal
import _re
from signal import [i for i in dir(_signal) if _re.search("^SIG",i)!=None ]
```
Is there a way to do this. | Use [`importlib`](http://docs.python.org/2/library/importlib.html):
```
import importlib
mod = importlib.import_module('signal')
loc = locals()
for name in dir(mod):
if name.startswith('SIG'):
loc[name] = getattr(mod, name)
del mod, loc, importlib
``` |
Pandas csv-import: Keep leading zeros in a column | 13,250,046 | 12 | 2012-11-06T11:27:42Z | 27,144,549 | 7 | 2014-11-26T08:38:24Z | [
"python",
"pandas"
] | I am importing study data into a Pandas data frame using `read_csv`.
My subject codes are 6 numbers coding, among others, the day of birth. For some of my subjects this results in a code with a leading zero (e.g. "010816").
When I import into Pandas, the leading zero is stripped of and the column is formatted as `int... | As indicated in [this question/answer](http://stackoverflow.com/questions/16929056/pandas-read-csv-dtype-leading-zeros) by [Lev Landau](http://stackoverflow.com/users/2626623/lev-landau), there could be a simple solution to use `converters` option for a certain column in `read_csv` function.
```
converters={'column_na... |
Python check if all elements of a list are the same type | 13,252,333 | 10 | 2012-11-06T13:44:20Z | 13,252,348 | 44 | 2012-11-06T13:45:01Z | [
"python",
"list",
"types"
] | How is possible in python to check (without checking individually every element if possible) if the elements of a list are of the same type?
For example, I would like to have a function to check that every element of this list is integer (which is clearly false):
```
x=[1, 2.5, 'a']
def checkIntegers(x):
# retur... | Try using [`all`](http://docs.python.org/2/library/functions.html#all) in conjunction with [`isinstance`](http://docs.python.org/2/library/functions.html#isinstance):
```
all(isinstance(x, int) for x in lst)
```
You can even check for multiple types with `isinstance` if that is desireable:
```
all(isinstance(x, (int... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.