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 |
|---|---|---|---|---|---|---|---|---|---|
is getPerspectiveTransform broken in opencv python2 wrapper? | 9,808,601 | 8 | 2012-03-21T16:16:38Z | 9,834,398 | 15 | 2012-03-23T05:04:04Z | [
"python",
"opencv"
] | Something appears to be afoul with "getPerspectiveTransform" in the python2 wrapper for opencv. For starters, it takes two arguments instead of the expected three.
So instead of the first wrapper's:
```
cv.GetPerspectiveTransform(source,destination,3x3mat)
```
It's now:
```
cv2.getPerspectiveTransform(?,?)
```
If ... | cv2.getPerspectiveTransform is not broken anyway.
May be, your points are of not length 4 or they may not be float32 numbers.
Try following :
```
import cv2
import numpy as np
img = cv2.imread('1original.jpg',0)
src = np.array([[50,50],[450,450],[70,420],[420,70]],np.float32)
dst = np.array([[0,0],[299,299],[0,299... |
Auto generate doctest output with Sphinx extension | 9,809,434 | 6 | 2012-03-21T17:06:34Z | 9,810,040 | 7 | 2012-03-21T17:47:36Z | [
"python",
"python-sphinx",
"doctest"
] | I think I am missing something about the sphinx extension for doctest.
The typical example in the documentation is:
```
.. doctest::
>>> print 1
1
```
Isn't there a way to let sphinx generate the output (here: `1`) automatically?
As far as I understood, it is possible to run:
```
$ make doctest
```
which h... | I have to strongly (but kindly) **advise against** what you're trying to do.
What you're asking is against the "test part" of the [doctest module](http://docs.python.org/py3k/library/doctest.html):
> The doctest module searches for pieces of text that look like interactive Python sessions, and then executes those ses... |
Python sax to lxml for 80+GB XML | 9,809,469 | 9 | 2012-03-21T17:08:21Z | 9,814,580 | 16 | 2012-03-21T23:55:26Z | [
"python",
"sax",
"lxml"
] | How would you read an XML file using sax and convert it to a lxml etree.iterparse element?
To provide an overview of the problem, I have built an XML ingestion tool using lxml for an XML feed that will range in the size of 25 - 500MB that needs ingestion on a bi-daily basis, but needs to perform a one time ingestion o... | `iterparse` is an iterative parser. It will emit `Element` objects and events and incrementally build the entire `Element` tree as it parses, so eventually it will have the whole tree in memory.
However, it is easy to have a bounded memory behavior: delete elements you don't need anymore as you parse them.
The typica... |
use a relative path in requirements.txt to install a tar.gz file with pip | 9,809,557 | 4 | 2012-03-21T17:14:22Z | 12,921,216 | 8 | 2012-10-16T18:34:24Z | [
"python",
"pip"
] | We're using a requirements.txt file to store all the external modules needed. Every module but one is gathered from internet. The other one is stored on a folder under the one holding the requirements.txt file.
BTW, this module can be easily installed with pip install
I've tried using this:
```
file:folder/module
``... | In the current version of pip (1.2.1) the way relative paths in a requirements file are interpreted is ambiguous and semi-broken. There is an open issue on the pip repository which explains the various problems and ambiguities in greater detail:
<https://github.com/pypa/pip/issues/328>
Long story short the current im... |
sentry, raven and django celery | 9,810,104 | 7 | 2012-03-21T17:51:40Z | 9,815,810 | 10 | 2012-03-22T02:56:23Z | [
"python",
"django",
"logging",
"sentry",
"raven"
] | Now that `django-sentry` has become a standalone server (and is fantastic) I'm trying to port my apps over to use it.
I have set up a standalone server configured a django application [to log using django 1.3's logging dictionary conf as per the raven docs](http://raven.readthedocs.org/en/latest/config/django.html). I... | You need to add this:
```
'celery': {
'level': 'WARNING',
'handlers': ['sentry'],
'propagate': False,
},
```
To your `loggers` in the variable `LOGGING` in your settings.
something like:
```
# the site admins on every HTTP 500 error.
# See http://docs.djangoproject.com/en/dev/topics/logg... |
Round to the nearest 500, Python | 9,810,391 | 8 | 2012-03-21T18:11:32Z | 9,810,408 | 19 | 2012-03-21T18:12:58Z | [
"python",
"rounding"
] | I'm looking to find a way to round up to the nearest 500.I've been using:
```
math.ceil(round(8334.00256 + 250, -3))
```
Whereby I have a value from a scale in a map I am making in ArcGIS. I have the ability to read and write the scale factor (i.e. 1:8334....basically, you set the thousandth and it defaults to a rati... | Scale, round, unscale:
```
round(x / 500.0) * 500.0
```
**Edit**: To round up to the next multiple of 500, use the same logic with `math.ceil()` instead of `round()`:
```
math.ceil(x / 500.0) * 500.0
``` |
Python String "Modifiers" | 9,810,589 | 4 | 2012-03-21T18:23:54Z | 9,810,622 | 13 | 2012-03-21T18:26:13Z | [
"python",
"django"
] | What are these "modifiers" called on the front of a python string? I don't understand what these are used for. Also, since I don't know what they are called, I don't know what to search for to learn about them (or the others that may be available if any).
In this example what does the "u" represent on the front of the... | The 'r' indicates a raw string, which alters the escaping behavior. This is useful for regular expressions to make them easier to read. The 'u' indicates that it is a Unicode string. They're called **[string literal prefixes](http://docs.python.org/reference/lexical_analysis.html#strings)**.
From the docs:
> String l... |
Adding 'install_requires' to setup.py when making a python package | 9,810,603 | 32 | 2012-03-21T18:25:04Z | 13,468,644 | 48 | 2012-11-20T07:44:29Z | [
"python"
] | I'm following [this](http://guide.python-distribute.org/creation.html#basics-creating-and-distributing-distributions) guide to make a python package. In the setup.py they have the following:
```
setup(
name='TowelStuff',
version='0.1.0',
author='J. Random Hacker',
author_email='jrh@example.com',
pa... | You need to be using setuptools instead of distutils.
Near the top of your script, try replacing
```
from distutils.core import setup
```
with
```
from setuptools import setup
``` |
Adding 'install_requires' to setup.py when making a python package | 9,810,603 | 32 | 2012-03-21T18:25:04Z | 17,855,230 | 29 | 2013-07-25T10:19:08Z | [
"python"
] | I'm following [this](http://guide.python-distribute.org/creation.html#basics-creating-and-distributing-distributions) guide to make a python package. In the setup.py they have the following:
```
setup(
name='TowelStuff',
version='0.1.0',
author='J. Random Hacker',
author_email='jrh@example.com',
pa... | ```
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
``` |
Name of this algorithm, and is there a numpy/scipy implementation of it? | 9,810,775 | 4 | 2012-03-21T18:35:58Z | 9,810,817 | 8 | 2012-03-21T18:39:17Z | [
"python",
"algorithm",
"numpy",
"scipy"
] | # Motivation:
I've seen this algorithm described, and I'd rather not reinvent the wheel if a standard implementation exists. I've also learned that if there is a scipy/numpy implementation, it is usually much faster than anything I can roll myself in python.
# Algorithm Description
I have a large number of points on... | It's called a [quadtree](http://en.wikipedia.org/wiki/Quadtree) partition. As far as Python code, see [this thread](http://stackoverflow.com/questions/2298517/are-any-of-these-quad-tree-libraries-any-good). |
Cancellable threading.Timer in Python | 9,812,344 | 14 | 2012-03-21T20:30:54Z | 9,812,802 | 9 | 2012-03-21T21:01:43Z | [
"python",
"timer",
"python-multithreading"
] | I am trying to write a method that counts down to a given time and unless a restart command is given, it will execute the task. But I don't think Python `threading.Timer` class allows for timer to be cancelable.
```
import threading
def countdown(action):
def printText():
print 'hello!'
t = threading... | I'm not sure if I understand correctly. Do you want to write something like in this example?
```
>>> import threading
>>> t = None
>>>
>>> def sayHello():
... global t
... print "Hello!"
... t = threading.Timer(0.5, sayHello)
... t.start()
...
>>> sayHello()
Hello!
Hello!
Hello!
Hello!
Hello!
>>> t.c... |
Cancellable threading.Timer in Python | 9,812,344 | 14 | 2012-03-21T20:30:54Z | 9,812,806 | 17 | 2012-03-21T21:02:04Z | [
"python",
"timer",
"python-multithreading"
] | I am trying to write a method that counts down to a given time and unless a restart command is given, it will execute the task. But I don't think Python `threading.Timer` class allows for timer to be cancelable.
```
import threading
def countdown(action):
def printText():
print 'hello!'
t = threading... | You would call the cancel method after you start the timer:
```
import time
import threading
def hello():
print "hello, world"
time.sleep(2)
t = threading.Timer(3.0, hello)
t.start()
var = 'something'
if var == 'something':
t.cancel()
```
You might consider using a while-loop on a [*Thread*](http://docs... |
Valid zip file in python | 9,812,899 | 7 | 2012-03-21T21:08:54Z | 9,812,966 | 10 | 2012-03-21T21:14:40Z | [
"python",
"zip"
] | I uploaded zip folder using file input,but when i check if this zip is valid or not;the result was:is not a valid pkzip file,i don't know what is the specification for valid pkzip.
I used this code to check:
```
form = cgi.FieldStorage()
file_upload = form['file[]']
if zipfile.is_zipfile(file_upload.filename):
pr... | `zipfile.is_zipfile` takes a path to a file or a file-like object. You're passing it neither, so it fails.
Ask it about `file_upload.file` instead. |
Extract files from zip file and retain mod date- Python 2.7.1 on Windows 7 | 9,813,243 | 7 | 2012-03-21T21:36:45Z | 9,813,471 | 7 | 2012-03-21T21:56:29Z | [
"python",
"zip",
"extraction"
] | I'm trying to extract files from a zip file using Python 2.7.1 (on Windows, fyi) and each of my attempts shows extracted files with Modified Date = time of extraction (which is incorrect).
```
import os,zipfile
outDirectory = 'C:\\_TEMP\\'
inFile = 'test.zip'
fh = open(os.path.join(outDirectory,inFile),'rb')
z = zipf... | Well, it does take a little post-processing, but it's not that bad:
```
import os
import zipfile
importtime
outDirectory = 'C:\\TEMP\\'
inFile = 'test.zip'
fh = open(os.path.join(outDirectory,inFile),'rb')
z = zipfile.ZipFile(fh)
for f in z.infolist():
name, date_time = f.filename, f.date_time
name = os.pat... |
Returning const char*; how ugly is static? | 9,814,040 | 4 | 2012-03-21T22:54:20Z | 9,814,104 | 10 | 2012-03-21T23:01:18Z | [
"c++",
"python",
"c",
"swig"
] | For reasons beyond my control, I need to return `const char*` from a function, but I don't know what the `char`s need to be at compile time. My solution is something like the following:
```
const char* __str__() {
static std::string String;
String = [some fancy stuff];
return String.c_str();
}
```
The `static` ... | `static` presents additional troubles besides the allocation scope:
* The function is not reentrant
* There is no way to clean up when the caller is done with the return value
Any reason not to return the value and let the caller free it?:
```
const char* __str__() {
char *s = malloc(2 * 1024 * 1024 * 1024); //... |
error extracting element from an array. python | 9,814,226 | 13 | 2012-03-21T23:15:37Z | 9,814,246 | 23 | 2012-03-21T23:18:15Z | [
"python",
"numpy"
] | I have a numpy array something like this
```
a = np.array(1)
```
Now if I want to get 1 back from this array. how do i retreive this??
I have tried
```
a[0], a(0)..
```
like
```
IndexError: 0-d arrays can't be indexed
```
or
```
TypeError: 'numpy.ndarray' object is not callable
```
I even tried to do some weir... | What you create with
```
a = np.array(1)
```
is a zero-dimensional array, and these cannot be indexed. You also don't *need* to index it -- you can use `a` directly as if it were a scalar value. If you really need the value in a different type, say `float`, you can explicitly convert it with `float(a)`. If you need i... |
Find all A^x in a given range | 9,814,333 | 2 | 2012-03-21T23:28:11Z | 9,814,393 | 7 | 2012-03-21T23:34:44Z | [
"python",
"algorithm",
"optimization"
] | I need to find all monomials in the form AX that when evaluated falls within a range from `m` to `n`. It is safe to say that the base `A` is greater than 1, the power `X` is greater than 2, and only integers need to be used. For example, in the range 50 to 100, the solutions would be:
```
2^6
3^4
4^3
```
My first att... | Using the fact that log(x) is an increasing function:
`m <= a^x <= n` if and only if `log(m) <= x * log(a) <= log(n)`
Then finding numbers `x`, `log(a)` whose product lies within this transformed interval will be much easier. |
Embedded Python 2.7.2 Importing a module from a user-defined directory | 9,814,512 | 7 | 2012-03-21T23:46:22Z | 9,814,744 | 12 | 2012-03-22T00:15:14Z | [
"c++",
"python",
"c",
"python-c-api",
"python-embedding"
] | I'm embedding Python into a C/C++ application that will have a defined API.
The application needs to instantiate classes defined in a script, which are structured roughly like this:
```
class userscript1:
def __init__(self):
##do something here...
def method1(self):
## method that can be call... | you need to specify `userscript` and not `userscript.py` also use `PyImport_ImportModule` it directly takes a `char *`
`userscript.py` means module `py` in package `userscript`
this code works for me:
```
#include <stdio.h>
#include <stdlib.h>
#include <Python.h>
int main(void)
{
const char *scriptDirectoryName... |
Identifying a complex number | 9,814,577 | 3 | 2012-03-21T23:54:23Z | 9,814,600 | 9 | 2012-03-21T23:58:30Z | [
"python",
"complex-numbers"
] | I am creating a calculator application for all types of mathematical algorithms. However, I want to identify if a root is complex and then have an exception for it.
I came up with this:
```
if x == complex():
print("Error 05: Complex Root")
```
However, nothing is identified or printed when I run the app, knowing... | I'm not 100% sure what you're asking, but if you want to check if a variable is of complex type you can use [isinstance](http://docs.python.org/library/functions.html#isinstance). For example,
```
x = 5j
if isinstance(x, complex):
print 'X is complex'
```
prints
```
X is complex
``` |
split a comma, space, or semicolon separated string using regex | 9,815,095 | 3 | 2012-03-22T01:05:04Z | 9,815,128 | 7 | 2012-03-22T01:09:28Z | [
"python",
"regex"
] | I use the regex [,;\s]+ to split a comma, space, or semicolon separated string. This works fine if the string doesn't have a comma at the end:
```
>>> p=re.compile('[,;\s]+')
>>> mystring='a,,b,c'
>>> p.split(mystring)
['a', 'b', 'c']
```
When the string has a comma at the end:
```
>>> mystring='a,,b,c,'
>>> p.split... | Here's something very low tech that should still work:
```
mystring='a,,b,c'
for delim in ',;':
mystring = mystring.replace(delim, ' ')
results = mystring.split()
```
**PS**:
While regexes are very useful, I would strongly suggest thinking twice about whether it is the right tool for the job here. While I'm not s... |
Pyramid: Custom 404 page returns as "200 OK" | 9,815,224 | 15 | 2012-03-22T01:25:08Z | 9,815,676 | 18 | 2012-03-22T02:37:10Z | [
"python",
"pyramid"
] | I have a custom 404 view defined in my Pyramid app:
```
@view_config(context=HTTPNotFound, renderer='404.pt')
def not_found(self, request):
return {}
```
It works fine, except that the HTTP status code sent with the content is 200 OK, which is not OK by any means. I'm having the same problem with 403 Forbidden. ... | The exception view is a separate view that provides a spot for you to do whatever you want. Just like any view that uses a renderer, you can affect the response object via `request.response` to modify its behavior. The renderer then fills in the body.
```
@view_config(context=HTTPNotFound, renderer='404.pt')
def not_f... |
Why is math.factorial much slower in Python 2.x than 3.x? | 9,815,252 | 30 | 2012-03-22T01:29:37Z | 9,815,339 | 42 | 2012-03-22T01:41:20Z | [
"python",
"performance",
"python-3.x",
"python-2.x",
"factorial"
] | I get the following results on my machine:
```
Python 3.2.2 (default, Sep 4 2011, 09:51:08) [MSC v.1500 32 bit (Intel)] on win
32
Type "help", "copyright", "credits" or "license" for more information.
>>> import timeit
>>> timeit.timeit('factorial(10000)', 'from math import factorial', number=100)
1.9785256226699202
... | Python 2 uses the [naive factorial algorithm](http://hg.python.org/cpython/file/2145593d108d/Modules/mathmodule.c#l1121):
```
1121 for (i=1 ; i<=x ; i++) {
1122 iobj = (PyObject *)PyInt_FromLong(i);
1123 if (iobj == NULL)
1124 goto error;
1125 newresult = PyNumber_Multiply(result, iobj);
1126 P... |
App Engine - AttributeError: 'function' object has no attribute 'id' | 9,815,260 | 2 | 2012-03-22T01:30:43Z | 9,815,288 | 7 | 2012-03-22T01:34:16Z | [
"python",
"google-app-engine",
"gae-datastore"
] | I'm using App Engine, SDK 1.6.3 with Python 2.7.
I've created a model like this:
```
class MyModel(db.Model):
name = db.StringProperty()
website = db.StringProperty()
```
I can iterate and see everything except the Key id's. For example, in the interactive shell I can run this:
```
from models import *
list... | key() and id() are instance methods. Try with parenthesis:
```
for p in list:
print(p.key().id())
```
See the [documentation](http://code.google.com/appengine/docs/python/datastore/keyclass.html#Key). |
Efficient way to convert delimiter separated string to numpy array | 9,815,911 | 7 | 2012-03-22T03:11:00Z | 9,816,147 | 11 | 2012-03-22T03:42:48Z | [
"python",
"numpy"
] | I have a String as follows :
```
1|234|4456|789
```
I have to convert it into numpy array.I would like to know the most efficient way.Since I will be calling this function for more than 50 million times! | The fastest way is to use the [numpy.fromstring](http://docs.scipy.org/doc/numpy/reference/generated/numpy.fromstring.html) method:
```
>>> import numpy
>>> data = "1|234|4456|789"
>>> numpy.fromstring(data, dtype=int, sep="|")
array([ 1, 234, 4456, 789])
``` |
Efficient way to convert delimiter separated string to numpy array | 9,815,911 | 7 | 2012-03-22T03:11:00Z | 9,816,200 | 7 | 2012-03-22T03:50:25Z | [
"python",
"numpy"
] | I have a String as follows :
```
1|234|4456|789
```
I have to convert it into numpy array.I would like to know the most efficient way.Since I will be calling this function for more than 50 million times! | [@jterrace](http://stackoverflow.com/a/9816147/42346) wins one (1) internet.
In the measurements below the example code has been shortened to allow the tests to fit on one line without scrolling where possible.
For those not familiar with `timeit` [the `-s` flag allows you to specify a bit of code which will only be ... |
Pluck in Python | 9,816,545 | 28 | 2012-03-22T04:41:53Z | 9,816,560 | 33 | 2012-03-22T04:44:49Z | [
"python",
"functional-programming"
] | I started reading about [underscore.js](http://documentcloud.github.com/underscore/) today, it is a library for javascript that adds some functional programming goodies I'm used to using in Python. One pretty cool shorthand method is [pluck](http://documentcloud.github.com/underscore/#pluck).
Indeed in Python I often ... | Just use a list comprehension in whatever function is consuming `uids`:
instead of
```
uids = map(operator.itemgetter("uid"), users)
foo(uids)
```
do
```
foo([x["uid"] for x in users])
```
If you just want `uids` to iterate over, you don't need to make a list -- use a generator instead. (Replace `[]` with `()`.)
... |
Pluck in Python | 9,816,545 | 28 | 2012-03-22T04:41:53Z | 16,710,119 | 11 | 2013-05-23T09:23:31Z | [
"python",
"functional-programming"
] | I started reading about [underscore.js](http://documentcloud.github.com/underscore/) today, it is a library for javascript that adds some functional programming goodies I'm used to using in Python. One pretty cool shorthand method is [pluck](http://documentcloud.github.com/underscore/#pluck).
Indeed in Python I often ... | From **[funcy](https://github.com/Suor/funcy)** module (<https://github.com/Suor/funcy>) you can pick **pluck** function.
In this case, provided that funcy is available on your host, the following code should work as expected:
```
from funcy import pluck
users = [{
"name" : "Bemmu",
"uid" : "297200003"
},
{
... |
Range is too large Python | 9,816,603 | 14 | 2012-03-22T04:50:18Z | 9,816,671 | 24 | 2012-03-22T04:59:59Z | [
"python",
"range"
] | I'm trying to find the largest prime factor of the number x, Python gives me the error that the range is too large. I've tried using x range but I get an OverflowError: Python int too large to convert to C long
```
x = 600851475143
maxPrime = 0
for i in range(x):
isItPrime = True
if (x%i == 0):
for p... | In old (2.x) versions of Python, `xrange` can only handle Python 2.x `int`s, which are bound by the native *long integer* size of your platform. Additionally, `range` allocates a list with all numbers beforehand on Python 2.x, and is therefore unsuitable for large arguments.
You can either switch to 3.x (recommended),... |
Relative and Absolute paths of all files | 9,816,816 | 9 | 2012-03-22T05:16:01Z | 9,816,863 | 18 | 2012-03-22T05:20:13Z | [
"python",
"absolute-path"
] | How do I get the absolute paths of all the files in a directory, that could have many sub-folders, in Python?
I know the os.walk gives me a list of directories and files, recursively in a list.
But that doesn't seem to trigger a way, to get what I want. | [`os.path.abspath`](http://docs.python.org/library/os.path.html#os.path.abspath) makes sure a path is absolute. Use the following helper function:
```
import os
def absoluteFilePaths(directory):
for dirpath,_,filenames in os.walk(directory):
for f in filenames:
yield os.path.abspath(os.path.join(... |
Relative and Absolute paths of all files | 9,816,816 | 9 | 2012-03-22T05:16:01Z | 9,816,913 | 7 | 2012-03-22T05:25:52Z | [
"python",
"absolute-path"
] | How do I get the absolute paths of all the files in a directory, that could have many sub-folders, in Python?
I know the os.walk gives me a list of directories and files, recursively in a list.
But that doesn't seem to trigger a way, to get what I want. | Try:
```
import os
for root, dirs, files in os.walk('.'):
for file in files:
p=os.path.join(root,file)
print p
print os.path.abspath(p)
print
``` |
is python str.split() inconsistent? | 9,817,073 | 3 | 2012-03-22T05:43:47Z | 9,817,097 | 12 | 2012-03-22T05:48:21Z | [
"python",
"split",
"whitespace"
] | ```
>>> ".a string".split('.')
['', 'a string']
>>> "a .string".split('.')
['a ', 'string']
>>> "a string.".split('.')
['a string', '']
>>> "a ... string".split('.')
['a ', '', '', ' string']
>>> "a ..string".split('.')
['a ', '', 'string']
>>> 'this is a test'.split(' ')
['this', '', 'is', 'a', 'test']
>>> 'thi... | See the [`str.split` docs](http://docs.python.org/library/stdtypes.html#str.split), this behavior is specifically mentioned:
> If `sep` is given, consecutive delimiters are not grouped together and
> are deemed to delimit empty strings (for example, `'1,,2'.split(',')`
> returns `['1', '', '2']`). The sep argument may... |
Applying low-level keyboard hooks with Python and SetWindowsHookExA | 9,817,531 | 7 | 2012-03-22T06:35:17Z | 16,430,918 | 10 | 2013-05-08T00:49:24Z | [
"python",
"winapi"
] | So I'm trying to figure out how to register a global keyboard hook using Python. From what I have read, it seems to be okay to not have the callback in a DLL. If you use WH\_KEYBOARD\_LL. I can't confirm that for sure but I find it encouraging that I don't get a 1428 error like I do if I try to hook into say `WH_CBT`.
... | I couldn't get your class to work, but I found a similar way to accomplish the same goal [in this thread](http://www.hackerthreads.org/Topic-42395).
Here's the adapted code:
```
from collections import namedtuple
KeyboardEvent = namedtuple('KeyboardEvent', ['event_type', 'key_code',
... |
How do I see the Python doc on Linux? | 9,817,712 | 13 | 2012-03-22T06:56:22Z | 9,817,782 | 7 | 2012-03-22T07:03:21Z | [
"python",
"linux",
"doc"
] | In Windows, Python has a chm type document, and it is very convenient to read.
But in the Linux, is there any document let me to read? | <http://www.google.cz/search?q=linux+chm+viewer>
The docs are available in various formats:
<http://docs.python.org/download.html>
There is a python documentation server, which you can run locally: <http://docs.python.org/library/pydoc.html?highlight=pydoc#pydoc> |
How do I see the Python doc on Linux? | 9,817,712 | 13 | 2012-03-22T06:56:22Z | 26,333,949 | 9 | 2014-10-13T06:13:45Z | [
"python",
"linux",
"doc"
] | In Windows, Python has a chm type document, and it is very convenient to read.
But in the Linux, is there any document let me to read? | ## Online documentation
The simplest way is to use Google to get to online documentation. There is no single point where you find all documentations of all modules. However, a few common ones are:
* [Python 3](https://docs.python.org/)
* [NumPy and SciPy](http://docs.scipy.org/doc/)
* [Theano](http://deeplearning.net... |
Profiling a long-running Python Server | 9,819,142 | 6 | 2012-03-22T09:07:47Z | 9,819,426 | 10 | 2012-03-22T09:25:48Z | [
"python",
"performance",
"profiling"
] | I have a long-running [twisted](http://twistedmatrix.com/trac/) server.
In a large system test, at one particular point several minutes into the test, when some clients enter a particular state and a particular outside event happens, *then* this server takes several minutes of 100% CPU and does its work very slowly. I... | [yappi](http://code.google.com/p/yappi/) profiler can be started and stopped at runtime. |
Python to parser a web page's images URLs | 9,819,501 | 2 | 2012-03-22T09:30:19Z | 9,819,986 | 8 | 2012-03-22T10:01:54Z | [
"python",
"regex",
"urllib"
] | This is my code to get a web page's image's URLs
for some webpage, it works very well, while it' dosen't work for some web page
this is my code:
#!/usr/bin/python
```
import urllib2
import re
#bufOne = urllib2.urlopen(r"http://vgirl.weibo.com/5show/user.php?fid=17262", timeout=4).read()
bufTwo = urllib2.urlopen(r"ht... | [Don't use regex to parse HTML](http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags). Rather use [Beautiful Soup](http://www.crummy.com/software/BeautifulSoup/) to find all `img` tags and then get the `src` attributes.
```
from BeautifullSoup import BeautifullSoup
#...
s... |
How can I override class attribute access in python? | 9,820,314 | 5 | 2012-03-22T10:20:38Z | 9,820,370 | 10 | 2012-03-22T10:23:51Z | [
"python",
"attributes"
] | How can I override class attribute access in python?
P.S. Is there a way to leave regular access to class attributes alone but calling a more specific exception on missing attribute? | The [`__getattr__`](http://docs.python.org/dev/reference/datamodel.html#object.__getattr__) magic method is called when the attribute doesn't exist on the instance / class / parent classes. You'd use it to raise a special exception for a missing attribute:
```
class Foo(object):
def __getattr__(self, attr):
... |
HTML Parsing using Python | 9,821,143 | 3 | 2012-03-22T11:11:45Z | 9,821,532 | 7 | 2012-03-22T11:39:21Z | [
"python",
"html",
"parsing",
"html-parsing"
] | I need to parse a webpage and extract some values from it. So I created a python parser as follow:
```
from HTMLParser import HTMLParser
class MyHTMLParser(HTMLParser):
def handle_data(self, data):
print "Data :", data
f=open("result.html","r")
s=f.read()
parser = MyHTMLParser()
parser.feed(s)
```
Th... | My preferred solution for parsing HTML or XML is `lxml` and `xpath`.
A quick and dirty example of how you might use `xpath`:
```
from lxml import etree
data = open('result.html','r').read()
doc = etree.HTML(data)
for tr in doc.xpath('//table/tr[@class="trmenu1"]'):
print tr.xpath('./td/text()')
```
Yields:
```
[... |
How to check in PyMongo if collection exists and if exists empty (remove all from collection)? | 9,822,575 | 12 | 2012-03-22T12:46:25Z | 9,823,024 | 10 | 2012-03-22T13:15:28Z | [
"python",
"mongodb",
"pymongo"
] | How to check in PyMongo if collection exists and if exists empty (remove all from collection)?
I have tried like
```
collection.remove()
```
or
```
collection.remove({})
```
but it doesn't delete collection. How to do that ? | You should use `.drop()` instead of `.remove()`, see documentation for detail: <http://api.mongodb.org/python/current/api/pymongo/collection.html#pymongo.collection.Collection.drop>
=====
Sorry for misunderstanding your question.
To check if a collection exists, use method `collection_names` on database:
```
>>> co... |
How to check in PyMongo if collection exists and if exists empty (remove all from collection)? | 9,822,575 | 12 | 2012-03-22T12:46:25Z | 9,826,294 | 28 | 2012-03-22T16:15:25Z | [
"python",
"mongodb",
"pymongo"
] | How to check in PyMongo if collection exists and if exists empty (remove all from collection)?
I have tried like
```
collection.remove()
```
or
```
collection.remove({})
```
but it doesn't delete collection. How to do that ? | Sample code in Pymongo with comment as explanation:
```
from pymongo import Connection
connection = Connection('localhost', 27017) #Connect to mongodb
print(connection.database_names()) #Return a list of db, equal to: > show dbs
db = connection['testdb1'] #equal to: > use testdb1
print(db.collection_names(... |
Python: How to read a data file with uneven number of columns | 9,823,037 | 8 | 2012-03-22T13:15:59Z | 9,823,556 | 10 | 2012-03-22T13:46:34Z | [
"python",
"file",
"numpy"
] | A friend of mine needs to to read a lot of data (about 18000 data sets) that is all formatted annoyingly. Specifically the data is supposed to be 8 columns and ~ 8000 rows of data, but instead the data is delivered as columns of 7 with the last entry spilling into the first column of the next row.
In addition every ~3... | An even easier approach I just thought of:
```
with open("hk_L1.ref") as f:
data = numpy.array(f.read().split(), dtype=float).reshape(7000, 8)
```
This reads the data as a one-dimensional array first, completely ignoring all new-line characters, and then we reshape it to the desired shape.
While I think that the... |
Check if a directory is a (file system) root | 9,823,143 | 6 | 2012-03-22T13:22:01Z | 9,823,271 | 7 | 2012-03-22T13:29:44Z | [
"python"
] | I have a script that searches for a directory containing a specific file, starting from the current directory and going up the tree (think of trying to find out where the `.git` directory sits).
My method looks like this:
```
def getDir(self,cwd):
path = os.path.abspath(cwd)
if not os.path.isdir(path):
raise ... | I don't think you can find out if it's a file system root portably, however I'd suggest doing a call to [`os.path.realpath()`](https://docs.python.org/2/library/os.path.html#os.path.realpath) on both the current dir and your calculated parent and compare if they're the same -- this means you are spinning your wheels an... |
Check if a directory is a (file system) root | 9,823,143 | 6 | 2012-03-22T13:22:01Z | 10,803,459 | 13 | 2012-05-29T16:54:12Z | [
"python"
] | I have a script that searches for a directory containing a specific file, starting from the current directory and going up the tree (think of trying to find out where the `.git` directory sits).
My method looks like this:
```
def getDir(self,cwd):
path = os.path.abspath(cwd)
if not os.path.isdir(path):
raise ... | ```
if os.path.dirname(path) == path:
# you have yourself root.
# works on Windows and *nix paths.
# does NOT work on Windows shares (\\server\share)
``` |
Python Selenium (waiting for frame, element lookups) | 9,823,272 | 2 | 2012-03-22T13:29:45Z | 9,867,477 | 9 | 2012-03-26T06:19:42Z | [
"python",
"selenium",
"automation",
"frames"
] | I have these includes:
```
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.keys import Keys
```
Browser set up via
```
browser = webdriver.Firefox()
browser.get(loginURL)
```
However sometimes I do
```
browser.switch_to_frame("nameofframe... | You could use `WebDriverWait`:
```
from contextlib import closing
from selenium.webdriver import Chrome as Browser
from selenium.webdriver.support.ui import WebDriverWait
from selenium.common.exceptions import NoSuchFrameException
def frame_available_cb(frame_reference):
"""Return a callback that checks whether ... |
Taking a string of numbers and inserting + and - operators | 9,823,797 | 8 | 2012-03-22T14:00:49Z | 9,823,968 | 9 | 2012-03-22T14:10:22Z | [
"python",
"string",
"recursion"
] | I'm stumped by this seemingly trivial problem...
I would like to use python to take a string of numbers (`"123"` for example) and create a list that has all possible expressions where a `"+"` or `"-"` (or nothing at all) can be inserted between any numbers.
For the example `"123"` the list would be:
```
["123","12+3... | Here's a slightly hacky, but short solution using `itertools.product()`:
```
def plus_minus(s):
for t in itertools.product(["", "+", "-"], repeat=len(s) - 1):
yield "".join(itertools.chain.from_iterable(zip(s, t))) + s[-1]
```
Example:
```
>>> list(plus_minus("123"))
['123', '12+3', '12-3', '1+23', '1+2+... |
python: How do I know what type of exception occured? | 9,823,936 | 64 | 2012-03-22T14:08:54Z | 9,824,019 | 9 | 2012-03-22T14:12:47Z | [
"python",
"exception"
] | I have a function called by the main program:
```
try:
someFunction()
except:
print "exception happened!"
```
but in the middle of the execution of the function it raises exception, so it jumps to the `except` part.
How can I see exactly what happened in the `someFunction()` that caused the exception to happ... | You usually should not catch all possible exceptions with `try: ... except` as this is overly broad. Just catch those that are expected to happen for whatever reason. If you really must, for example if you want to find out more about some problem while debugging, you should do
```
try:
...
except Exception as ex:
... |
python: How do I know what type of exception occured? | 9,823,936 | 64 | 2012-03-22T14:08:54Z | 9,824,050 | 122 | 2012-03-22T14:14:22Z | [
"python",
"exception"
] | I have a function called by the main program:
```
try:
someFunction()
except:
print "exception happened!"
```
but in the middle of the execution of the function it raises exception, so it jumps to the `except` part.
How can I see exactly what happened in the `someFunction()` that caused the exception to happ... | The other answers all point out that you should not catch generic exceptions, but no one seems to want to tell you why, which is essential to understanding when you can break the "rule". [Here](http://stackoverflow.com/a/736029/566644) is an explanation. Basically, it's so that you don't hide
* the fact that an error ... |
Find out whether celery task exists | 9,824,172 | 32 | 2012-03-22T14:21:05Z | 10,074,280 | 7 | 2012-04-09T13:56:20Z | [
"python",
"task",
"status",
"celery"
] | Is it possible to find out whether a task with a certain task id exists? When I try to get the status, I will always get pending.
```
>>> AsyncResult('...').status
'PENDING'
```
I want to know whether a given task id is a real celery task id and not a random string. I want different results depending on whether there... | AsyncResult.state returns PENDING in case of unknown task ids.
> PENDING
>
> Task is waiting for execution or unknown. Any task id that is not
> known is implied to be in the pending state.
<http://docs.celeryproject.org/en/latest/userguide/tasks.html#pending>
You can provide custom task ids if you need to distingui... |
Find out whether celery task exists | 9,824,172 | 32 | 2012-03-22T14:21:05Z | 10,089,358 | 25 | 2012-04-10T13:04:33Z | [
"python",
"task",
"status",
"celery"
] | Is it possible to find out whether a task with a certain task id exists? When I try to get the status, I will always get pending.
```
>>> AsyncResult('...').status
'PENDING'
```
I want to know whether a given task id is a real celery task id and not a random string. I want different results depending on whether there... | Celery does not write a state when the task is sent, this is partly an optimization
(see <http://docs.celeryproject.org/en/latest/userguide/tasks.html#state>).
If you really need it, it's simple to add:
```
from celery import current_app
# `after_task_publish` is available in celery 3.1+
# for older versions use the ... |
Django static Files | 9,824,359 | 4 | 2012-03-22T14:33:11Z | 9,825,550 | 21 | 2012-03-22T15:34:13Z | [
"python",
"html",
"django"
] | I am trying to develop a website with Django following various guides, the documentation and google. I have some flat pages set up that need access to images/css files.
My settings.py file looks like this:
```
# Django settings for FirstBlog project.
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name'... | Django is an fantastic system. Feature rich and yet still simple, elegant & extremely well documented, with excellent examples.....for everything EXCEPT static content. We struggle with this on every new Django project. But we recently solved this, in what we believe is the "recommended" way.
The key bit of knowledge ... |
How come a file doesn't get written until I stop the program? | 9,824,806 | 7 | 2012-03-22T14:56:44Z | 9,824,894 | 27 | 2012-03-22T15:01:10Z | [
"python",
"file",
"operating-system"
] | I'm running a test, and found that the file doesn't actually get written until I control-C to abort the program. Can anyone explain why that would happen?
I expected it to write at the same time, so I could read the file in the middle of the process.
```
import os
from time import sleep
f = open("log.txt", "a+")
i =... | Writing to disk is slow, so many programs store up writes into large chunks which they write all-at-once. This is called *buffering*, and Python does it automatically when you open a file.
When you write to the file, you're actually writing to a "buffer" in memory. When it fills up, Python will automatically write it ... |
Run many functions in parallel, and gather all results in a list | 9,825,777 | 4 | 2012-03-22T15:46:26Z | 9,826,110 | 8 | 2012-03-22T16:04:52Z | [
"python",
"python-3.x",
"parallel-processing"
] | I have a very CPU-intensive function:
```
def entity_intersections(ent, collidable):
intersections = []
for line1, line2 in product(ent.shape, collidable.shape):
pair_intersections = find_intersections(line1 + ent.position, ent.velocity, ent.acceleration, line2 + collidable.position, collidable.veloc... | The easiest way is to use the `multiprocessing` module:
```
class FindIntersectionsWrapper(object):
def __init__(self, ent, collidable):
self.ent = ent
self.collidable = collidable
def __call__(self, dims):
line1, line2 = dims
return find_intersections(
line1 + self.... |
Trying to understand linking procedure for writing Python/C++ hybrid | 9,826,311 | 6 | 2012-03-22T16:16:06Z | 9,826,603 | 8 | 2012-03-22T16:35:00Z | [
"c++",
"python"
] | I want to start learning more about using SWIG and other methods to interface Python and C++. To get started, I wanted to compile this simple program mentioned in [another post](http://stackoverflow.com/questions/9824949/how-to-solve-the-segmentation-fault-when-hybrid-programming-of-c-python):
```
#include <Python.h> ... | What you are seeing are linker errors. To fix those, you need to link `python2.7` library.
Try next line :
```
gcc -I/usr/include/python2.7 test.c -lpython2.7
```
it should work. |
Python values of multiple lists in one list comprehension | 9,826,867 | 8 | 2012-03-22T16:51:49Z | 9,826,895 | 17 | 2012-03-22T16:53:12Z | [
"python",
"list",
"iterator",
"list-comprehension"
] | Is there any smart way to write a list comprehension over more than one list?
I know I could use a separate range list as index but this way I have to know the length (or get it separately with a `len()` function call).
```
>>> a = range(10)
>>> b = range(10, 0, -1)
>>> [(a[x],b[x]) for x in range(10)]
[(0, 10), (1, ... | Your example is just:
```
zip(range(10), range(10, 0, -1))
```
More generally, you can join any set of iterables using [`zip`](http://docs.python.org/library/functions.html#zip):
```
[func(a, d, ...) for a, b, ..., n in zip(iterable1, iterable2, ..., iterableN)]
``` |
Django ModelChoiceField - use something other than id? | 9,827,057 | 5 | 2012-03-22T17:06:20Z | 11,522,820 | 14 | 2012-07-17T12:49:25Z | [
"python",
"django",
"validation",
"django-forms",
"django-validation"
] | Say I have an `address` table and it has a `postal_code` field -- ModelChoiceField does not allow me to use something other than PKs to validate existence correct? What would be the way to go? Normal input and use `clean_*()`? | What about `to_field_name`? I'm not sure if it's documented anywhere, but you can find it easily between `ModelChoiceField` constructor params: <https://github.com/django/django/blob/master/django/forms/models.py>. It is used to filter field queryset.
For example:
```
articles = ModelChoiceField(queryset=Articles.obj... |
zipping a python dict of lists | 9,828,072 | 2 | 2012-03-22T18:11:31Z | 9,828,130 | 10 | 2012-03-22T18:15:45Z | [
"python"
] | I have a python dictionary of type defaultdict(list)
This dictionary is something like this:
```
a = {1:[1,2,3,4],2:[5,6,7,8]....n:[some 4 elements]}
```
So basically it has n keys which has a list as values and all the list are of same lenght.
Now, i want to build a list which has something like this.
```
[[1,5,...... | ```
>>> a = {1:[1,2,3,4],2:[5,6,7,8], 3:[9, 10, 11, 12]}
>>>
>>> zip(*(a[k] for k in sorted(a)))
[(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)]
```
(Okay, this produces tuples, not lists, but hopefully that's not a problem.)
Update: I like the above more than this, but the following is a few keystrokes shorter:
``... |
How to get min, seconds and milliseconds from datetime.now() in python? | 9,828,311 | 3 | 2012-03-22T18:27:48Z | 9,828,399 | 15 | 2012-03-22T18:34:16Z | [
"python",
"datetime",
"time"
] | ```
>>> a = str(datetime.now())
>>> a
'2012-03-22 11:16:11.343000'
```
I need to get a string like that: `'16:11.34'`.
Should be as compact as possible.
Or should I use time() instead?
How do I get it? | What about:
`datetime.now().strftime('%M:%S.%f')[:-4]`
I'm not sure what you mean by "Milliseconds only 2 digits", but this should keep it to 2 decimal places. There may be a more elegant way by manipulating the strftime format string to cut down on the precision as well -- I'm not completely sure.
**EDIT**
If the ... |
Pip install Matplotlib error with virtualenv | 9,829,175 | 86 | 2012-03-22T19:28:30Z | 9,843,560 | 149 | 2012-03-23T17:14:03Z | [
"python",
"matplotlib",
"pip",
"virtualenv"
] | I am trying to install matplotlib in a new virtualenv.
When I do:
```
pip install matplotlib
```
or
```
pip install http://sourceforge.net/projects/matplotlib/files/matplotlib/matplotlib-1.1.0/matplotlib-1.1.0.tar.gz
```
I get this error:
```
building 'matplotlib._png' extension
gcc -pthread -fno-strict-aliasing... | Building Matplotlib requires `libpng` (and `freetype`, as well) which isn't a python library, so `pip` doesn't handle installing it (or `freetype`).
You'll need to install something along the lines of `libpng-devel` and `freetype-devel` (or whatever the equivalent is for your OS).
See the [building requirements/instr... |
Pip install Matplotlib error with virtualenv | 9,829,175 | 86 | 2012-03-22T19:28:30Z | 21,883,098 | 43 | 2014-02-19T14:15:28Z | [
"python",
"matplotlib",
"pip",
"virtualenv"
] | I am trying to install matplotlib in a new virtualenv.
When I do:
```
pip install matplotlib
```
or
```
pip install http://sourceforge.net/projects/matplotlib/files/matplotlib/matplotlib-1.1.0/matplotlib-1.1.0.tar.gz
```
I get this error:
```
building 'matplotlib._png' extension
gcc -pthread -fno-strict-aliasing... | To generate graph in png format you need to Install following dependent packages
```
sudo apt-get install libpng-dev
sudo apt-get install libfreetype6-dev
``` |
Pip install Matplotlib error with virtualenv | 9,829,175 | 86 | 2012-03-22T19:28:30Z | 23,671,651 | 21 | 2014-05-15T07:18:46Z | [
"python",
"matplotlib",
"pip",
"virtualenv"
] | I am trying to install matplotlib in a new virtualenv.
When I do:
```
pip install matplotlib
```
or
```
pip install http://sourceforge.net/projects/matplotlib/files/matplotlib/matplotlib-1.1.0/matplotlib-1.1.0.tar.gz
```
I get this error:
```
building 'matplotlib._png' extension
gcc -pthread -fno-strict-aliasing... | As a supplementary, on Amazon EC2, what I need to do is:
```
sudo yum install freetype-devel
sudo yum install libpng-devel
sudo pip install matplotlib
``` |
Pip install Matplotlib error with virtualenv | 9,829,175 | 86 | 2012-03-22T19:28:30Z | 32,347,231 | 25 | 2015-09-02T07:39:56Z | [
"python",
"matplotlib",
"pip",
"virtualenv"
] | I am trying to install matplotlib in a new virtualenv.
When I do:
```
pip install matplotlib
```
or
```
pip install http://sourceforge.net/projects/matplotlib/files/matplotlib/matplotlib-1.1.0/matplotlib-1.1.0.tar.gz
```
I get this error:
```
building 'matplotlib._png' extension
gcc -pthread -fno-strict-aliasing... | As I have struggled with this issue twice (even after fresh kubuntu 15.04 install) and installing freetype did not solve anything, I investigated further.
**The solution:**
[From github issue:](https://github.com/matplotlib/matplotlib/issues/3029/)
> This bug only occurs if pkg-config is not installed;
> a simple... |
How do I handle multiple asserts within a single Python unittest? | 9,829,331 | 8 | 2012-03-22T19:40:28Z | 14,107,323 | 11 | 2013-01-01T01:43:45Z | [
"python",
"unit-testing",
"testing",
"unittest2"
] | This is a problem that came up when performing a single test that had multiple independent failure modes, due to having multiple output streams. I also wanted to show the results of asserting the data on all those modes, regardless of which failed first. Python's unittest has no such feature outside of using a Suite to... | I disagree with the dominant opinion that one should write a test method for each assertion. There are situations where you want to check multiple things in one test method. Here is my answer for how to do it:
```
# Works with unittest in Python 2.7
class ExpectingTestCase(unittest.TestCase):
def run(self, result=... |
fast way of counting non-zero bits in python | 9,829,578 | 58 | 2012-03-22T19:58:59Z | 9,829,736 | 9 | 2012-03-22T20:09:27Z | [
"python",
"binary",
"counting"
] | I need a fast way to count the number of bits in an integer in python.
My current solutions is
```
bin(n).count("1")
```
but I am wondering if there is any faster way of doing this?
PS: (i am representing a big 2D binary array as a singe list of numbers and doing bitwise operations, and that brings the time down fro... | Here's a Python implementation of the population count algorithm, as explained in this [post](http://stackoverflow.com/questions/109023/best-algorithm-to-count-the-number-of-set-bits-in-a-32-bit-integer#109025):
```
def numberOfSetBits(i):
i = i - ((i >> 1) & 0x55555555)
i = (i & 0x33333333) + ((i >> 2) & 0x33... |
fast way of counting non-zero bits in python | 9,829,578 | 58 | 2012-03-22T19:58:59Z | 9,830,282 | 14 | 2012-03-22T20:48:53Z | [
"python",
"binary",
"counting"
] | I need a fast way to count the number of bits in an integer in python.
My current solutions is
```
bin(n).count("1")
```
but I am wondering if there is any faster way of doing this?
PS: (i am representing a big 2D binary array as a singe list of numbers and doing bitwise operations, and that brings the time down fro... | You can adapt the following algorithm:
```
def CountBits(n):
n = (n & 0x5555555555555555) + ((n & 0xAAAAAAAAAAAAAAAA) >> 1)
n = (n & 0x3333333333333333) + ((n & 0xCCCCCCCCCCCCCCCC) >> 2)
n = (n & 0x0F0F0F0F0F0F0F0F) + ((n & 0xF0F0F0F0F0F0F0F0) >> 4)
n = (n & 0x00FF00FF00FF00FF) + ((n & 0xFF00FF00FF00FF00) >> 8... |
fast way of counting non-zero bits in python | 9,829,578 | 58 | 2012-03-22T19:58:59Z | 9,831,671 | 52 | 2012-03-22T22:46:15Z | [
"python",
"binary",
"counting"
] | I need a fast way to count the number of bits in an integer in python.
My current solutions is
```
bin(n).count("1")
```
but I am wondering if there is any faster way of doing this?
PS: (i am representing a big 2D binary array as a singe list of numbers and doing bitwise operations, and that brings the time down fro... | For arbitrary-length integers, `bin(n).count("1")` is the fastest I could find in pure Python.
I tried adapting Ãscar's and Adam's solutions to process the integer in 64-bit and 32-bit chunks, respectively. Both were at least ten times slower than `bin(n).count("1")` (the 32-bit version took about half again as much ... |
Determine non-convex hull of collection of line segments | 9,830,218 | 28 | 2012-03-22T20:44:44Z | 9,830,609 | 14 | 2012-03-22T21:12:18Z | [
"python",
"algorithm",
"language-agnostic",
"geometry",
"computational-geometry"
] | I have a computational geometry problem that I feel should have a relatively simple solution, but I can't quite figure it out.
I need to determine the non-convex outline of a region defined by several line segments.
I'm aware of various non-convex hull algorithms (e.g. alpha shapes), but I don't need a fully general ... | 1. Pick a safe starting point. Can be e.g. the endpoint with maximum x.
2. March along the line segment.
3. Upon encountering any intersection, always turn left and march along this new segment.
4. Upon encountering an endpoint, record it. Goto 2.
5. Stop when you have returned to your starting point. Your list of reco... |
Is open().read() safe? | 9,831,097 | 16 | 2012-03-22T21:50:05Z | 9,831,151 | 19 | 2012-03-22T21:54:36Z | [
"python",
"file"
] | I write a lot of Python code where I just want to read a file to a variable. I know the two recommended ways are these -
```
with open('file') as f:
data = f.read()
# or
fo = open('file')
data = f.read()
fo.close()
```
My questions, is what are the downsides of this?
```
data = open('file').read()
``` | The downside of
```
data = open('file').read()
```
is that depending on your Python implementation, the cleanup of the open file object may or may not happen right away. This means that the file will stay open, consuming a file handle. This probably isn't a problem for a single file, but in a loop it could certainly ... |
Break string into list of characters in Python | 9,833,392 | 17 | 2012-03-23T02:32:20Z | 9,833,405 | 41 | 2012-03-23T02:34:10Z | [
"python",
"list",
"readlines"
] | So what i want to do is essentially suck a line of txt from a .txt file, then assign the characters to a list, and then creat a list of all the separate characters in a list.
So a list of lists.
At the moment, I've tried:
```
fO = open(filename, 'rU')
fL = fO.readlines()
```
and that's all im up to. I dont quite kn... | You can do this using [list](http://docs.python.org/library/functions.html#list):
```
fNewList=list(fL);
```
Be aware that any spaces in the line will be included in this list, to the best of my knowledge. |
Break string into list of characters in Python | 9,833,392 | 17 | 2012-03-23T02:32:20Z | 9,833,427 | 13 | 2012-03-23T02:37:27Z | [
"python",
"list",
"readlines"
] | So what i want to do is essentially suck a line of txt from a .txt file, then assign the characters to a list, and then creat a list of all the separate characters in a list.
So a list of lists.
At the moment, I've tried:
```
fO = open(filename, 'rU')
fL = fO.readlines()
```
and that's all im up to. I dont quite kn... | Strings are iterable (just like a list).
I'm interpreting that you really want something like:
```
fd = open(filename,'rU')
chars = []
for line in fd:
for c in line:
chars.append(c)
```
or
```
fd = open(filename, 'rU')
chars = []
for line in fd:
chars.extend(line)
```
or
```
chars = []
with open(fil... |
django order_by query set, ascending and descending | 9,834,038 | 83 | 2012-03-23T04:05:29Z | 9,834,153 | 178 | 2012-03-23T04:24:35Z | [
"python",
"django",
"sorting"
] | How can I order by descending my query set in django by date?
```
Reserved.objects.all().filter(client=client_id).order_by('check_in')
```
I just want to filter from descending all the Reserved by check\_in date. | ```
Reserved.objects.filter(client=client_id).order_by('-check_in')
```
Notice the `-` before `check_in`.
[Django Documentation](https://docs.djangoproject.com/en/dev/ref/models/querysets/#order-by "Documentation") |
django order_by query set, ascending and descending | 9,834,038 | 83 | 2012-03-23T04:05:29Z | 9,835,125 | 30 | 2012-03-23T06:42:47Z | [
"python",
"django",
"sorting"
] | How can I order by descending my query set in django by date?
```
Reserved.objects.all().filter(client=client_id).order_by('check_in')
```
I just want to filter from descending all the Reserved by check\_in date. | ```
Reserved.objects.filter(client=client_id).order_by('-check_in')
```
A hyphen "-" in front of "check\_in" indicates descending order. Ascending order is implied.
We don't have to add an all() before filter(). That would still work, but you only need to add all() when you want all objects from the root QuerySet.
M... |
django order_by query set, ascending and descending | 9,834,038 | 83 | 2012-03-23T04:05:29Z | 21,253,215 | 7 | 2014-01-21T08:50:30Z | [
"python",
"django",
"sorting"
] | How can I order by descending my query set in django by date?
```
Reserved.objects.all().filter(client=client_id).order_by('check_in')
```
I just want to filter from descending all the Reserved by check\_in date. | It works removing `.all()`:
```
Reserved.objects.filter(client=client_id).order_by('-check_in')
``` |
how do I make a single legend for many subplots with matplotlib? | 9,834,452 | 39 | 2012-03-23T05:13:11Z | 9,837,940 | 38 | 2012-03-23T10:50:49Z | [
"python",
"matplotlib"
] | I am plotting the same type of information, but for different countries, with multiple subplots with matplotlib. That is, I have 9 plots on a 3x3 grid, all with the same for lines (of course, different values per line).
However, I have not figured out how to put a single legend (since all 9 subplots have the same line... | figlegend may be what you're looking for: <http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.figlegend>
Example here: <http://matplotlib.org/examples/pylab_examples/figlegend_demo.html>
Another example:
```
plt.figlegend( lines, labels, loc = 'lower center', ncol=5, labelspacing=0. )
```
or:
```
fig.lege... |
how do I make a single legend for many subplots with matplotlib? | 9,834,452 | 39 | 2012-03-23T05:13:11Z | 17,328,230 | 7 | 2013-06-26T18:54:50Z | [
"python",
"matplotlib"
] | I am plotting the same type of information, but for different countries, with multiple subplots with matplotlib. That is, I have 9 plots on a 3x3 grid, all with the same for lines (of course, different values per line).
However, I have not figured out how to put a single legend (since all 9 subplots have the same line... | For the automatic positioning of a single legend in a `figure` with many axes, like those obtained with `subplots()`, the following solution works really well:
```
plt.legend( lines, labels, loc = 'lower center', bbox_to_anchor = (0,-0.1,1,1),
bbox_transform = plt.gcf().transFigure )
```
With `bbox_to_anc... |
Where is a good place to work on accounts/profile in Django with the Django registration app? | 9,835,760 | 15 | 2012-03-23T07:59:48Z | 9,835,980 | 10 | 2012-03-23T08:23:49Z | [
"python",
"django",
"django-registration",
"django-profiles"
] | I've noticed that after I log in with Django registration it redirects me to `accounts/profile/`. By default Django registration's `url.py` doesn't handle `accounts/profile/`, so I need to create my own.
Actually this questions is three-fold:
1. Why does after logging in, it redirects to `accounts/profile/`? Is there... | > Why does after logging in, it redirects to accounts/profile/? Is there
> a way to change that? Preferably after successfully logging in I would
> like Django to redirect back to the page before the login page.
Just change setting [LOGIN\_REDIRECT\_URL](https://docs.djangoproject.com/en/dev/ref/settings/#login-redire... |
Find and list duplicates in Python list | 9,835,762 | 144 | 2012-03-23T07:59:59Z | 9,835,819 | 165 | 2012-03-23T08:05:44Z | [
"python",
"list",
"duplicates"
] | How can I find the duplicates in a Python list and create another list of the duplicates? The list is just integers. | To remove duplicates use `set(a)`, to print duplicates - something like
```
a = [1,2,3,2,1,5,6,5,5,5]
import collections
print [item for item, count in collections.Counter(a).items() if count > 1]
## [1, 2, 5]
```
Note that `Counter` is not particularly efficient ([timings](http://stackoverflow.com/a/25706298/98912... |
Find and list duplicates in Python list | 9,835,762 | 144 | 2012-03-23T07:59:59Z | 9,836,685 | 39 | 2012-03-23T09:25:06Z | [
"python",
"list",
"duplicates"
] | How can I find the duplicates in a Python list and create another list of the duplicates? The list is just integers. | You don't need the count, just whether or not the item was seen before. Adapted [that answer](http://stackoverflow.com/a/480227/1025391) to this problem:
```
def list_duplicates(seq):
seen = set()
seen_add = seen.add
# adds all elements it doesn't know yet to seen and all other to seen_twice
seen_twice = set( ... |
Find and list duplicates in Python list | 9,835,762 | 144 | 2012-03-23T07:59:59Z | 15,155,286 | 132 | 2013-03-01T10:19:20Z | [
"python",
"list",
"duplicates"
] | How can I find the duplicates in a Python list and create another list of the duplicates? The list is just integers. | ```
>>> l = [1,2,3,4,4,5,5,6,1]
>>> set([x for x in l if l.count(x) > 1])
set([1, 4, 5])
``` |
Find and list duplicates in Python list | 9,835,762 | 144 | 2012-03-23T07:59:59Z | 31,439,372 | 9 | 2015-07-15T19:28:04Z | [
"python",
"list",
"duplicates"
] | How can I find the duplicates in a Python list and create another list of the duplicates? The list is just integers. | I came across this question whilst looking in to something related - and wonder why no-one offered a generator based solution? Solving this problem would be:
```
>>> print list(getDupes_9([1,2,3,2,1,5,6,5,5,5]))
[1, 2, 5]
```
I was concerned with scalability, so tested several approaches, including naive items that w... |
Why raising a tuple works if first element is an Exception? | 9,836,756 | 17 | 2012-03-23T09:30:29Z | 9,837,552 | 13 | 2012-03-23T10:24:15Z | [
"python",
"exception",
"tuples"
] | I have a hard time figuring this one out, it's about mistakes that can be done when raising an exception in Python 2.7:
```
try:
raise [1, 2, 3, 4]
except Exception as ex:
print ex
```
the message here is "exceptions must be old-style classes or derived from BaseException, not list" - This part is ok, but when I ... | As [documented in the python reference](http://docs.python.org/reference/simple_stmts.html#the-raise-statement), the `raise` statement takes up to 3 expressions to create the exception being raised:
> raise\_stmt ::= "raise" [expression ["," expression ["," expression]]]
In python 2, if the first expression is a tupl... |
scipy linkage format | 9,838,861 | 11 | 2012-03-23T12:01:46Z | 10,956,285 | 13 | 2012-06-08T21:33:20Z | [
"python",
"scipy",
"dendrogram"
] | I have written my own clustering routine and would like to produce a dendrogram. The easiest way to do this would be to use scipy dendrogram function. However, this requires the input to be in the same format that the scipy linkage function produces. I cannot find an example of how the output of this is formatted. I wa... | This is from the [scipy.cluster.hierarchy.linkage()](http://docs.scipy.org/doc/scipy/reference/generated/scipy.cluster.hierarchy.linkage.html#scipy.cluster.hierarchy.linkage) function documentation, I think it's a pretty clear description for the output format:
> A 4 by (*n*-1) matrix Z is returned. At the *i*-th iter... |
HTTPS request in Python | 9,839,179 | 7 | 2012-03-23T12:27:21Z | 9,839,316 | 10 | 2012-03-23T12:36:57Z | [
"python",
"https"
] | I would like to connect to a site via HTTPS in Python 3.2.
I tried
```
conn = http.client.HTTPSConnection(urlStr, 8443)
conn.putrequest('GET', '/')
response = conn.getresponse()
print(response.read())
```
but I get
```
http.client.ResponseNotReady: Request-started
```
Anyone know what the pro... | First of all, if you just want to download something and don't want any special HTTP requests, you should use [`urllib.request`](http://docs.python.org/release/3.2/library/urllib.request.html) instead of `http.client`.
```
import urllib.request
r = urllib.request.urlopen('https://paypal.com/')
print(r.read())
```
If ... |
How to determine if Python script was run via command line? | 9,839,240 | 14 | 2012-03-23T12:32:08Z | 9,839,287 | 10 | 2012-03-23T12:35:32Z | [
"python",
"command-line"
] | ## Background
I would like my Python script to pause before exiting using something similar to:
`raw_input("Press enter to close.")`
but only if it is NOT run via command line. Command line programs shouldn't behave this way.
## Question
Is there a way to determine if my Python script was invoked from the command ... | If you're running it without a terminal, as when you click on "Run" in Nautilus, you can just check if it's attached to a tty:
```
import sys
if sys.stdin.isatty():
# running interactively
print "running interactively"
else:
with open('output','w') as f:
f.write("running in the background!\n")
```
... |
Subclass - Arguments From Superclass | 9,840,197 | 15 | 2012-03-23T13:40:03Z | 9,840,380 | 12 | 2012-03-23T13:53:50Z | [
"python",
"inheritance"
] | I'm a little confused about how arguments are passed between Subclasses and Superclasses in Python. Consider the following class structure:
```
class Superclass(object):
def __init__(self, arg1, arg2, arg3):
#Inilitize some variables
#Call some methods
class Subclass(Superclass):
def __init__(... | There's no magic happening! `__init__` methods work just like all others. You need to explicitly take all the arguments you need in the subclass initialiser, and pass them through to the superclass.
```
class Superclass(object):
def __init__(self, arg1, arg2, arg3):
#Initialise some variables
#Call... |
How do I turn a list of tuples into a dictionary while keeping redundant values? | 9,840,783 | 2 | 2012-03-23T14:17:29Z | 9,840,828 | 14 | 2012-03-23T14:19:51Z | [
"python",
"list",
"dictionary",
"tuples"
] | I'm getting a data set that's formatted as a list of key-value pairs. The key is the data source, and the value is the data element. For example:
```
[('a', 3), ('b', 5), ('a', 7), ('c', 15), ('d', 12)]
```
I want to turn this list into a dictionary. I could use Python's built-in `dict()`, but it throws away redundan... | You can use the `setdefault()` method of dictionaries:
```
d = {}
for key, value in my_list:
d.setdefault(key, []).append(value)
```
This can also be done with a `defaultdict`. Which of the two options is preferable depends on how `d` is used in the rest of the code. A `defaultdict` will never give you a `KeyErro... |
How do I turn a list of tuples into a dictionary while keeping redundant values? | 9,840,783 | 2 | 2012-03-23T14:17:29Z | 9,840,844 | 7 | 2012-03-23T14:21:02Z | [
"python",
"list",
"dictionary",
"tuples"
] | I'm getting a data set that's formatted as a list of key-value pairs. The key is the data source, and the value is the data element. For example:
```
[('a', 3), ('b', 5), ('a', 7), ('c', 15), ('d', 12)]
```
I want to turn this list into a dictionary. I could use Python's built-in `dict()`, but it throws away redundan... | The `dict` subclass `defaultdict` in the `collections` module can be used to automatically initialize a new `list` for each key the first time you access it.
With it, you just need to loop through the input pairs and append each value to the `list` of the corresponding key in order to produce the lists of values you w... |
How to use assertRaises in a trial test case using inlineCallbacks | 9,840,884 | 9 | 2012-03-23T14:23:19Z | 9,845,956 | 13 | 2012-03-23T20:15:24Z | [
"python",
"twisted",
"trial"
] | I'm trying to figure out how to write a trial test case which asserts an exception is raised.
Currently I have 2 simple methods to test (success and failure). Each method returns a deferred which has already been either callback'd or errback'd. Testing the success method works fine. When testing the failure method I e... | Use `TestCase.assertFailure` instead:
```
yield self.assertFailure(self.o.failure(), ConnectionRefusedError)
```
Starting in Twisted 12.3, there's also a `TestCase.failureResultOf` helper:
```
self.failureResultOf(self.o.failure()).trap(ConnectionRefusedError)
```
And starting in 13.1 this API takes an additional a... |
how to plot on a smaller scale | 9,841,220 | 4 | 2012-03-23T14:43:39Z | 9,841,910 | 9 | 2012-03-23T15:25:00Z | [
"python",
"matplotlib"
] | I am using matplotlib and I'm finding some problems when trying to plot large vectors.
sometimes get "MemoryError"
My question is whether there is any way to reduce the scale of values ââthat i need to plot ?

In this example I'm plotting a vector... | It is very unlikely that you have so much resolution on your display that you can see 2.6 million data points in your plot. A simple way to plot less data is to sample e.g. every 1000th point: `plot(x[::1000])`. If that loses too much and it is e.g. important to see the extremal values, you could write some code to spl... |
Removing duplicate characters from a string | 9,841,303 | 15 | 2012-03-23T14:50:11Z | 9,841,328 | 34 | 2012-03-23T14:51:46Z | [
"python"
] | How can I remove duplicate characters from a string using Python? For example, let's say I have a string:
```
foo = 'mppmt'
```
How can I make the string:
```
foo = 'mpt'
```
NOTE: Order is not important | If order does not matter, you can use
```
"".join(set(foo))
```
`set()` will create a set of unique letters in the string, and `"".join()` will join the letters back to a string in arbitrary order.
If order *does* matter, you can use `collections.OrderedDict` in Python 2.7:
```
from collections import OrderedDict
f... |
Removing duplicate characters from a string | 9,841,303 | 15 | 2012-03-23T14:50:11Z | 9,841,401 | 14 | 2012-03-23T14:56:00Z | [
"python"
] | How can I remove duplicate characters from a string using Python? For example, let's say I have a string:
```
foo = 'mppmt'
```
How can I make the string:
```
foo = 'mpt'
```
NOTE: Order is not important | If order *does* matter, how about:
```
>>> foo = 'mppmt'
>>> ''.join(sorted(set(foo), key=foo.index))
'mpt'
``` |
BeautifulSoup HTMLParseError | 9,841,757 | 4 | 2012-03-23T15:17:12Z | 9,841,943 | 22 | 2012-03-23T15:27:12Z | [
"python",
"beautifulsoup"
] | New to Python, have a simple, situational question:
Trying to use BeautifulSoup to parse a series of pages.
```
from bs4 import BeautifulSoup
import urllib.request
BeautifulSoup(urllib.request.urlopen('http://bit.ly/xg7enD'))
```
Traceback ...
`html.parser.HTMLParseError: expected name token at '<!=KN\x01...`
Wor... | If that URL is correct, you're asking why an HTML parser throws an error parsing an MP3 file. I believe the answer to this to be self-evident... |
Pythonic way to eval all octal values in a string as integers | 9,843,033 | 6 | 2012-03-23T16:38:18Z | 9,843,145 | 8 | 2012-03-23T16:45:28Z | [
"python",
"string",
"eval"
] | So I've got a string that looks like `"012 + 2 - 01 + 24"` for example. I want to be able to quickly (less code) evaluate that expression...
I could use eval() on the string, but I don't want `012` to be represented in octal form (10), I want it to be represented as an int (12).
My solution for this works, but it is ... | I'd be tempted to use regular expressions to remove the leading zeroes:
```
>>> re.sub(r'\b0+(?!\b)', '', '012 + 2 + 0 - 01 + 204 - 0')
'12 + 2 + 0 - 1 + 204 - 0'
```
This removes zeroes at the start of every number, except when the number consists entirely of zeroes:
* the first `\b` matches a word (token) boundary... |
If duck-typing in Python, should you test isinstance? | 9,843,569 | 13 | 2012-03-23T17:14:55Z | 9,843,690 | 11 | 2012-03-23T17:22:15Z | [
"python",
"equality",
"duck-typing"
] | You have a Python class which needs an equals test. Python should use duck-typing but is it (better/more accurate) to include or exclude an isinstance test in the **eq** function? For example:
```
class Trout(object):
def __init__(self, value):
self.value = value
def __eq__(self, other):
retur... | Using isinstance in `__eq__` methods is pretty common. The reason for this is that if the `__eq__` method fails, it can fallback on an `__eq__` method from another object. Most normal methods are called explicitly, but `__eq__` is called implicitly, so it requires look-before-you-leap more frequently.
EDIT (thanks for... |
Flask-SQLAlchemy nullable=False | 9,844,150 | 3 | 2012-03-23T17:53:05Z | 9,845,764 | 10 | 2012-03-23T19:59:54Z | [
"python",
"sqlalchemy",
"flask",
"flask-sqlalchemy"
] | I'm messing around with Flask and the Flask-SQLAlchemy extension to create a simple registration form. In my User class, I have the attribute "email" set to nullable=False, but when I test the form on the site without including an email, it saves the new user to the db instead of throwing an exception as I expected. An... | The problem is when you submit the webform without entering an email it will contain an empty string "" .. not None... and an empty string is not the same als null and it is ok to store it in the field.
I suggest using something like wtforms to validate the input of the user. |
Using MySQL in Flask | 9,845,102 | 5 | 2012-03-23T19:06:52Z | 10,257,572 | 15 | 2012-04-21T08:56:02Z | [
"python",
"mysql",
"web-services",
"flask"
] | Can someone share example codes in Flask on how to access a MySQL DB? There have been documents showing how to connect to sqlite but not on MySQL.
Thank you very much in advance | ```
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://username:password@server/db'
db = SQLAlchemy(app)
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True)
... |
Using MySQL in Flask | 9,845,102 | 5 | 2012-03-23T19:06:52Z | 28,784,451 | 10 | 2015-02-28T17:07:15Z | [
"python",
"mysql",
"web-services",
"flask"
] | Can someone share example codes in Flask on how to access a MySQL DB? There have been documents showing how to connect to sqlite but not on MySQL.
Thank you very much in advance | Firstly you need to install Flask-MySQL package. Using `pip` for example:
`pip install flask-mysql`
Next you need to add some configuration and initialize MySQL:
```
from flask import Flask
from flaskext.mysql import MySQL
app = Flask(__name__)
mysql = MySQL()
app.config['MYSQL_DATABASE_USER'] = 'root'
app.config['... |
Comparing 2 lists consisting of dictionaries with unique keys in python | 9,845,369 | 8 | 2012-03-23T19:28:13Z | 9,845,430 | 16 | 2012-03-23T19:32:54Z | [
"python",
"list",
"dictionary",
"compare"
] | I have 2 lists, both of which contain same number of dictionaries. Each dictionary has a unique key. There is a match for each dictionary of the first list in the second list, that is a dictionary with a unique key exists in the other list. But the other elements of such 2 dictionaries may vary. For example:
```
list_... | Assuming that the dicts line up like in your example input, you can use the `zip()` function to get a list of associated pairs of dicts, then you can use `any()` to check if there is a difference:
```
>>> list_1 = [{'unique_id':'001', 'key1':'AAA', 'key2':'BBB', 'key3':'EEE'},
{'unique_id':'002', 'key1'... |
Does Python csv writer always use DOS end-of-line characters? | 9,845,681 | 11 | 2012-03-23T19:53:05Z | 9,845,731 | 28 | 2012-03-23T19:58:12Z | [
"python",
"csv",
"line-endings",
"writer"
] | I realize that the **csv** library in Python always generates DOS end-of-line characters. Even if I use the `'wb'` mode, even if I use Linux.
```
import csv
f = open('output.txt', 'wb');
writer = csv.writer(f)
writer.writerow([2,3,4]);
f.close()
```
The above code always uses `'\r\n'` as the end of line separator. H... | You can [give your `writer`](http://docs.python.org/library/csv.html#csv.writer) instance a custom [`lineterminator`](http://docs.python.org/library/csv.html#csv.Dialect.lineterminator) argument in the constructor:
```
writer = csv.writer(f, lineterminator="\n")
``` |
Does Python csv writer always use DOS end-of-line characters? | 9,845,681 | 11 | 2012-03-23T19:53:05Z | 29,976,091 | 11 | 2015-04-30T19:24:05Z | [
"python",
"csv",
"line-endings",
"writer"
] | I realize that the **csv** library in Python always generates DOS end-of-line characters. Even if I use the `'wb'` mode, even if I use Linux.
```
import csv
f = open('output.txt', 'wb');
writer = csv.writer(f)
writer.writerow([2,3,4]);
f.close()
```
The above code always uses `'\r\n'` as the end of line separator. H... | As [Niklas answered](http://stackoverflow.com/a/9845731/4794), the [lineterminator argument](https://docs.python.org/2/library/csv.html#csv.Dialect.lineterminator) lets you choose your line endings. Rather than hard coding it to `\n`, make it platform independent by using your platform's [line separator](https://docs.p... |
Bytes in a unicode Python string | 9,845,842 | 24 | 2012-03-23T20:05:54Z | 9,846,246 | 11 | 2012-03-23T20:42:10Z | [
"python",
"unicode",
"utf-8",
"character-encoding"
] | In Python 2, Unicode strings may contain both unicode and bytes:
```
a = u'\u0420\u0443\u0441\u0441\u043a\u0438\u0439 \xd0\xb5\xd0\xba'
```
I understand that this is absolutely **not something one should write** in his own code, but this is a string that I have to deal with.
The bytes in the string above are UTF-8 f... | The problem is that your string is **not actually encoded in a specific encoding**. Your example string:
```
a = u'\u0420\u0443\u0441\u0441\u043a\u0438\u0439 \xd0\xb5\xd0\xba'
```
Is mixing python's internal representation of unicode strings with `utf-8` encoded text. If we just consider the 'special' characters:
``... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.