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
python pandas date read_table
13,953,276
4
2012-12-19T13:17:29Z
13,953,332
8
2012-12-19T13:21:07Z
[ "python", "date", "pandas" ]
I have the following input file: ``` 2012,10,3,AAPL,BUY,200 2012,12,5,AAPL,SELL,200 ``` How can I read this in into a pandas dataframe wth following columns: ``` index: default int range # 0 column1: datetime(2012,10,3,16) # 2012-10-03 16:00 column2: string # AAPL column3: string # BUY column4: integer # 200 ``` Ex...
Try using the [read\_csv()](http://pandas.pydata.org/pandas-docs/dev/generated/pandas.io.parsers.read_csv.html#pandas.io.parsers.read_csv) function. Ensure that your csv includes a header or pass `header=None` for correct parsing. `parse_dates=[[0,1,2]]` will facilitate the desired dattime parsing. ``` In [4]: pandas....
How to join mixed list (array) (with integers in it) in Python?
13,954,222
9
2012-12-19T14:13:28Z
13,954,247
10
2012-12-19T14:15:12Z
[ "python" ]
I have a list (array) with mixed ``` a = ["x", "2", "y"] b = ["x", 2, "y"] print ":".join(a) print ":".join(b) ``` The first join works, but the second one throws a TypeError exception I came up with this, but is this the Python solution? ``` print ":".join(map(str, b)) ``` BTW in the end I just would like to writ...
Your solution works nicely and is probably one of the fastest ways to do this for small to medium sized lists, but it creates an unnecessary list (in python2.x). Usually that's not a problem, but in a few cases, depending on the object `b`, it could be an issue. Another which is lazy in python2 as well as python 3 is: ...
How do I convert LF to CRLF?
13,954,840
5
2012-12-19T14:47:26Z
13,954,965
15
2012-12-19T14:53:16Z
[ "python", "unix" ]
I found a list of the majority of English words online, but the line breaks are of unix-style (encoded in Unicode: UTF-8). I found it on this website: <http://dreamsteep.com/projects/the-english-open-word-list.html> How do I convert the line breaks to CRLF so I can iterate over them? The program I will be using them i...
Instead of converting, you should be able to just open the file using Python's [universal newline support](http://docs.python.org/2/glossary.html#term-universal-newlines): ``` f = open('words.txt', 'rU') ``` (Note the `U`.)
python sort upper case and lower case
13,954,841
12
2012-12-19T14:47:35Z
13,954,857
24
2012-12-19T14:48:18Z
[ "python", "sorting" ]
I have a list which contains list of animal names. I need to sort the list. If I use sort(list), will give the list output with uppercase string first and then lowercase. But I need the below output. Input: ``` var=['ant','bat','cat','Bat','Lion','Goat','Cat','Ant'] ``` Output: ``` ['ant', 'Ant', 'bat', 'Bat', 'ca...
The `sort()` method and the `sorted()` function take a key argument: ``` var.sort(key=lambda v: v.upper()) ``` The function named in `key` is called for each value and the return value is used when sorting, without affecting the actual values: ``` >>> var=['ant','bat','cat','Bat','Lion','Goat','Cat','Ant'] >>> sorte...
Python unicode normalization: is it correct to translate u'\xb4' to u' \u0301'
13,954,852
7
2012-12-19T14:48:07Z
13,954,918
10
2012-12-19T14:51:05Z
[ "python", "unicode" ]
look at the following snippet: ``` >>> import unicodedata >>> from unicodedata import normalize, name >>> normalize('NFKD', u'\xb4') u' \u0301' >>> normalize('NFKD', u'a\xb4a') u'a \u0301a' >>> normalize('NFKC', u'a\xb4a') u'a \u0301a' >>> name(u'\xb4'), name(u'\u0301') ('ACUTE ACCENT', 'COMBINING ACUTE ACCENT') `...
An accent character is the combination of a space and a combining accent character, as specified in the Unicode standard: ``` >>> import unicodedata >>> unicodedata.decomposition(u'\xb4') '<compat> 0020 0301' ``` The `\u00B4` character has a somewhat ambiguous history, but the Unicode standard has decided to treat it...
multiprocessing? multithreading? pool? queue? brute forcing
13,954,999
2
2012-12-19T14:55:26Z
13,955,101
8
2012-12-19T15:00:17Z
[ "python", "multithreading", "hash", "multiprocessing", "pool" ]
this is a general knowledge question, soon to turn into a project. I have a script that attempts to brute force a sha1 with a known salt. In this application anyways the salt is known. Anyways, script works fine, it's a python script. When I run it, it tops out one core of 16 I have available. I would like too utilize ...
Due to the Global Interpreter Lock, you cannot usefully use Python threads for CPU-bound work. In this case, you're going to have to use `multiprocessing`. `multiprocessing` child processes may not work 100% of a given CPU core due to communication overhead. To minimize communication overhead, allocate work to your chi...
List comprehension without using an iterable
13,955,161
2
2012-12-19T15:02:51Z
13,955,224
15
2012-12-19T15:06:09Z
[ "python", "list-comprehension" ]
I am trying to build a list by picking random elements from another list with no duplicates. Think shuffling a pack of cards. I could obviously write some unpythonic code for this, which I dont want to. So here is what I am trying to do: `new = [deck[i] where 0<(i = some_rand_int)<51 if new.count(deck[i]) == 0]` Is ...
> I am trying to build a list by picking random elements from another list with no duplicates. Use [`random.sample`](http://docs.python.org/2/library/random.html#random.sample): > **random.sample(population, k)** > > Return a k length list of unique elements chosen from the population sequence. Used for random sampli...
File paths in Python in the form of string throw errors
13,955,176
3
2012-12-19T15:03:25Z
13,955,197
10
2012-12-19T15:04:13Z
[ "python", "string", "error-handling", "filepath" ]
I need to put a lot of filepaths in the form of strings in Python as part of my program. For example one of my directories is `D:\ful_automate\dl`. But Python recognizes some of the characters together as other characters and throws an error. In the example the error is `IOError: [Errno 22] invalid mode ('wb') or filen...
The `\` character is used to form character escapes; `\f` has special meaning. Use `/` or use raw string `r''` instead. Alternatively, you could ensure that Python reads the backslash as a backslash by escaping it with an additional `\`. ``` r'D:\ful_automate\dl' 'D:\\ful_automate\\dl' 'D:/ful_automate/dl' ``` Demo ...
List of pylint human readable message ids?
13,955,361
12
2012-12-19T15:13:34Z
13,966,145
21
2012-12-20T05:57:08Z
[ "python", "pylint" ]
Recent versions of pylint allow for suppressing messages with human readable message ids. For example, instead of ``` class MyTest(unittest.TestCase): # pylint: disable=R0904 ... ``` you can specify: ``` class MyTest(unittest.TestCase): # pylint: disable=too-many-public-methods ... ``` This [page](http://...
I don't think there exists (yet) such list on the web, though "pylint --list-msgs" automatically produce one
AttributeError: 'module' object has no attribute 'Datefield'
13,956,280
3
2012-12-19T16:00:29Z
13,956,327
9
2012-12-19T16:02:23Z
[ "python", "django" ]
In the file models.py ``` from django.db import models # Create your models here. class Publisher(models.Model): name = models.CharField(max_length=30) address = models.CharField(max_length=50) city = models.CharField(max_length=60) state_province = models.CharField(max_length=30) country = model...
It should be [`models.DateField`](https://docs.djangoproject.com/en/dev/ref/models/fields/#datefield) with a capital `F`. So your `Books` model should look like this: ``` class Books(models.Model): title = models.CharField(max_length=100) authors = models.ManyToManyField(Author) publishers = models.Foreig...
How to check if given variable exist in jinja2 template?
13,956,728
8
2012-12-19T16:24:57Z
13,956,817
22
2012-12-19T16:29:54Z
[ "python", "jinja2" ]
Let's say, I created a template object (f.e. using `environment.from_string(template_path)`). Is it possible to check whether given variable name exist in created template? I would like to know, if ``` template.render(x="text for x") ``` would have any effect (if something would be actually replaced by "text for x" ...
From the documentation: **defined(value)** Return true if the variable is defined: ``` {% if variable is defined %} value of variable: {{ variable }} {% else %} variable is not defined {% endif %} See the default() filter for a simple way to set undefined variables. ``` EDIT: It seems you want to know if a ...
Sort List in Python by two other lists
13,957,624
12
2012-12-19T17:15:08Z
13,957,692
12
2012-12-19T17:19:09Z
[ "python", "list", "sorting" ]
My question is very similar to these two links [1](http://stackoverflow.com/questions/3979872/python-how-to-sort-a-complex-list-on-two-different-keys) and [2](http://stackoverflow.com/questions/5212870/sorting-a-python-list-by-two-criteria): I have three different lists. I want to sort List1 based on List2 (in ascendi...
I think you should be able to do this by: ``` paired_sorted = sorted(zip(List2,List3,List1),key = lambda x: (x[0],-x[1])) l2,l3,l1 = zip(*paired_sorted) ``` In action: ``` >>> List1 = ['a', 'b', 'c', 'd', 'e'] >>> List2 = [4, 2, 3, 2, 4] >>> List3 = [0.1, 0.8, 0.3, 0.6, 0.4] >>> paired_sorted = sorted(zip(List2,List...
How to use "raise" keyword in Python
13,957,829
92
2012-12-19T17:27:28Z
13,957,849
18
2012-12-19T17:28:28Z
[ "python", "keyword", "raise" ]
So I have read the official definition of "raise", but I still don't quite understand what it is doing. In simplest terms, what is "raise"? A small example of it's use would help too.
It's used for raising errors. ``` if something: raise Exception('My error!') ``` Some examples [here](http://infohost.nmt.edu/tcc/help/pubs/python/web/raise-statement.html)
How to use "raise" keyword in Python
13,957,829
92
2012-12-19T17:27:28Z
13,957,915
120
2012-12-19T17:32:03Z
[ "python", "keyword", "raise" ]
So I have read the official definition of "raise", but I still don't quite understand what it is doing. In simplest terms, what is "raise"? A small example of it's use would help too.
It has 2 purposes. [yentup has given the first one.](http://stackoverflow.com/a/13957849/20862) > It's used for raising your own errors. > > ``` > if something: > raise Exception('My error!') > ``` The second is to reraise the *current* exception in an exception handler, so that it can be handled further up the ...
How to use "raise" keyword in Python
13,957,829
92
2012-12-19T17:27:28Z
27,947,646
8
2015-01-14T16:21:12Z
[ "python", "keyword", "raise" ]
So I have read the official definition of "raise", but I still don't quite understand what it is doing. In simplest terms, what is "raise"? A small example of it's use would help too.
`raise` without any arguments is a special use of python syntax. It means get the exception and re-raise it. If this usage it could have been called `reraise`. ``` raise ``` From [The Python Language Reference](https://docs.python.org/2/reference/simple_stmts.html?highlight=raise#grammar-token-raise_stmt): > If ...
How can I unit test this Flask app?
13,959,209
4
2012-12-19T18:57:31Z
13,962,619
9
2012-12-19T22:54:00Z
[ "python", "unit-testing", "flask" ]
I have a Flask app that is using Flask-Restless to serve an API. I have just written some authentication that checks 1. If the consumers host is recognised 2. The request includes a hash (calculated by encrypting the request content for POST and URL for GET along with a secret API key) and 3. The hash is valid I wan...
`test_request_object()` did the trick, thanks monkey. ``` from flask import request with app.test_request_context('/hello', method='POST'): # now you can do something with the request until the # end of the with block, such as basic assertions: assert request.path == '/hello' assert request.method == ...
Speeding up python code with cython
13,959,281
5
2012-12-19T19:01:19Z
13,962,753
10
2012-12-19T23:06:47Z
[ "python", "optimization", "cython" ]
I have a function which just basically makes lots of calls to a simple defined hash function and tests to see when it finds a duplicate. I need to do lots of simulations with it so would like it to be as fast as possible. I am attempting to use cython to do this. The cython code is currently called with a normal python...
First of all, it seems that you must type the variables *inside* the function. [A good example of it is here.](http://docs.cython.org/src/userguide/early_binding_for_speed.html) Second, `cython -a`, for "annotate", gives you a really excellent break down of the code generated by the cython compiler and a color-coded i...
Python list initialization using multiple range statements
13,959,510
5
2012-12-19T19:15:59Z
13,959,549
7
2012-12-19T19:18:24Z
[ "python", "list", "initialization", "range" ]
I want one long list, say [1,2,3,4,5,15,16,17,18,19] as an example. To initialize this, I try typing: ``` new_list = [range(1,6),range(15,20)] ``` However this doesn't do what I want, returning: ``` [[1, 2, 3, 4, 5], [15, 16, 17, 18, 19]] ``` When I do: ``` len(new_list) ``` It returns 2, instead of the 10 elemen...
You can use [itertools.chain](http://docs.python.org/2.7/library/itertools.html#itertools.chain) to flatten the output of your `range()` calls. ``` import itertools new_list = list(itertools.chain(xrange(1,6), xrange(15,20))) ``` Using `xrange` (or simply `range()` for python3) to get an iterable and chaining them to...
Python list initialization using multiple range statements
13,959,510
5
2012-12-19T19:15:59Z
13,959,555
12
2012-12-19T19:18:47Z
[ "python", "list", "initialization", "range" ]
I want one long list, say [1,2,3,4,5,15,16,17,18,19] as an example. To initialize this, I try typing: ``` new_list = [range(1,6),range(15,20)] ``` However this doesn't do what I want, returning: ``` [[1, 2, 3, 4, 5], [15, 16, 17, 18, 19]] ``` When I do: ``` len(new_list) ``` It returns 2, instead of the 10 elemen...
Try this for Python 2.x: ``` range(1,6) + range(15,20) ``` Or if you're using Python3.x, try this: ``` list(range(1,6)) + list(range(15,20)) ``` For dealing with elements in-between, for Python 2.x: ``` range(101,6284) + [8001,8003,8010] + range(10000,12322) ``` And finally for dealing with elements in-between, ...
Which fields of the model in the django-haystack tutorial get indexed?
13,959,525
11
2012-12-19T19:16:43Z
13,960,287
16
2012-12-19T20:04:01Z
[ "python", "django", "django-haystack" ]
I'm trying to get my head around the [django-haystack tutorial](http://django-haystack.readthedocs.org/en/latest/tutorial.html) in order to add search functionality to my application. Unfortunately, I don't quite understand some key parts when it comes to build the search index. In the tutorial, the following django m...
You're right, the tutorial seems a little vague, but here's how I understand it. For each instance of the `Note` model, Haystack renders the data template using that instance and indexes the rendered templates. The rendered template is the "document" for the instance. The tutorial says, "This allows us to use a data te...
pymongo: MongoClient or Connection
13,959,790
8
2012-12-19T19:33:56Z
13,960,078
8
2012-12-19T19:51:20Z
[ "python", "mongodb", "pymongo" ]
I am trying to connect mongodb using pymongo. I see two classes to connect to mongodb. ``` MongoClient and Connection. ``` What is the difference of these two classes?
`MongoClient` is the preferred method of connecting to a mongo instance. The `Connection` class is deprecated. But, in terms of use they are very similar.
How to choose days off evenly in a month using python?
13,960,045
3
2012-12-19T19:49:45Z
13,960,123
8
2012-12-19T19:53:35Z
[ "python", "algorithm", "random" ]
I will assign 8 days off to a crew randomly in a calendar month. I would like to randomly choose 8 days, and the days off distribution should be as even as possible. I mean all 8 days-off shouldn't be gathered in first 8 days of the month, for example. For example: [1, 5, 8, 14, 18, 24, 27, 30] is a good distribution...
Use [`random.sample()`](http://docs.python.org/2/library/random.html#random.sample) to get a random set from a sequence. List the days that are available, then pass that to the `.sample()` function: ``` import sample daysoff = [1, 2, 3, 4, 5, 6, 8, 9, 10, 11, 12, 13, 15, 16, 17, 18, 19, 20] picked = random.sample(day...
Reading dynamically generated web pages using python
13,960,567
12
2012-12-19T20:23:33Z
13,961,035
9
2012-12-19T20:56:13Z
[ "python", "web-scraping" ]
I am trying to scrape a web site using python and beautiful soup. I encountered that in some sites, the image links although seen on the browser is cannot be seen in the source code. However on using Chrome Inspect or Fiddler, we can see the the corresponding codes. What I see in the source code is: ``` <div id="cntnt...
You need JavaScript Engine to parse and run JavaScript code inside the page. There are a bunch of headless browsers that can help you <http://code.google.com/p/spynner/> <http://phantomjs.org/> <http://zombie.labnotes.org/> <http://github.com/ryanpetrello/python-zombie> <http://jeanphix.me/Ghost.py/> <http://webs...
Does Python evaluate if's conditions lazily?
13,960,657
28
2012-12-19T20:31:12Z
13,960,667
38
2012-12-19T20:32:06Z
[ "python", "lazy-evaluation" ]
For example, if I have the following statement: ``` if( foo1 or foo2) ... ... ``` if foo1 is true, will python check the condition of foo2?
Yes, Python evaluates boolean conditions lazily. The [docs say](http://docs.python.org/2/reference/expressions.html#boolean-operations), > The expression x and y first evaluates x; if x is false, its value is > returned; otherwise, y is evaluated and the resulting value is > returned. > > The expression x or y first ...
pymongo : delete records elegantly
13,960,959
15
2012-12-19T20:51:50Z
13,961,110
40
2012-12-19T21:00:20Z
[ "python", "mongodb", "pymongo" ]
Here is my code to delete a bunch of records using pymongo ``` ids = [] with MongoClient(MONGODB_HOST) as connection: db = connection[MONGODB_NAME] collection = db[MONGODN_COLLECTION] for obj in collection.find({"date": {"$gt": "2012-12-15"}}): ids.append(obj["_id"]) for id in ids: prin...
You can use the following: ``` collection.remove({"date": {"$gt": "2012-12-15"}}) ```
Advantages of using keys() function when iterating over a dictionary
13,961,030
5
2012-12-19T20:55:55Z
13,961,050
12
2012-12-19T20:56:53Z
[ "python" ]
Is there any advantage to using keys() function? ``` for word in dictionary.keys(): print word ``` vs ``` for word in dictionary: print word ```
Yes, in Python 2.x iterating directly over the dictionary saves some memory, as the keys list isn't duplicated. You could also use `.iterkeys()`, or in Python 2.7, use `.viewkeys()`. In Python 3.x, `.keys()` is a view, and there is no difference. So, in conclusion: use `d.keys()` (or `list(d.keys())` in python 3) on...
syntax error when using command line in python
13,961,140
16
2012-12-19T21:02:32Z
13,961,161
23
2012-12-19T21:04:07Z
[ "python", "command-line", "syntax-error" ]
I am a beginner to python and am at the moment having trouble using the command line. I have a script test.py (which only contains `print "Hello."`), and it is located in the map C:\Python27. In my system variables, I have specified python to be C:\Python27 (I have other versions of Python installed on my computer as w...
Looks like your problem is that you are trying to run `python test.py` *from within the Python interpreter*, which is why you're seeing that traceback. Make sure you're out of the interpreter, then run the `python test.py` command from bash or command prompt or whatever.
Difference between .items() and .keys()
13,963,258
3
2012-12-20T00:03:16Z
13,963,278
9
2012-12-20T00:05:11Z
[ "python" ]
Is there any advantage to using the first block of code over the second one when iterating over a dictionary? ``` for k, v in mydict.items(): if v == None: mydict[k] = '' ``` and ``` for k in mydict.keys(): if mydict[k] == None: mydict[k] = '' ```
The first method is arguably clearer and easier to read, so I would always recommend it over the latter. That said, in a simple case like this, the better option would be a [dictionary comprehension](http://www.youtube.com/watch?v=pShL9DCSIUw): ``` {k: v if v is not None else "" for k, v in mydict.items()} ``` It's ...
Build a Call graph in python including modules and functions?
13,963,321
22
2012-12-20T00:09:01Z
13,963,520
17
2012-12-20T00:32:08Z
[ "python", "function", "static", "module", "call-graph" ]
I have a bunch of scripts to perform a task. And I really need to know the call graph of the project because it is very confusing. I am not able to execute the code because it needs extra HW and SW to do so. However, I need to understand the logic behind it. So, I need to know if there is a tool (which do not require a...
You might want to check out pycallgraph: [pycallgraph](http://pycallgraph.slowchop.com/) Also in this link a more manual approach is described: [generating-call-graphs-for-understanding-and-refactoring-python-code](http://blog.prashanthellina.com/2007/11/14/generating-call-graphs-for-understanding-and-refactoring-py...
How have other languages overcame the limitations of Python's GIL?
13,963,887
2
2012-12-20T01:19:50Z
13,963,903
7
2012-12-20T01:23:22Z
[ "python", "multithreading", "concurrency" ]
As the industry trends to "web scale" application architecture (as much as I hate buzz words), I know Python has caught a lot of criticism for how the [GIL](http://wiki.python.org/moin/GlobalInterpreterLock) handles concurrency and becomes a bottleneck. I understand the problem on the surface, but not well enough to kn...
The GIL exists because it's needed (mainly) for CPython's implementation of reference counting - it's method of garbage collection. So let's be clear, *Python* doesn't have a GIL, the reference implementation does, and it's just an implementation detail. The GIL exists because it makes the implementation simple and fa...
Not a Valid Choice for Dynamic Select Field WTFORMS
13,964,152
21
2012-12-20T01:56:52Z
13,964,913
48
2012-12-20T03:37:19Z
[ "python", "flask", "wtforms" ]
I currently am creating a dynamic select field using WTFORMS, however it never submits and fails the validation with the following error. ``` Not a valid choice ``` My Field is created like this: ``` area = SelectField() ``` and in the view, i am grabbing the options from the db like so: ``` form = MytestForm() fo...
My guess is that `Area.id` is a `int` - when data comes back from the client it is treated as a *string* by WTForms unless a callable is passed to the `coerce` keyword argument of the [`wtforms.fields.SelectField`](http://wtforms.readthedocs.org/en/latest/fields.html?highlight=fields.selectfield#wtforms.fields.SelectFi...
Longest strings from list
13,964,637
7
2012-12-20T03:00:47Z
13,964,650
17
2012-12-20T03:02:16Z
[ "python" ]
I was making a function that returns the longest string value from a list. My code works when there is only one string with the most characters. I tried to make it print all of the longest strings if there were more than one, and I do not want them to be repeated. When I run this, it only returns 'hello', while I want ...
**First**, we can find the maximum length of any string in the list: ``` stringlist = ['hi', 'hello', 'hey','ohman', 'yoloo', 'hello'] #maxlength = max([len(s) for s in stringlist]) maxlength = max(len(s) for s in stringlist) # omitting the brackets causes max # to operat...
Longest strings from list
13,964,637
7
2012-12-20T03:00:47Z
13,964,797
9
2012-12-20T03:20:20Z
[ "python" ]
I was making a function that returns the longest string value from a list. My code works when there is only one string with the most characters. I tried to make it print all of the longest strings if there were more than one, and I do not want them to be repeated. When I run this, it only returns 'hello', while I want ...
I highly endorse Jonathon Reinhart's answer, but I just couldn't hold it... How about this? ``` max(map(len, stringlist)) ``` There is no need to write a list comprehension, this is even simpler...
Regex and the OR operator without grouping in Python?
13,964,986
5
2012-12-20T03:46:17Z
13,964,998
13
2012-12-20T03:48:26Z
[ "python", "regex", "groups" ]
Here are the cases. I'm looking for the following pattern in a log file. All strings are in the form of `AB_N` or `CDE_N`. `AB` and `CDE` are fixed letters, followed by an underscore. `N` can be either 2 or 3 numbers. I tried `(AB|CDE)_\d{2,3}` but that returns a group. I can't do `\w{2,3}\d{2,3}` because it has to b...
A `?:` inside a parenthesis in a regex makes it non-capturing. Like so: `(?:AB|CDE)_\d{2,3}` See docs here: <http://docs.python.org/3/library/re.html> About a third of the way through it goes over the non-capturing syntax.
Converting Matlab's datenum format to Python
13,965,740
8
2012-12-20T05:14:24Z
13,965,852
9
2012-12-20T05:25:14Z
[ "python", "matlab" ]
I just started moving from Matlab to Python 2.7 and I have some trouble reading my .mat-files. Time information is stored in Matlab's datenum format. For those who are not familiar with it: > A serial date number represents a calendar date as the number of days that has passed since a fixed base date. In MATLAB, seria...
You link to the solution, it has a small issue. It is this: ``` python_datetime = datetime.fromordinal(int(matlab_datenum)) + timedelta(days=matlab_datenum%1) - timedelta(days = 366) ``` a longer explanation can be found [here](http://sociograph.blogspot.com/2011/04/how-to-avoid-gotcha-when-converting.html)
Resource 'corpora/wordnet' not found on Heroku
13,965,823
18
2012-12-20T05:21:21Z
14,869,451
38
2013-02-14T07:02:50Z
[ "python", "django", "heroku", "nltk", "wordnet" ]
I'm trying to get NLTK and wordnet working on Heroku. I've already done ``` heroku run python nltk.download() wordnet pip install -r requirements.txt ``` But I get this error: ``` Resource 'corpora/wordnet' not found. Please use the NLTK Downloader to obtain the resource: >>> nltk.download() Searched in: ...
I just had this same problem. What ended up working for me is creating an 'nltk\_data' directory in the application's folder itself, downloading the corpus to that directory and adding a line to my code that lets the nltk know to look in that directory. You can do this all locally and then push the changes to Heroku. ...
Parent instance is not bound to a Session; lazy load operation of attribute ’account’ cannot proceed
13,967,093
8
2012-12-20T07:19:47Z
14,012,881
17
2012-12-23T17:06:23Z
[ "python", "sqlalchemy" ]
While trying to do the following operation: ``` for line in blines: line.account = get_customer(line.AccountCode) ``` I am getting an error while trying to assign a value to `line.account`: ``` DetachedInstanceError: Parent instance <SunLedgerA at 0x16eda4d0> is not bound to a Session; lazy load operation ...
"detached" means you're dealing with an ORM object that is not associated with a `Session`. The `Session` is the gateway to the relational database, so anytime you refer to attributes on the mapped object, the ORM will sometimes need to go back to the database to get the current value of that attribute. In general, you...
ImportError: No module named six
13,967,428
30
2012-12-20T07:45:24Z
13,967,865
45
2012-12-20T08:19:43Z
[ "python", "module", "importerror" ]
I'm trying to build OpenERP project, done with dependencies. It's giving this error now ``` Traceback (most recent call last): File "openerp-client.py", line 105, in <module> File "modules\__init__.pyo", line 23, in <module> File "modules\gui\__init__.pyo", line 22, in <module> File "modules\gui\main.pyo", lin...
You probably don't have the `six` Python module installed. You can find it on [pypi](http://pypi.python.org/pypi/six). To install it: ``` $ easy_install six ``` (if you have [`pip`](https://pypi.python.org/pypi/pip/) installed, use `pip install six` instead)
MySQL for Python on Windows via Xampp
13,969,077
4
2012-12-20T09:36:11Z
13,971,696
7
2012-12-20T11:57:05Z
[ "python", "mysql", "django", "xampp", "mysql-python" ]
I've MySQL running through XAMPP, and I've also installed MySQLdb for python installed. I, however cannot figure out a way of using my XAMPP's MySQL for Python. Each time I execute `python manage.py runserver` it shows an error: `..2.4c1-py2.7-win32.egg.tmp\MySQLdb\connections.py", line 187, in __init__ _mysql_excepti...
After 5-6 hours of trying, I finally got it working. ``` DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'. 'NAME': 'tester', # Or path to database file if using sqlite3. 'USER': 'root', ...
Qt on Mac OS X: How to get rid of QListView's blue outline?
13,973,165
3
2012-12-20T13:23:20Z
13,978,651
10
2012-12-20T18:54:57Z
[ "c++", "python", "css", "osx", "qt" ]
I am using a `QListView` with custom background image and I want to get rid of the blue outline-border that appears around QListView on OS X. I tried styling it with: ``` border: 0 none; outline: 0 none; border-collapse: collapse; ``` But it still appears. What do I need to do to get rid of this blue hue?
This should work: ``` yourListView->setAttribute(Qt::WA_MacShowFocusRect, false); ```
Requests with multiple connections
13,973,188
12
2012-12-20T13:24:47Z
13,973,531
13
2012-12-20T13:44:54Z
[ "python", "networking", "download", "python-requests" ]
I use the Python Requests library to download a big file, e.g.: ``` r = requests.get("http://bigfile.com/bigfile.bin") content = r.content ``` The big file downloads at +- 30 Kb per second, which is a bit slow. Every connection to the bigfile server is throttled, so I would like to make multiple connections. Is ther...
You can use HTTP [`Range`](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35) header to fetch just part of file ([already covered for python here](http://stackoverflow.com/questions/1798879/download-file-using-partial-download-http)). Just start several threads and fetch different range with each and you...
igraph: why is add_edge function so slow ompared to add_edges?
13,974,279
6
2012-12-20T14:26:59Z
13,975,986
8
2012-12-20T16:01:07Z
[ "python", "igraph" ]
i am surprised that: ``` import igraph import random, time start_time = time.time() G = igraph.Graph(directed = True) G.add_vertices(10000) for i in range(30000): G.add_edge(random.randint(0,9999), random.randint(0,9999)) print "done in " + str(int(time.time() - start_time)) + " seconds" ``` returns done in 63 sec...
The reason is that igraph uses an indexed edge list as its data structure in the C layer. The index makes it possible to query the neighbors of a specific vertex in constant time. This is good if your graph rarely changes, but it becomes a burden when the modification operations are far more frequent than the queries, ...
General Programming Algorithm: Execute a function only 12% of all cases
13,974,624
2
2012-12-20T14:44:35Z
13,974,668
7
2012-12-20T14:46:44Z
[ "python", "algorithm", "random", "probability" ]
Im struggling with a simple problem. I have a function and I want to let it do things only in 12% of the cases I call it. I already wrote a function that works, but its not accurate enough. Example in Python: ``` // probability to execute the function is 50% anz_prozent_wahrscheinlichkeit = 50 if anz_prozent_wahrsch...
I would use `random.random()` for this, like so: ``` if random.random() < anz_prozent_wahrscheinlichkeit / 100.: execute my function() ``` This uses floating-point maths and is therefore not restricted to integer percentages (for example, `anz_prozent_wahrscheinlichkeit = 0.1` would work correctly).
Merge/join lists of dictionaries based on a common value in Python
13,975,021
11
2012-12-20T15:06:45Z
13,975,090
14
2012-12-20T15:10:36Z
[ "python", "django" ]
I have two lists of dictionaries (returned as Django querysets). Each dictionary has an ID value. I'd like to merge the two into a single list of dictionaries, based on the ID value. For example: ``` list_a = [{'user__name': u'Joe', 'user__id': 1}, {'user__name': u'Bob', 'user__id': 3}] list_b = [{'hours_wo...
I'd use `itertools.groupby` to group the elements: ``` lst = sorted(itertools.chain(list_a,list_b), key=lambda x:x['user__id']) list_c = [] for k,v in itertools.groupby(lst, key=lambda x:x['user__id']): d = {} for dct in v: d.update(dct) list_c.append(d) #could also do: #list_c.append( dict...
Keep a figure "on hold" after running a script
13,975,756
9
2012-12-20T15:48:35Z
13,994,023
13
2012-12-21T16:47:46Z
[ "python", "numpy", "matplotlib" ]
I have this Python code: ``` from pylab import * from numpy import * time=linspace(-pi,pi,10000) ycos=cos(time) ysin=sin(time) plot(time,ycos) plot(time,ysin) show() ``` If I do all these steps via an Ipython terminal, I can keep the figure open and interact with it. However, if I run the script via `$python scrip...
Here is a more sensible answer after taking a quick look into the problem. First, let us suppose that ``` from matplotlib import pylab pylab.plot(range(10), range(10)) pylab.show() ``` does not "hold on" the plot, i.e., it is barely shown before the program ends. If that happens, then the call `pylab.show()` assumed...
For-loops in Python 3.0
13,975,889
5
2012-12-20T15:55:44Z
13,975,916
8
2012-12-20T15:57:00Z
[ "python", "palindrome" ]
I am currently working on a palindrome-detector (anna, lol, hahah etc) and I am requested to use for-loops. I want the program to loop through two strings (read them regularly and backwards at the same time while comparing the values). If the values are the same then the palindrome is True; if not, it's False. My que...
You use `zip` ``` s = 'hannah' for c_forward,c_backward in zip(s,s[::-1]): ... ``` Maybe a slightly lower level approach would be to loop over the indices (provided your items are indexible): ``` for i in range(len(s)): c_forward = s[i] #character as you loop going forward c_backward = s[-(i+1)] ...
Split a series on time gaps in pandas?
13,976,491
4
2012-12-20T16:29:56Z
13,977,632
8
2012-12-20T17:42:15Z
[ "python", "pandas" ]
Is it possible to split a time series on it's gaps. For example, suppose we had the following: ``` rng2011 = pd.date_range('1/1/2011', periods=72, freq='H') rng2012 = pd.date_range('1/1/2012', periods=72, freq='H') Y = rng2011.union(rng2012) ``` Is it possible to look for gaps of a year or more, and split the data fr...
Assuming Y is a column in your dataframe, one way is to use `diff` and [cumsum](http://pandas.pydata.org/pandas-docs/dev/generated/pandas.Series.cumsum.html): ``` df = DataFrame(Y) df[1] = df[0].diff() > 600000000000.0 #nanoseconds in ten minutes df[1] = df[1].apply(lambda x: 1 if x else 0).cumsum() df.groupby(1) ``` ...
Handling names and values of attributes
13,978,049
3
2012-12-20T18:12:13Z
13,978,114
8
2012-12-20T18:17:24Z
[ "python", "attributes" ]
I am probably approaching this wrong, but would appreciate being straightened out. I would like to be able to use both the values and the names of some attributes of a class Sample: ``` class DoStuff(object): def __init__(self): self.a="Alpha" self.b="Beta" self.c="Gamma" def printStu...
The way your class and `for` loop are set up, there is nothing you can put in place of `NAMEOFTHING` to get to the names of those variables. Here are a few alternatives on how you can modify your approach: * Use a dictionary instead of individual attributes, and then provide a list of keys in your `for` loop: ``` ...
Django: ImportError, No module named urls
13,978,266
6
2012-12-20T18:27:33Z
14,003,708
7
2012-12-22T14:39:08Z
[ "python", "django", "django-urls" ]
I have the following `urls.py` file in my project directory: ``` from django.conf.urls import patterns, include, url from django.contrib import admin admin.autodiscover() urlpatterns = patterns('wb.views', url(r'^areas/$', 'arealist'), url(r'^areas/(?P<area_id>\d+)/$', 'area_roomlist'), url(r'^areas/(?P<a...
ROOT\_URLCONF was set to the wrong urls.py path in settings.py. Sorry!
How to have two models reference each other Django
13,978,503
10
2012-12-20T18:44:47Z
13,978,636
7
2012-12-20T18:53:50Z
[ "python", "django", "django-models", "models" ]
I have the following code: ``` class Game(models.Model): title = models.CharField(max_length=50) summery = models.CharField(max_length=500) key = models.IntegerField() pin = models.CharField(max_length=12) complete = models.BooleanField() invite_sent = models.DateTimeField() on = models.For...
You don't need to have the two models reference each other with foreign keys. Remove the line: ``` on = models.ForeignKey(Member, blank = True) #<---- ``` and logically your `Member`'s will still be associated to different `Game`'s (and this makes more sense because a member can belong to one game at a time, whereas ...
How to have two models reference each other Django
13,978,503
10
2012-12-20T18:44:47Z
13,979,828
21
2012-12-20T20:18:16Z
[ "python", "django", "django-models", "models" ]
I have the following code: ``` class Game(models.Model): title = models.CharField(max_length=50) summery = models.CharField(max_length=500) key = models.IntegerField() pin = models.CharField(max_length=12) complete = models.BooleanField() invite_sent = models.DateTimeField() on = models.For...
The [Django documentation for the ForeignKey field](https://docs.djangoproject.com/en/1.4/ref/models/fields/#foreignkey) states: > If you need to create a relationship on a model that has not yet been defined, you can use the name of the model, rather than the model object itself. So in your case, that would be: ```...
Is possible to create Column in SQLAlchemy which is going to be automatically populated with time when it inserted/updated last time?
13,978,554
12
2012-12-20T18:48:08Z
13,978,770
24
2012-12-20T19:02:54Z
[ "python", "python-3.x", "sqlalchemy" ]
Is possible to create Column in SQLAlchemy which is going to be automatically populated with time when it inserted/updated last time ? I created models, inherited from Base class ``` class Base(object): def __tablename__(self): return self.__name__.lower() id = Column(Integer, primary_key=True) las...
In Base class add onupdate in the last statement as follows: ``` last_time = Column(TIMESTAMP, server_default=func.now(), onupdate=func.current_timestamp()) ```
Is possible to create Column in SQLAlchemy which is going to be automatically populated with time when it inserted/updated last time?
13,978,554
12
2012-12-20T18:48:08Z
13,979,333
10
2012-12-20T19:43:02Z
[ "python", "python-3.x", "sqlalchemy" ]
Is possible to create Column in SQLAlchemy which is going to be automatically populated with time when it inserted/updated last time ? I created models, inherited from Base class ``` class Base(object): def __tablename__(self): return self.__name__.lower() id = Column(Integer, primary_key=True) las...
If you use MySQL, I believe you can only have one auto-updating datetime column, so we use SQLAlchemy's event triggers instead. You just attach a listener to the 'before\_insert' and 'before\_update' hooks and update as necessary: ``` from sqlalchemy import event @event.listen(YourModel, 'before_insert') def update_...
igraph: how to use add_edges when there are attributes?
13,979,508
4
2012-12-20T19:55:28Z
20,377,420
7
2013-12-04T14:03:06Z
[ "python", "igraph" ]
What if I need to create a graph in `igraph` and add a bunch of edges, but the edges have associated attributes? It looks like `.add_edges` can only take a list of edges without attributes, so I've been adding them one by one with `.add_edge`
``` graph.add_edge('A','B',weight = 20) ``` Here A and B are names of nodes
Heap Sort: how to sort?
13,979,714
10
2012-12-20T20:11:09Z
13,980,081
12
2012-12-20T20:37:40Z
[ "python", "sorting", "heapsort" ]
I'm trying to implement Heap Sort in Python, but I can't seem to get it right. I've tried to implement this [pseudo code](http://en.wikipedia.org/wiki/Heapsort), but my code does not sort! It just sifts to ridiculous effect. I'm inclined to think that the problem is in this line: > swap the root(maximum value) of the ...
**How do I get the maximum value?** You don't need to "get" it. The root is exactly the maximum, that's a defined property of a heap. If you feel tough to understand heap sort, [this chapter](http://books.google.com.hk/books?id=NLngYyWFl_YC&pg=PA127&dq=introduction%20to%20algorithm%20heap%20sort&hl=zh-CN&sa=X&ei=HnnTU...
pip install matplotlib: "no pkg-config"
13,979,916
4
2012-12-20T20:23:43Z
21,096,063
8
2014-01-13T16:17:02Z
[ "python", "osx", "matplotlib", "virtualenv", "pip" ]
When I run `pip install matplotlib` (within a virtualenv), the first lines of output are: ``` Downloading/unpacking matplotlib Running setup.py egg_info for package matplotlib basedirlist is: ['/usr/local/', '/usr', '/usr/X11', '/opt/local'] ===================================================================...
``` sudo apt-get build-dep python-matplotlib ```
Data structure for Markov Decision Process
13,980,063
8
2012-12-20T20:36:04Z
13,980,486
7
2012-12-20T21:09:12Z
[ "python", "artificial-intelligence", "markov" ]
I have implemented the value iteration algorithm for simple Markov decision process [Wikipedia](http://en.wikipedia.org/wiki/Markov_decision_process) in Python. In order to keep the structure (states, actions, transitions, rewards) of the particular Markov process and iterate over it I have used the following data stru...
Whether a data structure is suitable or not mostly depends on what you do with the data. You mention that you want to iterate over the process, so optimize your data structure for this purpose. Transitions in Markov processes are often modeled by matrix multiplications. The transition probabilities `Pa(s1,s2)` and the...
Can the usage of `setattr` (and `getattr`) be considered as bad practice?
13,982,297
6
2012-12-20T23:47:48Z
13,982,449
8
2012-12-21T00:05:08Z
[ "python", "getattr", "setattr" ]
`setattr` and `getattr` kind of got into my style of programing (mainly scientific stuff, my knowledge about python is self told). Considering that `exec` and `eval` inherit a potential danger since in some cases they might lead to security issues, I was wondering if for `setattr` the same argument is considered to be...
First, it could definitely make it easier to an existing security hole. For example, let's say you have code that does `exec`, `eval`, SQL queries or URLs built via string formatting, etc. And let's say you're passing, say, `locals()` or a filtered `__dict__` to the formatting command or as the `eval` context or whate...
PythonMagick can't find my pdf files
13,984,357
4
2012-12-21T04:41:01Z
13,986,768
9
2012-12-21T08:39:24Z
[ "python", "windows", "pdf", "runtime-error", "pythonmagick" ]
I've downloaded and installed PythonMagick for python 2.7, 64 bit Windows 7, from the [Unofficial Windows Binaries.](http://www.lfd.uci.edu/~gohlke/pythonlibs/) I am trying to run this code (Processor.py) ``` import PythonMagick pdf = 'test.pdf' p = PythonMagick.Image() p.density('600') p.read(pdf) p.write('doc....
I had exactly the same problem couple of days ago. While converting from .gif (oder something else) to .jpg worked really fine, converting from .pdf to .jpg produced exactly the same error. Thats happing because ImageMagick uses Ghostscript for reading/converting PDFs. You can solve the problem by installing [Ghostscr...
python dictionary conundrum
13,984,473
7
2012-12-21T04:55:20Z
13,984,519
8
2012-12-21T05:01:00Z
[ "python", "dictionary" ]
On the console I typed in ``` >>> class S(str): pass ... >>> a = 'hello' >>> b = S('hello') >>> d = {a:a, b:b} >>> d {'hello': 'hello'} >>> type(d[a]) <class '__main__.S'> >>> type(d[b]) <class '__main__.S'> ``` I thought at first that the reason that `d` only kept one pair was because `hash(a)` and `hash(b)` returne...
The two objects in your original example were collapsed not because they have the same hash, but because they compare equal. Dict keys are unique with respect to *equality*, not hash. Python requires that any two objects that compare equal must have the same hash (but not necessarily the reverse). In your first exampl...
break and continue in function
13,986,884
4
2012-12-21T08:48:43Z
13,986,939
9
2012-12-21T08:52:17Z
[ "python", "function", "loops", "break", "continue" ]
``` def funcA(i): if i%3==0: print "Oh! No!", print i break for i in range(100): funcA(i) print "Pass", print i ``` I know script above won't work. So, how can I write if I need put a function with break or continue into a loop?
A function cannot cause a break or continue in the code from which it is called. The break/continue has to appear literally inside the loop. Your options are: 1. return a value from funcA and use it to decide whether to break 2. raise an exception in funcA and catch it in the calling code (or somewhere higher up the c...
(Python) ValueError: Program dot not found in path
13,987,353
3
2012-12-21T09:22:26Z
13,987,392
9
2012-12-21T09:24:52Z
[ "python", "graphviz", "networkx", "xubuntu", "pygraphviz" ]
I have the following problem: I am on xUbuntu OS and I am trying to use networkx in a Flask application, and I am having the following code: ``` ..... import networkx as nx ...... # Creating and initializing graph object which is networkx object hosts_graph = get_networkx_graph_object() # Variable 'coord' where the c...
PyGraphviz doesn't work without Graphviz. Install that too.
Directing PyCharm to Python 3.3 interpreter?
13,988,363
9
2012-12-21T10:28:19Z
14,019,235
10
2012-12-24T09:00:54Z
[ "python", "osx", "pycharm" ]
I'm not sure why I'm having so much trouble with this. I'm on OS X 10.7, and I installed Python with default settings and ran the .command file included. I just want to get PyCharm working with Python 3.3, but I can't seem to find a working interpreter. The only one I can find loads instantly (gives 'distribute' and '...
PyCharm detects Python 3.3 path automatically for the Python installed from <http://python.org> `mpkg` installer: ![Path](http://i.stack.imgur.com/neVa5.png) ``` /Library/Frameworks/Python.framework/Versions/3.3/bin/python3 ``` Once you add this interpreter to PyCharm, install the package management tools (click on ...
No constructor overloading in Python - Disadvantage?
13,989,304
5
2012-12-21T11:27:20Z
13,989,367
14
2012-12-21T11:32:19Z
[ "python" ]
I was going through DiveIntoPython and came across this: > Java and Powerbuilder support function overloading by argument list, > i.e. one class can have multiple methods with the same name but a > different number of arguments, or arguments of different types. Other > languages (most notably PL/SQL) even support func...
You're right that defining `__init__` in a subclass overrides the superclass's `__init__`, but you can always use `super(CurrentClass, self).__init__` to call the superclass's constructor from the subclass. So, you don't have to "manually" duplicate the superclass's initialization work. As a side note, even though Pyt...
cv2.videocapture.read() does not return a numpy array
13,989,627
3
2012-12-21T11:48:50Z
13,990,546
8
2012-12-21T12:50:21Z
[ "python", "opencv", "v4l2", "ftputil" ]
I have this code trying to capture a frame from my webcam on raspberry pi, and saving it as an image. I use opencv 2, but I get strange errors when I run the code.. ``` import time import sys from subprocess import call import ftputil import cv2 cam = cv2.VideoCapture() #cam.set(CV_CAP_PROP_FRAME_WIDTH, 640) #cam.set...
Reading (`cam.read()`) from a `VideoCapture` returns a tuple `(return value, image)`. With the first item you check wether the reading was successful, and if it was then you proceed to use the returned `image`. This is documented at <http://docs.opencv.org/modules/highgui/doc/reading_and_writing_images_and_video.html>
Regular Expression to match a dot
13,989,640
25
2012-12-21T11:49:34Z
13,989,661
46
2012-12-21T11:51:20Z
[ "python", "regex" ]
Was wondering what the best way is to match "test.this" from "blah blah blah test.this@gmail.com blah blah" is? Using Python. I've tried `re.split(r"\b\w.\w@")` Thanks!
A `.` in regex is a metacharacter, it is used to match any character. To match a literal dot, you need to escape it, so `\.`
Regular Expression to match a dot
13,989,640
25
2012-12-21T11:49:34Z
13,989,666
14
2012-12-21T11:51:22Z
[ "python", "regex" ]
Was wondering what the best way is to match "test.this" from "blah blah blah test.this@gmail.com blah blah" is? Using Python. I've tried `re.split(r"\b\w.\w@")` Thanks!
In your `regex` you need to escape the `dot(.) - "\."` or use it inside a `character class - "[.]"`, as it is a meta-character in regex, which matches any character. Also, you need `\w+` instead of `\w` to match one or more word. --- Now, if you want the `test.this` content, then `split` is not what you need. `split...
Generate python bindings, what methods/programs to use
13,990,317
9
2012-12-21T12:35:39Z
18,053,166
8
2013-08-05T07:54:01Z
[ "c++", "python", "python-bindings" ]
I'm looking at using python (CPython) in my program to both allow user scripting in my environment and to allow me to use pyside, the qt bindings for c++ to create the GUI for my application. These can be effectively separated with the idea that the GUI python code can later be compiled away for speed (if that would be...
There are only two projects I know to have automatic binding generators for C++. The first one is SWIG. As some other answer has already said, it is a little bit old style, but it works. The second one is Boost.Python - by itself, it does not generate the bindings automatically, but you can use [Boost.Pyste](http://www...
3d Numpy array to 2d
13,990,465
14
2012-12-21T12:44:53Z
13,990,648
24
2012-12-21T12:56:55Z
[ "python", "numpy", "multidimensional-array" ]
I have a 3d matrix like this ``` arange(16).reshape((4,2,2)) array([[[ 0, 1], [ 2, 3]], [[ 4, 5], [ 6, 7]], [[ 8, 9], [10, 11]], [[12, 13], [14, 15]]]) ``` and would like to stack them in grid format, ending up with ``` array([[ 0, 1, 4, 5], [...
``` In [27]: x = np.arange(16).reshape((4,2,2)) In [28]: x.reshape(2,2,2,2).swapaxes(1,2).reshape(4,-1) Out[28]: array([[ 0, 1, 4, 5], [ 2, 3, 6, 7], [ 8, 9, 12, 13], [10, 11, 14, 15]]) ``` --- I've posted more general functions for [reshaping/unshaping arrays into blocks, here](http://s...
How to import a globally installed package to virtualenv folder
13,992,214
19
2012-12-21T14:48:07Z
13,992,471
28
2012-12-21T15:07:52Z
[ "python", "ubuntu", "virtualenv" ]
So I have a virtualenv folder called venv for my python project. I can run: ``` venv/bin/pip install -r requirements.txt ``` Which installs all requirements I need for the project except one, M2Crypto. The only way to install it is through apt-get: ``` apt-get install python-m2crypto ``` How can I then add this pa...
``` --system-site-packages ``` gives access to the global site-packages modules to the virtual environment. you could do: ``` $ sudo apt-get install python-m2crypto $ virtualenv env --system-site-packages ``` ... and you would then have access to `m2crypto` (along with all other system-wide installed packages) insi...
How to import a globally installed package to virtualenv folder
13,992,214
19
2012-12-21T14:48:07Z
13,993,313
13
2012-12-21T16:02:48Z
[ "python", "ubuntu", "virtualenv" ]
So I have a virtualenv folder called venv for my python project. I can run: ``` venv/bin/pip install -r requirements.txt ``` Which installs all requirements I need for the project except one, M2Crypto. The only way to install it is through apt-get: ``` apt-get install python-m2crypto ``` How can I then add this pa...
What I did after all: ``` cp -R /usr/lib/python2.7/dist-packages/M2Crypto /home/richard/hello-project/venv/lib/python2.7/site-packages/ cp -R /usr/lib/python2.7/dist-packages/OpenSSL /home/richard/hello-project/venv/lib/python2.7/site-packages/ ```
Python: using sys.exit or SystemExit differences and suggestions
13,992,662
20
2012-12-21T15:20:15Z
13,992,714
17
2012-12-21T15:23:09Z
[ "python", "performance", "coding-style" ]
Reading online some programmers use `sys.exit`, others use `SystemExit`. Sorry for the basic question: 1. What is the difference? 2. When do I need to use SystemExit or sys.exit inside a function? Example ``` ref = osgeo.ogr.Open(reference) if ref is None: raise SystemExit('Unable to open %s' % reference) ``` ...
`sys.exit(s)` is just shorthand for `raise SystemExit(s)`, as described in the former's docstring; try `help(sys.exit)`. So, instead of either one of your example programs, you can do ``` sys.exit('Unable to open %s' % reference) ```
Python: using sys.exit or SystemExit differences and suggestions
13,992,662
20
2012-12-21T15:20:15Z
13,992,762
11
2012-12-21T15:26:07Z
[ "python", "performance", "coding-style" ]
Reading online some programmers use `sys.exit`, others use `SystemExit`. Sorry for the basic question: 1. What is the difference? 2. When do I need to use SystemExit or sys.exit inside a function? Example ``` ref = osgeo.ogr.Open(reference) if ref is None: raise SystemExit('Unable to open %s' % reference) ``` ...
No practical difference, but there's another difference in your example code - `print` goes to standard out, but the exception text goes to standard error (which is probably what you want).
reading and parsing a TSV file, then manipulating it for saving as CSV (*efficiently*)
13,992,971
27
2012-12-21T15:38:50Z
13,993,400
63
2012-12-21T16:07:16Z
[ "python", "csv", "python-2.7", "tab-delimited-text" ]
My source data is in a TSV file, 6 columns and greater than 2 million rows. Here's what I'm trying to accomplish: 1. I need to read the data in 3 of the columns (3, 4, 5) in this source file 2. The fifth column is an integer. I need to use this integer value to duplicate a row entry with using the data in the third a...
You should use the `csv` module to read the tab-separated value file. Do *not* read it into memory in one go. Each row you read has all the information you need to write rows to the output CSV file, after all. Keep the output file open throughout. ``` import csv with open('sample.txt','rb') as tsvin, open('new.csv', ...
Pandas slicing along multiindex and separate indices
13,993,524
7
2012-12-21T16:15:15Z
13,994,123
9
2012-12-21T16:53:53Z
[ "python", "pandas" ]
I've started using Pandas for some large Datasets and mostly it works really well. There are some questions I have regarding the indices though 1. I have a MultiIndex with three levels - let's say a, b, c. How do I slice along index a - I just want the values where a = 5, 7, 10, 13. Doing df.ix[[5, 7, 10, 13]] does no...
For the first part, you can use boolean indexing using [`get_level_values`](http://pandas.pydata.org/pandas-docs/stable/indexing.html#reconstructing-the-level-labels): ``` df[df.index.get_level_values('a').isin([5, 7, 10, 13])] ``` For the second two, you can inspect the [MultiIndex](http://pandas.pydata.org/pandas-d...
IntelliJ Python plugin & Run classpath
13,994,846
18
2012-12-21T17:49:04Z
14,014,823
13
2012-12-23T21:27:14Z
[ "python", "intellij-idea", "classpath", "pycharm" ]
I have a project located at /home/myself/workspace/Project1, for which I created an SDK from a Python 2.7.3 Virtualenv I have setup. This project uses some external code that I have in an accessible directory, e.g. /home/myself/LIBRARY; this directory contains several directories with code, docs etc.... For example...
Make sure you have `__init__.py` in `mymodule` directory: > The `__init__.py` files are required to make Python treat the > directories as containing packages; this is done to prevent > directories with a common name, such as string, from unintentionally > hiding valid modules that occur later on the module search pat...
IntelliJ Python plugin & Run classpath
13,994,846
18
2012-12-21T17:49:04Z
29,804,378
9
2015-04-22T17:05:00Z
[ "python", "intellij-idea", "classpath", "pycharm" ]
I have a project located at /home/myself/workspace/Project1, for which I created an SDK from a Python 2.7.3 Virtualenv I have setup. This project uses some external code that I have in an accessible directory, e.g. /home/myself/LIBRARY; this directory contains several directories with code, docs etc.... For example...
In IntelliJ 14 it's a little different, you are modules/eggs like so: * Go to File -> Project Structure * Now select Modules and then "Dependencies" tab * Click the "+" icon and select "Library" * Click "New Library" and select Java (I know it's weird...) * Now choose multiple modules / egg and "OK". * Select "Classes...
Does Post-Mortem Debugging in Python allow for Stepping or Continuing?
13,994,847
6
2012-12-21T17:49:07Z
13,994,970
8
2012-12-21T17:58:11Z
[ "python", "debugging", "pdb" ]
I have been playing around with post-mortem debugging and am having some problems. Consider the following pyton script called `example.py`: ``` k = 0 print 1. / k print 'continue ...' ``` I can run this with: ``` > python -m pdb example.py ``` and then step to line 2 `print 1. / k` and then set `k = 1` and then con...
A post-mortem is invoked when an exception has been thrown. At that point, the stack is no longer 'active' and you cannot step through the code anymore. After all, an exception has just been thrown, signalling that the code path can no longer continue. What would you expect `result` to be if you had the expression `re...
Python multiprocessing pool.map raises IndexError
13,996,121
3
2012-12-21T19:35:00Z
13,998,052
9
2012-12-21T22:33:47Z
[ "python", "multiprocessing", "cython" ]
I've developed a utility using python/cython that sorts CSV files and generates stats for a client, but invoking pool.map seems to raise an exception before my mapped function has a chance to execute. Sorting a small number of files seems to function as expected, but as the number of files grows to say 10, I get the be...
The IndexError is an error you get somewhere in sort\_file(), i.e. in a subprocess. It is re-raised by the parent process. Apparently `multiprocessing` doesn't make any attempt to inform us about where the error really comes from (e.g. on which lines it occurred) or even just what argument to sort\_file() caused it. I ...
Python - rolling functions for GroupBy object
13,996,302
9
2012-12-21T19:49:00Z
13,998,600
14
2012-12-21T23:41:42Z
[ "python", "pandas" ]
I have a time series object `grouped` of the type `<pandas.core.groupby.SeriesGroupBy object at 0x03F1A9F0>`. `grouped.sum()` gives the desired result but I cannot get rolling\_sum to work with the `groupby` object. Is there any way to apply rolling functions to `groupby` objects? For example: ``` x = range(0, 6) id =...
``` In [16]: df.groupby('id')['x'].apply(pd.rolling_mean, 2, min_periods=1) Out[16]: 0 0.0 1 0.5 2 1.5 3 3.0 4 3.5 5 4.5 In [17]: df.groupby('id')['x'].cumsum() Out[17]: 0 0 1 1 2 3 3 3 4 7 5 12 ```
Django: How to check if something is an email without a form
13,996,622
3
2012-12-21T20:12:47Z
13,996,804
10
2012-12-21T20:28:22Z
[ "python", "django", "emailfield" ]
I have an HTML post form, but, because of some constraints, it's easier to do the validation without the usual Django form classes. The one thing that I need to use the forms for is the Email Field(s) that are entered. Is there a function to check if something is an email, or can I use the `EmailField` class on its own...
You can use the following ``` from django.core.validators import validate_email from django import forms ... if request.method == "POST": try: validate_email(request.POST.get("email", "")) except forms.ValidationError: ... ``` assuming you have a `<input type="text" name="email" />` in your f...
What are the available datatypes for 'dtype' with numpy's loadtxt an genfromtxt?
13,997,087
15
2012-12-21T20:56:57Z
25,615,575
14
2014-09-02T03:53:07Z
[ "python", "numpy" ]
What are the available [numpy.loadtxt](http://docs.scipy.org/doc/numpy/reference/generated/numpy.loadtxt.html) or [numpy.genfromtxt](http://docs.scipy.org/doc/numpy/reference/generated/numpy.genfromtxt.html) for importing table data with varying datatypes, and what are the available abbreviations for the use(e.g. **i32...
In addition to `np.sctypeDict`, there are these variables: ``` In [141]: np.typecodes Out[141]: {'All': '?bhilqpBHILQPefdgFDGSUVOMm', 'AllFloat': 'efdgFDG', 'AllInteger': 'bBhHiIlLqQpP', 'Character': 'c', 'Complex': 'FDG', 'Datetime': 'Mm', 'Float': 'efdg', 'Integer': 'bhilqp', 'UnsignedInteger': 'BHILQP'} I...
zookeeper lock stayed locked
13,997,263
7
2012-12-21T21:14:25Z
14,003,767
7
2012-12-22T14:45:59Z
[ "python", "locking", "celery", "zookeeper", "kazoo" ]
I am using celery and zookeeper (kazoo lock) to lock my workers. I have a problem when I kill (-9) one of the workers before releasing the lock then that lock stays locked forever. So my question is: Does killing the process release locks in that process or is this some bug in zookeeper?
Zookeeper [locks](http://zookeeper.apache.org/doc/r3.4.5/recipes.html#Shared+Locks) use [ephemeral nodes](http://zookeeper.apache.org/doc/r3.4.5/zookeeperOver.html#Nodes+and+ephemeral+nodes). An ephemeral node is a node that lives as long as the session that created it is alive. Sessions are kept alive by the process c...
iteritems in Python
13,998,492
49
2012-12-21T23:27:24Z
13,998,509
28
2012-12-21T23:29:17Z
[ "python", "python-3.x" ]
Is it legitimate to use `items()` instead of `iteritems()` in all places? Why was `iteritems()` removed from Python 3? Seems like a terrific and useful method. What's the reasoning behind it? EDIT: To clarify, I want to know what is the correct idiom for iterating over a dictionary in a generator-like way (one item at...
`dict.iteritems` was removed because `dict.items` now does the thing `dict.iteritems` did in python 2.x and even improved it a bit by making it an [`itemview`](http://docs.python.org/3.3/library/stdtypes.html#dict-views).
iteritems in Python
13,998,492
49
2012-12-21T23:27:24Z
13,998,534
49
2012-12-21T23:31:48Z
[ "python", "python-3.x" ]
Is it legitimate to use `items()` instead of `iteritems()` in all places? Why was `iteritems()` removed from Python 3? Seems like a terrific and useful method. What's the reasoning behind it? EDIT: To clarify, I want to know what is the correct idiom for iterating over a dictionary in a generator-like way (one item at...
In Python 2.x - [`.items()`](https://docs.python.org/2/library/stdtypes.html#dict.items) returned a list of (key, value) pairs. In Python 3.x, [`.items()`](https://docs.python.org/3/library/stdtypes.html#dict.items) is now an `itemview` object, which behaves different - so it **has** to be iterated over, or materialise...
iteritems in Python
13,998,492
49
2012-12-21T23:27:24Z
25,082,467
20
2014-08-01T14:27:50Z
[ "python", "python-3.x" ]
Is it legitimate to use `items()` instead of `iteritems()` in all places? Why was `iteritems()` removed from Python 3? Seems like a terrific and useful method. What's the reasoning behind it? EDIT: To clarify, I want to know what is the correct idiom for iterating over a dictionary in a generator-like way (one item at...
[The six library](https://pythonhosted.org/six/) helps with writing code that is compatible with both python 2.5+ and python 3. It has an iteritems method that will work in both python 2 and 3. Example: ``` from __future__ import division, absolute_import, print_function, unicode_literals import six d = dict( foo=1, ...
Route requests based on the Accept header in Python web frameworks
13,998,607
3
2012-12-21T23:42:43Z
14,003,847
12
2012-12-22T15:00:27Z
[ "python", "django", "flask", "pyramid", "cherrypy" ]
I have some experience with different web frameworks (Django, web.py, Pyramid and CherryPy), and I'm wondering in which one will it be easier and hopefully cleaner to implement a route dispatcher to a different "view/handler" based on the "Accept" header and the HTTP method e.g.: ``` Accept: application/json POST /pos...
If all you are looking for is *one* framework that can do this easily, then use [`pyramid`](http://www.pylonsproject.org/projects/pyramid/about). Pyramid view definitions are made with [predicates](http://docs.pylonsproject.org/projects/pyramid/en/1.3-branch/narr/viewconfig.html#view-configuration-parameters), not jus...
Generating a Random Hex Color in Python
13,998,901
25
2012-12-22T00:25:45Z
13,999,052
9
2012-12-22T00:50:27Z
[ "python", "django" ]
For a Django App, each "member" is assigned a color to help identify them. Their color is stored in the database and then printed/copied into the HTML when it is needed. The only issue is that I am unsure how to generate random `Hex` colors in python/django. It's easy enough to generate RGB colors, but to store them I ...
Store it as a HTML color value: **Updated:** now accepts both integer (0-255) and float (0.0-1.0) arguments. These will be clamped to their allowed range. ``` def htmlcolor(r, g, b): def _chkarg(a): if isinstance(a, int): # clamp to range 0--255 if a < 0: a = 0 elif...
Generating a Random Hex Color in Python
13,998,901
25
2012-12-22T00:25:45Z
14,019,260
56
2012-12-24T09:04:18Z
[ "python", "django" ]
For a Django App, each "member" is assigned a color to help identify them. Their color is stored in the database and then printed/copied into the HTML when it is needed. The only issue is that I am unsure how to generate random `Hex` colors in python/django. It's easy enough to generate RGB colors, but to store them I ...
``` import random r = lambda: random.randint(0,255) print('#%02X%02X%02X' % (r(),r(),r())) ```
Generating a Random Hex Color in Python
13,998,901
25
2012-12-22T00:25:45Z
18,035,471
19
2013-08-03T17:32:59Z
[ "python", "django" ]
For a Django App, each "member" is assigned a color to help identify them. Their color is stored in the database and then printed/copied into the HTML when it is needed. The only issue is that I am unsure how to generate random `Hex` colors in python/django. It's easy enough to generate RGB colors, but to store them I ...
Here is a simple way: ``` import random color = "#%06x" % random.randint(0, 0xFFFFFF) ``` To generate a random 3 char color: ``` import random color = "#%03x" % random.randint(0, 0xFFF) ``` `%x` in C-based languages is a string formatter to format integers as hexadecimal strings while `0x` is the prefix to write nu...
How to specify date format when using pandas.to_csv?
13,999,850
25
2012-12-22T03:40:35Z
14,000,420
24
2012-12-22T05:46:53Z
[ "python", "pandas" ]
The default output format of `to_csv()` is: ``` 12/14/2012 12:00:00 AM ``` I cannot figure out how to output only the date part with specific format: ``` 20121214 ``` or date and time in two separate columns in the csv file: ``` 20121214, 084530 ``` The documentation is too brief to give me any clue as to how t...
You could use [`strftime`](http://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior) to save these as separate columns: ``` df['date'] = df['datetime'].apply(lambda x: x.strftime('%d%m%Y')) df['time'] = df['datetime'].apply(lambda x: x.strftime('%H%M%S')) ``` and then be specific about which colu...
How to specify date format when using pandas.to_csv?
13,999,850
25
2012-12-22T03:40:35Z
22,798,849
32
2014-04-01T23:30:20Z
[ "python", "pandas" ]
The default output format of `to_csv()` is: ``` 12/14/2012 12:00:00 AM ``` I cannot figure out how to output only the date part with specific format: ``` 20121214 ``` or date and time in two separate columns in the csv file: ``` 20121214, 084530 ``` The documentation is too brief to give me any clue as to how t...
With the new version of Pandas you can use the date\_format parameter of the [to\_csv](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_csv.html) method: ``` df.to_csv(filename, date_format='%Y%m%d') ```
graphing an equation with matplotlib
14,000,595
8
2012-12-22T06:22:49Z
14,000,631
26
2012-12-22T06:32:16Z
[ "python", "matplotlib" ]
I'm trying to make a function that will graph whatever formula I tell it to. ``` import numpy as np import matplotlib.pyplot as plt def graph(formula, x_range): x = np.array(x_range) y = formula plt.plot(x, y) plt.show() ``` When I try to call it the following error happens, I believe it's...
Your guess is right: the code is trying to evaluate `x**3+2*x-4` immediately. Unfortunately you can't really prevent it from doing so. The good news is that in Python, functions are first-class objects, by which I mean that you can treat them like any other variable. So to fix your function, we could do: ``` import nu...
graphing an equation with matplotlib
14,000,595
8
2012-12-22T06:22:49Z
14,000,664
7
2012-12-22T06:37:51Z
[ "python", "matplotlib" ]
I'm trying to make a function that will graph whatever formula I tell it to. ``` import numpy as np import matplotlib.pyplot as plt def graph(formula, x_range): x = np.array(x_range) y = formula plt.plot(x, y) plt.show() ``` When I try to call it the following error happens, I believe it's...
This is because in line ``` graph(x**3+2*x-4, range(-10, 11)) ``` x is not defined. The easiest way is to pass the function you want to plot as a string and use `eval` to evaluate it as an expression. So your code with minimal modifications will be ``` import numpy as np import matplotlib.pyplot as plt def gra...
Python - Extract multiple lists from a list of lists by index
14,000,734
5
2012-12-22T06:51:34Z
14,000,765
7
2012-12-22T06:57:49Z
[ "python" ]
Is there an efficient way to loop through a list of lists and extract the 1st element of each list into another list, 2nd elements into another one, etc. Such as: ``` x = [[1, 2, 3], [4, 5, 6] , [7, 8, 9]] y1 = [i[0] for i in x] y2 = [i[1] for i in x] ``` Is there a way to extract y1 and y2 in a single list comprehen...
You could use `zip`: ``` >>> x = [[1, 2, 3], [4, 5, 6] , [7, 8, 9]] >>> for l in zip(*x): ... print l ... (1, 4, 7) (2, 5, 8) (3, 6, 9) ``` You can use [`itertools.izip()`](http://docs.python.org/2/library/itertools.html#itertools.izip) in place of `zip()` to make an iterator instead of a list.
Finding the currently selected tab of Ttk Notebook
14,000,944
6
2012-12-22T07:28:54Z
14,012,720
10
2012-12-23T16:43:30Z
[ "python", "tkinter", "ttk" ]
I have a Ttk Notebook widget containing 8 Frames - so, 8 tabs. Each frame contains a Text widget. I have a button outside the Notebook widget, and I want to insert text into the current tabs Text widget when this button is pressed. This would seem to require working out which widget in the Notebook is currently select...
You can retrieve the selected tab through `select` method. However, this method returns a tab\_id which is not much useful as is. `index` convert it to the number of the selected tab. ``` >>> nb.select() '.4299842480.4300630784' >>> nb.index(nb.select()) 2 ``` Note that you coud also get more information about the se...
2D and 3D Scatter Histograms from arrays in Python
14,002,480
5
2012-12-22T11:33:34Z
16,496,996
9
2013-05-11T12:18:17Z
[ "python", "numpy", "matplotlib", "histogram", "binning" ]
have you any idea, how I can bin 3 arrays to a histogram. My arrays look like ``` Temperature = [4, 3, 1, 4, 6, 7, 8, 3, 1] Radius = [0, 2, 3, 4, 0, 1, 2, 10, 7] Density = [1, 10, 2, 24, 7, 10, 21, 102, 203] ``` And the 1D plot should look: ``` Density | ...
Here it follows two functions: `hist2d_bubble` and `hist3d_bubble`; that may fit for your purpose: ![enter image description here](http://i.stack.imgur.com/48K32.png) ``` def hist2d_bubble(x_data, y_data, bins=10): import numpy as np import matplotlib.pyplot as pyplot ax = np.histogram2d(x_data, y_data, b...
Flask Jsonify mongoengine query
14,003,103
5
2012-12-22T13:10:21Z
19,591,654
11
2013-10-25T13:48:46Z
[ "python", "json", "flask", "mongoengine", "simplejson" ]
I have method like this , and want to return as Json , but it writes that Posts object is not Json serializable :S ``` def show_results_async(text): query = { '$or':[{'title':{'$regex':text}},{'author':{'$regex':text}} ]} posts = Posts.objects(__raw__=(query)) return jsonify(result = posts) ```
You can use mongoengine built-in method : to\_json(). Example above that , you can use like this: ``` def show_results_async(text): query = { '$or':[{'title':{'$regex':text}},{'author':{'$regex':text}} ]} posts = Posts.objects(__raw__=(query)) return jsonify(result = posts.to_json()) ```
How can I convert a hex ASCII string to a signed integer
14,003,281
5
2012-12-22T13:38:20Z
14,003,981
7
2012-12-22T15:21:30Z
[ "python", "binary" ]
Input = 'FFFF' # 4 ASCII F's desired result ... -1 as an integer code tried: ``` hexstring = 'FFFF' result = (int(hexstring,16)) print result #65535 ``` Result: 65535 Nothing that I have tried seems to recognized that a 'FFFF' is a representation of a negative number.
Python converts FFFF at 'face value', to decimal 65535 ``` input = 'FFFF' val = int(input,16) # is 65535 ``` You want it interpreted as a 16-bit signed number. The code below will take the lower 16 bits of any number, and 'sign-extend', i.e. interpret as a 16-bit signed value and deliver the corresponding integer ``...
n-grams with Naive Bayes classifier
14,003,291
2
2012-12-22T13:40:43Z
14,025,991
7
2012-12-24T21:56:23Z
[ "python", "nltk", "n-gram" ]
Im new to python and need help! i was practicing with python NLTK text classification. Here is the code example i am practicing on <http://www.laurentluce.com/posts/twitter-sentiment-analysis-using-python-and-nltk/> Ive tried this one ``` from nltk import bigrams from nltk.probability import ELEProbDist, FreqDist fro...
A bigram feature vector follows the exact same principals as a unigram feature vector. So, just like the tutorial you mentioned you will have to check if a bigram feature is present in any of the documents you will use. As for the bigram features and how to extract them, I have written the code bellow for it. You can s...