title stringlengths 12 150 | question_id int64 469 40.1M | question_score int64 2 5.52k | question_date stringdate 2008-08-02 15:11:16 2016-10-18 06:16:31 | answer_id int64 536 40.1M | answer_score int64 7 8.38k | answer_date stringdate 2008-08-02 18:49:07 2016-10-18 06:19:33 | tags listlengths 1 5 | question_body_md stringlengths 15 30.2k | answer_body_md stringlengths 11 27.8k |
|---|---|---|---|---|---|---|---|---|---|
How can I hex edit files in python2 byte by byte? | 12,445,043 | 3 | 2012-09-16T07:05:30Z | 12,445,127 | 7 | 2012-09-16T07:24:55Z | [
"python",
"hex"
] | I am trying to make a python script that will edit the hex value of the file that I load and I got stuck. How can I hex edit a file byte by byte in python?? | If the file is very large and you are doing only overwrite operations (no insertions or deletions), the [`mmap`](http://docs.python.org/library/mmap.html) module allows you to treat a file as essentially a large mutable string. This allows you to edit the contents of the file byte-by-byte, or edit whole slices, without... |
How can I get the href of elements found by partial link text? | 12,445,612 | 17 | 2012-09-16T09:00:24Z | 12,459,228 | 21 | 2012-09-17T12:32:43Z | [
"python",
"selenium",
"selenium-chromedriver"
] | Using Selenium and the Chrome Driver I do:
`links = browser.find_elements_by_partial_link_text('##')` matches about 160 links.
If I try,
```
for link in links:
print link.text
```
with it I get the text of all the links:
```
##1
##2
...
##160
```
The links are like this:
```
<a href="1.html">##1</a>
<a href=... | You simply need to call get\_attribute on each of the links you have found. So the following should work:
```
links = browser.find_elements_by_partial_link_text('##')
for link in links:
print link.get_attribute("href")
```
This should now output what you need. |
SQLAlchemy won't update my database | 12,446,220 | 9 | 2012-09-16T10:34:31Z | 12,446,234 | 22 | 2012-09-16T10:36:48Z | [
"python",
"sqlalchemy",
"pyramid",
"python-3.2"
] | I'm making a Pyramid app using SQLAlchemy-0.7.8. I'm using 64bit Python3.2.
The question is, why does the following function not commit anything to the database?
```
def create_card(sText,sCard):
"""
create a wildcard instance if all is well (ie,sCard match in sText)
return
oCard, dCard
other... | You need to *commit* your transaction.
You can do this explicitly (by calling `DBSession.commit()` or by using the [`pyramid_tm` middleware](http://docs.pylonsproject.org/projects/pyramid_tm/en/latest/); the latter commits transactions automatically on successful responses (with a 2xx HTTP response).
The latter only ... |
why __getitem__ cannot be classmethod? | 12,447,036 | 13 | 2012-09-16T12:56:56Z | 12,447,071 | 8 | 2012-09-16T13:02:48Z | [
"python",
"class-method"
] | Suppose following class:
```
class Class(object):
@classmethod
def getitem(*args):
print 'getitem %s' % (args,)
@classmethod
def __getitem__(*args):
print '__getitem__ %s' % (args,)
```
The getitem method behaves as expected: it receives `Class` as first arg, but `__getitem__` receives... | When you call `x[test]`, the interpreter inspects `type(x)` for the `__getitem__` attribute. In case of `Class[test]` it's the `Class`'s metaclass, i.e. `type`. If you want to have a class-wide `__getitem__`, define it inside a new metaclass. (Needless to say, that's a sort of magic, as anything you do with metaclasses... |
why __getitem__ cannot be classmethod? | 12,447,036 | 13 | 2012-09-16T12:56:56Z | 12,447,078 | 18 | 2012-09-16T13:03:45Z | [
"python",
"class-method"
] | Suppose following class:
```
class Class(object):
@classmethod
def getitem(*args):
print 'getitem %s' % (args,)
@classmethod
def __getitem__(*args):
print '__getitem__ %s' % (args,)
```
The getitem method behaves as expected: it receives `Class` as first arg, but `__getitem__` receives... | Special methods are looked up on the class, and not on the instance - unlike regular methods that are looked up on the instance first. See [Special method lookup](http://docs.python.org/reference/datamodel.html#special-method-lookup-for-new-style-classes) in the Python data model docs.
Thinking about `Class` as an ins... |
Pythonic way to "merge" two lists to a list of tuples | 12,447,500 | 3 | 2012-09-16T14:03:12Z | 12,447,520 | 8 | 2012-09-16T14:05:15Z | [
"python",
"list"
] | Suppose I have two lists
`L1 = [1,2,3]`
and
`L2 = [a,b,c]`
Whats the fastest way to convert this to the list `M = [(1,a),(2,b),(3,c)]`?
I tried `M = [(x,y) for x in L1 for y in L2]` but this gives me all possible combination of elements. Sure I can write a loop to do it, but is there a more pythonic way to do this... | Use [`zip()`](http://docs.python.org/library/functions.html#zip).
> This function returns a list of tuples, where the *i*-th tuple contains
> the *i*-th element from each of the argument sequences or iterables. The
> returned list is truncated in length to the length of the shortest
> argument sequence.
```
>> zip([1... |
Compiler Python, why are some wrong things overlooked? | 12,447,703 | 2 | 2012-09-16T14:30:29Z | 12,447,731 | 8 | 2012-09-16T14:33:31Z | [
"python",
"compiler-construction",
"compilation",
"interpreter"
] | I wrote a Python routine with a mistake in it: `false` instead of `False`. However, it was not discovered at compilation. The program had to run until this line to notify the wrongdoing.
Why is it so? What in the Python interpreter/compiler things make it work so?
Do you have some reference? | Due to Python's dynamic nature, it is impossible to detect undefined names at compile time. Only the syntax is checked; if the syntax is fine, the compiler generates the bytecode, and Python starts to execute the code.
In the given example, you will get a reference to a global name `false`. Only when the bytecode inte... |
Finding a Eulerian Tour | 12,447,880 | 5 | 2012-09-16T14:52:10Z | 12,458,027 | 7 | 2012-09-17T11:12:47Z | [
"python",
"algorithm",
"graph",
"discrete-mathematics"
] | I am trying to solve a problem on Udacity described as follows:
```
# Find Eulerian Tour
#
# Write a function that takes in a graph
# represented as a list of tuples
# and return a list of nodes that
# you would follow on an Eulerian Tour
#
# For example, if the input graph was
# [(1, 2), (2, 3), (3, 1)]
# A possible ... | Here's a valid case where your algorithm fails:
```
graph = [(1, 2), (2, 3), (3, 1), (3, 4), (4, 3)]
```
Use the power of `print` to find out what happens to `graph` and `current_vertex`.
Another hint: Move the `else` down so that it belongs to the `for` and is executed when the `for` loop is not broken. As it is no... |
Confused about __str__ in Python | 12,448,175 | 43 | 2012-09-16T15:30:27Z | 12,448,198 | 8 | 2012-09-16T15:33:16Z | [
"python",
"string",
"object",
"printing",
"tostring"
] | Coming from a Java background, I understand that `__str__` is something like a Python version of toString (while I do realize that Python is the older language).
So, I have defined a little class along with an `__str__` method as follows:
```
class Node:
def __init__(self, id):
self.id = id
self.... | Well, container objects' `__str__` methods will use `repr` on their contents, not `str`. So you could use `__repr__` instead of `__str__`, seeing as you're using an ID as the result. |
Confused about __str__ in Python | 12,448,175 | 43 | 2012-09-16T15:30:27Z | 12,448,200 | 49 | 2012-09-16T15:33:30Z | [
"python",
"string",
"object",
"printing",
"tostring"
] | Coming from a Java background, I understand that `__str__` is something like a Python version of toString (while I do realize that Python is the older language).
So, I have defined a little class along with an `__str__` method as follows:
```
class Node:
def __init__(self, id):
self.id = id
self.... | Python has two different ways to convert an object to a string: `str()` and `repr()`. Printing an object uses `str()`; printing a list containing an object uses `str()` for the list itself, but the implementation of `list.__str__()` calls `repr()` for the individual items.
So you should also overwrite `__repr__()`. A ... |
Confused about __str__ in Python | 12,448,175 | 43 | 2012-09-16T15:30:27Z | 12,448,230 | 11 | 2012-09-16T15:37:38Z | [
"python",
"string",
"object",
"printing",
"tostring"
] | Coming from a Java background, I understand that `__str__` is something like a Python version of toString (while I do realize that Python is the older language).
So, I have defined a little class along with an `__str__` method as follows:
```
class Node:
def __init__(self, id):
self.id = id
self.... | Because of the infinite superiority of Python over Java, Python has not *one*, but *two* toString operations.
One is `__str__`, the other is `__repr__`
`__str__` will return a human readable string.
`__repr__` will return an internal representation.
`__repr__` can be invoked on an object by calling `repr(obj)` or by... |
"This constructor takes no arguments" error in __init__ | 12,448,414 | 11 | 2012-09-16T16:03:13Z | 12,448,441 | 24 | 2012-09-16T16:05:12Z | [
"python",
"python-3.x"
] | I'm getting an error while running the following code:
```
class Person:
def _init_(self, name):
self.name = name
def hello(self):
print 'Initialising the object with its name ', self.name
p = Person('Constructor')
p.hello()
```
The output is:
```
Traceback (most recent call last):
File "./class_in... | The method should be named `__init__` to be a constructor, not `_init_`. (Note the double underscores.)
If you use single underscores, you merely create a method named `_init_`, and get a default constructor, which takes no arguments. |
How to add delta to python datetime.time? | 12,448,592 | 14 | 2012-09-16T16:24:21Z | 12,448,721 | 23 | 2012-09-16T16:42:57Z | [
"python",
"datetime",
"time",
"timedelta"
] | From:
<http://docs.python.org/py3k/library/datetime.html#timedelta-objects>
> A timedelta object represents a duration, the difference between two
> dates or times.
So why i get error with this:
```
>>> from datetime import datetime, timedelta, time
>>> datetime.now() + timedelta(hours=12)
datetime.datetime(2012, 9... | `datetime.time` objects do not support addition with `datetime.timedelta`s.
There is one natural definition though, clock arithmetic.
You could compute it like this:
```
import datetime as dt
now = dt.datetime.now()
delta = dt.timedelta(hours = 12)
t = now.time()
print(t)
# 12:39:11.039864
print((dt.datetime.combine... |
Difference between django-webtest and selenium | 12,448,878 | 8 | 2012-09-16T17:05:49Z | 12,461,794 | 7 | 2012-09-17T14:48:38Z | [
"python",
"django",
"selenium",
"django-forms",
"django-testing"
] | I have been reading about testing in django. One thing that was recommended was use of django-webtest for functional testing. I found a decent article [here](http://blog.fruiapps.com/2012/08/Functional-Testing-with-Selenium-WebDriver-and-Selector-in-Python) that teaches how to go about functional testing in selenium us... | The important thing to know about Selenium is that it's primarily built to be a server-agnostic testing framework. It doesn't matter what framework or server-side implementation is used to create the front-end as long as it behaves as expected. Also, while you *can* (and when possible you probably *should*) write tests... |
Difference between django-webtest and selenium | 12,448,878 | 8 | 2012-09-16T17:05:49Z | 12,552,319 | 18 | 2012-09-23T12:18:18Z | [
"python",
"django",
"selenium",
"django-forms",
"django-testing"
] | I have been reading about testing in django. One thing that was recommended was use of django-webtest for functional testing. I found a decent article [here](http://blog.fruiapps.com/2012/08/Functional-Testing-with-Selenium-WebDriver-and-Selector-in-Python) that teaches how to go about functional testing in selenium us... | The key difference is that selenium runs an actual browser, while WebTest hooks to the WSGI.
This results in the following differences:
* You can't test JS code with WebTest, since there is nothing to run it.
* WebTest is much faster since it hooks to the WSGI, this also means a smaller memory footprint
* WebTest does... |
How to debug gunicorn failure issues? (Worker failed to boot) | 12,449,172 | 17 | 2012-09-16T17:42:02Z | 12,982,084 | 20 | 2012-10-19T20:36:10Z | [
"python",
"django",
"gunicorn"
] | I have a Django web application that uses Gunicorn and runs good locally, but when I deploy app on EC2, I see that Gunicorn is failing:
> ```
> $ gunicorn_django -b 127.0.0.1:8000 --settings=myapp.settings.dev --debug --log-level info
> 2012-09-16 17:39:24 [28333] [INFO] Starting gunicorn 0.14.6
> 2012-09-16 17:39:24 ... | You need `--debug --log-level debug` |
How to debug gunicorn failure issues? (Worker failed to boot) | 12,449,172 | 17 | 2012-09-16T17:42:02Z | 22,981,212 | 8 | 2014-04-10T07:18:29Z | [
"python",
"django",
"gunicorn"
] | I have a Django web application that uses Gunicorn and runs good locally, but when I deploy app on EC2, I see that Gunicorn is failing:
> ```
> $ gunicorn_django -b 127.0.0.1:8000 --settings=myapp.settings.dev --debug --log-level info
> 2012-09-16 17:39:24 [28333] [INFO] Starting gunicorn 0.14.6
> 2012-09-16 17:39:24 ... | Try running with `--preload` as an argument to `gunicorn_django` - it should show you the error the workers are having when starting. See [this bug](https://github.com/benoitc/gunicorn/issues/338#issuecomment-7425197) |
Python string replacement with random items | 12,449,555 | 8 | 2012-09-16T18:34:30Z | 12,449,623 | 9 | 2012-09-16T18:42:39Z | [
"python",
"regex",
"string"
] | [String replacement in Python](http://docs.python.org/library/string.html) is not difficult, but I want to do something special:
```
teststr = 'test test test test'
animals = ['bird','monkey','dog','fox']
#replace 'test' with random item from animals
finalstr = ['dog fox dog monkey']
```
I write a very inefficient ve... | Use a [re.sub callback](http://docs.python.org/library/re.html#re.sub):
```
import re
import random
animals = ['bird','monkey','dog','fox']
def callback(matchobj):
return random.choice(animals)
teststr = 'test test test test'
ret = re.sub(r'test', callback, teststr)
print(ret)
```
yields (for example)
```
bir... |
Loading and parsing a JSON file in Python | 12,451,431 | 48 | 2012-09-16T23:00:56Z | 12,451,465 | 100 | 2012-09-16T23:08:23Z | [
"python",
"json",
"jsonlines"
] | I am trying to load and parse a JSON file in [Python](http://en.wikipedia.org/wiki/Python_%28programming_language%29). But I'm stuck trying to load the file:
```
import json
json_data = open('file')
data = json.load(json_data)
```
Yields:
```
ValueError: Extra data: line 2 column 1 - line 225116 column 1 (char 232 -... | You have a [JSON Lines format text file](http://jsonlines.org/). You need to parse your file line by line:
```
import json
data = []
with open('file') as f:
for line in f:
data.append(json.loads(line))
```
Each *line* contains valid JSON, but as a whole, it is not a valid JSON value as there is no top-le... |
Python Try Catch Block inside lambda | 12,451,531 | 19 | 2012-09-16T23:22:24Z | 12,451,537 | 23 | 2012-09-16T23:23:24Z | [
"python",
"lambda"
] | Is it possible to use try catch block inside of a lambda function. I need the lambda function to convert a certain variable into an integer, but not all of the values will be able to be converted into integers. | Nope. A Python lambda can only be a single expression. Use a named function.
It is convenient to write a generic function for converting types:
```
def tryconvert(value, default, *types):
for t in types:
try:
return t(value)
except ValueError, TypeError:
continue
return... |
Python Try Catch Block inside lambda | 12,451,531 | 19 | 2012-09-16T23:22:24Z | 12,451,551 | 7 | 2012-09-16T23:25:15Z | [
"python",
"lambda"
] | Is it possible to use try catch block inside of a lambda function. I need the lambda function to convert a certain variable into an integer, but not all of the values will be able to be converted into integers. | In this specific instance, you can avoid using a `try` block like this:
```
lambda s: int(s) if s.isdigit() else 0
```
The [`isdigit()` string method](http://docs.python.org/library/stdtypes.html#str.isdigit) returns true if *all* the characters of `s` are digits. (If you need to accept negative numbers, you will hav... |
Get the number of nonzero elements in a numpy array? | 12,451,954 | 3 | 2012-09-17T00:43:56Z | 12,451,985 | 9 | 2012-09-17T00:49:58Z | [
"python",
"numpy"
] | Is it possible to get the length of the nonzero elements in a numpy array without iterating over the array or masking the array. Speed is the main goal of calculating the length.
Essentially, something like `len(array).where(array != 0)`.
If it changes the answer, each row will begin with zeros. The array is filled o... | Assuming you mean total number of nonzero elements (and not total number of nonzero rows):
```
In [12]: a = np.random.randint(0, 3, size=(100,100))
In [13]: timeit len(a.nonzero()[0])
1000 loops, best of 3: 306 us per loop
In [14]: timeit (a != 0).sum()
10000 loops, best of 3: 46 us per loop
```
or even better:
``... |
replacing lines with elements from a list | 12,452,218 | 3 | 2012-09-17T01:41:38Z | 12,452,233 | 7 | 2012-09-17T01:44:39Z | [
"python"
] | I am reading a file and looking for a particular string in it like this :
```
template = open('/temp/template.txt','r')
new_elements = ["movie1","movies2"]
for i in template.readlines():
if "movie" in i:
print "replace me"
```
This is all good but I would like to replace the lines that are found with the... | One way is to make `new_elements` an iterator:
```
template = open('/temp/template.txt','r')
new_elements = iter(["movie1","movies2"])
for i in template.readlines():
if "movie" in i:
print "replace line with", new_elements.next()
```
You haven't said how you want to do the replacement- whether you want t... |
Go - What is the equivalent of Python's "pass"? | 12,452,254 | 4 | 2012-09-17T01:48:30Z | 12,452,332 | 7 | 2012-09-17T02:00:28Z | [
"python",
"select",
"go"
] | I have a default cause in a select statement that I want to do nothing, just continue, but leaving the line blank stops anything in the statement from happening
```
select {
case quit_status := <-quit:
if quit_status == true {
fmt.Printf("********************* GOROUTINE [%d]... | The `default` case in a `select` statement is intended to provide non-blocking I/O for channel reads and writes. The code in the `default` case is executed whenever none of the channels in any of the cases are ready to be read/written to.
So in your case, the `default` block is executed if the quit channel has nothing... |
Fastest way to count number of occurrences in a Python list | 12,452,678 | 15 | 2012-09-17T03:02:24Z | 12,452,684 | 32 | 2012-09-17T03:03:54Z | [
"python",
"list",
"repetition"
] | I have a Python list and I want to know what's the quickest way to count the number of occurrences of the item, `'1'` in this list. In my actual case, the item can occur tens of thousands of times which is why I want a fast way.
```
['1', '1', '1', '1', '1', '1', '2', '2', '2', '2', '7', '7', '7', '10', '10']
```
Doe... | ```
a = ['1', '1', '1', '1', '1', '1', '2', '2', '2', '2', '7', '7', '7', '10', '10']
print a.count("1")
```
It's probably optimized heavily at the C level.
Edit: I randomly generated a large list.
```
In [8]: len(a)
Out[8]: 6339347
In [9]: %timeit a.count("1")
10 loops, best of 3: 86.4 ms per loop
```
Edit edit: ... |
Concatenate item in list to strings | 12,453,580 | 111 | 2012-09-17T05:32:25Z | 12,453,584 | 213 | 2012-09-17T05:33:41Z | [
"python",
"string",
"list",
"join",
"concatenation"
] | Is there a simpler way to concatenate string items in list into a single string?
Can I use the `str.join()` function to join items in list?
E.g. this is the input `['this','is','a','sentence']` and this is the desired output `this-is-a-sentence`
```
sentence = ['this','is','a','sentence']
sent_str = ""
for i in sent... | Use [`join`](http://docs.python.org/library/stdtypes.html#str.join):
```
>>> sentence = ['this','is','a','sentence']
>>> '-'.join(sentence)
'this-is-a-sentence'
``` |
Concatenate item in list to strings | 12,453,580 | 111 | 2012-09-17T05:32:25Z | 34,011,944 | 18 | 2015-12-01T03:11:58Z | [
"python",
"string",
"list",
"join",
"concatenation"
] | Is there a simpler way to concatenate string items in list into a single string?
Can I use the `str.join()` function to join items in list?
E.g. this is the input `['this','is','a','sentence']` and this is the desired output `this-is-a-sentence`
```
sentence = ['this','is','a','sentence']
sent_str = ""
for i in sent... | A more generic way to convert python lists to strings would be:
```
>>> my_lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> my_lst_str = ''.join(map(str, my_lst))
>>> print(my_lst_str)
'12345678910'
``` |
Python - Removing punctuation from a list | 12,453,595 | 2 | 2012-09-17T05:34:57Z | 12,453,622 | 9 | 2012-09-17T05:37:11Z | [
"python",
"python-3.x"
] | I need to remove the punc from a text file.
The text file is like this
> ffff, hhhh, & tommorw home,
> Have you from gone?
I am trying
> punc=(",./;'?&-")
>
> f = open('file.txt', 'r')
>
> ```
> for line in f:
> strp=line.replace(punc,"")
> print(strp)
> ```
I need the output to be:
> ffff hhhh tommorw ... | Use `str.translate` to delete characters from a string.
In Python 2.x:
```
# first arg is translation table, second arg is characters to delete
strp = line.translate(None, punc)
```
In Python 3:
```
# translation table maps code points to replacements, or None to delete
transtable = {ord(c): None for c in punc}
str... |
What's the return value of Socket.accept() in python | 12,454,675 | 12 | 2012-09-17T07:17:35Z | 12,454,722 | 12 | 2012-09-17T07:21:17Z | [
"python",
"sockets",
"network-programming"
] | I made a simple server and a simple client with `socket` module in python.
server:
```
# server.py
import socket
s = socket.socket()
host = socket.gethostname()
port = 1234
s.bind((host, port))
s.listen(5)
while True:
c, addr = s.accept()
print 'Got connection from', addr
c.send('Thank you for your con... | From the [`socket` documentation](http://docs.python.org/library/socket.html):
> A pair (host, port) is used for the AF\_INET address family, where host is a string representing either a hostname in Internet domain notation like 'daring.cwi.nl' or an IPv4 address like '100.50.200.5', and port is an integer.
So the se... |
Checking for the existence of a key in request.args in Flask | 12,455,484 | 6 | 2012-09-17T08:21:35Z | 12,455,908 | 15 | 2012-09-17T08:53:28Z | [
"python",
"flask"
] | I am using Flask.
I am doing a ajax post and I need to check for existence if keys.
I tried this but did not work.
```
if request.args.has_key('campaign_id_crid'):
print True
```
What is a better way to test? | Your example works fine (once an `if` is added to the start anyway...)
Anyway, although `dict.has_key` is still about (in existing 2.x code - but removed in Python 3), it's generally considered more Pythonic to use the `in` operator such as:
```
if 'campaign_id_crid' in request.args:
pass # do something
``` |
Is it possible to generate correct PKCS12 (.pfx) file in Python? | 12,456,453 | 3 | 2012-09-17T09:27:34Z | 12,456,912 | 7 | 2012-09-17T09:55:47Z | [
"python",
"cryptography",
"openssl"
] | I need to generate a PKCS12 file in python that will contain self-signed certificate and private key for it. I assembled the following python code for this task:
```
import OpenSSL
key = OpenSSL.crypto.PKey()
key.generate_key( OpenSSL.crypto.TYPE_RSA, 1024 )
cert = OpenSSL.crypto.X509()
cert.set_serial_number(0)
cert.... | I have an assumption, that you need to open `container.pfx` in binary mode:
```
open( "container.pfx", 'wb' ).write( p12.export() )
``` |
XML header getting removed after processing with elementtree | 12,457,400 | 4 | 2012-09-17T10:27:57Z | 12,457,501 | 7 | 2012-09-17T10:33:59Z | [
"python",
"elementtree"
] | i have an xml file and i used Elementtree to add a new tag to the xml file.My xml file before processing is as follows
```
<?xml version="1.0" encoding="utf-8"?>
<PackageInfo xmlns="http://someurlpackage">
<data ID="http://someurldata1">data1</data >
<data ID="http://someurldata2">data2</data >
<data ID="http://som... | It looks like you need optional arguments to the `write` method to output the declaration.
<http://docs.python.org/library/xml.etree.elementtree.html#elementtree-elementtree-objects>
```
tree.write(xmlfile,xml_declaration=True)
```
---
I'm afraid I'm not that familiar with `xml.etree.ElementTree` and it's variation... |
Shutting down sockets properly | 12,458,019 | 2 | 2012-09-17T11:12:17Z | 12,458,069 | 8 | 2012-09-17T11:15:28Z | [
"python",
"sockets"
] | I'm trying to make a server / client connection with sockets. But they will not close properly and I can't wrap my head around why.
### Update 1
I've corrected my stupid misstake below of not actually CALLING the s.close function in the question.
But it turn out this was'nt my problem.
### End of updates
This is my... | ```
s.close # Close the socket when done
```
Sticks out to my eyes because you don't actually CALL anything, you should try `s.close()` |
Shutting down sockets properly | 12,458,019 | 2 | 2012-09-17T11:12:17Z | 12,458,083 | 8 | 2012-09-17T11:16:12Z | [
"python",
"sockets"
] | I'm trying to make a server / client connection with sockets. But they will not close properly and I can't wrap my head around why.
### Update 1
I've corrected my stupid misstake below of not actually CALLING the s.close function in the question.
But it turn out this was'nt my problem.
### End of updates
This is my... | you need `socket.socket.setsockopt`, .i.e `s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)`
Though the socket will be closed by the os when process ended, it is a good behavior to call close() explicitly.
However, after that, the local addr(local\_ip, local\_port) is not avaiable until 2 `MSL(maximum segment l... |
Convert timestamp since epoch to datetime.datetime | 12,458,595 | 25 | 2012-09-17T11:50:41Z | 12,458,703 | 27 | 2012-09-17T11:58:25Z | [
"python"
] | I have the following timestamps since epoch:
```
Timestamp
1346114717972
1354087827000
```
How can I convert these timestamps to some specific output format, e.g., `mm/dd/yyyy hr:min:sec`?
I have tried to convert them to `datetime.datetime` but it failed:
```
>>> datetime.datetime.fromtimestamp(1346114717972)
Tra... | I would use the `time` module
```
>>> import time
>>> time.gmtime(1346114717972/1000.)
time.struct_time(tm_year=2012, tm_mon=8, tm_mday=28, tm_hour=0, tm_min=45, tm_sec=17, tm_wday=1, tm_yday=241, tm_isdst=0)
```
the timestamp is divided by 1000 as the stamps you have provided are in **milliseconds** since the epoch,... |
Convert timestamp since epoch to datetime.datetime | 12,458,595 | 25 | 2012-09-17T11:50:41Z | 12,458,763 | 15 | 2012-09-17T12:03:12Z | [
"python"
] | I have the following timestamps since epoch:
```
Timestamp
1346114717972
1354087827000
```
How can I convert these timestamps to some specific output format, e.g., `mm/dd/yyyy hr:min:sec`?
I have tried to convert them to `datetime.datetime` but it failed:
```
>>> datetime.datetime.fromtimestamp(1346114717972)
Tra... | I assume this is millisecond resolution:
```
import datetime
s = '1346114717972'
t = datetime.datetime.fromtimestamp(float(s)/1000.)
fmt = "%Y-%m-%d %H:%M:%S"
print t.strftime(fmt)
# prints 2012-08-28 02:45:17
```
Adapting the format string to this specific case is left as an excercise to the reader.
Have a look at... |
Max in a list with two conditions | 12,459,656 | 4 | 2012-09-17T12:55:06Z | 12,459,675 | 11 | 2012-09-17T12:56:27Z | [
"python",
"list",
"max"
] | I have a list in Python in which each element is a tuple like this:
```
(attr1, attr2, attr3)
```
I want to find the tuple that has the largest `attr2`, but that have `attr3 >= 100`.
What is the pythonic approach to this?
Thanks | You have to both filter and use a `key` argument to max:
```
from operator import itemgetter
max(filter(lambda a: a[2] >= 100, yourlist), key=itemgetter(1))
```
The filter can also be expressed as a generator expression:
```
max((t for t in yourlist if t[2] >= 100), key=itemgetter(1))
```
Demo:
```
>>> yourlist =... |
How to embed matplotib in pyqt - for Dummies | 12,459,811 | 32 | 2012-09-17T13:04:39Z | 12,465,861 | 55 | 2012-09-17T19:26:05Z | [
"python",
"matplotlib",
"pyqt4"
] | I am currently trying to embed a graph I want to plot in a pyqt4 user interface I designed. As I am almost completely new to programming - I do not get how people did the embedding in the examples I found - [this one (at the bottom)](http://www.python-forum.de/viewtopic.php?f=24&t=22673) and [that one](http://eli.thegr... | It is not that complicated actually. Relevant Qt widgets are in [`matplotlib.backends.backend_qt4agg`](http://matplotlib.org/api/backend_qt4agg_api.html). `FigureCanvasQTAgg` and `NavigationToolbar2QTAgg` are usually what you need. These are regular Qt widgets. You treat them as any other widget. Below is a very simple... |
Why is function not working? Trying to replace words in string | 12,460,959 | 2 | 2012-09-17T14:03:07Z | 12,460,993 | 8 | 2012-09-17T14:05:10Z | [
"python",
"string"
] | I am trying to replace some key words in a string. Here is my function:
```
def clean_code(input):
input.replace('<script>', " ")
input.replace('</script>', " ")
input.replace('<a href>', " ")
input.replace('</a>', " ")
input.replace('>', ">")
input.replace('>', "<")
return input
```
... | Python strings are **immutable**:
```
input = input.replace('<script>', " ")
input = ...
```
See [`replace` documentation](http://docs.python.org/library/string.html#string.replace):
> **Return a copy of string str** with all occurrences of substring old replaced by new. |
argparse: How can I allow multiple values to override a default | 12,460,989 | 10 | 2012-09-17T14:05:02Z | 12,461,237 | 7 | 2012-09-17T14:17:45Z | [
"python",
"python-3.x",
"default-value",
"argparse"
] | This is slightly related to the topic covered in a [question about allowing an argument to be specified multiple times](http://stackoverflow.com/questions/5176846/why-does-argparse-give-me-a-list-in-a-list).
**I'd like to be able to specify an option multiple times like this:**
```
tool --foo 1 --foo 2 --foo 3
```
... | I think this is a slightly more clean variation on the other answer (relying on the `self.default` attribute of custom actions):
```
import argparse
import sys
class Extender(argparse.Action):
def __call__(self,parser,namespace,values,option_strings=None):
#Need None here incase `argparse.SUPPRESS` was su... |
Bits list to integer in Python | 12,461,361 | 10 | 2012-09-17T14:23:44Z | 12,461,400 | 22 | 2012-09-17T14:25:16Z | [
"python",
"arrays",
"list",
"bit-manipulation"
] | I have such list in Python: `[1,0,0,0,0,0,0,0]`. Can I convert it to integer like as I've typed 0b10000000 (i.e. convert to 128)?
I need also to convert sequences like `[1,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0]` to integers (here it will return 0b1100000010000000, i.e. 259).
Length of list is always a multiple of 8, if it is n... | You can use bitshifting:
```
out = 0
for bit in bitlist:
out = (out << 1) | bit
```
This easily beats the "int cast" method proposed by A. R. S., or the modified cast with lookup proposed by Steven Rumbalski:
```
>>> def intcaststr(bitlist):
... return int("".join(str(i) for i in bitlist), 2)
...
>>> def in... |
Bits list to integer in Python | 12,461,361 | 10 | 2012-09-17T14:23:44Z | 12,461,546 | 9 | 2012-09-17T14:33:45Z | [
"python",
"arrays",
"list",
"bit-manipulation"
] | I have such list in Python: `[1,0,0,0,0,0,0,0]`. Can I convert it to integer like as I've typed 0b10000000 (i.e. convert to 128)?
I need also to convert sequences like `[1,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0]` to integers (here it will return 0b1100000010000000, i.e. 259).
Length of list is always a multiple of 8, if it is n... | ...or using the [bitstring](http://packages.python.org/bitstring/index.html#) module
```
>>> from bitstring import BitArray
>>> bitlist=[1,0,0,0,0,0,0,0]
>>> b = BitArray(bitlist)
>>> b.uint
128
``` |
Setting up setup.py for packaging of a single .py file and a single data file without needing to create any folders | 12,461,603 | 15 | 2012-09-17T14:37:19Z | 12,462,083 | 9 | 2012-09-17T15:04:18Z | [
"python",
"packaging",
"setup.py"
] | **Project tree:**
```
$.
âââ happy_birthday-art.txt
âââ happy_birthday.py
âââ MANIFEST.in
âââ README.rst
âââ setup.py
```
**setup.py**
```
from setuptools import setup
setup(
name='Happy_birthday',
py_modules=['happy_birthday'],
data_files=['happy_birthday-art.txt'],
en... | If you have a single-file module like this, no folder will be created, your `.py` file will be moved directly into the directory which contains the other python modules (`/usr/lib/pythonX.X/site-packages/`, for example). That's why you *have* to create a directory:
```
$ .
|-- happy_birthday/
|-- __init__.py
|... |
How to use regexp function in sqlite with sqlalchemy? | 12,461,814 | 4 | 2012-09-17T14:49:19Z | 12,474,979 | 7 | 2012-09-18T10:18:15Z | [
"python",
"regex",
"sqlalchemy"
] | I'd like to use regexp query in "sqlalchemy" as well as is done in "python sqlite", code below..
Unfinished sandbox script is this:
```
import os
import re
import sqlite3
#
# python sqlite
#
DB_PATH = __name__ + '.db'
try:
os.remove(DB_PATH)
except:
pass
def re_fn(expr, item):
reg = re.compile(expr, ... | I've got the answer..
Complete working script with missing one line is this:
```
import os
import re
import sqlite3
DB_PATH = __name__ + '.db'
try:
os.remove(DB_PATH)
except:
pass
def re_fn(expr, item):
reg = re.compile(expr, re.I)
return reg.search(item) is not None
conn = sqlite3.connect(':memor... |
What to do first: Feature Selection or Model Parameters Setting? | 12,462,410 | 10 | 2012-09-17T15:24:36Z | 12,473,032 | 12 | 2012-09-18T08:22:52Z | [
"python",
"machine-learning",
"scikit-learn",
"feature-selection"
] | This is more of a "theoretical" question. I'm working with the scikit-learn package to perform some NLP task. Sklearn provides many methods to perform both feature selection and setting of a model parameters. I'm wondering what I should do first.
If I use [univariate feature selection](http://scikit-learn.org/stable/m... | Personally I think RFE is overkill and too expensive in most cases. If you want to do feature selection on linear models, use univariate feature selection, for instance with chi2 tests or L1 or L1 + L2 regularized models with grid searched regularization parameter (usually named `C` or `alpha` in sklearn models).
For ... |
numpy.getbuffer and numpy.frombuffer | 12,462,547 | 5 | 2012-09-17T15:32:24Z | 12,462,633 | 13 | 2012-09-17T15:38:19Z | [
"python",
"numpy",
"buffer"
] | I am trying to wrap my head around the numpy implementation of PEP3118. How exactly does buffer access work in numpy.
```
>>> p = numpy.getbuffer(numpy.arange(10))
>>> p
<read-write buffer for 0x1003e5b10, size -1, offset 0 at 0x1016ab4b0>
>>> numpy.frombuffer(p)
array([ 0.00000000e+000, 4.94065646e-324, 9.881312... | You have a simple `dtype` problem. The buffer you create with
```
np.getbuffer(np.arange(10))
```
has a `dtype=int`, because `np.arange` uses `dtype=int` by default.
Then, when you try to read your buffer with
```
np.frombuffer(p)
```
you're in fact using the `dtype=float` default of `np.frombuffer`. Instead, use
... |
Loaddata not dealing with timestamps and timezones properly | 12,462,634 | 4 | 2012-09-17T15:38:23Z | 13,403,929 | 7 | 2012-11-15T18:35:32Z | [
"python",
"django",
"yaml"
] | I'm using django 1.4.1 with mysql and timezones enabled. I did a dump data to yaml, modified some fields to create some test data, and am trying to load it back in. however, Django keeps complaining about naive datetimes even though a tz is specified
specifically, my loaddata has:
```
fields: {created_date: !!timesta... | From the [docs](https://docs.djangoproject.com/en/dev/topics/i18n/timezones/#fixtures)...
> When serializing an aware datetime, the UTC offset is included, like
> this:
>
> ```
> "2011-09-01T13:20:30+03:00"
> ```
>
> For a naive datetime, it obviously isn't:
>
> ```
> "2011-09-01T13:20:30"
> ```
...so instead of...
... |
Loaddata not dealing with timestamps and timezones properly | 12,462,634 | 4 | 2012-09-17T15:38:23Z | 13,711,316 | 14 | 2012-12-04T20:28:29Z | [
"python",
"django",
"yaml"
] | I'm using django 1.4.1 with mysql and timezones enabled. I did a dump data to yaml, modified some fields to create some test data, and am trying to load it back in. however, Django keeps complaining about naive datetimes even though a tz is specified
specifically, my loaddata has:
```
fields: {created_date: !!timesta... | The problem stems from PyYAML. When loaddata hands off the datetime to PyYAML, it takes the aware datetime, adjusts the time to UTC, and then returns a naive datetime, which generates the warning.
There is a [Django ticket](https://code.djangoproject.com/ticket/18867), as well as a [PyYAML ticket](http://pyyaml.org/ti... |
Truth tables in python using sympy | 12,462,747 | 6 | 2012-09-17T15:45:10Z | 12,463,178 | 7 | 2012-09-17T16:10:38Z | [
"python",
"symbolic-computation"
] | I'm trying to create a program, that uses sympy to take a set of variables and evaluate a symbolic logic expression over the domain of those variables. The problem is that I cannot get python to evaluate the expression after it spits out the truth table.
Here's the code:
```
from sympy import *
from sympy.abc imp... | You're really close! Once you've got `And(p, q, r)` and your truth tables, you can use the `subs` method to push your `values` dict into the expression: i.e.
```
yield cond + [eval(expr).subs(values)]
```
gives
```
p&q&r
recieved input: ['p', 'q', 'r'] expr p&q&r
Truth table for 3variable(s)
(0, [True, True, Tru... |
Elegant way to calculate first generator result larger than X | 12,463,375 | 2 | 2012-09-17T16:24:05Z | 12,463,420 | 8 | 2012-09-17T16:26:38Z | [
"python",
"generator"
] | I have a generator and would like to find out what the first value which it generates larger than X. One way to do this is as follows, but it seems rather long-winded (it reads like it repeats itself).
```
def long_winded(gen,X)
n = next(gen)
while n < X: n=next(gen)
return n
```
What I wanted to write wa... | ```
from itertools import dropwhile
def first_result_larger_than_x(gen, X):
return next(dropwhile(lambda n: n <= X, gen))
```
Note that your code examples from the OP are actually returning the first result greater than *or equal to* X. I've corrected that in this code example, but if that was what you actually w... |
What is the simplest and most efficient function to return a sublist based on an index list? | 12,465,403 | 2 | 2012-09-17T18:50:56Z | 12,465,426 | 7 | 2012-09-17T18:52:39Z | [
"python",
"list"
] | Say I have a list `l`:
```
['a','b','c','d','e']
```
and a list of indexes `idx`:
```
[1,3]
```
What is the simplest and most efficient function that will return:
```
['b','d']
``` | You want `operator.itemgetter`.
In my first example, I'll show how you can use `itemgetter` to construct a callable which you can use on any indexable object:
```
from operator import itemgetter
items = itemgetter(1,3)
items(yourlist) #('b', 'd')
```
Now I'll show how you can use argument unpacking to store your in... |
What is the simplest and most efficient function to return a sublist based on an index list? | 12,465,403 | 2 | 2012-09-17T18:50:56Z | 12,465,445 | 13 | 2012-09-17T18:53:44Z | [
"python",
"list"
] | Say I have a list `l`:
```
['a','b','c','d','e']
```
and a list of indexes `idx`:
```
[1,3]
```
What is the simplest and most efficient function that will return:
```
['b','d']
``` | Try using this:
```
[l[i] for i in idx]
``` |
Convert a JSON schema to a python class | 12,465,588 | 15 | 2012-09-17T19:05:21Z | 13,182,344 | 11 | 2012-11-01T17:25:14Z | [
"python",
"json",
"jsonschema"
] | Is there a python library for converting a JSON schema to a python class definition, similar to jsonschema2pojo -- <https://github.com/joelittlejohn/jsonschema2pojo> -- for Java? | So far the closest thing I've been able to find is [warlock](http://pypi.python.org/pypi/warlock), which advertises this workflow:
**Build your schema**
```
>>> schema = {
'name': 'Country',
'properties': {
'name': {'type': 'string'},
'abbreviation': {'type': 'string'},
},
'additionalP... |
Parameter naming convention in Python | 12,465,921 | 3 | 2012-09-17T19:31:01Z | 12,465,949 | 8 | 2012-09-17T19:33:14Z | [
"python",
"coding-style",
"naming-conventions"
] | For functions with closely related formal parameters, such as
```
def add_two_numbers(n1, n2):
return n1 + n2
def multiply_two_numbers(n1, n2):
return n1 * n2
```
Is it a good idea to give the same names to the parameters in both functions, as shown above?
The alternative is to rename the parameters in one ... | I would keep the names the same unless you have a good reason to use different names ... Remember that even positional arguments can be called by keywords, e.g.:
```
>>> def foo(a,b):
... print a
... print b
...
>>> foo(b=2,a=1)
```
Keeping the "keywords" the same helps in that rare, but legal corner case ..... |
Function printing correct Output and None | 12,466,233 | 3 | 2012-09-17T19:55:40Z | 12,466,256 | 7 | 2012-09-17T19:57:35Z | [
"python"
] | I have defined this function that takes a word and a string of required letters and that returns True if the word uses all the required letters at least once. When I run this, it gives me the correct output but I do not understand why it also outputs 'None'.
Here is my code:
```
def uses_all(word, allused):
bool... | Your program prints `boolean`, which is False, so you know where that comes from.
If a function doesn't return anything explicitly, it automatically returns None, and when you use
```
print uses_all('facebook', 'd')
```
you're asking it to print what `uses_all` returns, which is None. Hence:
```
False
None
```
BTW... |
Why urllib.urlopen.read() does not correspond to source code? | 12,466,900 | 11 | 2012-09-17T20:48:37Z | 12,466,941 | 9 | 2012-09-17T20:51:13Z | [
"python",
"urllib",
"urlopen"
] | I'm trying to fetch the following webpage:
```
import urllib
urllib.urlopen("http://www.gallimard-jeunesse.fr/searchjeunesse/advanced/(order)/author?catalog[0]=1&SearchAction=1").read()
```
The result does not correspond to what I see when inspecting the source code of the webpage using Google Chrome for example.
Co... | What you are getting from `urlopen` is the raw webpage meaning no javascript is executed css is not used; where as what you get from Chrome (or other browsers) is final webpage which included executable javascript (which might alter the HTML), css rendering etc. all of which does not happen in `urlopen`...
Hence the d... |
Why urllib.urlopen.read() does not correspond to source code? | 12,466,900 | 11 | 2012-09-17T20:48:37Z | 21,276,452 | 9 | 2014-01-22T07:12:14Z | [
"python",
"urllib",
"urlopen"
] | I'm trying to fetch the following webpage:
```
import urllib
urllib.urlopen("http://www.gallimard-jeunesse.fr/searchjeunesse/advanced/(order)/author?catalog[0]=1&SearchAction=1").read()
```
The result does not correspond to what I see when inspecting the source code of the webpage using Google Chrome for example.
Co... | you can use python Selenium to solved your issue. Here is a example code have a look.
```
from selenium import webdriverr
url = "http://www.gallimard-jeunesse.fr/searchjeunesse/advanced/(order)/author?catalog[0]=1&SearchAction=1"
browser = webdriver.Firefox()
browser.get(url)
sleep(10)
all_body_id_html = browser.find... |
Install PIL on Windows 7 64-bit PC | 12,467,091 | 4 | 2012-09-17T21:04:33Z | 14,875,872 | 7 | 2013-02-14T13:24:46Z | [
"python",
"windows-7",
"install",
"python-imaging-library"
] | Python by itself works fine, but when I try to add PIL to it, the installation gives an error message:
> python version 2.7 required, which was not found in the registry
What can I do? | This problem had already seen before, it is true that python and windows registry has become problematic for this library, you create a new own registry on the following address `HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Python\PythonCore\2.7\InstallPath` and then copy and paste there the value that is in `HKEY_LOCAL_MAC... |
Python: Way to speed up a repeatedly executed eval statement? | 12,467,570 | 8 | 2012-09-17T21:46:30Z | 12,467,714 | 11 | 2012-09-17T22:01:22Z | [
"python",
"eval"
] | In my code, I'm using `eval` to evaluate a string expression given by the user. Is there a way to compile or otherwise speed up this statement?
```
import math
import random
result_count = 100000
expression = "math.sin(v['x']) * v['y']"
variable = dict()
variable['x'] = [random.random() for _ in xrange(result_count)... | You can avoid the overhead by compiling the expression in advance using [`compiler.compile()`](http://docs.python.org/library/compiler.html#compiler.compile):
```
In [1]: import math, compiler
In [2]: v = {'x': 2, 'y': 4}
In [3]: expression = "math.sin(v['x']) * v['y']"
In [4]: %timeit eval(expression)
10000 loops,... |
Python: Way to speed up a repeatedly executed eval statement? | 12,467,570 | 8 | 2012-09-17T21:46:30Z | 12,467,755 | 13 | 2012-09-17T22:05:32Z | [
"python",
"eval"
] | In my code, I'm using `eval` to evaluate a string expression given by the user. Is there a way to compile or otherwise speed up this statement?
```
import math
import random
result_count = 100000
expression = "math.sin(v['x']) * v['y']"
variable = dict()
variable['x'] = [random.random() for _ in xrange(result_count)... | You can also trick python:
```
expression = "math.sin(v['x']) * v['y']"
exp_as_func = eval('lambda: ' + expression)
```
And then use it like so:
```
exp_as_func()
```
Speed test:
```
In [17]: %timeit eval(expression)
10000 loops, best of 3: 25.8 us per loop
In [18]: %timeit exp_as_func()
1000000 loops, best of 3:... |
Python "FileExists" error when making directory | 12,468,022 | 13 | 2012-09-17T22:35:30Z | 12,468,041 | 13 | 2012-09-17T22:37:56Z | [
"python",
"file-io",
"filesystems",
"queue",
"cluster-computing"
] | I have several threads running in parallel from Python on a cluster system. Each python thread outputs to a directory `mydir`. Each script, before outputting checks if *mydir* exists and if not creates it:
```
if not os.path.isdir(mydir):
os.makedirs(mydir)
```
but this yields the error:
```
os.makedirs(self.log... | Catch the exception and, if the errno is 17, ignore it. That's the only thing you can do if there's a race condition between the `isdir` and `makedirs` calls.
However, it could also be possible that a *file* with the same name exists - in that case `os.path.exists` would return `True` but `os.path.isdir` returns false... |
Python "FileExists" error when making directory | 12,468,022 | 13 | 2012-09-17T22:35:30Z | 12,468,091 | 21 | 2012-09-17T22:44:47Z | [
"python",
"file-io",
"filesystems",
"queue",
"cluster-computing"
] | I have several threads running in parallel from Python on a cluster system. Each python thread outputs to a directory `mydir`. Each script, before outputting checks if *mydir* exists and if not creates it:
```
if not os.path.isdir(mydir):
os.makedirs(mydir)
```
but this yields the error:
```
os.makedirs(self.log... | Any time code can execute between when you check something and when you act on it, you will have a race condition. One way to avoid this (and the usual way in Python) is to just try and then handle the exception
```
while True:
mydir = next_dir_name()
try:
os.makedirs(mydir)
break
except OS... |
UnicodeDecodeError: 'utf8' codec can't decode byte 0x9c | 12,468,179 | 75 | 2012-09-17T22:55:52Z | 12,468,274 | 122 | 2012-09-17T23:05:11Z | [
"python",
"linux"
] | I have a socket server that is supposed to receive UTF-8 valid characters from clients.
The problem is some clients (mainly hackers) are sending all the wrong kind of data over it.
I can easily distinguish the genuine client, but I am logging to files all the data sent so I can analyze it later.
Sometimes I get char... | <http://docs.python.org/howto/unicode.html#the-unicode-type>
```
str = unicode(str, errors='replace')
```
or
```
str = unicode(str, errors='ignore')
```
**Note:**
This solution will strip out (ignore) the characters in question returning the string without them.
Only use this if your need is to strip them not conve... |
UnicodeDecodeError: 'utf8' codec can't decode byte 0x9c | 12,468,179 | 75 | 2012-09-17T22:55:52Z | 12,468,284 | 15 | 2012-09-17T23:06:39Z | [
"python",
"linux"
] | I have a socket server that is supposed to receive UTF-8 valid characters from clients.
The problem is some clients (mainly hackers) are sending all the wrong kind of data over it.
I can easily distinguish the genuine client, but I am logging to files all the data sent so I can analyze it later.
Sometimes I get char... | ```
>>> '\x9c'.decode('cp1252')
u'\u0153'
>>> print '\x9c'.decode('cp1252')
Å
``` |
UnicodeDecodeError: 'utf8' codec can't decode byte 0x9c | 12,468,179 | 75 | 2012-09-17T22:55:52Z | 37,723,241 | 7 | 2016-06-09T10:21:19Z | [
"python",
"linux"
] | I have a socket server that is supposed to receive UTF-8 valid characters from clients.
The problem is some clients (mainly hackers) are sending all the wrong kind of data over it.
I can easily distinguish the genuine client, but I am logging to files all the data sent so I can analyze it later.
Sometimes I get char... | This type of issue crops up for me now that I've moved to Python 3. I had no idea Python 2 was simply steam rolling any issues with file encoding.
I found this nice explanation of the differences and how to find a solution after none of the above worked for me.
<http://python-notes.curiousefficiency.org/en/latest/pyt... |
yaml multi nested and python dictionary | 12,468,806 | 7 | 2012-09-18T00:19:55Z | 12,469,381 | 12 | 2012-09-18T01:55:17Z | [
"python",
"yaml"
] | I am new to yaml the output is in the expected format but wondering if there is a better way to construct the below nested objects in yaml.
```
import yaml
yaml.load ("""
test1:
a:
a1:
a2:
a3: 0
b3: 0
c3: 0
b2:
a3: 0
b3: 0
... | I can think of two ways that will save you some typing on the yaml front.
*Use the short mapping syntax:*
```
test1:
a:
a1:
a2: {a3: 0, b3: 0, c3: 0}
b2: {a3: 0, b3: 0, c3: 0}
c2: {a3: 0, b3: 0, c3: 0}
b1:
a2: {a3: 0, b3: 0, c3: 0}
b2: {a3: 0, b3: 0, c3: 0}
... |
Python datetime - setting fixed hour and minute after using strptime to get day,month,year | 12,468,823 | 40 | 2012-09-18T00:22:41Z | 12,468,869 | 110 | 2012-09-18T00:28:24Z | [
"python",
"date",
"datetime",
"time",
"date-manipulation"
] | I've successfully converted something of `26 Sep 2012` format to `26-09-2012` using:
`datetime.strptime(request.POST['sample_date'],'%d %b %Y')`
**However, I don't know how to set the hour and minute of something like the above to 11:59. Does anyone know how to do this?**
Note, this can be a future date or any rando... | Use [`datetime.replace`](https://docs.python.org/3.5/library/datetime.html#datetime.datetime.replace):
```
from datetime import datetime
date = datetime.strptime('26 Sep 2012', '%d %b %Y')
newdate = date.replace(hour=11, minute=59)
``` |
In python, bash, or perl, how can I artificially inflate my memory | 12,468,983 | 3 | 2012-09-18T00:46:59Z | 12,468,991 | 7 | 2012-09-18T00:48:46Z | [
"python",
"memory"
] | Hopefull really simple. I want to artifically inflate my memory... i'm doing this for testing purposes... Any way in linux would be fine. | Python:
```
x = [0]
while True: x.extend(x)
```
This will double the size of `x` until memory runs out (you get `MemoryError`). |
Organizing source code in python | 12,469,002 | 4 | 2012-09-18T00:49:52Z | 12,469,044 | 7 | 2012-09-18T00:56:54Z | [
"python",
"package"
] | I am writing a game framework. Here is my current file structure:
```
src/
framework/
__init__.py
util.py
render.py
game.py
pong.py
```
I want to be able to simply do `import game` or `import render` directly from the `pong.py` file. What's the best way to accomplish this? Initially the `util.py, ... | The best way to do this would be not to do it at all. For exactly the reasons you moved them in the first place - the sake of organization - you'll want them to be in a separate module. If you want to refer to the module as `game` in your code, you can do this:
```
from framework import game
game.foo()
```
Generally... |
UUID field added after data already in database. Is there any way to populate the UUID field for existing data? | 12,469,638 | 17 | 2012-09-18T02:33:08Z | 15,163,767 | 19 | 2013-03-01T17:44:44Z | [
"python",
"django",
"django-models",
"django-south"
] | I've added a UUID field to some of my models and then migrated with South. Any new objects I create have the UUID field populated correctly. However the UUID fields on all my older data is null.
Is there any way to populate UUID data for existing data? | For the following sample class:
```
from django_extensions.db.fields import UUIDField
def MyClass:
uuid = UUIDField(editable=False, blank=True)
name = models.CharField()
```
If you're using South, create a data migration:
```
python ./manage.py datamigration <appname> --auto
```
And then use the following ... |
How can I write data in YAML format in a file? | 12,470,665 | 31 | 2012-09-18T05:04:54Z | 12,471,272 | 38 | 2012-09-18T06:09:04Z | [
"python",
"yaml",
"pyyaml"
] | I need to write the below data to yaml file using Python:
```
{A:a, B:{C:c, D:d, E:e}}
```
i.e., dictionary in a dictionary. How can I achieve this? | ```
import yaml
data = dict(
A = 'a',
B = dict(
C = 'c',
D = 'd',
E = 'e',
)
)
with open('data.yml', 'w') as outfile:
yaml.dump(data, outfile, default_flow_style=True)
```
The `default_flow_style=True` parameter is necessary to produce the format you want (flow style), otherwi... |
How can I write data in YAML format in a file? | 12,470,665 | 31 | 2012-09-18T05:04:54Z | 18,210,750 | 25 | 2013-08-13T13:41:25Z | [
"python",
"yaml",
"pyyaml"
] | I need to write the below data to yaml file using Python:
```
{A:a, B:{C:c, D:d, E:e}}
```
i.e., dictionary in a dictionary. How can I achieve this? | [Link](http://pyyaml.org/wiki/PyYAMLDocumentation#FrequentlyAskedQuestions) to the PyYAML documentation showing the difference for the `default_flow_style` parameter.
To write it to a file in block mode (often more readable):
```
d = {'A':'a', 'B':{'C':'c', 'D':'d', 'E':'e'}}
with open('result.yml', 'w') as yaml_file:... |
How can I write data in YAML format in a file? | 12,470,665 | 31 | 2012-09-18T05:04:54Z | 27,467,024 | 10 | 2014-12-14T06:48:31Z | [
"python",
"yaml",
"pyyaml"
] | I need to write the below data to yaml file using Python:
```
{A:a, B:{C:c, D:d, E:e}}
```
i.e., dictionary in a dictionary. How can I achieve this? | Just want to point out that PyYAML support directly write to a file object to save memory.
```
d = {'A':'a', 'B':{'C':'c', 'D':'d', 'E':'e'}}
with open('result.yaml', 'w') as f:
yaml.dump(d, f, default_flow_style=False)
``` |
Frequently http 500 internal error with google drive API drive.files.get | 12,471,180 | 8 | 2012-09-18T05:59:02Z | 12,640,475 | 8 | 2012-09-28T12:57:03Z | [
"python",
"google-drive-sdk"
] | We have a service which highly depends on Google Drive (uses Python SDK got from <https://developers.google.com/api-client-library/python/>), our service goes through google drive collections and files.
Checked production log, we found there are many http 500 server internal errors when we call google drive API drive.... | Because Google infrastructure is complex, large scale and distributed it is close to impossible to have a 0% error rate - servers or hard disks dying during the request, unexpected timeouts between servers internally, datacenter outage or increased load, tentative DOS attacks, misbehaving applications... - all of which... |
How can you determine if a function return value is a generator? | 12,471,610 | 2 | 2012-09-18T06:39:49Z | 12,471,662 | 7 | 2012-09-18T06:44:30Z | [
"python",
"python-3.x"
] | the yield return a collections.Iterable but many types are also iterable
```
def aaaa():
yield 1
yield 2
yield 3
d = aaaa()
print(d,type(d),isinstance(d, collections.Iterable))
```
the print type
```
<generator object aaaa at 0x0000000002626B88> <class 'generator'> True
```
i didn't find the class 'g... | Have a look at the inspect module, and in particular [inspect.isgeneratorfunction](http://docs.python.org/library/inspect.html#inspect.isgeneratorfunction).
That said, the more interesting question is whether it's a list or other iterable. To answer that question, you can just check if `__getitem__` is defined on it. |
How can you determine if a function return value is a generator? | 12,471,610 | 2 | 2012-09-18T06:39:49Z | 12,471,676 | 10 | 2012-09-18T06:45:17Z | [
"python",
"python-3.x"
] | the yield return a collections.Iterable but many types are also iterable
```
def aaaa():
yield 1
yield 2
yield 3
d = aaaa()
print(d,type(d),isinstance(d, collections.Iterable))
```
the print type
```
<generator object aaaa at 0x0000000002626B88> <class 'generator'> True
```
i didn't find the class 'g... | If you want to check if the *iterable* is a generator object:
```
import types
isinstance(aaaa(), types.GeneratorType) # ==> True
```
If you want to check if the *function* contains `yield` statements (i.e. the function is a generator):
```
import inspect
inspect.isgeneratorfunction(aaaa) # ==> True
``` |
Better way to find if a number is present in between two numbers of a sorted list | 12,473,413 | 3 | 2012-09-18T08:46:59Z | 12,473,462 | 7 | 2012-09-18T08:49:47Z | [
"python",
"list",
"sorting"
] | I have a sorted list like this
```
s = [1 , 4 ,6 , 9 ,10 ]
```
I want to know if either a number is present in the list or if it is present in between two numbers. If it is present in between two numbers, I want to print them out.
Right now my code looks like this
```
for x in s:
if b == x: \\ b is the number
... | [bisect module](http://docs.python.org/library/bisect.html#module-bisect) does exactly that:
```
s = [1 , 4 ,6 , 9 ,10 ]
import bisect
x = 5
n = bisect.bisect_left(s, x)
if s[n:n+1] == [x]:
print x, 'is in the list'
else:
print x, 'comes between', s[n-1:n], 'and', s[n:n+1]
``` |
Editing Google docs with drive API | 12,474,115 | 6 | 2012-09-18T09:27:40Z | 12,474,952 | 7 | 2012-09-18T10:16:32Z | [
"python",
"google-app-engine",
"google-drive-sdk",
"google-api-python-client"
] | (For clarity, this post relates to the difference between the Google [Documents List API](https://developers.google.com/google-apps/documents-list/) and [Google Drive API](https://developers.google.com/drive/) on [Google App Engine](https://developers.google.com/appengine/) with Python)
With the [now deprecated] Docum... | i suspect the issue is that the default for conversion has changed from true to false. You must explicitly set convert=true on the upload. See <https://developers.google.com/drive/v2/reference/files/insert> |
Asynchronously read and process an image in python | 12,474,182 | 10 | 2012-09-18T09:31:38Z | 12,484,183 | 8 | 2012-09-18T20:04:57Z | [
"python",
"image-processing",
"asynchronous",
"numpy",
"scipy"
] | **Context**
I often found myself in the following situation:
* I have a list of image filenames I need to process
* I read each image sequentially using for instance scipy.misc.imread
* Then I do some kind of processing on each image and return a result
* I save the result along the image filename into a Shelf
The p... | The multiprocessing package is pretty easy to use. Look at the [Queues example](http://docs.python.org/library/multiprocessing.html#exchanging-objects-between-processes) for a guide. You'll be following the producer consumer model. You want one (or more) producer processes reading images, and one (or more) consumer pro... |
Asynchronously read and process an image in python | 12,474,182 | 10 | 2012-09-18T09:31:38Z | 12,485,079 | 7 | 2012-09-18T21:08:53Z | [
"python",
"image-processing",
"asynchronous",
"numpy",
"scipy"
] | **Context**
I often found myself in the following situation:
* I have a list of image filenames I need to process
* I read each image sequentially using for instance scipy.misc.imread
* Then I do some kind of processing on each image and return a result
* I save the result along the image filename into a Shelf
The p... | [Philip's answer](http://stackoverflow.com/a/12484183/24283) is good, but will only create a couple of processes (one reading, one computing) which will hardly max out a modern >2 core system. Here's an alternative using [`multiprocessing.Pool`](http://docs.python.org/library/multiprocessing.html#module-multiprocessing... |
Python: How to get the Content-Type of an URL? | 12,474,406 | 4 | 2012-09-18T09:45:10Z | 12,474,734 | 8 | 2012-09-18T10:03:29Z | [
"python",
"python-2.7",
"urllib"
] | I need to get the content-type of an internet(intranet) resource not a local file. How can I get the MIME type from a resource behind an URL:
I tried this:
```
res = urllib.urlopen("http://www.iana.org/assignments/language-subtag-registry")
http_message = res.info()
message = http_message.getplist()
```
I get:
`['ch... | ```
res = urllib.urlopen("http://www.iana.org/assignments/language-subtag-registry" )
http_message = res.info()
full = http_message.type # 'text/plain'
main = http_message.maintype # 'text'
``` |
Python 3: Unroll arguments from tuple | 12,475,448 | 4 | 2012-09-18T10:46:14Z | 12,475,493 | 12 | 2012-09-18T10:49:05Z | [
"python",
"arguments",
"tuples"
] | Given a Python tuple `t = v1, v2, v3` is there a utility to unpack these so that given:
```
def foo(v1,v2,v3): pass
```
Instead of this:
```
foo(t[0],t[1],t[2])
```
You can do this:
```
foo(unpack(t))
```
I'd like to know of any such utility available for tuples and/or lists.
Sincere thanks. | Yep. You can use the unpacking operator (`'*'`)
```
foo(*t)
```
Note that this works if t is a `list`, `tuple`, or even a generator
---
There's an analogous way to pass arguments to functions with keywords using the `**` operator on mapping objects (typically dictionaries):
```
def foo(key=None,foo=None):
pass... |
How can I return HTTP status code 204 from a Django view? | 12,476,452 | 34 | 2012-09-18T11:50:40Z | 12,476,918 | 64 | 2012-09-18T12:20:34Z | [
"python",
"django",
"http",
"http-status-codes"
] | I want to return status code `204 No Content` from a Django view. It is in response to an automatic POST which updates a database and I just need to indicate the update was successful (without redirecting the client).
There are subclasses of `HttpResponse` to handle most other codes but not 204.
What is the simplest ... | ```
return HttpResponse(status=204)
``` |
How can I return HTTP status code 204 from a Django view? | 12,476,452 | 34 | 2012-09-18T11:50:40Z | 12,477,267 | 12 | 2012-09-18T12:43:20Z | [
"python",
"django",
"http",
"http-status-codes"
] | I want to return status code `204 No Content` from a Django view. It is in response to an automatic POST which updates a database and I just need to indicate the update was successful (without redirecting the client).
There are subclasses of `HttpResponse` to handle most other codes but not 204.
What is the simplest ... | Either what Steve Mayne answered, or build your own by subclassing HttpResponse:
```
from django.http import HttpResponse
class HttpResponseNoContent(HttpResponse):
status_code = 204
def my_view(request):
return HttpResponseNoContent()
``` |
Python generator objects: __sizeof__() | 12,477,835 | 9 | 2012-09-18T13:16:24Z | 12,477,858 | 19 | 2012-09-18T13:17:47Z | [
"python",
"generator",
"internals"
] | This may be a stupid question but I will ask it anyway. I have a generator object:
```
>>> def gen():
... for i in range(10):
... yield i
...
>>> obj=gen()
```
I can measure it's size:
```
>>> obj.__sizeof__()
24
```
It is said that generators get consumed:
```
>>> for i in obj:
... print ... | `__sizeof__()` does not do what you think it does. The method returns the internal size in bytes for the given object, not the number of items a generator is going to return.
Python cannot beforehand know the size of a generator. Take for example the following endless generator (example, there are better ways to creat... |
How to run functions outside websocket loop in python (tornado) | 12,479,054 | 22 | 2012-09-18T14:28:09Z | 12,479,455 | 19 | 2012-09-18T14:48:42Z | [
"python",
"websocket",
"tornado"
] | I'm trying to set up a small example of a public Twitter stream over websockets. This is my websocket.py, and it's working.
What I'm wondering is: how can I interact with the websocket from 'outside' the class WSHandler (ie. not only answer when receiving a message from websocket.js)? Say I want to run some other func... | You could call a
```
IOLoop.add_timeout(deadline, callback)
```
that calls the callback at specified deadline timeout (one shot, but you can reschedule), or use the
`tornado.ioloop.PeriodicCallback` if you have a more periodic task.
See: <http://www.tornadoweb.org/en/stable/ioloop.html#tornado.ioloop.IOLoop.add_tim... |
How to run functions outside websocket loop in python (tornado) | 12,479,054 | 22 | 2012-09-18T14:28:09Z | 15,488,430 | 14 | 2013-03-18T22:48:27Z | [
"python",
"websocket",
"tornado"
] | I'm trying to set up a small example of a public Twitter stream over websockets. This is my websocket.py, and it's working.
What I'm wondering is: how can I interact with the websocket from 'outside' the class WSHandler (ie. not only answer when receiving a message from websocket.js)? Say I want to run some other func... | I stumbled upon similar problem. Here is my solution. Hope this will be helpful to someone out there
```
wss = []
class wsHandler(tornado.websocket.WebSocketHandler):
def open(self):
print 'Online'
if self not in wss:
wss.append(self)
def on_close(self):
print 'Offline'
... |
Python - Global counter | 12,479,574 | 2 | 2012-09-18T14:55:52Z | 12,479,596 | 8 | 2012-09-18T14:57:24Z | [
"python"
] | I am recursively generating few objects, which need a contiguous, unique id. How can I guarantee (easiest) the synchronization in python 2.7.
```
iid = 1
def next_id():
iid += 1
return iid
def process():
# .. do something
id = next_id()
``` | Use a [mutex](http://docs.python.org/library/threading.html#lock-objects):
```
import threading
iid = 1
iid_lock = threading.Lock()
def next_id():
global iid
with iid_lock:
result = iid
iid += 1
return result
```
You might like to hide the internals in a class:
```
class IdGenerator(obje... |
Python - Global counter | 12,479,574 | 2 | 2012-09-18T14:55:52Z | 12,480,131 | 10 | 2012-09-18T15:26:09Z | [
"python"
] | I am recursively generating few objects, which need a contiguous, unique id. How can I guarantee (easiest) the synchronization in python 2.7.
```
iid = 1
def next_id():
iid += 1
return iid
def process():
# .. do something
id = next_id()
``` | ```
from itertools import count
iid = count()
print next(iid) # 0
print next(iid) # 1
print next(iid) # 2
```
etc., and
```
new_iid = count(10)
print next(new_iid) # 10
print next(new_iid) # 11
print next(new_iid) # 12
```
for starting at other values than 0.
`count()` is essentially a generator which infinitely y... |
Handling Variables To Be Used Across Functions Without Global Variables | 12,482,237 | 3 | 2012-09-18T17:43:00Z | 12,482,272 | 9 | 2012-09-18T17:45:16Z | [
"python",
"oop",
"encapsulation"
] | So I'm working on a basic word game where you're dealt a "hand" (a dictionary object) of letters that you use to create words and get points.
This "hand" is used in the parameters of a number of functions: calculating a player's score, updating the number of letters in a hand after a player has used one or more letter... | It's called an object. Create a [class](http://docs.python.org/tutorial/classes.html) with the shared state, and the functions that share that state.
The reason why this is better than global variables is that it's a much more restricted version of the same concept - you can clearly see which functions are manipulatin... |
Handling Variables To Be Used Across Functions Without Global Variables | 12,482,237 | 3 | 2012-09-18T17:43:00Z | 12,482,309 | 8 | 2012-09-18T17:47:59Z | [
"python",
"oop",
"encapsulation"
] | So I'm working on a basic word game where you're dealt a "hand" (a dictionary object) of letters that you use to create words and get points.
This "hand" is used in the parameters of a number of functions: calculating a player's score, updating the number of letters in a hand after a player has used one or more letter... | Use class encapusulation ... see below ... game is aware of both hands
```
class Hand:
def __init__(self):
num_cards = 7
self.cards = ["a" for i in range(num_cards)]
class Game:
def __init__(self,num_hands=2):
self.hands = [Hand() for i in range(num_hands)]
self.current_turn = 0 ... |
Why are Python multiprocessing Pipe unsafe? | 12,483,231 | 4 | 2012-09-18T18:55:38Z | 12,484,615 | 9 | 2012-09-18T20:37:37Z | [
"python",
"multiprocessing",
"pipe",
"unsafe"
] | I don't understand why [`Pipes`](http://docs.python.org/library/multiprocessing.html#multiprocessing.Pipe) are said unsafe when there are multiple senders and receivers.
How the following code can be turned into code using [`Queues`](http://docs.python.org/library/multiprocessing.html#multiprocessing.Queue) if this is... | Essentially, the problem is that `Pipe` is a thin wrapper around a platform-defined pipe object. `recv` simply repeatedly receives a buffer of bytes until a complete Python object is obtained. If two threads or processes use `recv` on the same pipe, the reads may interleave, leaving each process with half a pickled obj... |
Finding if a string exists in a nested tuple in Python | 12,483,330 | 3 | 2012-09-18T19:03:02Z | 12,483,532 | 7 | 2012-09-18T19:18:07Z | [
"python",
"python-2.7"
] | What is the best (and fastest) way, in Python 2.7.x, to check if a string (or any other data type) exists in a nested tuple?
For example:
```
RECIPES = (
('apple', 'sugar', 'extreme_Force'),
('banana', 'syrup', 'magical_ends'),
('caramel', 'chocolate', 'pancake_MONSTER'),
('banana',('someAnother','ban... | Recursive multi-location indexing:
```
import sys
from collections import Sequence,defaultdict
#making code python3-compatible
if sys.version_info[0] == 3:
basestring = str
def buildLocator(tree):
locator = defaultdict(list)
def fillLocator(tree, locator,location):
for index,item in enumerate(tre... |
python multiprocessing apply_async only uses one process | 12,483,512 | 12 | 2012-09-18T19:16:40Z | 12,484,048 | 20 | 2012-09-18T19:55:20Z | [
"python",
"multiprocessing"
] | I have a script that includes opening a file from a list and then doing something to the text within that file. I'm using python multiprocessing and Pool to try to parallelize this operation. A abstraction of the script is below:
```
import os
from multiprocessing import Pool
results = []
def testFunc(files):
for... | * `apply_async` farms out one task to the pool. You would need to call
`apply_async` many times to exercise more processors.
* Don't allow both processes to try to write to the same list,
`results`. Since the pool workers are separate processes, the two
won't be writing to the same list. One way to work around th... |
SciPy and scikit-learn - ValueError: Dimension mismatch | 12,484,310 | 8 | 2012-09-18T20:16:32Z | 12,485,573 | 16 | 2012-09-18T21:46:40Z | [
"python",
"numpy",
"scipy",
"scikit-learn"
] | I use [SciPy](http://scipy.org/) and [scikit-learn](http://scikit-learn.org/stable/) to train and apply a Multinomial Naive Bayes Classifier for binary text classification. Precisely, I use the module [`sklearn.feature_extraction.text.CountVectorizer`](http://scikit-learn.org/stable/modules/generated/sklearn.feature_ex... | Sounds to me, like you just need to use `vectorizer.transform` for the test dataset, since the training dataset fixes the vocabulary (you cannot know the full vocabulary including the training set afterall). Just to be clear, thats `vectorizer.transform` instead of `vectorizer.fit_transform`. |
What am I doing wrong when installing lxml on Mac OS X 10.8.1? | 12,484,664 | 8 | 2012-09-18T20:41:04Z | 12,486,657 | 17 | 2012-09-18T23:45:18Z | [
"python",
"osx",
"installation",
"lxml"
] | I'm building lxml on Mac OS X 10.8.1 and Python 2.7.2 and having problems. (I've cloned the Github repository and followed the instructions for Mac OS X here: <http://lxml.de/build.html>)
It appears something hangs in building libxml2; the following is the tail end of the terminal output:
```
configure: creating ./co... | This is a bug in libxml2 2.9.
The error you're getting is on this line:
```
once_control = PTHREAD_ONCE_INIT;
```
That's illegal code, that just happens to work on linux. `PTHREAD_ONCE_INIT` can only be used for initialization, not assignment, and there's a specific reason for that: so platforms can define `PTHREAD_... |
Tuple conversion to a string | 12,485,244 | 4 | 2012-09-18T21:22:25Z | 12,485,326 | 11 | 2012-09-18T21:27:26Z | [
"python"
] | I have the following list:
```
[('Steve Buscemi', 'Mr. Pink'), ('Chris Penn', 'Nice Guy Eddie'), ...]
```
I need to convert it to a string in the following format:
```
"(Steve Buscemi, Mr. Pink), (Chris Penn, Nice Guy Eddit), ..."
```
I tried doing
```
str = ', '.join(item for item in items)
```
but run into the ... | ```
', '.join('(' + ', '.join(i) + ')' for i in L)
```
Output:
```
'(Steve Buscemi, Mr. Pink), (Chris Penn, Nice Guy Eddie)'
``` |
Python read file as stream from HDFS | 12,485,718 | 13 | 2012-09-18T22:00:22Z | 12,485,760 | 23 | 2012-09-18T22:04:22Z | [
"python",
"hadoop",
"subprocess",
"hdfs"
] | Here is my problem: I have a file in HDFS which can potentially be huge (=not enough to fit all in memory)
What I would like to do is avoid having to cache this file in memory, and only process it line by line like I would do with a regular file:
```
for line in open("myfile", "r"):
# do some processing
```
I am... | You want [xreadlines](http://docs.python.org/release/2.3/lib/module-xreadlines.html), it reads lines from a file without loading the whole file into memory.
**Edit**:
Now I see your question, you just need to get the stdout pipe from your `Popen` object:
```
cat = subprocess.Popen(["hadoop", "fs", "-cat", "/path/to/... |
Python read file as stream from HDFS | 12,485,718 | 13 | 2012-09-18T22:00:22Z | 14,335,456 | 18 | 2013-01-15T10:15:33Z | [
"python",
"hadoop",
"subprocess",
"hdfs"
] | Here is my problem: I have a file in HDFS which can potentially be huge (=not enough to fit all in memory)
What I would like to do is avoid having to cache this file in memory, and only process it line by line like I would do with a regular file:
```
for line in open("myfile", "r"):
# do some processing
```
I am... | If you want to avoid adding external dependencies at any cost, Keith's answer is the way to go. [Pydoop](http://pydoop.sourceforge.net), on the other hand, could make your life much easier:
```
import pydoop.hdfs as hdfs
with hdfs.open('/user/myuser/filename') as f:
for line in f:
do_something(line)
```
R... |
How do I skip a whole Python unittest module at run-time? | 12,487,532 | 12 | 2012-09-19T01:54:12Z | 12,488,542 | 9 | 2012-09-19T04:22:04Z | [
"python",
"unit-testing"
] | I would like my Python unittest module to tell the test runner to skip its entirety under some situations (such as being unable to import a module or locate a critical resource).
I can use `@unittest.skipIf(...)` to skip a unittest.TestCase class, but how do I skip the **entire module**? Applying skips to every class ... | If you look at the definition of `unittest.skipIf` and `unittest.skip`, you can see that the key is doing `raise unittest.SkipTest(reason)` when the test is executed. If you're okay with having it show up as **one** skipped test instead of several in the testrunner, you can simply raise `unittest.SkipTest` yourself on ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.