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 using variables from another file
14,573,021
8
2013-01-28T23:14:53Z
14,573,181
20
2013-01-28T23:30:30Z
[ "python" ]
I'm new and trying to make a simple random sentence generator- How can I pull a random item out of a list that is stored in another .py document? I'm using ``` random.choice(verb_list) ``` to pull from the list. How do I tell python that verb\_list is in another document? Also it would be helpful to know what the pr...
You can import the variables from the file: **vardata.py** ``` verb_list = [x, y, z] other_list = [1, ,2, 3] something_else = False ``` **mainfile.py** ``` from vardata import verb_list, other_list import random print random.choice(verb_list) ``` you can also do: ``` from vardata import * ``` to import everythi...
How do I include related model fields using Django Rest Framework?
14,573,102
74
2013-01-28T23:22:19Z
14,581,826
107
2013-01-29T11:27:15Z
[ "python", "django", "django-rest-framework" ]
Let's say that we have the following model: ``` class Classroom(models.Model): room_number = [....] class Teacher(models.Model): name = [...] tenure = [...] classroom = models.ForeignKey(Classroom) ``` Let's say that instead of getting a result like this per the ManyRelatedPrimaryKeyField function: ...
The simplest way is to use [the depth argument](http://django-rest-framework.org/api-guide/serializers#specifiying-nested-serialization) ``` class ClassroomSerializer(serializers.ModelSerializer): class Meta: model = Classroom depth = 1 ``` However, that will only include relationships for forward...
How does using the try statement avoid a race condition?
14,574,518
15
2013-01-29T02:05:18Z
14,574,562
7
2013-01-29T02:11:20Z
[ "python", "race-condition" ]
When determining whether or not a file exists, how does using the try statement avoid a "race condition"? I'm asking because a highly upvoted [answer](http://stackoverflow.com/a/85237/1217270) (update: it was deleted) seems to imply that using `os.path.exists()` creates an opportunity that would not exist otherwise. ...
Here's an example of usage: ``` try: with open('filename') as f: do_stuff_that_depends_on_the_existence_of_the_file(f) except IOError as e: print 'Trouble opening file' ``` If you are opening the file with any access at all, then the OS will guarantee that the file exists, or else it will fail with an...
How does using the try statement avoid a race condition?
14,574,518
15
2013-01-29T02:05:18Z
14,575,508
18
2013-01-29T04:08:56Z
[ "python", "race-condition" ]
When determining whether or not a file exists, how does using the try statement avoid a "race condition"? I'm asking because a highly upvoted [answer](http://stackoverflow.com/a/85237/1217270) (update: it was deleted) seems to imply that using `os.path.exists()` creates an opportunity that would not exist otherwise. ...
The race condition is, of course, between your program and some other code that operates on file (race condition always requires at least two parallel processes or threads, see [this](http://en.wikipedia.org/wiki/Race_condition) for details). That means using `open()` instead of `exists()` may really help only in two s...
Why does this python code have a syntax error?
14,574,916
2
2013-01-29T02:56:12Z
14,574,929
7
2013-01-29T02:58:21Z
[ "python" ]
To practice python, I made a simple class for a tree structure in which each node can have infinite child nodes. ``` class Tree(): def __init__(self, children, val): self.children = children self.val = val def add(self, child): self.children.append(child) def remove(self, index): child = self....
In Python 2 `print` is a keyword, so you can't use it as the name of a function or method.
How to create a list that exceeds the maximum size in Python
14,576,838
6
2013-01-29T06:21:35Z
25,275,253
9
2014-08-12T22:39:38Z
[ "python", "list" ]
According to [this](http://stackoverflow.com/questions/855191/how-big-can-a-python-array-get), *The maximum size of a Python list on a 32 bit system is 536,870,912 elements*. Is there any possible way to initialize a list with bigger size than that? Let's say: ``` list1 = [None]*1000000000 ```
Lists that large would take up a massive amount of space, as each element in the list would occupy at least 4 bytes, so just one list with maximum allowed elements would take up minimum 2GB of RAM1. And that's without even considering 64-bit systems2. 1. `4 * 5.4e+8 = 2.1e+9`, 2.1 GB 2. `8 * 1.2e+18 = 9.2+18`, 9.2 EB ...
multiprocessing.Pool spawning new childern after terminate() on Linux/Python2.7?
14,579,474
3
2013-01-29T09:24:18Z
14,583,746
11
2013-01-29T13:11:33Z
[ "python", "linux", "multiprocessing", "subprocess" ]
I have an executable file which I need to run very often, with different parameters. For this I wrote a small Python (2.7) wrapper, using the multiprocessing module, following the pattern given [here](http://stackoverflow.com/a/2561809/152439.). My code looks like this: ``` try: logging.info("starting pool runs"...
On [this page](http://jessenoller.com/2009/01/08/multiprocessingpool-and-keyboardinterrupt/), Jesse Noller, author of the multiprocessing module, shows that the correct way to handle `KeyboardInterrupt` is to have the subprocesses return -- not reraise the exception. This allows the main process to terminate the pool. ...
How do I concatenate two matrices in Python OpenCV?
14,579,541
6
2013-01-29T09:28:09Z
14,584,537
8
2013-01-29T13:49:52Z
[ "python", "opencv" ]
How do I concatenate two matrices into one matrix? The resulting matrix should have the same height as the two input matrices, and its width will equal the sum of the width of the two input matrices. I am looking for a pre-existing method that will perform the equivalent of this code: ``` def concatenate(mat0, mat1):...
If you are using cv2, (you will get Numpy support then), you can use Numpy function `np.hstack((img1,img2))` to do this. eg : ``` import cv2 import numpy as np # Load two images of same size img1 = cv2.imread('img1.jpg') img2 = cv2.imread('img2.jpg') both = np.hstack((img1,img2)) ```
Getting standard errors on fitted parameters using the optimize.leastsq method in python
14,581,358
14
2013-01-29T11:01:04Z
21,844,726
33
2014-02-18T04:58:51Z
[ "python", "scipy", "data-fitting" ]
I have a set of data (displacement vs time) which I have fitted to a couple of equations using the optimize.leastsq method. I am now looking to get error values on the fitted parameters. Looking through the documentation the matrix outputted is the jacobian matrix, and I must multiply this by the residual matrix to get...
Updated on 4/6/2016 ## Getting the correct errors in the fit parameters can be subtle in most cases. Let's think about fitting a function `y=f(x)` for which you have a set of data points `(x_i, y_i, yerr_i)`, where `i` is an index that runs over each of your data points. In most physical measurements, the error `yer...
what does @tornado.web.asynchronous decorator mean?
14,582,415
14
2013-01-29T12:02:25Z
14,605,399
15
2013-01-30T13:38:52Z
[ "python", "tornado" ]
1. If code didn't use this decorator, is it non-blocking? 2. Why this name is asynchronous, it means add decorator let code asynchronous? 3. Why @tornado.gen always use with @tornado.web.asynchronous together?
`@tornado.web.asynchronous` [prevents the the `RequestHandler` from automatically calling `self.finish()`](http://www.tornadoweb.org/en/stable/overview.html#non-blocking-asynchronous-requests). That's it; it just means Tornado will keep the connection open until you manually call `self.finish()`. 1. Code not using thi...
How to convert output to list to count it amount?
14,583,339
2
2013-01-29T12:51:17Z
14,583,395
7
2013-01-29T12:54:17Z
[ "python", "list" ]
I wrote a script that parses a webpage and get the amount of links('a' tag) on it: ``` import urllib import lxml.html connection = urllib.urlopen('http://test.com') dom = lxml.html.fromstring(connection.read()) for link in dom.xpath('//a/@href'): print link ``` The output of a script: ``` ./01.html ./52.html ./...
`link.split()` tries to split link itself. But you must work with entity that represents all links. In your case: `dom.xpath('//a/@href')`. So this must help you: ``` links = list(dom.xpath('//a/@href')) ``` And getting length with a built-in `len` function: ``` print len(links) ```
TypeError: module.__init__() takes at most 2 arguments (3 given)
14,583,761
41
2013-01-29T13:12:06Z
14,584,837
84
2013-01-29T14:07:33Z
[ "python", "python-3.x" ]
``` import Object class Visitor(Object): def __init__(self): super(Visitor,self).__init__() def visit(self, obj): pass def getIsDone(self): return False isDone = property(fget =lambda self:self.getIsDone()) ``` I get this error: `TypeError: module.__init__() takes at most 2 ar...
``` class A:pass print(A) #outputs <class '__main__.A'> import urllib print(urllib) #outputs <module 'urllib' from '/usr/lib/python3.2/urllib/__init__.py'> ``` Your error is happening because `Object` is a module, not a class. So your inheritance is screwy. Change your import statement to: ``` f...
Django Rest Framework - How to add custom field in ModelSerializer
14,583,816
31
2013-01-29T13:15:18Z
14,584,287
32
2013-01-29T13:38:57Z
[ "python", "django", "django-rest-framework" ]
I created a `ModelSerializer` and want to add a custom field which is not part of my model. I found a description to add extra fields [here](http://django-rest-framework.org/api-guide/serializers.html#specifying-fields-explicitly) and I tried the following: ``` customField = CharField(source='my_field') ``` When I a...
You're doing the right thing, except that `CharField` (and the other typed fields) are for writable fields. In this case you just want a simple read-only field, so instead just use: ``` customField = Field(source='get_absolute_url') ```
Django Rest Framework - How to add custom field in ModelSerializer
14,583,816
31
2013-01-29T13:15:18Z
21,270,278
10
2014-01-21T22:21:10Z
[ "python", "django", "django-rest-framework" ]
I created a `ModelSerializer` and want to add a custom field which is not part of my model. I found a description to add extra fields [here](http://django-rest-framework.org/api-guide/serializers.html#specifying-fields-explicitly) and I tried the following: ``` customField = CharField(source='my_field') ``` When I a...
here answer for your question. you should add to your model Account: ``` @property def my_field(self): return None ``` now you can use: ``` customField = CharField(source='my_field') ``` source: <http://stackoverflow.com/a/18396622/3220916>
Django Rest Framework - How to add custom field in ModelSerializer
14,583,816
31
2013-01-29T13:15:18Z
29,475,731
9
2015-04-06T16:56:44Z
[ "python", "django", "django-rest-framework" ]
I created a `ModelSerializer` and want to add a custom field which is not part of my model. I found a description to add extra fields [here](http://django-rest-framework.org/api-guide/serializers.html#specifying-fields-explicitly) and I tried the following: ``` customField = CharField(source='my_field') ``` When I a...
...for clarity, if you have a Model Method defined in the following way: ``` class MyModel(models.Model): ... def model_method(self): return "some_calculated_result" ``` You can add the result of calling said method to your serializer like so: ``` class MyModelSerializer(serializers.ModelSerializer)...
Passing memoryview to C function
14,584,439
13
2013-01-29T13:45:47Z
14,585,530
15
2013-01-29T14:44:09Z
[ "python", "numpy", "cython" ]
I have a C function declared as follows: ``` void getIndexOfState(long *p, long C, long G, long B, long *state); ``` Nowadays my cython wrapper code uses the buffer syntax from numpy array: ``` cpdef int getIndexOfState(self, np.ndarray[np.int_t, ndim=1, mode="c"] s): cdef long out getIndexOfState(&out, self...
If the underlying data is [properly contiguous/strided](http://docs.cython.org/src/userguide/memoryviews.html#specifying-more-general-memory-layouts) and there is at least one element in the memory, then it should suffice to pass a pointer to the first element (and maybe the length): ``` getIndexOfState(&out, self.C, ...
Learning about Queue module in python (how to run it)
14,585,597
3
2013-01-29T14:47:21Z
14,586,659
16
2013-01-29T15:41:48Z
[ "python", "multithreading", "python-3.x", "queue" ]
Was recently introduced to the queue design in regards to ability to defer processing as well as implementing a "FIFO" etc. Looked through the documentation in attempt to get a sample queue going to understand how to implement it in my own design / program. But I'm having issues with just running this code: ``` impor...
The for loop is launching a number of worker threads to perform the function defined by "worker". Here is working code that should run on your system in python 2.7. ``` import Queue import threading # input queue to be processed by many threads q_in = Queue.Queue(maxsize=0) # output queue to be processed by one thre...
making a class callable in same instance
14,585,987
5
2013-01-29T15:07:24Z
14,586,103
8
2013-01-29T15:14:01Z
[ "python", "class", "callable" ]
``` class Foo(object): def tick(self): print("something") class Bar(object): def __init__(self): self.foo = Foo() def tick(self): #Here's what I do.... self.foo.tick() #here's what my goal would be self.foo() b = Bar() b.tick() ``` That's essentially my g...
Changing `tick(self)` to `__call__(self)` is the correct solution. This has nothing to do with memory allocation. All `__call__` signifies is the function which Python calls when you use (for an object `foo`) the syntax `foo()`. For your later question: to check whether something is an object, use `isinstance` or `is...
Oreo colored text possible in matplotlib?
14,586,173
11
2013-01-29T15:18:11Z
14,676,271
7
2013-02-03T19:20:44Z
[ "python", "matplotlib" ]
Is there an easy way to have text (specifically axis-label text) with a white outline color, but black fill color. My axis labels fall over portions of my graph that are in some areas are light and others dark, so some label are obscured. An easy way to solve this problem would be to set the background color of the ax...
You should be able to pull this off using `PathEffects`, and `ax.(x/y)axis.label` or `ax.get_(x/y)ticklabels()` to get the `txt` objects. See the examples here: <http://matplotlib.org/examples/pylab_examples/patheffect_demo.html>
"ImportError: No module named tkinter" when using Pmw
14,587,980
5
2013-01-29T16:52:12Z
14,588,889
24
2013-01-29T17:40:12Z
[ "python", "python-2.7", "tkinter", "importerror" ]
Here's my problem: I'm running the code in [this](http://code.activestate.com/recipes/271249-how-to-create-linked-optionmenus-or-other-lists-in/) example. I have Python 2.7 and 3 installed on my RaspberryPi but I have checked and double-checked, and I am running the code in 2.7. I've installed Pmw 2.0.0 under 2.7, not ...
Maybe I can help you on how to remove the error. here are two thoughts: 1) you use python 2.xx and have installed the python 3 pwm module (Tkinter was renamed to tkinter from Python 2 to 3) 2) you do the following before the import and hope it helps: ``` #import tkinter #Traceback (most recent call last): # File "...
docopt + schema validation
14,588,098
4
2013-01-29T16:58:46Z
14,590,233
8
2013-01-29T18:59:12Z
[ "python", "validation", "parsing", "schema", "docopt" ]
Is there a better way of handling this validation: ``` #!/usr/bin/env python """ command. Usage: command start ID command finish ID FILE command (-h | --help) command (-v | --version) Arguments: FILE input file PATH out directory Options: -h --help Show this screen. -v --version Show ve...
I would do the following: ``` #!/usr/bin/env python """Command. Usage: command start ID command finish ID FILE command (-h | --help) command (-v | --version) Arguments: ID FILE input file Options: -h --help Show this screen. -v --version Show version. """ from docopt import docopt from sch...
FREAK Descriptor with Opencv Python
14,588,682
9
2013-01-29T17:28:05Z
20,632,100
7
2013-12-17T10:47:11Z
[ "python", "opencv", "feature-detection", "freak" ]
I was trying to implement the FREAK Descriptor in Python using Opencv. Here is the code i'm using: ``` def surf_freak_detect(image,hessianThreshold): surfDetector = cv2.SURF(hessianThreshold) surfDetector=cv2.GridAdaptedFeatureDetector(surfDetector,50) keypoints = surfDetector.detect(image,None) freak...
If the keypoints are detected properly but the program crashes when generating the descriptors it is because the **descriptor region** (which surrounds the keypoint) comes out of the image and there is a **memory access to a position that does not exist**. You have to somehow limit the operating region for freak descr...
How to get instance given a method of the instance?
14,588,905
6
2013-01-29T17:41:05Z
14,588,947
10
2013-01-29T17:43:06Z
[ "python", "class", "methods", "instance" ]
``` class MyClass: def myMethod(self): pass myInstance = MyClass() methodReference = myInstance.myMethod ``` Now can you get a reference to `myInstance` if you now only have access to `methodReference`?
Try this: ``` methodReference.im_self ``` If you are using Python 3: ``` methodReference.__self__ ```
Creating multiple objects with foreign key
14,589,362
5
2013-01-29T18:07:03Z
14,593,483
7
2013-01-29T22:48:19Z
[ "python", "django", "factory-boy" ]
I need to create ten sample users (`User`) and each of them must have fifty documents (`Doc`). How to do this in tests.py using factoryboy? ``` #factories.py from app_name.models import * import factory from datetime import datetime, timedelta, time from django.contrib.auth.models import User class UserFactory(fact...
``` users = UserFactory.create_batch(10) for user in users: doc = DocFactory.create(user=user) ```
How to actually upload a file using Flask WTF FileField
14,589,393
6
2013-01-29T18:09:26Z
14,589,898
12
2013-01-29T18:39:48Z
[ "python", "python-2.7", "flask", "flask-wtforms" ]
In my forms.py file I have I have ``` class myForm(Form): fileName = FileField() ``` In my views.py file I have ``` form = myForm() if form.validate_on_submit(): fileName = secure_filename(form.fileName.file.filename) ``` In my .html file I have ``` {% block content %} <form ac...
Have you looked at this: <http://flask.pocoo.org/docs/patterns/fileuploads/#uploading-files> You have to set a few configs such as UPLOAD\_FOLDER etc. You also have to call the save() function which I don't see in your posted code for views.py. ``` file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) ```
How to actually upload a file using Flask WTF FileField
14,589,393
6
2013-01-29T18:09:26Z
23,939,416
7
2014-05-29T17:33:13Z
[ "python", "python-2.7", "flask", "flask-wtforms" ]
In my forms.py file I have I have ``` class myForm(Form): fileName = FileField() ``` In my views.py file I have ``` form = myForm() if form.validate_on_submit(): fileName = secure_filename(form.fileName.file.filename) ``` In my .html file I have ``` {% block content %} <form ac...
On form.fileName.file, call '.save'. ``` filename = secure_filename(form.fileName.file.filename) file_path = os.path.join(app.config['UPLOAD_FOLDER'], filename) form.fileName.file.save(file_path) ``` Make sure to use secure\_filename() to prevent users from putting in bad file names, such as "../../../../home/usernam...
Python. Matplotlib inverted image
14,589,642
5
2013-01-29T18:23:38Z
14,590,351
12
2013-01-29T19:05:57Z
[ "python", "image", "matplotlib" ]
I haven't an idea what is wrong here. ``` import matplotlib.pyplot as plt im = plt.imshow(plt.imread('tas.png')) plt.show() ``` And the Y axis has inverted. So I wrote an argument `origin='lower'`. ``` im = plt.imshow(plt.imread('tas.png'), origin='lower') plt.show() ``` And what I have got. The Y axis came no...
You are running into an artifact of how images are encoded. For historical reasons, the origin of an image is the top left (just like the indexing on 2D array ... imagine just printing out an array, the first row of your array is the first row of your image, and so on.) Using `origin=lower` effectively flips your imag...
Use Python Selenium to get span text
14,590,341
5
2013-01-29T19:05:43Z
14,590,619
9
2013-01-29T19:23:25Z
[ "python", "selenium" ]
This should be easy, but I can't get it to work. I'm running a little demo using the Google homepage as a test. Here's my script: ``` from selenium import webdriver from selenium.common.exceptions import NoSuchElementException from selenium.webdriver.common.keys import Keys import time browser = webdriver.Chrome() b...
This should do it: ``` from selenium import webdriver browser = webdriver.Firefox() browser.get("http://www.google.com") for elem in browser.find_elements_by_xpath('.//span[@class = "gbts"]'): print elem.text ``` --- `text` is a property of the `WebElement` class, thus it is not callable. ``` class WebElement(o...
Support Vector - / Logistic - regression: do you have benchmark results for the boston housing data?
14,590,879
4
2013-01-29T19:40:32Z
14,592,663
8
2013-01-29T21:30:38Z
[ "python", "machine-learning", "regression", "scikit-learn" ]
I was going to test my implementation of the sklearn support vector regression package by running it on the boston housing prices dataset that ships with sklearn (sklearn.datasets.load\_boston). After playing around with it for a while (trying different regularization and tube parameters, randomization of cases and cr...
Change the kernel from `rbf` to `linear` will solve the problem. If you want to use `rbf`, try some different parameters, especially for `gamma`. The default `gamma` (`1/# features`) is too large for your case. ![enter image description here](http://i.stack.imgur.com/xIPyN.png) This is the parameter I used for linear...
How to make a RadioField in Flask?
14,591,202
3
2013-01-29T20:01:33Z
14,591,681
14
2013-01-29T20:31:14Z
[ "python", "python-2.7", "flask", "flask-wtforms" ]
I have a form with a TextField, FileField, and I want to add a RadioField. I'd like to have a radio field with two options, where the user can only select one. I'm following the example of the two previous forms that work. My forms.py looks like this ``` from flask import Flask, request from werkzeug import ...
In the forms.py the RadioField needs to look like this ``` RadioField('Label', choices=[('value','description'),('value_two','whatever')]) ``` Where the options are 'description' and 'whatever' with the submitted values being 'value' an 'value\_two' respectively.
How can Linux program, e.g. bash or python script, know how it was started: from command line or interactive GUI?
14,592,390
4
2013-01-29T21:12:51Z
14,592,608
8
2013-01-29T21:27:12Z
[ "python", "linux", "bash", "user-interface", "command-line-interface" ]
I want to do the following: If the bash/python script is launched from a terminal, it shall do something such as printing an error message text. If the script is launched from GUI session like double-clicking from a file browser, it shall do something else, e.g. display a GUI message box.
You can check to see whether `stdin` and `stdout` are connected to a terminal or not. When run from a GUI, generally `stdin` is not connected at all, and `stdout` is connected to a log file. When run from a terminal, both `stdin` and `stdout` will be connected to a terminal. In Python: ``` import os import sys if os...
Unstable results from Python factoring function
14,592,649
3
2013-01-29T21:30:00Z
14,592,819
10
2013-01-29T21:40:41Z
[ "python", "factorization" ]
``` def test_prime(n): q = True for p in range(2,n): #Only need to check up to rootn for primes and n/2 for factors if int(n%p) is 0: q = False print(p, 'and', int(n/p), 'are factors of ', n) if q: print(n, 'IS a prime number!') else: print(n...
You want `n % p == 0`, not `n % p is 0`. `is` tests identity, not equality, and not every 0 **is** the same as every other 0. ``` >>> 659306 % 329653 0 >>> (659306 % 329653) == 0 True >>> (659306 % 329653) is 0 False >>> id(0) 136748976 >>> id(659306 % 329653) 3070888160 ``` The `id` there basically corresponds to a...
A good way to get the charset/encoding of an HTTP response in Python
14,592,762
20
2013-01-29T21:36:39Z
14,592,894
16
2013-01-29T21:45:28Z
[ "python", "character-encoding", "httprequest", "urllib2" ]
Looking for an easy way to get the charset/encoding information of an HTTP response using Python urllib2, or any other Python library. ``` >>> url = 'http://some.url.value' >>> request = urllib2.Request(url) >>> conn = urllib2.urlopen(request) >>> response_encoding = ? ``` I know that it is sometimes present in the '...
To parse http header you could use [`cgi.parse_header()`](http://docs.python.org/2/library/cgi.html#functions): ``` _, params = cgi.parse_header('text/html; charset=utf-8') print params['charset'] # -> utf-8 ``` Or using the response object: ``` response = urllib2.urlopen('http://example.com') response_encoding = re...
How to reorder pixels
14,593,441
2
2013-01-29T22:45:21Z
14,594,003
8
2013-01-29T23:27:42Z
[ "python", "image-processing" ]
I have searched on Google but I couldn't find anything. I want to create a Python script that can import an image, change the order of pixels, and save an output image. I have worked with Python a lot, but only with the built-in libraries. So if I have to use new commands, please describe it as much as you can.
``` import sys import random from PIL import Image BLOCKLEN = 64 # Adjust and be careful here. img = Image.open(sys.argv[1]) width, height = img.size xblock = width / BLOCKLEN yblock = height / BLOCKLEN blockmap = [(xb*BLOCKLEN, yb*BLOCKLEN, (xb+1)*BLOCKLEN, (yb+1)*BLOCKLEN) for xb in xrange(xblock) for yb i...
selecting edges based on source/target in igraph
14,594,009
7
2013-01-29T23:28:19Z
14,600,513
9
2013-01-30T09:27:27Z
[ "python", "igraph" ]
is there an easy way to select/delete edges based on their source and target in igraph? what I am using is essentially ``` g.es["source"] = [e.source for e in g.es] g.es["target"] = [e.target for e in g.es] g.es["tuple"] = [e.tuple for e in g.es] g.es.select(target=root) ``` but I feel like there shou...
Just use `_source=whatever` and `_target=whatever` as keyword arguments to `select`, e.g.: ``` g.es.select(_source=root) ``` Alternatively, you can use the `incident` method of the graph, which gives you a list of edge IDs instead of a filtered `EdgeSeq` if that is better for your purposes: ``` g.incident(root, mode...
Python read-only property
14,594,120
26
2013-01-29T23:37:12Z
14,594,174
20
2013-01-29T23:42:35Z
[ "python", "properties", "python-2.7", "private", "readonly" ]
**I don't know when attribute should be private and if I should use property.** I read recently that setters and getters are not pythonic and I should use property decorator. It's ok. But what if I have attribute, that mustn't be set from outside of class but can be read (read-only attribute). Should this attribute b...
Generally, Python programs should be written with the assumption that all users are consenting adults, and thus are responsible for using things correctly themselves. However, in the rare instance where it just does not make sense for an attribute to be settable (such as a derived value, or a value read from some stati...
Python read-only property
14,594,120
26
2013-01-29T23:37:12Z
15,812,738
18
2013-04-04T13:30:24Z
[ "python", "properties", "python-2.7", "private", "readonly" ]
**I don't know when attribute should be private and if I should use property.** I read recently that setters and getters are not pythonic and I should use property decorator. It's ok. But what if I have attribute, that mustn't be set from outside of class but can be read (read-only attribute). Should this attribute b...
Just my two cents, [Silas Ray](http://stackoverflow.com/users/683020) is on the right track, however I felt like adding an example. ;-) Python is a type-unsafe language and thus you'll always have to trust the users of your code to use the code like a reasonable (sensible) person. Prefixing a property with an undersc...
Appengine - Upgrading from standard DB to NDB - ReferenceProperties
14,595,163
6
2013-01-30T01:24:07Z
14,595,379
11
2013-01-30T01:50:13Z
[ "python", "database", "google-app-engine", "datastore" ]
I have an AppEngine application that I am considering upgrading to use the NDB database. In my application, I have millions of objects that have old-style db references. I would like to know what the best migration path would be to get these ReferenceProperty values converted to KeyProperty values, or any other soluti...
Good news, you don't have to make any changes to your persisted data, as `ext.db` and `ndb` read and write the exact same data. Here's the quote from the [NDB Cheat Sheet](https://cloud.google.com/appengine/docs/python/ndb/db_to_ndb): > ### No Datastore Changes Needed! > > In case you wondered, despite the different ...
AttributeError: 'module' object has no attribute 'ZipFile'
14,595,280
4
2013-01-30T01:38:49Z
14,595,304
8
2013-01-30T01:41:45Z
[ "python" ]
just like i said,it's a very strange question.i hope you guys could help me solve this question thanks **the following is my code:** ``` import os import zipfile filename = "E:\\test.zip" currdir = "E:\\vpn\\" os.chdir(currdir) tfile = zipfile.ZipFile(filename, 'w') files = os.listdir(currdir) for f in files: ...
You called your script `zipfile.py`, which means it is trying to import itself. Change the name of the file to basically anything else.
Python dateutil.parser throws "ValueError: day is out of range for month"
14,595,401
7
2013-01-30T01:52:09Z
14,595,427
10
2013-01-30T01:56:06Z
[ "python", "python-dateutil" ]
I have a the following code that runs fine with input format like `{Year}/{Month}` except when it comes to `1994/02` Here is the sample code ``` >>> import dateutil.parser as dtp >>> dtp.parse('1994/01') datetime.datetime(1994, 1, 29, 0, 0) >>> dtp.parse('1994/03') datetime.datetime(1994, 3, 29, 0, 0) >>> dtp.parse('...
`dtp.parse` is filling in the missing day with the current date's day. You ran the code on 2013/01/29 and day 29 does not exist in February (i.e. 1994/02/29). Use this instead: ``` dtp.parse('1994/01'+'/01') ``` It will give consistent results (first day of month) regardless of when the code is executed.
Using Python to convert integer to binary
14,596,367
3
2013-01-30T03:49:50Z
14,596,397
10
2013-01-30T03:52:43Z
[ "python", "binary", "integer" ]
I'm trying to convert integer to binary. This is my work. I don't know how the make a list to show the binary. ``` num_str = input("Please give me a integer: ") num_int = int(num_str) while num_int > 0: if num_int % 2 == 0: num_int = int(num_int / 2) num_remainder = 1 print("The remainde...
Are you aware of the builtin `bin` function? ``` >>> bin(100) '0b1100100' >>> bin(1) '0b1' >>> bin(0) '0b0' ```
Remove text between () and [] in python
14,596,884
4
2013-01-30T04:46:35Z
14,598,135
8
2013-01-30T06:42:22Z
[ "python", "python-2.7" ]
I have a very long string of text with `()` and `[]` in it. I'm trying to remove the characters between the parentheses and brackets but I cannot figure out how. The list is similar to this: ``` x = "This is a sentence. (once a day) [twice a day]" ``` This list isn't what I'm working with but is very similar and a l...
Run this script, it works even with nested brackets. Uses basic logical tests. ``` def a(test_str): ret = '' skip1c = 0 skip2c = 0 for i in test_str: if i == '[': skip1c += 1 elif i == '(': skip2c += 1 elif i == ']' and skip1c > 0: skip1c -=...
Remove text between () and [] in python
14,596,884
4
2013-01-30T04:46:35Z
14,599,280
7
2013-01-30T08:10:16Z
[ "python", "python-2.7" ]
I have a very long string of text with `()` and `[]` in it. I'm trying to remove the characters between the parentheses and brackets but I cannot figure out how. The list is similar to this: ``` x = "This is a sentence. (once a day) [twice a day]" ``` This list isn't what I'm working with but is very similar and a l...
You can use re.sub function. ``` >>> import re >>> x = "This is a sentence. (once a day) [twice a day]" >>> re.sub("([\(\[]).*?([\)\]])", "\g<1>\g<2>", x) 'This is a sentence. () []' ``` If you want to remove the [] and the () you can use this code: ``` >>> import re >>> x = "This is a sentence. (once a day) [twic...
Custom tab completion in python argparse
14,597,466
19
2013-01-30T05:43:49Z
15,289,025
31
2013-03-08T07:41:05Z
[ "python", "bash", "command-line-interface", "argparse", "tab-completion" ]
Is it possible to get smarter tab completion cooperating with `argparse` in python scripts? My shell is bash. The information I can find about this stuff online is over a year old and mostly relates to `optparse`, which I don't want to use (deprecated). For the following script: ``` #!/usr/bin/env python import argp...
Have a look at [argcomplete](https://argcomplete.readthedocs.org/en/latest/#activating-global-completion%20argcomplete) by Andrey Kislyuk. Install it with: ``` sudo pip install argcomplete ``` Import the module and add one line in your source before calling `parser.parse_args()`: ``` #!/usr/bin/env python import a...
How to compare 2 list/array with python using for loops?
14,599,307
2
2013-01-30T08:11:26Z
14,599,346
7
2013-01-30T08:13:52Z
[ "python", "arrays", "list" ]
I want to compare ListA[0] to ListB[0]...etc. ``` ListA = [itemA, itemB, itemC] ListB = [true, false, true] for item in ListA: if ListB[item] == True: print"I have this item" ``` Current problem is that [item] is not a number, so ListB[item] will not work. What is the correct way if I want to do somethin...
You can iterate through the **lists** this way. ``` for a, b in zip(ListA, ListB): pass ```
How to compare 2 list/array with python using for loops?
14,599,307
2
2013-01-30T08:11:26Z
14,599,390
8
2013-01-30T08:16:15Z
[ "python", "arrays", "list" ]
I want to compare ListA[0] to ListB[0]...etc. ``` ListA = [itemA, itemB, itemC] ListB = [true, false, true] for item in ListA: if ListB[item] == True: print"I have this item" ``` Current problem is that [item] is not a number, so ListB[item] will not work. What is the correct way if I want to do somethin...
You can use `itertools.compress`: ``` Docstring: compress(data, selectors) --> iterator over selected data Return data elements corresponding to true selector elements. Forms a shorter iterator from selected data elements using the selectors to choose the data elements. ``` --- ``` In [1]: from itertools import com...
Using NOT EXISTS clause in sqlalchemy ORM query
14,600,619
7
2013-01-30T09:33:23Z
14,616,390
11
2013-01-31T00:21:48Z
[ "python", "sqlalchemy" ]
I want to convert the following raw sql query into a sqlalchemy ORM query : ``` SELECT * FROM kwviolations AS kwviol WHERE kwviol.proj_id=1 AND NOT EXISTS (SELECT * FROM kwmethodmetrics AS kwmetrics WHERE kwmetrics.kw_id=kwviol.kw_id AND kwmetrics.checkpoint_id=5); ``` I tried the following ORM query but didn't succe...
`kw_id` here seems to be a scalar column value, so you can't call `any()` on that - `any()` is only available from a [relationship()](http://docs.sqlalchemy.org/en/rel_0_8/orm/relationships.html#sqlalchemy.orm.relationship) bound attribute. Since I don't see one of those here you can call the [exists()](http://docs.sql...
Why do some Unix commands not work when called from inside Python? (command not found)
14,601,203
3
2013-01-30T10:02:48Z
14,601,615
8
2013-01-30T10:21:51Z
[ "python", "shell", "unix", "command" ]
I often wish to perform Unix commands from inside Python, but I have found recently that some commands are not found. An example is the 'limit' command: ``` $ echo $SHELL /bin/tcsh $ limit vmemoryuse 1000m $ python Python 2.7.3 (default, Aug 3 2012, 20:09:51) [GCC 4.1.2 20080704 (Red Hat 4.1.2-50)] on linux2 Type "h...
That's because some shell commands are not really programs, but internal shell commands. The classical example is `cd`: if it were an external program it would change the current directory of the new process, not the one of the shell, so it cannot be an external program. Roughly speaking there are two types of intern...
Joining 2 list of different size in Python
14,602,485
2
2013-01-30T11:05:40Z
14,602,567
8
2013-01-30T11:09:41Z
[ "python" ]
I get "list of index out of range" error when try to use 2 different size list. example: ``` ListA = [None, None, None, None, None] ListB = ['A', None, 'B'] for x, y in enumerate(ListA): if ListB[x]: ListA[x]=ListB[x] ``` Doing this will get "list of index out of range" error, because ListB[3] and ListB...
Use [itertools.izip\_longest](http://docs.python.org/2/library/itertools.html#itertools.izip_longest) ``` from itertools import izip_longest ListA = [b or a for a, b in izip_longest(ListA,ListB)] ```
Creating of new columns in pandas.DataFrame using apply() function
14,602,739
3
2013-01-30T11:19:21Z
14,603,893
8
2013-01-30T12:21:44Z
[ "python", "pandas" ]
I have a pandas DataFrame like: ``` A B '2010-01-01' 10 20 '2010-02-01' 20 30 '2010-03-01' 30 10 ``` I need to apply some function for every columns and create new columns in this DataFrame with special name. ``` A B A1 B1 '2010-01-01' 10 20 20 40 '2010-02-01' 20 30...
You can use `join` to do the combining: ``` >>> import pandas as pd >>> df = pd.DataFrame({"A": [10,20,30], "B": [20, 30, 10]}) >>> df A B 0 10 20 1 20 30 2 30 10 >>> df * 2 A B 0 20 40 1 40 60 2 60 20 >>> df.join(df*2, rsuffix='1') A B A1 B1 0 10 20 20 40 1 20 30 40 60 2 30 1...
Running a standalone script doing a model query in Django with `settings/dev.py` instead of `settings.py`
14,603,458
4
2013-01-30T11:59:00Z
14,603,619
7
2013-01-30T12:06:38Z
[ "python", "django", "django-settings" ]
Note the `settings/dev.py` instead of one `settings.py` file and the `script.py` in `my_app` in the following Django(1.4.3) project: ``` . ├── my_project │ ├── my_app │ │ ├── __init__.py │ │ ├── models.py │ │ ├── tests.py │ │ ├── views.py │ â”...
If you're looking to just run a script in the django environment, then the simplest way to accomplish this is to create a `./manage.py` subcommand, like this ``` from django.core.management.base import BaseCommand from my_app.models import MyModel class Command(BaseCommand): help = 'runs your code in the django e...
How to activate virtualenv?
14,604,699
58
2013-01-30T13:02:35Z
14,604,791
8
2013-01-30T13:07:38Z
[ "python", "virtualenv" ]
Newbie here so please be gentle. I have been through search and tried various alternatives without success and spent several days on it now - driving me mad. Running on Red Hat Linux with Python 2.5.2 Began using most recent Virtualenv but could not activate it, I found somewhere suggesting needed earlier version so I...
The problem there is the `/bin/.` command. That's really weird, since . should always be a link to the directory it's in. (Honestly, unless `.` is a strange alias or function, I don't even see how it's possible.) It's also a little unusual that your shell doesn't have a `.` [builtin for `source`](http://pubs.opengroup....
How to activate virtualenv?
14,604,699
58
2013-01-30T13:02:35Z
14,606,360
101
2013-01-30T14:27:57Z
[ "python", "virtualenv" ]
Newbie here so please be gentle. I have been through search and tried various alternatives without success and spent several days on it now - driving me mad. Running on Red Hat Linux with Python 2.5.2 Began using most recent Virtualenv but could not activate it, I found somewhere suggesting needed earlier version so I...
Here is my work flow after creating a folder and `cd`'ing into it: ``` $ virtualenv venv --distribute New python executable in venv/bin/python Installing distribute.........done. Installing pip................done. $ source venv/bin/activate (venv)$ python ```
How to activate virtualenv?
14,604,699
58
2013-01-30T13:02:35Z
24,720,790
35
2014-07-13T08:20:01Z
[ "python", "virtualenv" ]
Newbie here so please be gentle. I have been through search and tried various alternatives without success and spent several days on it now - driving me mad. Running on Red Hat Linux with Python 2.5.2 Began using most recent Virtualenv but could not activate it, I found somewhere suggesting needed earlier version so I...
You forgot to do `source bin/activate` where source is a executable name. Struck me first few times as well, easy to think that manual is telling "execute this from root of the environment folder". PS. no need to make activate executable via chmod, just FYI.
How to activate virtualenv?
14,604,699
58
2013-01-30T13:02:35Z
34,479,727
17
2015-12-27T10:57:00Z
[ "python", "virtualenv" ]
Newbie here so please be gentle. I have been through search and tried various alternatives without success and spent several days on it now - driving me mad. Running on Red Hat Linux with Python 2.5.2 Began using most recent Virtualenv but could not activate it, I found somewhere suggesting needed earlier version so I...
You can do ``` source ./python_env/bin/activate ``` or just go to the directory ``` cd /python_env/bin/ ``` and then ``` source ./activate ``` Good Luck.
All permutations of a Windows license key
14,606,351
96
2013-01-30T14:27:26Z
14,606,435
58
2013-01-30T14:31:24Z
[ "python", "itertools" ]
I need to apply for a Windows 8 upgrade for my laptop, for which I need the Windows 7 license key on the underside of the laptop. Because Microsoft decided in their infinite wisdom to create license labels that wear off, and I cannot read my license key clearly, it means I can't register my laptop for the windows upgr...
``` from itertools import product for perm in product('8B', 'B8', 'HN', '6G'): print 'MPP6R-09RXG-2H%sMT-%sK%sM9-V%sC8R' % perm ```
All permutations of a Windows license key
14,606,351
96
2013-01-30T14:27:26Z
14,606,540
163
2013-01-30T14:36:42Z
[ "python", "itertools" ]
I need to apply for a Windows 8 upgrade for my laptop, for which I need the Windows 7 license key on the underside of the laptop. Because Microsoft decided in their infinite wisdom to create license labels that wear off, and I cannot read my license key clearly, it means I can't register my laptop for the windows upgr...
**Disclaimer:** Yes, I know that this is not [Python](http://en.wikipedia.org/wiki/Python_%28programming_language%29) code. It just popped into my mind and I simply *had* to write it down. The simplest way is the use of shell expansion: ``` $ echo MPP6R-09RXG-2H{8,B}MT-{B,8}K{H,N}M9-V{6,G}C8R MPP6R-09RXG-2H8MT-BKHM9-...
All permutations of a Windows license key
14,606,351
96
2013-01-30T14:27:26Z
14,606,754
9
2013-01-30T14:49:11Z
[ "python", "itertools" ]
I need to apply for a Windows 8 upgrade for my laptop, for which I need the Windows 7 license key on the underside of the laptop. Because Microsoft decided in their infinite wisdom to create license labels that wear off, and I cannot read my license key clearly, it means I can't register my laptop for the windows upgr...
How about using itertools and functools at the same time? ``` >>> from operator import mod >>> from functools import partial >>> from itertools import product >>> map(partial(mod, 'MPP6R-09RXG-2H%sMT-%sK%sM9-V%sC8R'), product('8B', 'B8', 'HN', '6G')) ['MPP6R-09RXG-2H8MT-BKHM9-V6C8R', 'MPP6R-09RXG-2H8MT-BKHM9-VGC8R', '...
All permutations of a Windows license key
14,606,351
96
2013-01-30T14:27:26Z
14,612,768
16
2013-01-30T20:11:08Z
[ "python", "itertools" ]
I need to apply for a Windows 8 upgrade for my laptop, for which I need the Windows 7 license key on the underside of the laptop. Because Microsoft decided in their infinite wisdom to create license labels that wear off, and I cannot read my license key clearly, it means I can't register my laptop for the windows upgr...
Another way to generate the combinations ``` >>> ['MPP6R-09RXG-2H%sMT-%sK%sM9-V%sC8R' % (a, b, c, d) ... for a in '8B' for b in 'B8' for c in 'HN' for d in '6G'] ['MPP6R-09RXG-2H8MT-BKHM9-V6C8R', 'MPP6R-09RXG-2H8MT-BKHM9-VGC8R', 'MPP6R-09RXG-2H8MT-BKNM9-V6C8R', 'MPP6R-09RXG-2H8MT-BKNM9-VGC8R', 'MPP6R-09RXG-2H8MT-...
python nested classes
14,606,559
13
2013-01-30T14:37:47Z
14,606,571
8
2013-01-30T14:39:01Z
[ "python", "python-3.x" ]
First of all, here's my test code, I'm using python 3.2.x: ``` class account: def __init__(self): pass class bank: def __init__(self): self.balance = 100000 def balance(self): self.balance def whitdraw(self, amount): self.balance -= amount ...
There are several problems: 1. You're using the name `balance` for both the data member and for the function. 2. You're missing a `return` statement in `balance()`. 3. `balance()` operates on an *instance* of `bank`. There is no instance in `a.bank.balance`: here, `a.bank` refers to the inner class itself.
python nested classes
14,606,559
13
2013-01-30T14:37:47Z
14,607,121
22
2013-01-30T15:06:48Z
[ "python", "python-3.x" ]
First of all, here's my test code, I'm using python 3.2.x: ``` class account: def __init__(self): pass class bank: def __init__(self): self.balance = 100000 def balance(self): self.balance def whitdraw(self, amount): self.balance -= amount ...
My version of your code, with comments: ``` # # 1. CamelCasing for classes # class Account: def __init__(self): # 2. to refer to the inner class, you must use self.Bank # 3. no need to use an inner class here self.bank = self.Bank() class Bank: def __init__(self): s...
What does "\r" do in the following script?
14,606,799
8
2013-01-30T14:51:05Z
14,606,871
10
2013-01-30T14:54:37Z
[ "python", "telnet" ]
I am using following script to reboot my router using Telnet: ``` #!/usr/bin/env python import os import telnetlib from time import sleep host = "192.168.1.1" user = "USER" password = "PASSWORD" cmd = "system restart" tn = telnetlib.Telnet(host) sleep(1) tn.read_until("Login: ") tn.write(user + "\n\r") sleep(1) t...
The `'\r'` character is the carriage return, and the carriage return-newline pair is both needed for newline in a network virtual terminal session. --- From the [old telnet specification (RFC 854)](https://tools.ietf.org/html/rfc854) (page 11): > The sequence "CR LF", as defined, will cause the NVT to be > positione...
How to properly convert list of one element to a tuple with one element
14,607,128
4
2013-01-30T15:07:00Z
14,607,155
12
2013-01-30T15:08:18Z
[ "python", "python-2.6" ]
``` >>> list=['Hello'] >>> tuple(list) ('Hello',) ``` Why is the result of the above statements `('Hello',)` and not `('Hello')`?. I would have expected it to be the later.
You've got it right. In python if you do: ``` a = ("hello") ``` `a` will be a string since the parenthesis in this context are used for grouping things together. It is actually the comma which makes a tuple, not the parenthesis (parenthesis are just needed to avoid ambiguity in certain situations like function calls)...
How to debug code that never stops running?
14,607,876
2
2013-01-30T15:41:29Z
14,608,049
7
2013-01-30T15:48:56Z
[ "python", "python-2.7" ]
I have a large code base, and something is now taking too long to execute. I have no idea what. The code never raises an exception, it just appears to keep on processing something. What I'd like to do is place timers around some functions to test which one is the culprit. But I'm not sure if that is the right approac...
One solution is to use `cProfile`, which comes built into Python, to tell what functions your code is spending the most time in. Critically, this profiling works *even if you stop your code with a* `KeyboardInterrupt`. Thus, you can start your code running and profiling, stop it after a minute or two, and then see wher...
How to check if a specific integer is in a list
14,608,015
2
2013-01-30T15:47:20Z
14,608,067
11
2013-01-30T15:49:49Z
[ "python", "list", "if-statement", "python-2.7", "int" ]
I want to know how to make an if statement that executes a clause if a certain integer is in a list. All the other answers I've seen ask for a specific condition like prime numbers, duplicates, etc. and I could not glean the solution to my problem from the others.
You could simply use the `in` keyword. Like this : ``` if number_you_are_looking_for in list: # your code here ``` For instance : ``` myList = [1,2,3,4,5] if 3 in myList: print("3 is present") ```
Python 3: Change default values of existing function's parameters?
14,608,908
8
2013-01-30T16:30:19Z
14,608,958
12
2013-01-30T16:32:54Z
[ "python", "parameters", "python-3.x", "arguments", "default" ]
I'm creating a program which will eventually have like 500 calls for `print` function, and some others too. Each of these functions will take the exact same parameters every time, like this: ``` print(a, end='-', sep='.') print(b, end='-', sep='.') print(c, end='-', sep='.') print(..., end='-', sep='.') ``` Is there ...
You can define a special version of `print()` using [`functools.partial()`](http://docs.python.org/3/library/functools.html#functools.partial) to give it default arguments: ``` from functools import partial myprint = partial(print, end='-', sep='.') ``` and `myprint()` will then use those defaults throughout your co...
Python first and last element from array
14,609,720
11
2013-01-30T17:10:18Z
14,609,801
11
2013-01-30T17:14:07Z
[ "python", "arrays", "numpy" ]
I am trying to dynamically get the first and last element from an array. So, let us suppose the array has 6 elements. ``` test = [1,23,4,6,7,8] ``` If I am trying to get the `first and last = 1,8`, `23,7` and `4,6`. Is there a way to get elements in this order? I looked at a couple of questions [Link](http://stackov...
How about: ``` In [10]: arr = numpy.array([1,23,4,6,7,8]) In [11]: [(arr[i], arr[-i-1]) for i in range(len(arr) // 2)] Out[11]: [(1, 8), (23, 7), (4, 6)] ``` Depending on the size of `arr`, writing the entire thing in NumPy may be more performant: ``` In [41]: arr = numpy.array([1,23,4,6,7,8]*100) In [42]: %timeit...
Python first and last element from array
14,609,720
11
2013-01-30T17:10:18Z
21,169,102
30
2014-01-16T17:46:15Z
[ "python", "arrays", "numpy" ]
I am trying to dynamically get the first and last element from an array. So, let us suppose the array has 6 elements. ``` test = [1,23,4,6,7,8] ``` If I am trying to get the `first and last = 1,8`, `23,7` and `4,6`. Is there a way to get elements in this order? I looked at a couple of questions [Link](http://stackov...
I ended here, because I googled for "python first and last element of array", and found everything else but this. So here's the answer to the title question: ``` a = [1,2,3] a[0] # first element (returns 1) a[-1] # last element (returns 3) ```
Unreliable results with cv2.HoughCircles
14,609,980
8
2013-01-30T17:23:44Z
14,615,347
11
2013-01-30T22:46:58Z
[ "python", "image-processing", "opencv" ]
I have a video with 5 oil droplets, and I am trying to use cv2.HoughCircles to find them. This is my code: ``` import cv, cv2 import numpy as np foreground1 = cv2.imread("foreground1.jpg") vid = cv2.VideoCapture("NB14.avi") cv2.namedWindow("video") cv2.namedWindow("canny") cv2.namedWindow("blur") while True: r...
Initially I though there would be no overlapping in your oil droplets, but there are. So, Hough might indeed by a good method to use here, but I've had better experience when combining RANSAC with it. I would suggest exploring that, but here I will provide something different from that. First of all, I couldn't perfor...
How can I process a python dictionary with callables?
14,610,346
5
2013-01-30T17:43:18Z
14,610,441
8
2013-01-30T17:48:53Z
[ "python", "dictionary" ]
I would like to create a python directory whose values are to be evaluated separately. So, for example, in the following non-working example I define ``` a = {'key1': 'value1', 'key2': 42, 'key3': foo(20)} ``` for which e.g. ``` def foo(max): """Returns random float between 0 and max.""" return max*random.r...
Use the [`functools.partial()`](http://docs.python.org/2/library/functools.html#functools.partial) to create a callable that'll apply a set of arguments to another callable: ``` from functools import partial a = {'key1': 'value1', 'key2': 42, 'key3': partial(foo, 20)} ``` Now the `key3` value is a callable object; `...
How to connect to Facebook Graph API from Python using Requests if I do not need user access token?
14,611,240
6
2013-01-30T18:34:23Z
14,626,170
9
2013-01-31T12:47:03Z
[ "python", "facebook-graph-api", "python-requests" ]
I am trying to find the easiest way how to use Facebook Graph API using my favorite [Requests](http://docs.python-requests.org/) library. The problem is, all examples I found are about getting **user access token**, about redirects and user interaction. All I need is only **application access token**. I do not handle ...
Following <https://developers.facebook.com/docs/technical-guides/opengraph/publishing-with-app-token/>: ``` import requests r = requests.get('https://graph.facebook.com/oauth/access_token?grant_type=client_credentials&client_id=123&client_secret=XXX') access_token = r.text.split('=')[1] print access_token ``` (using ...
Malformed String ValueError ast.literal_eval() with String representation of Tuple
14,611,352
19
2013-01-30T18:41:06Z
14,611,535
12
2013-01-30T18:51:24Z
[ "python", "parsing", "python-2.x", "abstract-syntax-tree", "representation" ]
I'm trying to read in a string representation of a Tuple from a file, and add the tuple to a list. Here's the relevant code. ``` raw_data = userfile.read().split('\n') for a in raw_data : print a btc_history.append(ast.literal_eval(a)) ``` Here is the output: ``` (Decimal('11.66985'), Decimal('0E-8')) Trace...
From the [documentation](http://docs.python.org/2/library/ast.html#ast.literal_eval) for `ast.literal_eval()`: > Safely evaluate an expression node or a string containing a Python expression. **The string or node provided may only consist of the following Python literal structures: strings, numbers, tuples, lists, dic...
Malformed String ValueError ast.literal_eval() with String representation of Tuple
14,611,352
19
2013-01-30T18:41:06Z
18,178,379
21
2013-08-12T01:25:15Z
[ "python", "parsing", "python-2.x", "abstract-syntax-tree", "representation" ]
I'm trying to read in a string representation of a Tuple from a file, and add the tuple to a list. Here's the relevant code. ``` raw_data = userfile.read().split('\n') for a in raw_data : print a btc_history.append(ast.literal_eval(a)) ``` Here is the output: ``` (Decimal('11.66985'), Decimal('0E-8')) Trace...
`ast.literal_eval` (located in `ast.py`) parses the tree with `ast.parse` first, then it evaluates the code with quite an ugly recursive function, interpreting the parse tree elements and replacing them with their literal equivalents. Unfortunately the code is not at all expandable, so to add `Decimal` to the code you ...
Why is this flask-admin form alway failing validation?
14,611,374
4
2013-01-30T18:42:23Z
14,612,624
11
2013-01-30T20:01:19Z
[ "python", "sqlalchemy", "flask", "wtforms" ]
The status field shows the 3 options, but always displays "Not a valid choice" on submisison, whichever is chosen. ``` from website import app, db from flask.ext import admin from flask.ext.admin.contrib import sqlamodel from wtforms.fields import SelectField class Users(db.Model): id = db.Column(db.Integer,...
It is likely that the choices are being sent as unicode string while your status field in db is integer. Can you try the following: ``` form_args = dict( status=dict( choices=[(0, 'Regular'), (1, 'Guest'), (2, 'Banned')],coerce=int )) ```
Selenium not deleting profiles on browser close
14,612,294
3
2013-01-30T19:41:18Z
14,612,967
7
2013-01-30T20:22:13Z
[ "python", "firefox", "selenium" ]
I'm running some fairly simple tests using browsermob and selenium to open firefox browsers and navigate through a random pages. Each firefox instance is supposed to be independent and none of them share any cookies or cache. On my mac osx machine, this works quite nicely. The browsers open, navigate through a bunch of...
On your mac, have you looked in /var/folders/? You might find a bunch of anonymous\*webdriver-profile folders a few levels down. (mine appear in /var/folders/sm/jngvd6s57ldb916b7h25d57r0000dn/T/) Also, are you using driver.close() or driver.quit()? I thought driver.quit() cleans up the temp folder, but I could be wron...
Memcached: auto-discovery python support on AWS Elasticache?
14,612,632
6
2013-01-30T20:01:34Z
22,107,561
7
2014-02-28T23:11:20Z
[ "python", "django", "caching", "memcached" ]
I started to use AWS Elasticache with my django web app. I started by setting the cache location to the unique endpoint using the auto-discovery feature, but it doesn't seems to work. I'm using pylibmc (1.2.2) and django-pylibmc-sasl (0.2.4) to connect to memcached from python. Does the auto-discovery feature work o...
# Quick answer Yes for django: [django-elasticache](https://github.com/gusdan/django-elasticache) ## Long Answer ElastiCache provides memcached interface so there are three solution of using it: ## 1. Memcached configured with location = Configuration Endpoint. In this case your application will randomly connect t...
Plotting distance arrows in technical drawing
14,612,637
13
2013-01-30T20:01:52Z
14,613,143
8
2013-01-30T20:31:15Z
[ "python", "matplotlib" ]
I want to indicate a distance in one of my plots. What I have in mind is the way they do it in technical drawings, showing a double headed arrow with the distance as text beside it. **Example:** ``` from matplotlib.pyplot import * hlines(7,0,2, linestyles='dashed') hlines(11,0,2, linestyles='dashed') hlines(10,0,2, ...
Try using `annotate`: ``` annotate ('', (0.4, 0.2), (0.4, 0.8), arrowprops={'arrowstyle':'<->'}) ``` ![Image produced by annotate command](http://i.stack.imgur.com/vSoPf.png) I'm not sure about automatic text placement though.
Plotting distance arrows in technical drawing
14,612,637
13
2013-01-30T20:01:52Z
14,613,257
16
2013-01-30T20:37:20Z
[ "python", "matplotlib" ]
I want to indicate a distance in one of my plots. What I have in mind is the way they do it in technical drawings, showing a double headed arrow with the distance as text beside it. **Example:** ``` from matplotlib.pyplot import * hlines(7,0,2, linestyles='dashed') hlines(11,0,2, linestyles='dashed') hlines(10,0,2, ...
``` import matplotlib.pyplot as plt plt.hlines(7, 0, 2, linestyles='dashed') plt.hlines(11, 0, 2, linestyles='dashed') plt.hlines(10, 0, 2, linestyles='dashed') plt.hlines(8, 0, 2, linestyles='dashed') plt.annotate( '', xy=(1, 10), xycoords='data', xytext=(1, 8), textcoords='data', arrowprops={'arrowstyle'...
python os library source code location
14,613,223
4
2013-01-30T20:35:28Z
14,613,405
8
2013-01-30T20:45:00Z
[ "python" ]
I'm in learning mode --- this is probably a dumb or rtfm question but here it is: Where is the source code for the Python os library located? I've downloaded the Python tarball. Lots of usages in there but can't seem to find the source code itself and how it hooks into the OS. I'm interested in seeing what's done for t...
`os`'s implementation is scattered across a number of files. The core C functions are mostly located in [Modules/posixmodule.c](http://hg.python.org/cpython/file/v2.7.3/Modules/posixmodule.c), which, despite its name, contains implementations for OS routines on Windows NT and OS/2, in addition to POSIX routines. Wrap...
merging two tables with millions of rows in python
14,614,512
8
2013-01-30T21:51:56Z
14,617,925
12
2013-01-31T03:24:35Z
[ "python", "join", "merge", "pandas", "pytables" ]
I am using python for some data analysis. I have two tables, the first (lets call it 'A') has 10 million rows and 10 columns and the second ('B') has 73 million rows and 2 columns. They have 1 column with common ids and I want to intersect the two tables based on that column. In particular I want the inner join of the ...
this is a little pseudo codish, but I think should be quite fast. straightfoward disk based merge, with all tables on disk. The key is that you are not doing selection per se, just indexing into the table via start/stop, which is quite fast. Selecting the rows that meet a criteria in B (using A's ids) won't be very fa...
Why does communicate deadlock when used with multiple Popen subprocesses?
14,615,462
7
2013-01-30T22:57:32Z
14,617,026
8
2013-01-31T01:32:18Z
[ "python", "python-2.7", "multiprocessing", "subprocess" ]
The following issue does *not* occur in Python 2.7.3. However, it occurs with both Python 2.7.1 and Python 2.6 on my machine (64-bit Mac OSX 10.7.3). This is code I will eventually distribute, so I would like to know if there is any way to complete this task that does not depend so dramatically on the Python version. ...
I had to dig a bit for this one. (I ran into a similar problem once, so thought I knew the answer, but was wrong.) The issue (and patch for 2.7.3) is described here: <http://bugs.python.org/issue12786> The issue is that the PIPEs get inherited by subprocesses. The answer is to use 'close\_fds=True' in your Popen cal...
How can VIM tell the difference between `Ctrl-J` and `LF`?
14,615,717
6
2013-01-30T23:20:25Z
14,619,214
9
2013-01-31T05:39:53Z
[ "python", "vim", "ncurses", "python-curses" ]
I'm trying to create a little Python/curses app. But as far as I can see there's no way to tell whether `CTRL`+`J` or `Enter` have been pressed. Now this may be caused by the fact that they both have the same ascii code (10): <http://en.wikipedia.org/wiki/Control_character#In_ASCII> But how can VIM tell the differen...
`Enter` is usually equivalent to C-m. But, if the `icrnl` flag is active for the tty (see `stty -a`), then an input C-m will automatically be translated to C-j (so that it is easy to type Unix-ly terminated lines by just pressing `Enter`). In plain C you could use the *termios* functions *tcgetattr(3)* and *tcsetattr(...
Why won't Django use IPython?
14,616,805
19
2013-01-31T01:05:29Z
14,617,014
38
2013-01-31T01:31:14Z
[ "python", "django", "virtualenv", "ipython" ]
``` (myvenv)me:src orokusaki$ python manage.py shell -i ipython Python 2.7.2 (default, Jun 16 2012, 12:38:40) [GCC 4.2.1 Compatible Apple Clang 4.0 (tags/Apple/clang-418.0.60)] on darwin Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> while True: ... pass # :( ... `...
Try installing it into virtualenv! :-)
Why won't Django use IPython?
14,616,805
19
2013-01-31T01:05:29Z
20,043,174
12
2013-11-18T08:27:33Z
[ "python", "django", "virtualenv", "ipython" ]
``` (myvenv)me:src orokusaki$ python manage.py shell -i ipython Python 2.7.2 (default, Jun 16 2012, 12:38:40) [GCC 4.2.1 Compatible Apple Clang 4.0 (tags/Apple/clang-418.0.60)] on darwin Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> while True: ... pass # :( ... `...
I love iPython but don't like installing it in all my virtualenvs, and I've found a good solution to allow for that. Instead of using `python manage.py shell`, you can just use the system iPython directly. In order for this to work properly, you need to set the DJANGO\_SETTINGS\_MODULE so that it corresponds to your p...
Why is pip installing an old version of my package?
14,617,136
44
2013-01-31T01:46:33Z
15,189,799
14
2013-03-03T19:25:42Z
[ "python", "pip", "setuptools" ]
I've just uploaded a new version of my package to PyPi (1.2.1.0-r4): I can download the egg file and install it with easy\_install, and the version checks out correctly. But when I try to install using pip, it installs version 1.1.0.0 instead. Even if I explicitly specify the version to pip with `pip install -Iv tome==...
I found [here](http://python.6.n6.nabble.com/using-pip-to-install-an-specific-older-version-td4679821.html) that there is a known bug in pip that it won't check the version if there's a build directory with unpacked sources. I have checked this on my troubling package and after deleting its sources from build directory...
Why is pip installing an old version of my package?
14,617,136
44
2013-01-31T01:46:33Z
17,153,977
52
2013-06-17T18:09:27Z
[ "python", "pip", "setuptools" ]
I've just uploaded a new version of my package to PyPi (1.2.1.0-r4): I can download the egg file and install it with easy\_install, and the version checks out correctly. But when I try to install using pip, it installs version 1.1.0.0 instead. Even if I explicitly specify the version to pip with `pip install -Iv tome==...
This is an excellent question. It took me forever to figure out. This is the solution that works for me: Apparently, if `pip` can find a local version of the package, `pip` will prefer the local versions to remote ones. I even disconnected my computer from the internet and tried it again -- when `pip` still installed ...
Why is pip installing an old version of my package?
14,617,136
44
2013-01-31T01:46:33Z
18,105,975
16
2013-08-07T14:22:25Z
[ "python", "pip", "setuptools" ]
I've just uploaded a new version of my package to PyPi (1.2.1.0-r4): I can download the egg file and install it with easy\_install, and the version checks out correctly. But when I try to install using pip, it installs version 1.1.0.0 instead. Even if I explicitly specify the version to pip with `pip install -Iv tome==...
Thanks to [Marcus Smith](https://github.com/qwcode), who does amazing work as a maintener of pip, this was fixed in version 1.4 of pip which was released on 2013-07-23. Relevant information from the [changelog](http://www.pip-installer.org/en/latest/news.html#changelog) for this version > Fixed a number of issues (#4...
RFCOMM without pairing using PyBluez on Debian?
14,618,277
14
2013-01-31T04:05:10Z
14,827,036
15
2013-02-12T06:51:55Z
[ "python", "bluetooth", "rfcomm", "bluez" ]
I am trying to create an RFCOMM server process with Python that can be used without the need for pairing. Initially, I grabbed the two example scripts from the PyBluez documentation: Server: ``` # file: rfcomm-server.py # auth: Albert Huang <albert@csail.mit.edu> # desc: simple demonstration of a server application ...
This turned out to be a problem with the Debian Squeeze bluez default configuration. If anyone else hits this problem, disable the pnat plugin by editing /etc/bluetooth/main.conf: ``` DisablePlugins = pnat ``` Then restart bluetoothd. ``` $ sudo invoke-rc.d bluetooth restart ``` No changes were required to the PyB...
python inserting variable string as file name
14,622,314
5
2013-01-31T09:25:56Z
14,622,351
18
2013-01-31T09:27:34Z
[ "python", "file", "python-2.7" ]
I'm trying to create a file file a unique file name, every time my script is ran, it's only intended to be weekly or monthly. so I chose to use the date for the file name. ``` f = open('%s.csv', 'wb') %name ``` is where I'm getting this error. ``` Traceback (most recent call last): File "C:\Users\User\workspace\new3...
You need to put `% name` straight after the string: ``` f = open('%s.csv' % name, 'wb') ``` The reason your code doesn't work is because you are trying to `%` a file, which isn't string formatting, and is also invalid.
Google BigQuery, create a table from a query result
14,622,526
13
2013-01-31T09:36:18Z
14,634,697
12
2013-01-31T20:38:00Z
[ "python", "google-app-engine", "google-bigquery" ]
ok, so we're using [Google BigQuery](https://developers.google.com/bigquery/) via python **API**, my question is **how** to **create a table** (new one or overwrite old one) **from a query results** ? Some docs are [here](https://developers.google.com/bigquery/docs/queries), but I can't find it usefull. basically, we ...
You can do this by specifying a destination table in the query. You would need to use the Jobs.insert api rather than the Jobs.query call, and you should specify writeDisposition=WRITE\_APPEND and fill out the destination table. Here is what the configuration would look like, if you were using the raw api. If you're u...
Customize sphinxdoc theme
14,622,698
2
2013-01-31T09:45:41Z
24,932,178
7
2014-07-24T11:15:19Z
[ "python", "themes", "python-sphinx" ]
Is there an easy way to customize the existing `sphinxdoc` theme? For the default theme, there are many theme-attributes, but in sphinxdoc I can't even set a logo or change some colors? Or can you recommend my a site where I can learn how to modify themes?
All I wanted is to add [ReST strikethrough](http://stackoverflow.com/q/6518788/2923406) in my sphinx doc. Here is how I did it: ``` $ cd my-sphinx-dir $ mkdir -p theme/static $ touch theme/theme.conf $ touch theme/static/style.css ``` In `theme/theme.conf`: ``` [theme] inherit = default stylesheet = style.css pygmen...
Mongoengine - How to perform a "save new item or increment counter" operation?
14,623,430
5
2013-01-31T10:21:21Z
14,623,777
9
2013-01-31T10:39:34Z
[ "python", "mongodb", "mongoengine" ]
I'm using MongoEngine in a web-scraping project. I would like to keep track of all the images I've encountered on all the scraped webpages. To do so, I store the image `src` URL and the number of times the image has been encountered. The MongoEngine model definition is the following: ``` class ImagesUrl(Document): ...
You should be able to just do an [upsert](https://mongoengine-odm.readthedocs.org/en/latest/apireference.html?highlight=upsert#mongoengine.queryset.QuerySet.update_one) eg: ``` ImagesUrl.objects(src=self.src).update_one( upsert=True, inc__counter=1,...
boto encryption key with amazon s3
14,624,104
4
2013-01-31T10:58:48Z
14,624,505
9
2013-01-31T11:19:57Z
[ "python", "amazon-s3", "boto" ]
As I see there with the function calls `set_contents_with_filename` or `set_contents_with_file`, I can set encryption to true and while in s3, it stays encrypted I have some questions 1. If possible, I want to know, which is the key that is being used to encrypt the file. 2. If encryption is set to true, the encrypti...
The two functions you probably mean are [set\_contents\_from\_filename](http://boto.cloudhackers.com/en/latest/ref/s3.html#boto.s3.key.Key.set_contents_from_filename) and [set\_contents\_from\_file](http://boto.cloudhackers.com/en/latest/ref/s3.html#boto.s3.key.Key.set_contents_from_file) > If possible, I want to know...
What does a "version file" look like?
14,624,245
14
2013-01-31T11:06:35Z
14,626,175
13
2013-01-31T12:47:28Z
[ "python", "windows", "pyinstaller" ]
I've been googling this for ages now without results. The [PyInstaller](http://www.pyinstaller.org) manual says: ``` --version-file=FILE add a version resource from FILE to the exe ``` That sounds nice. I want to put version information in my executables. The problem is that I have no clue what a "version file" l...
Just had a quick look at the sources. It appears that the version file is expected to be Python source itself as the provided version file with be read and then `eval`'ed. The `GrabVersion.py` script appears to generate errors as you've already found, so I modified the `__repr__` function of `FixedFileInfo` to manuall...
Pip packages not found - Brewed Python
14,624,757
18
2013-01-31T11:34:14Z
14,739,278
32
2013-02-06T21:37:27Z
[ "python", "osx", "virtualenv", "pip", "homebrew" ]
Running Python 2.7.3, installed with HomeBrew, on a mac. Installed several packages using PIP, including virtualenv. (Using virtualenv as an example, but NONE of the packages work.) When I try to run them in terminal, it fails as follows: ``` $ virtualenv venv --distribute -bash: virtualenv: command not found ``` A...
The problem was that I had not added Python to the system $PATH. At the end of the brew install it says (viewable by typing `brew info python`): ``` Executable python scripts will be put in: /usr/local/share/python so you may want to put "/usr/local/share/python" in your PATH, too. ``` So, simply had to open .p...
Find http:// and or www. and strip from domain. leaving domain.com
14,625,693
6
2013-01-31T12:22:07Z
14,625,862
11
2013-01-31T12:31:11Z
[ "python", "url", "urlparse" ]
I'm quite new to python. I'm trying to parse a file of URLs to leave only the domain name. some of the urls in my log file begin with http:// and some begin with www.Some begin with both. This is the part of my code which strips the http:// part. What do I need to add to it to look for both http and www. and remove b...
It might be overkill for this specific situation, but i'd generally use [`urlparse.urlsplit`](http://docs.python.org/2/library/urlparse.html#urlparse.urlsplit) (Python 2) or [`urllib.parse.urlsplit`](http://docs.python.org/3.3/library/urllib.parse.html?highlight=urllib.parse#urllib.parse.urlsplit) (Python 3). ``` from...
Inheritance best practice : *args, **kwargs or explicitly specifying parameters
14,626,279
26
2013-01-31T12:52:45Z
14,626,574
12
2013-01-31T13:10:23Z
[ "python", "inheritance", "method-signature" ]
I often find myself overwriting methods of a parent class, and can never decide if I should explicitly list given parameters or just use a blanket `*args, **kwargs` construct. Is one version better than the other? Is there a best practice? What (dis-)advantages am I missing? ``` class Parent(object): def save(sel...
My choice would be: ``` class Child(Parent): def save(self, commit=True, **kwargs): super(Child, self).save(commit, **kwargs) # more logic ``` It avoids accessing commit argument from `*args` and `**kwargs` and it keeps things safe if the signature of `Parent:save` changes (for example adding a n...
Inheritance best practice : *args, **kwargs or explicitly specifying parameters
14,626,279
26
2013-01-31T12:52:45Z
14,770,951
18
2013-02-08T10:54:06Z
[ "python", "inheritance", "method-signature" ]
I often find myself overwriting methods of a parent class, and can never decide if I should explicitly list given parameters or just use a blanket `*args, **kwargs` construct. Is one version better than the other? Is there a best practice? What (dis-)advantages am I missing? ``` class Parent(object): def save(sel...
**Liskov Substitution Principle** Generally you don't want you method signature to vary in derived types. This can cause problems if you want to swap the use of derived types. This is often referred to as the [Liskov Substitution Principle](http://en.wikipedia.org/wiki/Liskov_substitution_principle). **Benefits of Ex...
pandas: HTML output with conditional formatting
14,627,380
21
2013-01-31T13:52:00Z
14,630,250
18
2013-01-31T16:16:27Z
[ "python", "html", "css", "dataframe", "pandas" ]
I am trying to format a table, such that data in each column are formatted in a style depending on their values (similar to conditional formatting in spreadsheet programs). How can I achieve that in pandas using the HTML formatter? A typical use case is highlighting significant values in a table. For example: ``` ...
You can use the DataFrame [`to_html`](http://pandas.pydata.org/pandas-docs/dev/generated/pandas.DataFrame.to_html.html) method, which comes with `formatters` argument. *An easier solution would be to surround by `<span class="significant">` and `</span>`, (rather than `*`). Note: by default this will be escaped (i.e. ...
Largest Eigenvector and possible Scipy weirdness
14,627,475
3
2013-01-31T13:56:36Z
14,627,916
7
2013-01-31T14:18:14Z
[ "python", "scipy", "eigenvector", "eigenvalue" ]
Not sure whether this is a bug in the package or due to some other cause, but here we go. I'm using the following package to find the largest eigenvalue and its corresponding eigenvector over a symmetric matrix of similarity scores (10x10 in size): ``` scipy.sparse.linalg.eigen.arpack.eigsh ``` , like so: ``` scipy...
This is actually a math question. But the reason is that there's an arbitrary phase when you calculate eigenvectors. You're solving Ax = bx for x. The equation is invariant under multiplication by a (possibly ocmplex) phase. As to why it happens in a (seemingly) random fashion, I don't know. But I'm pretty sure it's ...