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
Implementaion HMAC-SHA1 in python
8,338,661
31
2011-12-01T08:55:56Z
8,338,804
7
2011-12-01T09:08:17Z
[ "python", "oauth", "sha1", "hmac" ]
I am trying to use the OAuth of a website, which requires the signature method to be 'HMAC-SHA1' only. I am wondering how to implement this in Python?
It's already there [Keyed-Hashing for Message Authentication](https://docs.python.org/3/library/hmac.html#module-hmac)
Implementaion HMAC-SHA1 in python
8,338,661
31
2011-12-01T08:55:56Z
8,339,781
52
2011-12-01T10:25:15Z
[ "python", "oauth", "sha1", "hmac" ]
I am trying to use the OAuth of a website, which requires the signature method to be 'HMAC-SHA1' only. I am wondering how to implement this in Python?
Pseudocodish: ``` def sign_request(): from hashlib import sha1 import hmac # key = CONSUMER_SECRET& #If you dont have a token yet key = "CONSUMER_SECRET&TOKEN_SECRET" # The Base String as specified here: raw = "BASE_STRING" # as specified by oauth hashed = hmac.new(key, raw, sha1) ...
How to run py.test against different versions of python?
8,338,854
11
2011-12-01T09:13:27Z
9,117,368
8
2012-02-02T17:55:38Z
[ "python", "py.test" ]
Is it possible to run `py.test` with different versions of python without plugins (like `xdist`) or `tox`?
You can create a standalone pytest script with ``` py.test --genscript=mypytest ``` and then do ``` pythonXY mypytest ``` to run tests with a particular python version. You do not need to install pytest for that particular python version as pytest is completely contained in the "mypytest" script.
pykka -- Actors are slow?
8,339,348
5
2011-12-01T09:53:49Z
8,340,253
11
2011-12-01T11:00:26Z
[ "python", "actor", "pykka" ]
I am currently experimenting with Actor-concurreny (on Python), because I want to learn more about this. Therefore I choosed `pykka`, but when I test it, it's more than **half as slow** as an normal function. The Code is only to look if it works; it's not meant to be elegant. :) Maybe I made something wrong? ``` fro...
So what is happening here is that your functional version is creating two very large lists which is the bulk of the time. When you introduce actors, **mutable data like lists must be copied before being sent** to the actor **to maintain proper concurrency**. Also the list created inside the actor must be copied as well...
What are the possible ways to authenticate user when websocket connection is used?
8,339,506
16
2011-12-01T10:04:54Z
9,420,139
14
2012-02-23T19:47:32Z
[ "python", "authentication", "chat", "websocket", "tornado" ]
Example scenario: Web based multi-user chat application through websocket connection. How can I ensure (or guarantee) that each connection in this application belongs to certain authenticated user and "can't be" exploited by false user impersonation or intervene during the connection. by the way I am using tornado web...
First and foremost, there are two things you should remember about WebSockets: (a) it's an evolving standard and (b) it is designed with the intention of working with untrusted clients. The biggest and most important thing you should always do with WebSockets is check their origin. If the origin is mismatched, obvious...
Why in Python sometimes from PIL import Image fails and import Image works?
8,339,991
4
2011-12-01T10:42:01Z
8,340,233
7
2011-12-01T10:58:17Z
[ "python" ]
The below piece of code seems to fails for some people while the second one seems to works. I would like to know why and which would be the best option to choose in order to minimize potential import failures? ``` from PIL import Image # Fails for some ?! import Image ```
"`import Image`" works because PIL makes use of the [site-specific import hooks](http://docs.python.org/library/site.html) to add its install directory into the import path. ``` [me@oldserver]$ cat /usr/lib/python2.4/site-packages/PIL.pth PIL ``` The only situation I can think of where "`import Image`" works but "`fr...
Lazy data-flow (spreadsheet like) properties with dependencies in Python
8,340,289
12
2011-12-01T11:03:13Z
8,343,480
7
2011-12-01T15:05:56Z
[ "python", "properties", "dependencies", "lazy-loading", "dataflow" ]
My problem is the following: I have some python classes that have properties that are derived from other properties; and those should be cached once they are calculated, and the cached results should be invalidated each time the base properties are changed. I could do it manually, but it seems quite difficult to maint...
Here, this should do the trick. The descriptor mechanism (through which the language implements "property") is more than enough for what you want. If the code bellow does not work in some corner cases, just write me. ``` class DependentProperty(object): def __init__(self, calculate=None, default=None, depends_on=...
Appengine, performance degradation with python27
8,341,112
26
2011-12-01T12:07:11Z
8,405,785
16
2011-12-06T19:43:40Z
[ "python", "performance", "google-app-engine" ]
I wanted to test python27 on appengine so I have migrated my app from python25. Performance got more than 2x slower for every request! Then I've returned to python25 and performance is again as it was before. Here is a picture: ![enter image description here](http://i.stack.imgur.com/RGuKK.png) (milliseconds/request) ...
[Somewhere on Usenet](http://groups.google.com/group/google-appengine/msg/88fa978c4aa46041) I read a statement like this from Google "he Python 2.7 runtime is slower than the Python 2.5 runtime in some cases and faster in others. We aren't publicizing the reasons why at this point.". Seems nobody has found so far a sce...
k-permutations in lexicographical order
8,341,963
3
2011-12-01T13:12:26Z
8,342,021
7
2011-12-01T13:17:04Z
[ "python", "iterator", "combinatorics" ]
I'm trying to generate k-permutations (variations) in lexicographical (alphabetical) order. For example, this code ``` import itertools a = list('ABCD') k = 2 for c in itertools.combinations(a, k): for p in itertools.permutations(c): print "".join(p), ``` prints ``` AB BA AC CA AD DA BC CB BD DB CD DC ...
You can just use `permutations` without `combinations`: ``` import itertools a = 'ABCD' k = 2 for p in itertools.permutations(a, k): print "".join(p), ``` ### See also: * [Documentation for `permutations(iterable[,r])`](http://docs.python.org/library/itertools.html#itertools.permutations)
Xpath vs DOM vs BeautifulSoup vs lxml vs other Which is the fastest approach to parse a webpage?
8,342,335
4
2011-12-01T13:45:32Z
8,342,620
7
2011-12-01T14:06:09Z
[ "python", "dom", "xpath", "html-parsing", "lxml" ]
I know how to parse a page using Python. My question is which is the fastest method of all parsing techniques, how fast is it from others? The parsing techniques I know are Xpath, DOM, BeautifulSoup, and using the `find` method of Python.
<http://blog.ianbicking.org/2008/03/30/python-html-parser-performance/> ![Comparison](http://i.stack.imgur.com/FwFQb.png)
Matplotlib - add colorbar to a sequence of line plots
8,342,549
36
2011-12-01T14:02:14Z
8,363,391
20
2011-12-02T22:17:19Z
[ "python", "matplotlib", "colorbar" ]
I have a sequence of line plots for two variables (x,y) for a number of different values of a variable z. I would normally add the line plots with legends like this: ``` import matplotlib.pyplot as plt fig = plt.figure() ax = fig.add_subplot(111) # suppose mydata is a list of tuples containing (xs, ys, z) # where x...
Here's one way to do it while still using plt.plot(). Basically, you make a throw-away plot and get the colorbar from there. ``` import matplotlib as mpl import matplotlib.pyplot as plt min, max = (-40, 30) step = 10 # Setting up a colormap that's a simple transtion mymap = mpl.colors.LinearSegmentedColormap.from_li...
Matplotlib - add colorbar to a sequence of line plots
8,342,549
36
2011-12-01T14:02:14Z
11,558,629
68
2012-07-19T10:14:53Z
[ "python", "matplotlib", "colorbar" ]
I have a sequence of line plots for two variables (x,y) for a number of different values of a variable z. I would normally add the line plots with legends like this: ``` import matplotlib.pyplot as plt fig = plt.figure() ax = fig.add_subplot(111) # suppose mydata is a list of tuples containing (xs, ys, z) # where x...
(I know this is an old question but...) Colorbars require a `matplotlib.cm.ScalarMappable`, `plt.plot` produces lines which are not scalar mappable, therefore, in order to make a colorbar, we are going to need to make a scalar mappable. Ok. So the constructor of a `ScalarMappable` takes a `cmap` and a `norm` instance....
How can I get hours from a Python datetime?
8,343,385
18
2011-12-01T14:59:35Z
8,343,469
22
2011-12-01T15:04:43Z
[ "python", "datetime" ]
I have a Python datetime, d, and I want to get the number of hours since midnight as a floating point number. The best I've come up with is: ``` h = ((((d.hour * 60) + d.minute) * 60) + d.second) / (60.0 * 60) ``` Which gives 4.5 for 4:30am, 18.75 for 6:45pm, etc. Is there a better way?
``` h = d.hour + d.minute / 60. + d.second / 3600. ``` has less brackets…
What is the optimal naming convention for test files in Python?
8,343,711
18
2011-12-01T15:20:23Z
8,343,817
10
2011-12-01T15:28:02Z
[ "python", "unit-testing" ]
I am looking for an optimal naming convention for python test files that ease the usage of different test frameworks (unittest, note, pyunit, ...) and also that is friendly with test auto-discovery for these tools. I just want a clear set of recomandation that would require minimal configuration for tools. * Tests di...
Don't call the directory `test` or it will conflict with the built-in `test` package. The naming conventions are defined in [PEP 8](http://www.python.org/dev/peps/pep-0008/). See the 'Naming Conventions' section. Underscores are better than hyphens! The layout of your package is a bit more flexible. I tend to do the ...
How do you apply a list of lambda functions to a single element using an iterator?
8,344,058
3
2011-12-01T15:42:35Z
8,344,149
7
2011-12-01T15:49:16Z
[ "python", "list", "lambda", "iterator", "yield" ]
I want to apply a list of lambda functions to a single element using an iterable that has to be created with yield. The list of lambda functions would have something like: ``` [<function <lambda> at 0x1d310c8>, <function <lambda> at 0x1d355f0>] ``` And I want to apply every function, from left to right , to a single...
``` def apply_all(functions, item): for f in functions: yield f(item) ``` Example usage: ``` functions = [type, id, hex] for result in apply_all(functions, 55): print result ``` gives ``` <type 'int'> 20326112 0x37 ```
Pythons fastest way of randomising case of a string
8,344,905
6
2011-12-01T16:38:00Z
8,344,979
8
2011-12-01T16:43:16Z
[ "python", "string", "variables", "random" ]
I want to randomise the case of a string, heres what I have: ``` word="This is a MixeD cAse stRing" word_cap='' for x in word: if random.randint(0,1): word_cap += x.upper() else: word_cap += x.lower() word = word_cap print word ``` Im wondering if you could use...
``` import random s = 'this is a lower case string' ''.join(random.choice((str.upper,str.lower))(x) for x in s) ``` `random.choice` randomly selects one from two functions `str.upper`, `str.lower`. Then this function is applied to `x` for each letter in the input string `s`. If initial string has all the letters in...
Pycrypto aes 256 Initialization vector size
8,345,756
3
2011-12-01T17:37:25Z
8,355,432
11
2011-12-02T11:09:36Z
[ "python", "google-app-engine", "aes", "pycrypto" ]
here's the case i have a php script that's using aes256 ,CBC the both key and IV size are 32 bytes long ``` data= '123456789abcdef' from Crypto.Cipher import AES a = AES.new('oqufXQ(?bc=6_hR2I3sMZChDpb6dDlw4',2,'fOaiIOkD8*9Xeu_s4_bb87Ox_UG+D9GA') print a.encrypt(data) ``` and the error i got ``` <type 'exceptions.V...
Aha! There's a difference of opinion what the "256" refers to. AES has a fixed block size of 128 bits, so "AES 256" means 128 bit blocks, 256 bit *key*, 14 rounds. However, Rijndael allows both the key size and the block size to vary. `MCRYPT_RIJNDAEL_256` refers to Rijndael with *block size* set to 256 (and I don't...
Force python to not output a float in standard form / scientific notation / exponential form
8,345,795
5
2011-12-01T17:40:44Z
8,345,866
13
2011-12-01T17:46:08Z
[ "python" ]
So this works fine: ``` >>> float(1.0e-1) 0.10000000000000001 ``` But when dealing with a larger number, it won't print: ``` >>> float(1.0e-9) 1.0000000000000001e-09 ``` Is there a way to force this? Maybe using numpy or something.
``` print '{0:.10f}'.format(1.0e-9) ``` [String formatting](http://docs.python.org/library/string.html#format-string-syntax) in the documentation.
Selecting a random list element in python
8,346,067
2
2011-12-01T18:02:58Z
8,346,176
14
2011-12-01T18:12:18Z
[ "python", "list" ]
I'm trying to create a function that takes two lists and selects an element at random from each of them. Is there any way to do this using the random.seed function?
You can use [`random.choice`](http://docs.python.org/library/random.html#random.choice) to pick a random element from a sequence (like a list). If your two lists are `list1` and `list2`, that would be: ``` a = random.choice(list1) b = random.choice(list2) ``` Are you sure you want to use `random.seed`? This will ini...
How to handle multibyte string in Python
8,346,608
4
2011-12-01T18:46:10Z
8,346,663
8
2011-12-01T18:50:48Z
[ "python", "string", "multibyte", "multibyte-functions" ]
There are multibyte string functions in PHP to handle multibyte string (e.g:CJK script). For example, I want to count how many letters in a multi bytes string by using `len` function in python, but it return an inaccurate result (i.e number of bytes in this string) ``` japanese = "桜の花びらたち" print japanese...
Use [Unicode strings](http://docs.python.org/tutorial/introduction.html#unicode-strings): ``` # Encoding: UTF-8 japanese = u"桜の花びらたち" print japanese print len(japanese) ``` Note the `u` in front of the string. To convert a bytestring into Unicode, use `decode`: `"桜の花びらたち".decode('utf-8')...
CamelCase every string, any standard library?
8,347,048
24
2011-12-01T19:21:42Z
8,347,192
57
2011-12-01T19:33:25Z
[ "python" ]
Example: ``` HILO -> Hilo new york -> New York SAN FRANCISCO -> San Francisco ``` Is there a library or standard way to perform this task?
Why not use [`title`](http://docs.python.org/library/stdtypes.html#str.title) Right from the docs: ``` >>> "they're bill's friends from the UK".title() "They'Re Bill'S Friends From The Uk" ``` If you really wanted CamelCase you can use this: ``` >>> ''.join(x for x in 'make IT camel CaSe'.title() if not x.isspace())...
Drop in Single Breakpoint in Ruby Code
8,347,636
13
2011-12-01T20:12:38Z
8,347,791
15
2011-12-01T20:24:46Z
[ "python", "ruby-on-rails", "ruby", "debugging", "breakpoints" ]
I am trying to find ruby code that has commensurate functionality to these lines in python: ``` import code code.interact(local=locals()) ``` These lines essentially insert a single breakpoint into my code and open up a console where I can interact with any variables. Any thoughts on how to do this in Ruby?
You want the [Pry](https://github.com/pry/pry) library: ``` require 'pry' # gem install pry binding.pry # Drop into the pry console ``` Read more here: <http://banisterfiend.wordpress.com/2011/01/27/turning-irb-on-its-head-with-pry/> See also: [How to use Pry with Sinatra?](http://stackoverflow.com/questions/7...
Something more beautiful than <__main__.MyClass instance at 0x1624710>
8,349,054
6
2011-12-01T22:13:22Z
8,349,070
10
2011-12-01T22:15:14Z
[ "python", "class" ]
This is my class (as simple as it can be): ``` class MyClass(): def __init__(self, id): self.id = id def __str__(self): return "MyClass #%d" % self.id ``` When I print an object of MyClass, I get this beautiful string: `MyClass #id`. But when I just "show it" in the interpreter, I still get t...
``` def __repr__(self): return 'MyClass #%d' % (self.id,) ```
Python ncurses, CDK, urwid difference
8,349,085
20
2011-12-01T22:16:17Z
8,349,372
16
2011-12-01T22:43:33Z
[ "python", "ncurses", "curses", "urwid" ]
What's the difference between these 3? As far as I understand it they both provide binding to curses which is the C library for terminal text-based UI. I currently have no knowledge of any of the 3 and I've never used curses. Which one would you recommend? I've heard of ncurses many times but only once or twice about ...
What I get after looking at some references is: * [ncurses](http://en.wikipedia.org/wiki/Ncurses): It's a free software version of curses, so you have to deal with all kind low-level details. * [pyCDK](http://sourceforge.net/projects/pycdk/): It's a higher level library that provides some widgets. I haven't used this ...
Troubleshooting Fibonacci series with python
8,350,223
2
2011-12-02T00:14:11Z
8,350,251
13
2011-12-02T00:17:01Z
[ "python", "algorithm" ]
I am reading a textbook and I have no idea why is this code compiling differently on my compiler than what it says in the book. ``` def fibs(number): result = [0, 1] for i in range(number-2): result.append(result[-2] + result[-1]) return result ``` So this: `fibs(10)` should give me `[...
The code in your post isn't valid Python. Since your code was able to run, it's probably actually like this: ``` def fibs(number): result = [0, 1] for i in range(number-2): result.append(result[-2] + result[-1]) return result ``` Your `return result` is indented such that it's inside the `for`...
Python copy list issue
8,350,750
3
2011-12-02T01:41:36Z
8,350,785
7
2011-12-02T01:45:35Z
[ "python" ]
I don't know what's wrong here, I'm sure someone here can help though. I have a list `mylst` (list of lists) that's being copied and passed into the method `foo`. `foo` iterates through the list and replaces the first element in the row with a passed in var and returns the altered list. I print the list and I see it gi...
The `lst[:]` trick makes a copy of *one* level of list. You've got nested lists, so you may want to have a look at the services offered by the [`copy`](http://docs.python.org/library/copy.html) standard module. In particular: ``` first = foo(copy.deepcopy(mylst), "first") ```
How to import python module when module name has a '-' dash or hyphen in it?
8,350,853
54
2011-12-02T01:56:49Z
8,350,881
38
2011-12-02T02:00:45Z
[ "python", "import", "module", "hyphen" ]
I want to import foo-bar.py. This works: ``` foobar = __import__("foo-bar") ``` This does not: ``` from "foo-bar" import * ``` My question: Is there any way that I can use the above format i.e., `from "foo-bar" import *` to import a module that has a `-` in it?
you can't. `foo-bar` is not an identifier. rename the file to `foo_bar.py` **Edit:** If `import` is not your goal (as in: you don't care what happens with `sys.modules`, you don't need it to import itself), just getting all of the file's globals into your own scope, you can use `execfile` ``` # contents of foo-bar.py...
How to import python module when module name has a '-' dash or hyphen in it?
8,350,853
54
2011-12-02T01:56:49Z
8,350,938
47
2011-12-02T02:09:36Z
[ "python", "import", "module", "hyphen" ]
I want to import foo-bar.py. This works: ``` foobar = __import__("foo-bar") ``` This does not: ``` from "foo-bar" import * ``` My question: Is there any way that I can use the above format i.e., `from "foo-bar" import *` to import a module that has a `-` in it?
If you can't rename the module to match Python naming conventions, create a new module to act as an intermediary: ``` ---- foo_proxy.py ---- tmp = __import__('foo-bar') globals().update(vars(tmp)) ---- main.py ---- from foo_proxy import * ```
How to import python module when module name has a '-' dash or hyphen in it?
8,350,853
54
2011-12-02T01:56:49Z
21,025,462
21
2014-01-09T16:14:09Z
[ "python", "import", "module", "hyphen" ]
I want to import foo-bar.py. This works: ``` foobar = __import__("foo-bar") ``` This does not: ``` from "foo-bar" import * ``` My question: Is there any way that I can use the above format i.e., `from "foo-bar" import *` to import a module that has a `-` in it?
If you can't rename the original file, you could also use a symlink: ``` ln -s foo-bar.py foo_bar.py ``` Then you can just: ``` from foo_bar import * ```
Python 2.7 argparse
8,351,732
10
2011-12-02T04:17:27Z
8,351,779
26
2011-12-02T04:25:57Z
[ "python", "argparse" ]
I have a function: `def x(a,b,c)` How can I collect variable values from the command line that fit this pattern? `python test.py --x_center a --y_center b c` (`c` has, for example, 3, 4 or more values )
You can do something like that like this: ``` import argparse def x(x_center, y_center, values): print "X center:", x_center print "Y center:", y_center print "Values:", values def main(): parser = argparse.ArgumentParser(description="Do something.") parser.add_argument('-x', '--x-center', type=f...
Django model object initialization
8,352,862
3
2011-12-02T07:06:34Z
8,352,923
7
2011-12-02T07:13:32Z
[ "python", "django" ]
If I do ``` obj = Object() obj.att1 = 'test' obj.att2 = 'test' obj.save() ``` obj.id --> works fine But if I do ``` obj=Object(att1='test',att2='test').save() ``` Doing obj.id --> obj seems to be Nonetype at this stage Is this the case?
I don't know the exact framework you are using, but I am going to take a guess as to the problem: `Object(att1='test',att2='test').save()` The `save()` function doesn't appear to return the `Object` instance, it returns `None`. So you would normally: ``` obj=Object(att1='test',att2='test') obj.save() ``` Then check...
can python log output without INFO:root
8,353,594
4
2011-12-02T08:27:55Z
8,353,680
7
2011-12-02T08:36:20Z
[ "python", "logging" ]
I use the Python logging framework with default settings. For some data compare reason:I have to compare the log with other data output. But the python log begin with a default, something like: ``` INFO:root:post params in transmitter ``` Can I set the python log output without `INFO:root:`, like: ``` post params in...
Sure thing. You could set the format to watever you like: ``` format: '%(message)s' ``` Like this: ``` logging.basicConfig(format='%(message)s', ...) ``` See the doc for more info: <http://docs.python.org/library/logging.config.html>
python for loop list plus one item
8,353,676
4
2011-12-02T08:35:55Z
8,353,696
10
2011-12-02T08:38:00Z
[ "python", "list" ]
I'm handling mouse clicks on objects based on the location of the object on the screen. I record the xy coord of the mouse click and see if it matches any of the objects that are allowed to be clicked on. The objects are in different lists or just single objects, but I want them in one big list so I can just loop throu...
For 2nd method you need `itertools.chain` ``` for item in itertools.chain(list, [singleobj]): ... ```
How to capture output of Python's interpreter and show in a Text widget?
8,356,336
11
2011-12-02T12:28:29Z
8,356,465
26
2011-12-02T12:40:28Z
[ "python", "python-3.x", "pyqt" ]
I have a program in Python with PyQt, designed to run on Windows. This program makes a lot of operations and prints a lot of info. But as I want to freeze it and don't want the prompt screen to appear, I want that all that info appears in the main application, in a QTextEdit or so. How can i make the program work so it...
I assume that with "output from the interpreter", you mean output written to the console or terminal window, such as output produced with `print()`. All console output produced by Python gets written to the program's output streams `sys.stdout` (normal output) and `sys.stderr` (error output, such as exception tracebac...
Python format tabular output
8,356,501
22
2011-12-02T12:44:03Z
8,356,620
20
2011-12-02T12:55:42Z
[ "python" ]
Using python2.7, I'm trying to print to screen tabular data. This is roughly what my code looks like: ``` for i in mylist: print "{}\t|{}\t|".format (i, f(i)) ``` The problem is that, depending on the length of `i` or `f(i)` the data won't be aligned. This is what I'm getting: ``` |foo |bar | |foobo |foobar ...
It's not really hard to roll your own formatting function: ``` def print_table(table): col_width = [max(len(x) for x in col) for col in zip(*table)] for line in table: print "| " + " | ".join("{:{}}".format(x, col_width[i]) for i, x in enumerate(line)) + " |" table = [(...
Python format tabular output
8,356,501
22
2011-12-02T12:44:03Z
13,537,718
20
2012-11-24T02:28:25Z
[ "python" ]
Using python2.7, I'm trying to print to screen tabular data. This is roughly what my code looks like: ``` for i in mylist: print "{}\t|{}\t|".format (i, f(i)) ``` The problem is that, depending on the length of `i` or `f(i)` the data won't be aligned. This is what I'm getting: ``` |foo |bar | |foobo |foobar ...
There is a nice module for this in pypi, PrettyTable. <http://code.google.com/p/prettytable/wiki/Tutorial> <http://pypi.python.org/pypi/PrettyTable/> ``` $ pip install PrettyTable ```
Python format tabular output
8,356,501
22
2011-12-02T12:44:03Z
24,301,608
14
2014-06-19T08:02:36Z
[ "python" ]
Using python2.7, I'm trying to print to screen tabular data. This is roughly what my code looks like: ``` for i in mylist: print "{}\t|{}\t|".format (i, f(i)) ``` The problem is that, depending on the length of `i` or `f(i)` the data won't be aligned. This is what I'm getting: ``` |foo |bar | |foobo |foobar ...
For more beautiful table use the tabulate module: [Tabulate link](https://pypi.python.org/pypi/tabulate) Here reported an example: ``` >>> from tabulate import tabulate >>> table = [["Sun",696000,1989100000],["Earth",6371,5973.6], ... ["Moon",1737,73.5],["Mars",3390,641.85]] >>> print tabulate(table) -----...
ORM with Graph-Databases like Neo4j in Python
8,356,626
10
2011-12-02T12:56:09Z
13,144,407
8
2012-10-30T17:23:32Z
[ "python", "orm", "neo4j", "graph-databases", "bulbs" ]
i wonder wether there is a solution (or a need for) an ORM with Graph-Database (f.e. Neo4j). I'm tracking relationships (A is related to B which is related to A via C etc., thus constructing a large graph) of entities (including additional attributes for those entities) and need to store them in a DB, and i think a gra...
Shameless plug... there is also my own ORM which you may also want to checkout: <https://github.com/robinedwards/neomodel> It's built on top of py2neo, using cypher and rest API calls under hood, i.e no dependency on gremlin.
How to make this kind of equality array fast (in numpy)?
8,356,745
5
2011-12-02T13:06:56Z
8,356,787
10
2011-12-02T13:10:13Z
[ "python", "numpy" ]
I have two numpy array (2 dimensional) e.g. ``` a1 = array([["a","b"],["a","c"],["b","b"],["a","b"]]) a2 = array([["a","b"],["b","b"],["c","a"],["a","c"]]) ``` What is the most elegant way of getting a matrix like this: ``` array([[1,0,0,0], [0,0,0,1], [0,1,0,0], [1,0,0,0]]) ``` Where element (...
``` >>> (a1[:,numpy.newaxis] == a2).all(axis=2) array([[ True, False, False, False], [False, False, False, True], [False, True, False, False], [ True, False, False, False]], dtype=bool) ``` If you really need integers, convert to `int` as last step: ``` >>> (a1[:,numpy.newaxis] == a2).all(axis=...
How can I check if a URL is absolute using Python?
8,357,098
16
2011-12-02T13:33:25Z
8,357,262
12
2011-12-02T13:45:06Z
[ "python" ]
What is the preferred solution for checking if an URL is relative or absolute?
If you want to know if an URL is absolute or relative in order to join it with a base URL, I usually do `urlparse.urljoin` anyway: ``` >>> from urlparse import urljoin >>> urljoin('http://example.com/', 'http://example.com/picture.png') 'http://example.com/picture.png' >>> urljoin('http://example1.com/', '/picture.png...
How can I check if a URL is absolute using Python?
8,357,098
16
2011-12-02T13:33:25Z
8,357,518
25
2011-12-02T14:05:08Z
[ "python" ]
What is the preferred solution for checking if an URL is relative or absolute?
You can use the [`urlparse`](http://docs.python.org/library/urlparse.html) module to parse an URL and then you can check if it's relative or absolute by checking whether it has the host name set. ``` >>> import urlparse >>> def is_absolute(url): ... return bool(urlparse.urlparse(url).netloc) ... >>> is_absolute('...
Parsing puppet-api yaml with python
8,357,650
14
2011-12-02T14:15:15Z
9,730,761
23
2012-03-16T01:48:29Z
[ "python", "yaml", "puppet" ]
I am creating a script which need to parse the yaml output that the puppet outputs. When I does a request agains example *https://puppet:8140/production/catalog/my.testserver.no* I will get some yaml back that looks something like: ``` --- &id001 !ruby/object:Puppet::Resource::Catalog aliases: {} applying: false ...
I have emailed Kirill Simonov, the creator of PyYAML, to get help to parse Puppet YAML file. He gladly helped with the following code. This code is for parsing Puppet log, but I'm sure you can modify it to parse other Puppet YAML file. The idea is to create the correct loader for the Ruby object, then PyYAML can read...
List method to delete last element in list as well as all elements
8,358,101
20
2011-12-02T14:52:04Z
8,358,132
48
2011-12-02T14:54:03Z
[ "python", "list", "methods", "element" ]
yo folks, I have an issue with clearing lists. In the current program which I'm coding, I have a method that clears a certain number of lists. This is rather inconvenient since during one part of the program where this method is used, it would be a lot more helpful if it only deleted the last element from the lists. Is...
you can use `lst.pop()` or `del lst[-1]`
Python module to enable ANSI for stdout on Windows?
8,358,533
8
2011-12-02T15:22:56Z
8,358,565
8
2011-12-02T15:24:50Z
[ "python", "terminal", "console", "ansi-escape" ]
I am looking for a Python module that would add ANSI support under Windows. This means that after importing the module, if you output ANSI escaped strings, they will appear accordingly.
Your best bet is probably to use the [colorama](http://pypi.python.org/pypi/colorama) module. In fact, I believe that the Windows console does not support ANSI colors natively. colorama solves this difficulty by intercepting ANSI sequences and performing the appropriate Windows color change calls. This way, your code ...
Error while installing matplotlib
8,359,383
35
2011-12-02T16:23:53Z
8,520,900
13
2011-12-15T13:33:11Z
[ "python", "linux", "matplotlib" ]
I've tried using `pip install matplotlib` and `git clone` then `python setup.py install` as described in [the installation faq](http://matplotlib.sourceforge.net/faq/installing_faq.html#how-to-install) for Mac OS 10.7. But I get the same error: ``` [...] llvm-gcc-4.2 -fno-strict-aliasing -fno-common -dynamic -g -Os -p...
Same error, the install worked on one of my Lion machines but not the other. Tracked it down to a missing pkg-config ``` $ brew install pkg-config $ pip install -U 'http://sourceforge.net/projects/matplotlib/files/matplotlib/matplotlib-1.1.0/matplotlib-1.1.0.tar.gz/download' ``` (see also <https://jholewinski.org/blo...
Error while installing matplotlib
8,359,383
35
2011-12-02T16:23:53Z
13,793,890
80
2012-12-10T01:43:25Z
[ "python", "linux", "matplotlib" ]
I've tried using `pip install matplotlib` and `git clone` then `python setup.py install` as described in [the installation faq](http://matplotlib.sourceforge.net/faq/installing_faq.html#how-to-install) for Mac OS 10.7. But I get the same error: ``` [...] llvm-gcc-4.2 -fno-strict-aliasing -fno-common -dynamic -g -Os -p...
I had this issue on Ubuntu server 12.04. I had to install `libfreetype6-dev` and `libpng-dev` from the repositories. I was using a virtualenv and installing matplotlib using pip when I ran into this issue. Hints that I needed to do this came from the warning messages that popup early in the matplotlib installation so...
Kill process that raises Device or resource busy: '/dev/ttyUSB0'?
8,359,489
7
2011-12-02T16:32:41Z
8,359,544
7
2011-12-02T16:37:20Z
[ "python", "serial-port", "arduino", "pyserial" ]
I connect to my Arduino board with the following Python code. ``` device=glob.glob("/dev/ttyUSB*")[0] time.sleep(1) arduino = serial.Serial(device, 115200, timeout=5) ``` It generally works, but somehow some other process must be accessing the board after reboot giving me the error > serial.serialutil.SerialExceptio...
You can use ``` $ fuser /dev/ttyUSB0 ``` to list the PIDs of the processes using the file. Alternatively, if your `fuser` command supports it you can use the `-k` option to kill them.
assign the result of an list operation to var
8,359,557
3
2011-12-02T16:38:04Z
8,359,572
7
2011-12-02T16:39:33Z
[ "python" ]
In python, how can i do something like that ``` a = ["pera", "uva", "maca", "saladamista"] b = a.reverse() ``` but without assign the reverse list to `a`?
First copy the list, then reverse the copy: ``` a = ["pera", "uva", "maca", "saladamista"] b = a[:] b.reverse() ``` or use the "Martian smiley": ``` b = a[::-1] ``` **Edit**: In case someone is interested in timings, here they are: ``` In [1]: a = range(100000) In [2]: %timeit b = a[:]; b.reverse() 1000 loops, be...
How to extract info from scikits.learn classifier to then use in C code
8,360,253
7
2011-12-02T17:31:03Z
8,367,162
8
2011-12-03T10:53:10Z
[ "python", "svm", "libsvm", "scikits", "scikit-learn" ]
I have trained a bunch of RBF SVMs using scikits.learn in Python and then Pickled the results. These are for image processing tasks and one thing I want to do for testing is run each classifier on every pixel of some test images. That is, extract the feature vector from a window centered on pixel (i,j), run each classi...
Yes your solution looks alright. To pass the raw memory of a numpy array directly to a C program you can use the [ctypes helpers from numpy](http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.ctypes.html) or wrap you C program with cython and call it directly by passing the numpy array (see the doc at <h...
django python date time set to midnight
8,361,099
23
2011-12-02T18:47:32Z
8,361,184
15
2011-12-02T18:55:18Z
[ "python", "django", "date", "datetime", "date-manipulation" ]
I have a date time of my django object but it can be any time of the day. It can be at any time through the day, but I need to set my time to 00:00:00 (and another date to 23:59:59 but the principle will be the same) ``` end_date = lastItem.pub_date ``` currently the end date is 2002-01-11 12:34:56 What do I need to ...
Are you sure you don't want to use dates instead of datetimes? If you're always setting the time to midnight, you should consider using a date. If you really want to use datetimes, here's a function to get the same day at midnight: ``` def set_to_midnight(dt): midnight = datetime.time(0) return datetime.dateti...
django python date time set to midnight
8,361,099
23
2011-12-02T18:47:32Z
8,361,193
29
2011-12-02T18:56:35Z
[ "python", "django", "date", "datetime", "date-manipulation" ]
I have a date time of my django object but it can be any time of the day. It can be at any time through the day, but I need to set my time to 00:00:00 (and another date to 23:59:59 but the principle will be the same) ``` end_date = lastItem.pub_date ``` currently the end date is 2002-01-11 12:34:56 What do I need to ...
Try this: ``` import datetime pub = lastItem.pub_date end_date = datetime.datetime(pub.year, pub.month, pub.day) ```
django python date time set to midnight
8,361,099
23
2011-12-02T18:47:32Z
16,941,947
17
2013-06-05T13:58:31Z
[ "python", "django", "date", "datetime", "date-manipulation" ]
I have a date time of my django object but it can be any time of the day. It can be at any time through the day, but I need to set my time to 00:00:00 (and another date to 23:59:59 but the principle will be the same) ``` end_date = lastItem.pub_date ``` currently the end date is 2002-01-11 12:34:56 What do I need to ...
Using datetimes's "combine" with the time.min and time.max will give both of your datetimes. For example: ``` from datetime import date, datetime, time pub_date = date.today() min_pub_date_time = datetime.combine(pub_date, time.min) max_pub_date_time = datetime.combine(pub_date, time.max) ``` Result with pub\_date o...
STATIC_URL undefined in base Django template
8,361,538
10
2011-12-02T19:29:42Z
8,361,600
21
2011-12-02T19:35:07Z
[ "python", "django", "static" ]
I have a template, `base.html`, which is used in several other templates for various views. Each of those templates starts with the appropriate `{% extends "base.html" %}`. In the base template, I want to specify a static stylesheet thusly: ``` <link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}/base.css"/> ...
Perhaps this can help: > If {{ STATIC\_URL }} isn't working in your template, you're probably > not using RequestContext when rendering the template.As a brief > refresher, context processors add variables into the contexts of every > template. However, context processors require that you use > RequestContext when ren...
STATIC_URL undefined in base Django template
8,361,538
10
2011-12-02T19:29:42Z
10,247,392
15
2012-04-20T13:38:11Z
[ "python", "django", "static" ]
I have a template, `base.html`, which is used in several other templates for various views. Each of those templates starts with the appropriate `{% extends "base.html" %}`. In the base template, I want to specify a static stylesheet thusly: ``` <link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}/base.css"/> ...
You need to add 'django.core.context\_processors.static' to your TEMPLATE\_CONTEXT\_PROCESSORS variable in settings.py.
recover dict from 0-d numpy array
8,361,561
21
2011-12-02T19:31:25Z
8,361,740
33
2011-12-02T19:47:00Z
[ "python", "dictionary", "load", "numpy", "save" ]
What happened is that I (by mistake) saved a dictionary with the command `numpy.save()` (no error messages shown) and now I need to recover the data in the dictionary. When I load it with `numpy.load()` it has type (`numpy.ndarray`) and is 0-d, so it is not a dictionary any more and I can't access the data in it, 0-d a...
Use `mydict.item()` to obtain the array element as a Python scalar. ``` >>> import numpy as np >>> np.save('/tmp/data.npy',{'a':'Hi Mom!'}) >>> x=np.load('/tmp/data.npy') >>> x.item() {'a': 'Hi Mom!'} ```
recover dict from 0-d numpy array
8,361,561
21
2011-12-02T19:31:25Z
8,362,451
9
2011-12-02T20:48:28Z
[ "python", "dictionary", "load", "numpy", "save" ]
What happened is that I (by mistake) saved a dictionary with the command `numpy.save()` (no error messages shown) and now I need to recover the data in the dictionary. When I load it with `numpy.load()` it has type (`numpy.ndarray`) and is 0-d, so it is not a dictionary any more and I can't access the data in it, 0-d a...
0-d arrays can be indexed using the empty tuple: ``` >>> import numpy as np >>> x = np.array({'x': 1}) >>> x array({'x': 1}, dtype=object) >>> x[()] {'x': 1} >>> type(x[()]) <type 'dict'> ```
Get just a class name without module, etc
8,361,974
4
2011-12-02T20:05:39Z
8,361,990
11
2011-12-02T20:07:04Z
[ "python" ]
I'm probably overlooking something simple. Given an instance of a class, I'd like to get just the class name. For example: ``` class Foooo: pass instance = Foooo() print("instance.__class__ = "+str(instance.__class__)) print("Just the class name: "+str(instance.__class__).split(".")[-1][:-2]) ``` This gives the foll...
Try this: ``` instance.__class__.__name__ ```
Python & XAMPP on Windows: how to?
8,363,247
9
2011-12-02T22:01:05Z
8,365,990
12
2011-12-03T06:20:03Z
[ "python", "windows", "apache", "xampp", "mod-wsgi" ]
I have installed on my Win7x64 Xampp and Python 2.7. Now I'm trying to get the "power" of Python language... how can I do it? I've tried with mod\_python and mod\_wsgi but the first one does not exist for my version of Python, and when I try to start Apache after installing wsgi it gives me an error ``` < Directory ...
Yes you are right, mod\_python won't work with Python 2.7. So mod\_wsgi is the best option for you. I would recommend AMPPS as python environment is by default enabled with mod\_python and python 2.5. [AMPPS Website](http://www.ampps.com) if you still want to continue, Add this line in httpd.conf ``` LoadModule wsg...
Python & XAMPP on Windows: how to?
8,363,247
9
2011-12-02T22:01:05Z
14,288,366
9
2013-01-11T23:33:28Z
[ "python", "windows", "apache", "xampp", "mod-wsgi" ]
I have installed on my Win7x64 Xampp and Python 2.7. Now I'm trying to get the "power" of Python language... how can I do it? I've tried with mod\_python and mod\_wsgi but the first one does not exist for my version of Python, and when I try to start Apache after installing wsgi it gives me an error ``` < Directory ...
**WSGI is a lot better**, but at least I googled and tried to set it up for days without success. CGI is less efficient, but as most people use windows for development only, it makes little/no difference. It's super easy to set up! **CGI method:** 1. In xampp\apache\conf\httpd.conf look for this line: **AddHandler cg...
Counting equal strings in Python
8,364,045
3
2011-12-02T23:36:58Z
8,364,071
7
2011-12-02T23:39:43Z
[ "python", "string", "comparison" ]
I have a list of strings and some of them are equal. I need some script which would count equal strings. Ex: I have a list with some words : "House" "Dream" "Tree" "Tree" "House" "Sky" "House" And the output should look like this: "House" - 3 "Tree" - 2 "Dream" - 1 and so on
Use [collections.Counter()](http://docs.python.org/library/collections.html#module-collections). It is designed for exactly this use case: ``` >>> import collections >>> seq = ["House", "Dream", "Tree", "Tree", "House", "Sky", "House"] >>> for word, cnt in collections.Counter(seq).most_common(): print repr(wor...
How do you set the column width on a QTreeView?
8,364,061
7
2011-12-02T23:38:58Z
8,364,589
8
2011-12-03T00:57:20Z
[ "python", "pyqt", "pyqt4", "qtreeview" ]
Bear with me, I'm still new to QT and am having trouble wrapping my brain around how it does things. I've created and populated a QTreeView with two columns: ``` class AppForm(QMainWindow): def __init__(self, parent = None): super(AppForm, self).__init__(parent) self.model = QStandardItemModel() ...
When you call `setColumnWidth`, Qt will do the equivalent of: ``` self.view.header().resizeSection(column, width) ``` Then, when you call `setModel`, Qt will (amongst other things) do the equivalent of: ``` self.view.header().setModel(model) ``` So the column width *does* get set - just not on the model the tree vi...
Python Numpy: how to count the number of true elements in a bool array
8,364,674
56
2011-12-03T01:13:26Z
8,364,723
94
2011-12-03T01:22:14Z
[ "python", "arrays", "numpy", "count", "boolean" ]
I have a NumPy array 'boolarr' of boolean type. I want to count the number of elements whose values are `True`. Is there a NumPy or Python routine dedicated for this task? Or, do I need to iterate over the elements in my script?
You have multiple options. Two options are the following. ``` numpy.sum(boolarr) numpy.count_nonzero(boolarr) ``` Here's an example: ``` >>> import numpy as np >>> boolarr = np.array([[0, 0, 1], [1, 0, 1], [1, 0, 1]], dtype=np.bool) >>> boolarr array([[False, False, True], [ True, False, True], [ Tru...
Python Numpy: how to count the number of true elements in a bool array
8,364,674
56
2011-12-03T01:13:26Z
13,566,754
9
2012-11-26T14:21:29Z
[ "python", "arrays", "numpy", "count", "boolean" ]
I have a NumPy array 'boolarr' of boolean type. I want to count the number of elements whose values are `True`. Is there a NumPy or Python routine dedicated for this task? Or, do I need to iterate over the elements in my script?
That question solved a quite similar question for me and I thought I should share : In raw python you can use sum() to count True values in a dict : ``` >>> sum([True,True,True,False,False]) 3 ``` But this won't work : ``` >>> sum([[False, False, True], [True, False, True]]) TypeError... ``` Maybe this will help s...
how to convert string to datetime.timedelta()?
8,365,380
3
2011-12-03T03:53:39Z
8,365,423
8
2011-12-03T04:00:33Z
[ "python" ]
how can i convert my string of date to a datetime.timedelta() in python? I have this code : ``` import datetime date_select = '2011-12-1' delta = datetime.timedelta(days=1) target_date = date_select + delta print target_date ``` thanks in advance ...
You wouldn't convert `date_select` to a `timedelta`, instead, you need a `datetime` object, which can be added to a `timedelta` to produce an updated `datetime` object: ``` from datetime import datetime, timedelta date_select = datetime.strptime('2011-12-1', '%Y-%m-%d') delta = timedelta(days=1) target_date = date_se...
set environment variable in python script
8,365,394
15
2011-12-03T03:56:11Z
8,365,493
20
2011-12-03T04:17:08Z
[ "python", "export" ]
I have a bash script that sets an environment variable an runs a command ``` LD_LIBRARY_PATH=my_path sqsub -np $1 /homedir/anotherdir/executable ``` Now I want to use python instead of bash, because I want to compute some of the arguments that I am passing to the command. I have tried ``` putenv("LD_LIBRARY_PATH", ...
bash: ``` LD_LIBRARY_PATH=my_path sqsub -np $1 /path/to/executable ``` Similar, in Python: ``` import os import subprocess import sys os.environ['LD_LIBRARY_PATH'] = "my_path" # visible in this process + all children subprocess.check_call(['sqsub', '-np', sys.argv[1], '/path/to/executable'], e...
How to view .py in Eclipse
8,365,426
4
2011-12-03T04:00:56Z
8,365,445
7
2011-12-03T04:06:31Z
[ "python", "eclipse" ]
I just installed eclipse on my machine and want to modify a .py file. I tried opening the file and I get the error application not found. What do I need to install and how do I install it. I have searched the web and not found any clear instruction. I am using Java Eclipse SDK. I am trying to open the file .py with Ec...
Install the PyDev plug-in for Eclipse: <http://www.rose-hulman.edu/class/csse/resources/Eclipse/eclipse-python-configuration.htm>
Python & MySql: Unicode and Encoding
8,365,660
12
2011-12-03T05:07:40Z
8,365,782
51
2011-12-03T05:34:23Z
[ "python", "mysql", "unicode", "utf-8", "encode" ]
I am parsing json data and trying to store some of the json data into Mysql database. I am currently getting following unicode error. My question is how should I handle this. * Should I handle it from the database side, and if so how can I modify my table to do so? * Should I handle it from python side? Here is my ta...
I think that your MYSQLdb python library doesn't know it's supposed to encode to utf8, and is encoding to the default python system-defined charset `latin1`. When you `connect()` to your database, pass the `charset='utf8'` parameter. This should also make a manual `SET NAMES` or `SET character_set_client` unnecessary.
Python & MySql: Unicode and Encoding
8,365,660
12
2011-12-03T05:07:40Z
8,874,947
24
2012-01-16T01:32:30Z
[ "python", "mysql", "unicode", "utf-8", "encode" ]
I am parsing json data and trying to store some of the json data into Mysql database. I am currently getting following unicode error. My question is how should I handle this. * Should I handle it from the database side, and if so how can I modify my table to do so? * Should I handle it from python side? Here is my ta...
First, make sure you are assigning the **`charset`** and **`use_unicode`** parameters when making your MySQL connection: ``` conn = mysql.connect(host='127.0.0.1', user='user', passwd='passwd', db='db', charset='utf8', ...
Most elegant approach for writing JSON data to a relational database using Django Models?
8,367,609
17
2011-12-03T12:23:07Z
8,377,382
8
2011-12-04T18:01:44Z
[ "python", "django", "json", "django-models", "relational-database" ]
I have a typical Relational Database model laid out in Django where a typical model contains some `ForeignKeys`, some `ManyToManyFields`, and some fields that extend Django's `DateTimeField`. I want to save data that I am receiving in JSON format (not flat) from an external api. I wan't it such that data gets saved to...
In my opinion the cleanest place for the code you need is as a new Manager method (eg from\_json\_string) on a custom manager for the NinjaData model. I don't think you should override the standard create, get\_or\_create etc methods since you're doing something a bit different from what they normally do and it's good...
Python: argparse subcommand subcommand?
8,368,110
5
2011-12-03T13:54:04Z
8,368,962
7
2011-12-03T16:11:29Z
[ "python", "arguments", "argparse" ]
I have a program that has many available options. For example a configuration option to change settings. ``` ./app config -h ``` gives me the help using normal argparse subcommands now i would like to add another subcommand to the config subcommand called list to list config values ``` ./app config list ``` additi...
``` #file: argp.py import argparse parser = argparse.ArgumentParser(prog='PROG') parser_subparsers = parser.add_subparsers() sub = parser_subparsers.add_parser('sub') sub_subparsers = sub.add_subparsers() sub_sub = sub_subparsers.add_parser('sub_sub') ...
How do I read a text file into a string variable in Python
8,369,219
363
2011-12-03T16:47:54Z
8,369,272
14
2011-12-03T16:55:51Z
[ "python" ]
I use the following code segment to read a file in python ``` with open ("data.txt", "r") as myfile: data=myfile.readlines() ``` input file is ``` LLKKKKKKKKMMMMMMMMNNNNNNNNNNNNN GGGGGGGGGHHHHHHHHHHHHHHHHHHHHEEEEEEEE ``` and when I print data I get ``` ['LLKKKKKKKKMMMMMMMMNNNNNNNNNNNNN\n', 'GGGGGGGGGHHHHHHHHHH...
``` with open("data.txt") as myfile: data="".join(line.rstrip() for line in myfile) ``` join() will join a list of strings, and rstrip() with no arguments will trim whitespace, including newlines, from the end of strings.
How do I read a text file into a string variable in Python
8,369,219
363
2011-12-03T16:47:54Z
8,369,345
492
2011-12-03T17:06:34Z
[ "python" ]
I use the following code segment to read a file in python ``` with open ("data.txt", "r") as myfile: data=myfile.readlines() ``` input file is ``` LLKKKKKKKKMMMMMMMMNNNNNNNNNNNNN GGGGGGGGGHHHHHHHHHHHHHHHHHHHHEEEEEEEE ``` and when I print data I get ``` ['LLKKKKKKKKMMMMMMMMNNNNNNNNNNNNN\n', 'GGGGGGGGGHHHHHHHHHH...
You could use: ``` with open('data.txt', 'r') as myfile: data=myfile.read().replace('\n', '') ```
How do I read a text file into a string variable in Python
8,369,219
363
2011-12-03T16:47:54Z
16,082,963
260
2013-04-18T12:27:18Z
[ "python" ]
I use the following code segment to read a file in python ``` with open ("data.txt", "r") as myfile: data=myfile.readlines() ``` input file is ``` LLKKKKKKKKMMMMMMMMNNNNNNNNNNNNN GGGGGGGGGHHHHHHHHHHHHHHHHHHHHEEEEEEEE ``` and when I print data I get ``` ['LLKKKKKKKKMMMMMMMMNNNNNNNNNNNNN\n', 'GGGGGGGGGHHHHHHHHHH...
use read(), not readline() ``` data=myfile.read() ```
How do I read a text file into a string variable in Python
8,369,219
363
2011-12-03T16:47:54Z
29,178,816
12
2015-03-21T03:10:17Z
[ "python" ]
I use the following code segment to read a file in python ``` with open ("data.txt", "r") as myfile: data=myfile.readlines() ``` input file is ``` LLKKKKKKKKMMMMMMMMNNNNNNNNNNNNN GGGGGGGGGHHHHHHHHHHHHHHHHHHHHEEEEEEEE ``` and when I print data I get ``` ['LLKKKKKKKKMMMMMMMMNNNNNNNNNNNNN\n', 'GGGGGGGGGHHHHHHHHHH...
The simple way: ``` file = open('newfile.txt', 'r') print file.read() ```
How do I read a text file into a string variable in Python
8,369,219
363
2011-12-03T16:47:54Z
34,057,025
13
2015-12-03T02:52:56Z
[ "python" ]
I use the following code segment to read a file in python ``` with open ("data.txt", "r") as myfile: data=myfile.readlines() ``` input file is ``` LLKKKKKKKKMMMMMMMMNNNNNNNNNNNNN GGGGGGGGGHHHHHHHHHHHHHHHHHHHHEEEEEEEE ``` and when I print data I get ``` ['LLKKKKKKKKMMMMMMMMNNNNNNNNNNNNN\n', 'GGGGGGGGGHHHHHHHHHH...
Read from file in one line ``` str = open('very_Important.txt', 'r').read() ```
Checking contour area in opencv using python
8,369,547
5
2011-12-03T17:34:27Z
8,988,344
7
2012-01-24T14:17:34Z
[ "python", "opencv" ]
I try to use checkContour() function in new python api (cv2) and it **do** works if I create contours to be checked using findContours e.g. ``` contours, hierarchy = cv2.findContours(imgGray, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE) cv2.contourArea(contours[0]) ``` however when I create contour on my own the following...
This one should work: ``` contour = numpy.array([[[0,0]], [[10,0]], [[10,10]], [[5,4]]]) area = cv2.contourArea(contour) ```
How do I replace characters in a string in Python?
8,370,072
2
2011-12-03T18:51:20Z
8,370,102
8
2011-12-03T18:55:44Z
[ "python" ]
I'm trying to find the best way to do the following: I have a string lets say: ``` str = "pkm adp" ``` and I have a certain code in a dictionary to replace each charecter such as this one: ``` code = {'a': 'c', 'd': 'a', 'p': 'r', 'k': 'e', 'm': 'd'} ``` (`'a'` should be replaced by `'c'`, `'d'` by `'a'` ...) Ho...
Try this: ``` >>> import string >>> code = {'a': 'c', 'd': 'a', 'p': 'r', 'k': 'e', 'm': 'd'} >>> trans = string.maketrans(*["".join(x) for x in zip(*code.items())]) >>> str = "pkm adp" >>> str.translate(trans) 'red car' ``` Explanation: ``` >>> help(str.translate) Help on built-in function translate: translate(......
How to get a list of built-in modules in python?
8,370,206
17
2011-12-03T19:09:48Z
8,370,415
26
2011-12-03T19:39:45Z
[ "python" ]
I would like to get a list of names of built-in modules in python such that I can test the popularity of function's naming conventions (underline, CamelCase or mixedCase). I know there is a [Global Module Index](https://docs.python.org/2/py-modindex.html) but I am wondering if there is a list of strings, which is easi...
The compiled-in module names are in [`sys.builtin_module_names`](http://docs.python.org/library/sys.html#sys.builtin_module_names). For all importable modules, see [`pkgutil.iter_modules`](http://docs.python.org/library/pkgutil.html#pkgutil.iter_modules). Run these in a clean [`virtualenv`](http://pypi.python.org/pypi...
Add to list vs. Increment
8,371,433
6
2011-12-03T22:10:15Z
8,371,452
7
2011-12-03T22:13:37Z
[ "python" ]
Given that in Python: ``` element = element + [0] ``` should be equal to: ``` element += [0] ``` Why does one modify a list and the other does not? Here is a example: ``` >>> a = [[0, 0], [0,0]] >>> for element in a: ... element = element + [0] ... >>> a [[0, 0], [0, 0]] ``` a is not modified. But if I incre...
This is a fun side-effect of `+=` operatior, which calls `__iadd__` instead of `__add__`. The statement `x = x + y` is equivalent to `x = x.__add__(y)`, while `x += y` is equivalent to `x = x.__iadd__(y)`. This lets the `list` class optimize `+=` by extending the existing (ex, `x += y` is roughly equivalent to `x.ext...
Installing PIL on MAC OS X LION 10.7.2 with PIP INSTALLER
8,371,632
4
2011-12-03T22:40:13Z
9,667,662
9
2012-03-12T13:12:11Z
[ "python", "django", "python-imaging-library", "llvm", "pip" ]
I am trying to install PIL using PIP installer, and I'm getting this: ``` llvm-gcc-4.2 -fno-strict-aliasing -fno-common -dynamic -g -Os -pipe -fno-common -fno-strict-aliasing -fwrapv -mno-fused-madd -DENABLE_DTRACE -DMACOSX -DNDEBUG -Wall -Wstrict-prototypes -Wshorten-64-to-32 -DNDEBUG -g -fwrapv -Os -Wall -Wstrict-pr...
i got the same error. but additionally need to install the "commandline tools" under settings ![enter image description here](http://i.stack.imgur.com/LktyU.png) edit: just a few keywords for google, if someone is looking for this! easy\_install pip gcc not found mac osx xcode may be a moderator add this keywords to t...
Making all possible combinations of a list in python
8,371,887
15
2011-12-03T23:28:42Z
8,371,891
23
2011-12-03T23:29:36Z
[ "python", "list", "combinations" ]
I need to be able to make a list that contains all possible combinations of an inputted list. For example the list [1,2,3] should return [1 [1,2] [1,3] 2 [2,3] 3 [1,2,3]] The list doesn't have to be in any particular order. On this site I've found lots of functions using the itertools but those are returning objects wh...
**EDIT:** Changed algorithm for returning lists, instead of tuples. Simply use `itertools.combinations`. For example: ``` import itertools lst = [1, 2, 3] combs = [] for i in xrange(1, len(lst)+1): combs.append(i) els = [list(x) for x in itertools.combinations(lst, i)] combs.append(els) ``` Now `combs...
Zip with list output instead of tuple
8,372,399
24
2011-12-04T00:54:59Z
8,372,442
33
2011-12-04T01:00:44Z
[ "python", "list", "zip" ]
I might have overthink this one but maybe stupid question What is the fastest and most elegant way of doing list of lists from two lists? I have ``` In [1]: a=[1,2,3,4,5,6] In [2]: b=[7,8,9,10,11,12] In [3]: zip(a,b) Out[3]: [(1, 7), (2, 8), (3, 9), (4, 10), (5, 11), (6, 12)] ``` And I'd like to have ``` In [3]:...
If you are zipping more than 2 lists (or even only 2, for that matter), a readable way would be: ``` [list(a) for a in zip([1,2,3], [4,5,6], [7,8,9])] ``` This uses list comprehensions and converts each element in the list (tuples) into lists.
Zip with list output instead of tuple
8,372,399
24
2011-12-04T00:54:59Z
22,304,900
10
2014-03-10T15:50:06Z
[ "python", "list", "zip" ]
I might have overthink this one but maybe stupid question What is the fastest and most elegant way of doing list of lists from two lists? I have ``` In [1]: a=[1,2,3,4,5,6] In [2]: b=[7,8,9,10,11,12] In [3]: zip(a,b) Out[3]: [(1, 7), (2, 8), (3, 9), (4, 10), (5, 11), (6, 12)] ``` And I'd like to have ``` In [3]:...
I love the elegance of the zip function, but using the itemgetter() function in the operator module appears to be much faster. I wrote a simple script to test this: ``` import time from operator import itemgetter list1 = list() list2 = list() origlist = list() for i in range (1,5000000): t = (i, 2*i) ...
How can I use different pipelines for different spiders in a single Scrapy project
8,372,703
35
2011-12-04T02:08:25Z
8,372,894
9
2011-12-04T02:54:11Z
[ "python", "scrapy", "web-crawler" ]
I have a scrapy project which contains multiple spiders. Is there any way I can define which pipelines to use for which spider? Not all the pipelines i have defined are applicable for every spider. Thanks
I can think of at least four approaches: 1. Use a different scrapy project per set of spiders+pipelines (might be appropriate if your spiders are different enough warrant being in different projects) 2. On the scrapy tool command line, change the pipeline setting with `scrapy settings` in between each invocation of yo...
How can I use different pipelines for different spiders in a single Scrapy project
8,372,703
35
2011-12-04T02:08:25Z
14,165,844
27
2013-01-04T22:13:05Z
[ "python", "scrapy", "web-crawler" ]
I have a scrapy project which contains multiple spiders. Is there any way I can define which pipelines to use for which spider? Not all the pipelines i have defined are applicable for every spider. Thanks
Building on [the solution from Pablo Hoffman](http://groups.google.com/group/scrapy-users/browse_thread/thread/9ac290ed469887f1), you can use the following decorator on the `process_item` method of a Pipeline object so that it checks the `pipeline` attribute of your spider for whether or not it should be executed. For ...
How can I use different pipelines for different spiders in a single Scrapy project
8,372,703
35
2011-12-04T02:08:25Z
33,445,943
7
2015-10-30T22:46:16Z
[ "python", "scrapy", "web-crawler" ]
I have a scrapy project which contains multiple spiders. Is there any way I can define which pipelines to use for which spider? Not all the pipelines i have defined are applicable for every spider. Thanks
Above solutions are good, but I think they could be slow, because we are not really **not** using the pipeline per spider, instead we are checking if a pipeline exists every time an item is returned (and in some cases this could reach millions). A good way to completely disable (or enable) a feature per spider is usin...
How can I use different pipelines for different spiders in a single Scrapy project
8,372,703
35
2011-12-04T02:08:25Z
34,647,090
13
2016-01-07T03:53:43Z
[ "python", "scrapy", "web-crawler" ]
I have a scrapy project which contains multiple spiders. Is there any way I can define which pipelines to use for which spider? Not all the pipelines i have defined are applicable for every spider. Thanks
Just remove all pipelines from main settings and use this inside spider. This will define the pipeline to user per spider ``` class testSpider(InitSpider): name = 'test' custom_settings = { 'ITEM_PIPELINES': { 'app.MyPipeline': 400 } } ```
numpy function to set elements of array to a value given a list of indices
8,373,079
8
2011-12-04T03:36:45Z
8,373,103
15
2011-12-04T03:43:57Z
[ "python", "numpy", "variable-assignment", "indices" ]
I'm looking for a numpy function that will do the equivalent of: ``` indices = set([1, 4, 5, 6, 7]) zero = numpy.zeros(10) for i in indices: zero[i] = 42 ```
You can just give it a list of indices: ``` indices = [1, 4, 5, 6, 7] zero = numpy.zeros(10) zero[indices] = 42 ```
wrapping a numpy array in python
8,373,197
11
2011-12-04T04:10:34Z
8,373,470
10
2011-12-04T05:20:12Z
[ "python", "arrays", "numpy" ]
I'm using numpy arrays in python and am trying to better visualize them to see what I am working with. Is there a way to change when the array wraps to the next line? For instance, in the terminal window I have enough columns to show 0-49 on one line, but it automatically wraps on me when I convert to an array data typ...
<http://docs.scipy.org/doc/numpy/reference/generated/numpy.set_printoptions.html> Numpy by default prints only 75 characters when displaying arrays. You can change this by using numpy.set\_printoptions() For eg. I set my terminal to display 132x43 and got this: ``` >>> import numpy as np >>> np.set_printoptions(line...
How do a get a clean import namespace for a package in python?
8,373,813
3
2011-12-04T06:45:25Z
8,373,825
8
2011-12-04T06:49:05Z
[ "python" ]
I'm sure this is trivial to do, but I can't figure it out. Directory structure: ``` mylib/__init__.py mylib/MyClass.py ``` **init**.py reads: ``` import MyClass __all__ = [MyClass] ``` MyClass.py: ``` class MyClass(object): def __init__(self): pass ``` I have to create instances of MyClass using myl...
In your `__init__.py`, nstead of `import MyClass` try `from MyClass import MyClass`. The former command imports the module's name into your namespace; the second imports a symbol *from* the module (in this case, the name of a class) into your namespace. Also, `__all__` should be a list of *names,* i.e., strings, not ...
Styling part of label in legend in matplotlib
8,376,335
19
2011-12-04T15:33:33Z
8,384,685
14
2011-12-05T11:34:54Z
[ "python", "matplotlib" ]
Is it possible to have **part** of the text of a legend in a particular style, let's say, **bold** or *italic*?
As silvado mentions in his comment, you can use LaTeX rendering for more flexible control of the text rendering. See here for more information: <http://matplotlib.org/users/usetex.html> An example: ``` import numpy as np import matplotlib.pyplot as plt from matplotlib import rc # activate latex text rendering rc('te...
How to CREATE a transparent gif (or png) with PIL (python-imaging)
8,376,359
6
2011-12-04T15:36:24Z
8,377,135
13
2011-12-04T17:27:05Z
[ "python", "python-imaging-library", "transparent", "gif", "imaging" ]
Trying to *create* a transparent gif with PIL. So far I have this: ``` from PIL import Image img = Image.new('RGBA', (100, 100), (255, 0, 0, 0)) img.save("test.gif", "GIF", transparency=0) ``` Everything I've found so far refers to manipulating an existing image to adjust it's transparency settings or ov...
The following script creates a transparent GIF with a red circle drawn in the middle: ``` from PIL import Image, ImageDraw img = Image.new('RGBA',(100, 100)) draw = ImageDraw.Draw(img) draw.ellipse((25, 25, 75, 75), fill=(255, 0, 0)) img.save('test.gif', 'GIF', transparency=0) ```
Prevent anti-aliasing for imshow in matplotlib
8,376,609
37
2011-12-04T16:12:32Z
8,376,685
42
2011-12-04T16:25:59Z
[ "python", "numpy", "matplotlib", "scipy", "blurry" ]
When I use matplotlib's imshow() method to represent a small numpy matrix, it ends up doing some smoothing between pixels. Is there any way to disables this? It makes my figure's misleading in presentations.![A 28x28 matrix plotted with imshow()](http://i.stack.imgur.com/fg5ay.png) The figure above is a 28x28 image, s...
There is an interpolation option for `imshow` which controls how and if interpolation will be applied to the rendering of the matrix. If you try ``` imshow(array, interpolation="nearest") ``` you might get something more like you want. As an example ``` A=10*np.eye(10) + np.random.rand(100).reshape(10,10) imshow(A) ...
Prevent anti-aliasing for imshow in matplotlib
8,376,609
37
2011-12-04T16:12:32Z
9,251,767
15
2012-02-12T19:09:18Z
[ "python", "numpy", "matplotlib", "scipy", "blurry" ]
When I use matplotlib's imshow() method to represent a small numpy matrix, it ends up doing some smoothing between pixels. Is there any way to disables this? It makes my figure's misleading in presentations.![A 28x28 matrix plotted with imshow()](http://i.stack.imgur.com/fg5ay.png) The figure above is a 28x28 image, s...
you can also try the function ``` matshow ``` which name indicated that it does exactly what you asked - represent matrices. It is quite handy when you do not need to customise the figure too much. BTW, one of the best resources for matplotlib is their [Gallery](http://matplotlib.sourceforge.net/gallery.html)
Scrapy read list of URLs from file to scrape?
8,376,630
8
2011-12-04T16:16:37Z
8,378,474
27
2011-12-04T20:47:19Z
[ "python", "scrapy" ]
I've just installed scrapy and followed their simple dmoz [tutorial](http://doc.scrapy.org/en/latest/intro/tutorial.html) which works. I just looked up basic file handling for python and tried to get the crawler to read a list of URL's from a file but got some errors. This is probably wrong but I gave it a shot. Would ...
You were pretty close. ``` f = open("urls.txt") start_urls = [url.strip() for url in f.readlines()] f.close() ``` ...better still would be to use the context manager to ensure the file's closed as expected: ``` with open("urls.txt", "rt") as f: start_urls = [url.strip() for url in f.readlines()] ```
how to remove hashtag, @user, link of a tweet using regular expression
8,376,691
8
2011-12-04T16:26:38Z
8,377,440
13
2011-12-04T18:07:34Z
[ "python", "regex", "twitter" ]
I need to preprocess tweets using Python. Now I am wondering what would be the regular expression to remove all the hashtags, @user and links of a tweet respectively? for example, 1. `original tweet: @peter I really love that shirt at #Macy. http://bet.ly//WjdiW4` * processed tweet: `I really love that shirt at Ma...
The following example is a close approximation. Unfortunately there is no right way to do it just via regular expression. The following regex just strips of an URL (not just http), any punctuations, User Names or Any non alphanumeric characters. It also separates the word with a single space. If you want to parse the t...
Constructor chaining in python
8,376,758
3
2011-12-04T16:33:42Z
8,376,797
7
2011-12-04T16:38:53Z
[ "python", "constructor" ]
I have two constructors in my class: ``` def __init__(self): self(8) def __init__(self, size): self.buffer = [1] * size ``` Where I want the first constructor to call the second with a default size. Is this achievable in python?
You cannot define multiple initializers in Python (as pointed in the comments, `__init__` [is not really a constructor](http://stackoverflow.com/questions/6578487/init-as-a-initializer)), but you can define default values, for instance: ``` def __init__(self, size=8): self.buffer = [1] * size ``` In the above code,...
plotting many graphs with matplotlib
8,376,926
3
2011-12-04T16:59:53Z
8,377,940
7
2011-12-04T19:23:48Z
[ "python", "plot", "matplotlib" ]
Whenever, I want to plot multiple 2d line graphs graphs with matplotlib, I define two lists : `coloTypesList=["b","g","r","c","m","y","k"]; drawTypesList=["-","--","x"];` and select a pair from these at each iteration(for each graph). This is method only helps me when I have less than 22 graphs to draw. Any idea abou...
From the lists you give you have 21 combinations: ``` >>> from itertools import product >>> markers = ["-", "--", "x"] >>> colors = ["b", "g", "r", "c", "m", "y", "k"] >>> [a + b for a, b in product(colors, markers)] ['b-', 'b--', 'bx', 'g-', 'g--', 'gx', 'r-', 'r--', 'rx', 'c-', 'c--', 'cx', 'm-', 'm--', 'mx', 'y-', ...
Submit data via web form and extract the results
8,377,055
9
2011-12-04T17:14:48Z
8,377,285
9
2011-12-04T17:48:29Z
[ "python", "web-crawler", "web-scraping" ]
My python level is Novice. I have never written a web scraper or crawler. I have written a python code to connect to an api and extract the data that I want. But for some the extracted data I want to get the gender of the author. I found this web site `http://bookblog.net/gender/genie.php` but downside is there isn't a...
You can use [mechanize](http://wwwsearch.sourceforge.net/mechanize/) to submit and retrieve content, and the [re](http://docs.python.org/library/re.html) module for getting what you want. For example, the script below does it for the text of your own question: ``` import re from mechanize import Browser text = """ My...
Submit data via web form and extract the results
8,377,055
9
2011-12-04T17:14:48Z
8,377,373
18
2011-12-04T17:59:32Z
[ "python", "web-crawler", "web-scraping" ]
My python level is Novice. I have never written a web scraper or crawler. I have written a python code to connect to an api and extract the data that I want. But for some the extracted data I want to get the gender of the author. I found this web site `http://bookblog.net/gender/genie.php` but downside is there isn't a...
No need to use mechanize, just send the correct form data in a POST request. Also, using regular expression to parse HTML is a bad idea. You would be better off using a HTML parser like lxml.html. ``` import requests import lxml.html as lh def gender_genie(text, genre): url = 'http://bookblog.net/gender/analysi...