instruction stringlengths 12 148 | input stringlengths 16 30.2k | output stringlengths 11 27.3k |
|---|---|---|
Docker Compose vs. Dockerfile - which is better? | I have been reading up and learning about Docker, and am trying to correctly choose the Django setup to use. So far there is either:
Docker Compose or Dockerfile
I understand that Dockerfiles are used in Docker Compose, but I am not sure if it is good practice to put everything in one large Dockerfile with multiple FRO... | The answer is neither.
Docker Compose (herein referred to as compose) will use the Dockerfile if you add the build command to your project's docker-compose.yml.
Your Docker workflow should be to build a suitable Dockerfile for each image you wish to create, then use compose to assemble the images using the build comm... |
How can I tell if a string repeats itself in Python? | I'm looking for a way to test whether or not a given string repeats itself for the entire string or not.
Examples:
[
'0045662100456621004566210045662100456621', # '00456621'
'0072992700729927007299270072992700729927', # '00729927'
'001443001443001443001443001443001443001443', ... | Here's a concise solution which avoids regular expressions and slow in-Python loops:
def principal_period(s):
i = (s+s).find(s, 1, -1)
return None if i == -1 else s[:i]
See the Community Wiki answer started by @davidism for benchmark results. In summary,
David Zhang's solution is the clear winner, outperformi... |
How to get all values from python enum class? | I'm using Enum4 library to create an enum class as follows:
class Color(Enum):
RED = 1
BLUE = 2
I want to print [1, 2] as a list somewhere. How can I achieve this?
| You can do the following:
[e.value for e in Color]
|
Why do new style class and old style class have different behavior in this case? | I found something interesting, here is a snippet of code:
class A(object):
def __init__(self):
print "A init"
def __del__(self):
print "A del"
class B(object):
a = A()
If I run this code, I will get:
A init
But if I change class B(object) to class B(), I will get:
A init
A del
I found a... | TL;DR: this is an old issue in CPython, that was finally fixed in CPython 3.4. Objects kept live by reference cycles that are referred to by module globals are not properly finalized on interpreter exit in CPython versions prior to 3.4. New-style classes have implicit cycles in their type instances; old-style classes (... |
Celery & RabbitMQ running as docker containers: Received unregistered task of type '...' | I am relatively new to docker, celery and rabbitMQ.
In our project we currently have the following setup:
1 physical host with multiple docker containers running:
1x rabbitmq:3-management container
# pull image from docker hub and install
docker pull rabbitmq:3-management
# run docker image
docker run -d -e RABBITMQ_NO... | As you suspect, the issue is because the celery worker does not know the tasks module. There are two things you need to do:
Get your tasks definitions "into" the docker container.
Configure the celery worker to load those task definitions.
For Item (1), the easiest way is probably to use a "Docker Volume" to mount a... |
Add column to dataframe with default value | I have an existing dataframe which I need to add an additional column to which will contain the same value for every row.
Existing df:
Date, Open, High, Low, Close
01-01-2015, 565, 600, 400, 450
New df:
Name, Date, Open, High, Low, Close
abc, 01-01-2015, 565, 600, 400, 450
I know how to append an existing series / da... | df['Name']='abc' will add the new column and set all rows to that value:
In [79]:
df
Out[79]:
Date, Open, High, Low, Close
0 01-01-2015, 565, 600, 400, 450
In [80]:
df['Name'] = 'abc'
df
Out[80]:
Date, Open, High, Low, Close Name
0 01-01-2015, 565, 600, 400, 450 abc
|
Produce a RA vs DEC equatorial coordinates plot with python | I'm trying to generate an equatorial coordinates plot that should look more or less like this one:
(The figure is taken from this article, and it shows the position of the Large and Small MCs in equatorial coordinates)
Important things to notice about this plot:
The theta axis (ie: the right ascension) is in h:m:s (h... | Chewing on the AxisArtist example is actually pretty promising (this combines two AxisArtist examples -- I wouldn't be surprised if AxisArtist was written with RA plots in mind):
Still to do:
Declination should run from -90 at the origin to 0
Be able to use
and add a colorbar
adjust limits if plotting outside them
... |
SQLAlchemy ORM conversion to pandas DataFrame | This topic hasn't been addressed in a while, here or elsewhere. Is there a solution converting a SQLAlchemy <Query object> to a pandas DataFrame?
Pandas has the capability to use pandas.read_sql but this requires use of raw SQL. I have two reasons for wanting to avoid it: 1) I already have everything using the ORM (a g... | Below should work in most cases:
df = pd.read_sql(query.statement, query.session.bind)
|
Python pandas: check if any value is NaN in DataFrame | In python pandas, what's the best way to check whether a DataFrame has one (or more) NaN values?
I know about the function pd.isnan, but this returns a DataFrame of booleans for each element. This post right here doesn't exactly answer my question either.
| jwilner's response is spot on. I was exploring to see if there's a faster option, since in my experience, summing flat arrays is (strangely) faster than counting. This code seems faster:
df.isnull().values.any()
For example:
In [2]: df = pd.DataFrame(np.random.randn(1000,1000))
In [3]: df[df > 0.9] = pd.np.nan
In [4... |
Whats the best way to present a flask interface to ongoing backround task? | I have a long running process that continuously reads from a telnet port and may occasionally write to it. Sometimes I want to send an HTTP request to it to fetch the info its read since the last time I asked. Sometimes I may send an HTTP request to write certain data to another telnet port.
Should I do this with 2 thr... | These kind of long polling jobs are best achieved using sockets, they don't really fit the Flask/WSGI model as this is not geared to asynchronous operations. You may want to look at twisted or tornado.
That said your back-end process that reads/writes to telnet could be running in a separate thread that may or may not ... |
Python 2 - How would you round up/down to the nearest 6 minutes? | There are numerous examples of people rounding to the nearest ten minutes but I can't figure out the logic behind rounding to the nearest six. I thought it would be a matter of switching a few numbers around but I can't get it to work.
The code I'm working with is located at my Github. The block I've got that isn't eve... | Here's a general function to round to nearest x:
def round_to_nearest(num, base):
n = num + (base//2)
return n - (n % base)
[round_to_nearest(i, 6) for i in range(20)]
# [0, 0, 0, 6, 6, 6, 6, 6, 6, 12, 12, 12, 12, 12, 12, 18, 18, 18, 18, 18]
Explanation:
n % base is the remainder left over when dividing n ... |
Algorithm to group sets of points together that follow a direction | Note: I am placing this question in both the MATLAB and Python tags as I am the most proficient in these languages. However, I welcome solutions in any language.
Question Preamble
I have taken an image with a fisheye lens. This image consists of a pattern with a bunch of square objects. What I want to do with this ... | Note 1: It has a number of settings -> which for other images may need to altered to get the result you want see % Settings - play around with these values
Note 2: It doesn't find all of the lines you want -> but its a starting point....
To call this function, invoke this in the command prompt:
>> [h, v] = testLines;
... |
Why is "if not (a and b)" faster than "if not a or not b"? | On a whim, I recently tested these two methods with timeit, to see which evaluation method was faster:
import timeit
"""Test method returns True if either argument is falsey, else False."""
def and_chk((a, b)):
if not (a and b):
return True
return False
def not_or_chk((a, b)):
if not a or not b:
... | TL;DR
The not_or_chk function requires two unary operations in addition to two jumps (in the worst case), while the and_chk function only has the two jumps (again, in the worst case).
Details
The dis module to the rescue! The dis module lets you take a look at the Python bytecode disassembly of your code. For example:
... |
Using Django's collectstatic with boto S3 throws "Error 32: Broken Pipe" after a while | I'm using boto with S3 to store my Django site's static files. When using the collectstatic command, it uploads a good chunk of the files perfectly before stopping at a file and throwing "Error 32: Broken Pipe." When I try to run the command again, it skips over the files it has already uploaded and starts at the file ... | The key seems to be to specify which AWS Endpoint your bucket is located in. I tried doing this a bunch of different ways, but the solution that finally worked for me was to create a config file for boto as specified in the documentation.
Here are the contents of the config file I created at ~/.boto:
[Credentials]
aws_... |
How to suppress the deprecation warnings in Django? | Every time I'm using the django-admin command â even on TABâcompletion â it throws a RemovedInDjango19Warning (and a lot more if I use the test command). How can I suppress those warnings?
I'm using Django 1.8 with Python 3.4 (in a virtual environment).
As far as I can tell, all those warnings come from libraries... | Adding a logging filter to settings.py can suppress these console warnings (at least for manage.py commands in Django 1.7, Python 3.4).
A filter can selectively suppress warnings. The following code creates a new "suppress_deprecated" filter for the console and appends it to the default logging filters. Add this block ... |
Why don't I get any syntax errors when I execute my Python script with Perl? | I just wrote some testing python code into test.py, and I'm launching it as follows:
perl test.py
After a while I realized my mistake. I say "after a while", because the
Python code gets actually correctly executed, as if in Python interpreter!
Why is my Perl interpreting my Python? test.py looks like this:
#!/usr/bin... | From perlrun,
If the #! line does not contain the word "perl" nor the word "indir" the program named after the #! is executed instead of the Perl interpreter. This is slightly bizarre, but it helps people on machines that don't do #! , because they can tell a program that their SHELL is /usr/bin/perl, and Perl will th... |
Using lxml to parse namepaced HTML? | This is driving me totally nuts, I've been struggling with it for many hours. Any help would be much appreciated.
I'm using PyQuery 1.2.9 (which is built on top of lxml) to scrape this URL. I just want to get a list of all the links in the .linkoutlist section.
This is my request in full:
response = requests.get('htt... | You need to handle namespaces, including an empty one.
Working solution:
from pyquery import PyQuery as pq
import requests
response = requests.get('http://www.ncbi.nlm.nih.gov/pubmed/?term=The%20cost-effectiveness%20of%20mirtazapine%20versus%20paroxetine%20in%20treating%20people%20with%20depression%20in%20primary%20c... |
Avoiding code repetition in default arguments in Python | Consider a typical function with default arguments:
def f(accuracy=1e-3, nstep=10):
...
This is compact and easy to understand. But what if we have another function g that will call f, and we want to pass on some arguments of g to f? A natural way of doing this is:
def g(accuracy=1e-3, nstep=10):
f(accuracy, n... | Define global constants:
ACCURACY = 1e-3
NSTEP = 10
def f(accuracy=ACCURACY, nstep=NSTEP):
...
def g(accuracy=ACCURACY, nstep=NSTEP):
f(accuracy, nstep)
If f and g are defined in different modules, then you could make a constants.py module too:
ACCURACY = 1e-3
NSTEP = 10
and then define f with:
from consta... |
Generators and for loops in Python | So I have a generator function, that looks like this.
def generator():
while True:
for x in range(3):
for j in range(5):
yield x
After I load up this function and call "next" a bunch of times, I'd expect it to yield values
0 0 0 0 0 1 1 1 1 1 2 2 2 2 2 0 0 0 0 0 ...
But instead ... | generator() initializes new generator object:
In [4]: generator() is generator() # Creating 2 separate objects
Out[4]: False
Then generator().next() gets the first value from the newly created generator object (0 in your case).
You should call generator once:
In [5]: gen = generator() # Storing new generator object, w... |
Shuffle DataFrame rows | I have the following DataFrame:
Col1 Col2 Col3 Type
0 1 2 3 1
1 4 5 6 1
...
20 7 8 9 2
21 10 11 12 2
...
45 13 14 15 3
46 16 17 18 3
...
The DataFrame is read from a csv file. All rows which have Type 1 are on top, followed... | The more idiomatic way to do this with pandas is to use the .sample method of your dataframe, i.e.
df.sample(frac=1)
The frac keyword argument specifies the fraction of rows to return in the random sample, so frac=1 means return all rows (in random order).
Note:
If you wish to shuffle your dataframe in-place and reset... |
Still can't install scipy due to missing fortran compiler after brew install gcc on Mac OC X | I have read and followed this answer to install scipy/numpy/theano. However, it still failed on the same error of missing Fortran compiler after brew install gcc. While HomeBrew installed the gcc-4.8, it didn't install any gfortran or g95 commands. I figure gfortran may be just a synonymy of gcc, then I create a symlin... | Fixed by upgrading pip, even though I just installed my pip/virtualenv the first time anew on the same day.
(mypy)MAC0227: $ pip install --upgrade pip
...
(mypy)MAC0227: $ pip install theano
/Users/me/.virtualenvs/mypy/lib/python2.7/site-packages/pip/_vendor/requests/packages/urllib3/util/ssl_.py:79: InsecurePlatformWa... |
Plot width settings in ipython notebook | I've got the following plots:
It would look nicer if they have the same width. Do you have any idea how to do it in ipython notebook when I am using %matplotlib inline?
UPDATE:
To generate both figures I am using the following functions:
import numpy as np
import matplotlib.pyplot as plt
def show_plots2d(title, plots... | If you use %pylab inline you can (on a new line) insert the following command:
%pylab inline
pylab.rcParams['figure.figsize'] = (10, 6)
This will set all figures in your document (unless otherwise specified) to be of the size (10, 6), where the first entry is the width and the second is the height.
See this SO post fo... |
Is there an idiomatic file extension for Jinja templates? | I need to programatically distinguish between Jinja template files, other template files (such as ERB), and template-less plain text files.
According to Jinja documentation:
A Jinja template doesnât need to have a specific extension: .html, .xml, or any other extension is just fine.
But what should I use when an ex... | Jinja Authors did not define a default extension. Most of Jinja template editors like Vim extension, TextMate extension, Emacs extension, and PyCharm mention no default extension to enforce Jinja highlighting.
Django had already a similar debate about setting a default extension, and ended as a wontfix issue. I quote f... |
How should I handle inclusive ranges in Python? | I am working in a domain in which ranges are conventionally described inclusively. I have human-readable descriptions such as from A to B , which represent ranges that include both end points - e.g. from 2 to 4 means 2, 3, 4.
What is the best way to work with these ranges in Python code? The following code works to gen... | Write an additional function for inclusive slice, and use that instead of slicing. While it would be possible to e.g. subclass list and implement a __getitem__ reacting to a slice object, I would advise against it, since your code will behave contrary to expectation for anyone but you â and probably to you, too, in a... |
import check_arrays from sklearn | I'm trying to use a svm function from the scikit learn package for python but I get the error message:
from sklearn.utils.validation import check_arrays
ImportError: cannot import name 'check_arrays'
I'm using python 3.4. Can anyone give me an advice? Thanks in advance.
| This method was removed in 0.16, replaced by a (very different) check_array function.
You are likely getting this error because you didn't upgrade from 0.15 to 0.16 properly. [Or because you relied on a not-really-public function in sklearn]. See http://scikit-learn.org/dev/install.html#canopy-and-anaconda-for-all-supp... |
How to uninstall mini conda? python | I've install the conda package as such:
$ wget http://bit.ly/miniconda
$ bash miniconda
$ conda install numpy pandas scipy matplotlib scikit-learn nltk ipython-notebook seaborn
I want to uninstall it because it's messing up my pips and environment.
How do I uninstall conda totally?
Will it uninstall also my pip manag... | In order to uninstall miniconda, simply remove the miniconda folder,
rm -r ~/miniconda/
this should not remove any of your pip installed packages (but you should check the contents of the ~/miniconda folder to confirm).
As to avoid conflicts between different python environements, you can use virtualenv. In particular... |
regex.sub() gives different results to re.sub() | I work with Czech accented text in Python 3.4.
Calling re.sub() to perform substitution by regex on an accented sentence works well, but using a regex compiled with re.compile() and then calling regex.sub() fails.
Here is the case, where I use the same arguments for re.sub() and regex.sub()
import re
pattern = r'(?<!\... | As Padraic Cunningham figured out, this is not actually a bug.
However, it is related to a bug which you didn't run into, and to you using a flag you probably shouldn't be using, so I'll leave my earlier answer below, even though his is the right answer to your problem.
There's a recent-ish change (somewhere between 3... |
python Spark avro | When attempting to write avro, I get the following error:
org.apache.spark.SparkException: Job aborted due to stage failure: Task 7 in stage 35.0 failed 1 times, most recent failure: Lost task 7.0 in stage 35.0 (TID 110, localhost): java.lang.ClassCastException: java.util.HashMap cannot be cast to org.apache.avro.mapre... | It looks like this isn't supported at the moment. You are now trying to use the java map as an Avro Record and covert it to a Java map again. That's why you get the error the error about the java hashmap.
There is a pull request from staslos to add the Avro output format, see link for the pull request and the example.... |
ANTLR4 grammar token recognition error after import | I am using a parser grammar and a lexer grammar for antlr4 from GitHub to parse PHP in Python3.
When I use these grammars directly my PoC code works:
antlr-test.py
from antlr4 import *
# from PHPParentLexer import PHPParentLexer
# from PHPParentParser import PHPParentParser
# from PHPParentParser import PHPParentListe... | Import is ANTLR4 is kind of messy.
First, tokenVocab can not generate the lexer you need. It just means that this grammar is using the tokens of PHPLexer. If you delete PHPLexer.tokens, it won't even compile!
Take a look at PHPParser.g4 where we also use options { tokenVocab=PHPLexer; }. Yet in the python script we st... |
Better approach to handling sqlalchemy disconnects | We've been experimenting with sqlalchemy's disconnect handling, and how it integrates with ORM. We've studied the docs, and the advice seems to be to catch the disconnect exception, issue a rollback() and retry the code.
eg:
import sqlalchemy as SA
retry = 2
while retry:
retry -= 1
try:
for name in ses... | The way I like to approach this is place all my database code in a lambda or closure, and pass that into a helper function that will handle catching the disconnect exception, and retrying.
So with your example:
import sqlalchemy as SA
def main():
def query():
for name in session.query(Names):
p... |
Django 1.9 deprecation warnings app_label | I've just updated to Django v1.8, and testing my local setup before updating my project and I've had a deprecation warning that I've never seen before, nor does it make any sense to me. I may be just overlooking something or misunderstanding the documentation.
/Users/neilhickman/Sites/guild/ankylosguild/apps/raiding/m... | Similar error. In my case the error was:
RemovedInDjango19Warning: Model class django.contrib.sites.models.Site doesn't declare an explicit app_label and either isn't in an application in INSTALLED_APPS or else was imported before its application was loaded. This will no longer be supported in Django 1.9.
class Site(mo... |
igraph Graph from numpy or pandas adjacency matrix | I have an adjacency matrix stored as a pandas.DataFrame:
node_names = ['A', 'B', 'C']
a = pd.DataFrame([[1,2,3],[3,1,1],[4,0,2]],
index=node_names, columns=node_names)
a_numpy = a.as_matrix()
I'd like to create an igraph.Graph from either the pandas or the numpy adjacency matrices. In an ideal world the nodes woul... | In igraph you can use igraph.Graph.Adjacency to create a graph from an adjacency matrix without having to use zip. There are some things to be aware of when a weighted adjacency matrix is used and stored in a np.array or pd.DataFrame.
igraph.Graph.Adjacency can't take an np.array as argument, but that is easily solved... |
Normalize numpy array columns in python | I have a numpy array where each cell of a specific row represents a value for a feature. I store all of them in an 100*4 matrix.
A B C
1000 10 0.5
765 5 0.35
800 7 0.09
Any idea how I can normalize rows of this numpy.array where each value is between 0 and 1?
My desired output is:
A B C
1 ... | If I understand correctly, what you want to do is divide by the maximum value in each column. You can do this easily using broadcasting.
Starting with your example array:
import numpy as np
x = np.array([[1000, 10, 0.5],
[ 765, 5, 0.35],
[ 800, 7, 0.09]])
x_normed = x / x.max(axis... |
Strange if statement | I found this strange if-statement in somebody elseâs code:
if variable & 1 == 0:
I don't understand it. It should have two ==, right?
Can somebody explain this?
| The conditional is a bitwise operator comparison:
>>> 1 & 1
1
>>> 0 & 1
0
>>> a = 1
>>> a & 1 == 0
False
>>> b = 0
>>> b & 1 == 0
True
As many of the comments say, for integers this conditional is True for evens and False for odds. The prevalent way to write this is if variable % 2 == 0: or if not variable % 2:
Usin... |
Python app does not print anything when running detached in docker | I have a Python (2.7) app which is started in my dockerfile:
CMD ["python","main.py"]
main.py prints some strings when it is started and goes into a loop afterwards:
print "App started"
while True:
time.sleep(1)
As long as I start the container with the -it flag, everything works as expected:
$ docker run --name=... | Finally I found a solution to see Python output when running daemonized in Docker, thanks to @ahmetalpbalkan over at GitHub. Answering it here myself for further reference :
Using unbuffered output with
CMD ["python","-u","main.py"]
instead of
CMD ["python","main.py"]
solves the problem; you can see the output (both... |
What should I use instead of syncdb in Django 1.9? | Take a look at this:
$ pypy ./manage.py syncdb
/usr/lib64/pypy-2.4.0/site-packages/django/core/management/commands/syncdb.py:24: RemovedInDjango19Warning: The syncdb command will be removed in Django 1.9
warnings.warn("The syncdb command will be removed in Django 1.9", RemovedInDjango19Warning)
(cut)
I ran a quick ... | syncdb is deprecated because of the migration system1.
Now you can track your changes using makemigrations. This transforms your model changes into python code to make them deployable to another databases.
After you created the migrations you have to apply them: migrate.
So instead of using syncdb you should use makemi... |
Gettext message catalogues from virtual dir within PYZ for GtkBuilder widgets | Is there an established approach to embed gettext locale/xy/LC_MESSAGES/* in a PYZ bundle? Specifically to have Gtks automatic widget translation pick them up from within the ZIP archive.
For other embedded resources pkgutil.get_deta or inspect/get_source work well enough. But system and Python gettext APIs depend on b... | This my example Glade/GtkBuilder/Gtk application. I've defined a function xml_gettext which transparently translates glade xml files and passes to gtk.Builder instance as a string.
import mygettext as gettext
import os
import sys
import gtk
from gtk import glade
glade_xml = '''<?xml version="1.0" encoding="UTF-8"?>... |
Creating classes with a lot of imported functions here and there | Let's say i have a lot of functions in alotoffunc.py that is used by more than 1 type of object.
Let's say ObjectI and ObjectII and ObjectXI all uses some functions in alotoffunc.py. And each of the Object were using different set of functions but all the objects have the variable object.table.
alotoffunc.py:
def abc(... | (1) You can have a base class that implements all the methods then override the unnecessary ones to raise a NotImplementedError in the subclasses.
(2) You can have mixins to reduce repetition:
import alotoffunc
class MixinAbc:
def abc(self, x):
return alotoffunc.abc(self, x)
class MixinEfg:
def efg(se... |
mean, nanmean and warning: Mean of empty slice | Say I construct two numpy arrays:
a = np.array([np.NaN, np.NaN])
b = np.array([np.NaN, np.NaN, 3])
Now I find that np.mean returns nan for both a and b:
>>> np.mean(a)
nan
>>> np.mean(b)
nan
Since numpy 1.8, we've been blessed with nanmean, which ignores nan values:
>>> np.nanmean(b)
3.0
However, when the array has ... | I really can't see any good reason not to just suppress the warning.
The safest way would be to use the warnings.catch_warnings context manager to suppress the warning only where you anticipate it occurring - that way you won't miss any additional RuntimeWarnings that might be unexpectedly raised in some other part of ... |
auth_user error with Django 1.8 and syncdb / migrate | When upgrading to Django 1.8 (with zc.buildout) and running syncdb or migrate, I get this message:
django.db.utils.ProgrammingError: relation "auth_user" does not exist
One of my models contains django.contrib.auth.models.User:
user = models.ForeignKey(
User, related_name='%(app_label)s_%(class)s_user',
blank=T... | I fix this by running auth first, then the rest of my migrations:
python manage.py migrate auth
python manage.py migrate
|
Django-cms installs, but pull-downs and other JS doesn't work - ideas for fixing? | I've installed Django-CMS onto an existing site and while it isn't throwing errors, it isn't working. In particular, the header on a given page appears when I use "/?edit" but none of the pull down menus work, and very little (possibly none) of the JavaScript works.
Other facets:
I've done this on a local install of... | After staring at this for about 1.5 weeks, I think I found the answer.
The eventual process to the solution was to get the tutorial up and running in the same environment and start slavishly comparing settings and templates. With a working tutorial, I could see what was there and slavishly imitate it.
The settings.py ... |
Making an object x such that "x in [x]" returns False | If we make a pathological potato like this:
>>> class Potato:
... def __eq__(self, other):
... return False
... def __hash__(self):
... return random.randint(1, 10000)
...
>>> p = Potato()
>>> p == p
False
We can break sets and dicts this way (note: it's the same even if __eq__ returns True, i... | list, tuple, etc., does indeed do an identity check before an equality check, and this behavior is motivated by these invariants:
assert a in [a]
assert a in (a,)
assert [a].count(a) == 1
for a in container:
assert a in container # this should ALWAYS be true
Unfortunately, dicts, sets, and friends operate by ha... |
My answer is changing with the same code | I am a complete python beginner and I am trying to solve this problem :
A number is called triangular if it is the sum of the first n positive
integers for some n For example, 10 is triangular because 10 = 1+2+3+4
and 21 is triangular because 21 = 1+2+3+4+5+6. Write a Python program
to find the smallest 6-digit ... | Short Answer
In Python 3, division is always floating point division. So on the first pass you get something like str(trinum) == '0.5'. Which isn't what you want.
You're looking for integer division. The operator for that is //.
Long Answer
The division operator changed in Python 2.x to 3.x. Previously, the type of th... |
Finding highest product of three numbers | Given an array of ints, arrayofints, find the highest product, Highestproduct, you can get from three of the integers. The input array of ints will always have at least three integers.
So I've popped three numbers from arrayofints and stuck them in highestproduct:
Highestproduct = arrayofints[:2]
for item in arrayofint... | Keep track of the two minimal elements and three maximal elements, the answer should be min1 * min2 * max1 or max1 * max2 * max3.
To get the maximum product of 3 ints we have to choose 3 maximum elements. However there is a catch that we can substitute 2 of the smallest of 3 max elements with the 2 min ints. If both sm... |
PySpark groupByKey returning pyspark.resultiterable.ResultIterable | I am trying to figure out why my groupByKey is returning the following:
[(0, <pyspark.resultiterable.ResultIterable object at 0x7fc659e0a210>), (1, <pyspark.resultiterable.ResultIterable object at 0x7fc659e0a4d0>), (2, <pyspark.resultiterable.ResultIterable object at 0x7fc659e0a390>), (3, <pyspark.resultiterable.Result... | What you're getting back is an object which allows you to iterate over the results. You can turn the results of groupByKey into a list by calling list() on the values, e.g.
example = sc.parallelize([(0, u'D'), (0, u'D'), (1, u'E'), (2, u'F')])
example.groupByKey().collect()
# Gives [(0, <pyspark.resultiterable.ResultI... |
Python fails to open 11gb csv in r+ mode but opens in r mode | I'm having problems with some code that loops through a bunch of .csvs and deletes the final line if there's nothing in it (i.e. files that end with the \n newline character)
My code works successfully on all files except one, which is the largest file in the directory at 11gb. The second largest file is 4.5gb.
The li... | The default I/O stack in Python 2 is layered over CRT FILE streams. On Windows these are built on top of a POSIX emulation API that uses file descriptors (which in turn is layered over the user-mode Windows API, which is layered over the kernel-mode I/O system, which itself is a deeply layered system based on I/O reque... |
How can i get all models in django 1.8 | I am using this code in my admin.py
from django.db.models import get_models, get_app
for model in get_models(get_app('myapp')):
admin.site.register(model)
But i get warning that get_models is deprecated
How can i do that in django 1.8
| This should work,
from django.apps import apps
apps.get_models()
The get_models method returns a list of all installed models. You can also pass three keyword arguments include_auto_created, include_deferred and include_swapped.
If you want to get the models for a specific app, you can do something like this.
from dja... |
Error packaging Kivy with numpy library for Android using buildozer | I am trying to create an Android package of my Kivy application using buildozer but I am getting this error when I try to include the numpy:
resume of the error:
compile options: '-DNO_ATLAS_INFO=1 -Inumpy/core/include -Ibuild/src.linux-x86_64-2.7/numpy/core/include/numpy -Inumpy/core/src/private -Inumpy/core/src -Inum... | Try sudo apt-get install libatlas-base-dev it looks like you're missing some libraries
|
Append to a list defined in a tuple - is it a bug? | So I have this code:
tup = ([1,2,3],[7,8,9])
tup[0] += (4,5,6)
which generates this error:
TypeError: 'tuple' object does not support item assignment
While this code:
tup = ([1,2,3],[7,8,9])
try:
tup[0] += (4,5,6)
except TypeError:
print tup
prints this:
([1, 2, 3, 4, 5, 6], [7, 8, 9])
Is this behavior expe... | Yes it's expected.
A tuple cannot be changed. A tuple, like a list, is a structure that points to other objects. It doesn't care about what those objects are. They could be strings, numbers, tuples, lists, or other objects.
So doing anything to one of the objects contained in the tuple, including appending to that obj... |
How to find a Python package's dependencies | How can you programmatically get a Python package's list of dependencies?
The standard setup.py has these documented, but I can't find an easy way to access it from either Python or the command line.
Ideally, I'm looking for something like:
$ pip install somepackage --only-list-deps
kombu>=3.0.8
billiard>=3.3.0.13
boto... | Try to use show command in pip, for example:
$ pip show tornado
---
Name: tornado
Version: 4.1
Location: *****
Requires: certifi, backports.ssl-match-hostname
Update (retrieve deps with specified version):
from pip._vendor import pkg_resources
_package_name = 'somepackage'
_package = pkg_resources.working_set.by_key... |
Scope of variables in python decorator | I'm having a very weird problem in a Python 3 decorator.
If I do this:
def rounds(nr_of_rounds):
def wrapper(func):
@wraps(func)
def inner(*args, **kwargs):
return nr_of_rounds
return inner
return wrapper
it works just fine. However, if I do this:
def rounds(nr_of_rounds):
... | Since nr_of_rounds is picked up by the closure, you can think of it as a "read-only" variable. If you want to write to it (e.g. to decrement it), you need to tell python explicitly -- In this case, the python3.x nonlocal keyword would work.
As a brief explanation, what Cpython does when it encounters a function defini... |
How can I resolve 'django_content_type already exists'? | After upgrading to django 1.8 I'm recieving the error during migration:
ProgrammingError: relation "django_content_type" already exists
I'd be interested in the background behind this error, but more importantly,
How can I resolve it?
| Initial migrations on a project can sometimes be troubleshot using --fake-initial
python manage.py migrate --fake-initial
It's new in 1.8. In 1.7, --fake-initial was an implicit default, but explicit in 1.8.
From the Docs:
The --fake-initial option can be used to allow Django to skip an appâs initial migration if a... |
Joining elements in a list without the join command | I need to join the elements in a list without using the join command, so if for example I have the list:
[12,4,15,11]
The output should be:
1241511
Here is my code so far:
def lists(list1):
answer = 0
h = len(list1)
while list1 != []:
answer = answer + list1[0] * 10 ** h
h = h - 1
... | If you just want to print the number rather than return an actual int:
>>> a = [12,4,15,11]
>>> print(*a, sep='')
1241511
|
How / why does Python type hinting syntax work? | I have just seen the following example in PEP 484:
def greeting(name: str) -> str:
return 'Hello ' + name
print(greeting('Martin'))
print(greeting(1))
As expected, this does not work in Python 2:
File "test.py", line 1
def greeting(name: str) -> str:
^
SyntaxError: invalid syntax
Howev... | There is no type hinting going on here. All you did was provide annotations; these were introduced with PEP 3107 (only in Python 3, there is no support for this in Python 2); they let you annotate arguments and return values with arbitrary information for later inspection:
>>> greeting.__annotations__
{'name': <class '... |
Make ipython notebook print in real time | Ipython Notebook doesn't seem to print results in real time, but seems to buffer in a certain way and then bulk output the prints. How can I make ipython print my results as soon as the print command is processed?
Example code:
import time
def printer():
for i in range(100):
time.sleep(5)
print i
... | This is merely one of the answers to the question suggested by Carsten incorporating the __getattr__ delegation suggested by diedthreetimes in a comment:
import sys
oldsysstdout = sys.stdout
class flushfile():
def __init__(self, f):
self.f = f
def __getattr__(self,name):
return object.__getattr... |
Run specific Django tests (with django-nose?) | I am having a very complicated tests.py file.
Actually the tests classes and methods are generated at run time w/ type (to account for data listed in auxiliary files). I am doing things in the following fashion (see below for more code):
klass = type(name, (TestCase,), attrs)
setattr(current_module, name, klass)
FYI, ... | The problem you ran into is that Nose determines whether or not to include a method into the set of tests to run by looking at the name recorded on the function itself, rather than the attribute that gives access to the function. If I rename your passer and failer to test_pass and test_fail then Nose is able to find th... |
Given 2 int values, return True if one is negative and other is positive | def logical_xor(a, b): # for example, -1 and 1
print (a < 0) # evaluates to True
print (b < 0) # evaluates to False
print (a < 0 != b < 0) # EVALUATES TO FALSE! why??? it's True != False
return (a < 0 != b < 0) # returns False when it should return True
print ( logical_xor(-1, 1) ) # returns FALSE!
# ... | All comparison operators in Python have the same precedence. In addition, Python does chained comparisons. Thus,
(a < 0 != b < 0)
breaks down as:
(a < 0) and (0 != b) and (b < 0)
If any one of these is false, the total result of the expression will be False.
What you want to do is evaluate each condition separately... |
Delaunay Triangulation of points from 2D surface in 3D with python? | I have a collection of 3D points. These points are sampled at constant levels (z=0,1,...,7). An image should make it clear:
These points are in a numpy ndarray of shape (N, 3) called X. The above plot is created using:
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
X = load('points.npy')
fig ... | I realise that you mentioned in your question that you didn't want to use the convex hull because you might lose some shape information. I have a simple solution that works pretty well for your 'jittered spherical' example data, although it does use scipy.spatial.ConvexHull. I thought I would share it here anyway, just... |
Python multiprocessing doesn't seem to use more than one core | I want to use Python multiprocessing to run grid search for a predictive model.
When I look at core usage, it always seem to be using only one core. Any idea what I'm doing wrong?
import multiprocessing
from sklearn import svm
import itertools
#first read some data
#X will be my feature Numpy 2D array
#y will be my 1D... | Your problem is that you join each job immediately after you started it:
for g in grid:
p = multiprocessing.Process(target=worker, args=(g,GRID_hx))
jobs.append(p)
p.start()
p.join()
join blocks until the respective process has finished working. This means that your code starts only one process at once... |
Why use re.match(), when re.search() can do the same thing? | From the documentation, it's very clear that:
match() -> apply pattern match at the beginning of the string
search() -> search through the string and return first match
And search with '^' and without re.M flag would work the same as match.
Then why does python have match()? Isn't it redundant?
Are there any performa... | The pos argument behaves differently in important ways:
>>> s = "a ab abc abcd"
>>> re.compile('a').match(s, pos=2)
<_sre.SRE_Match object; span=(2, 3), match='a'>
>>> re.compile('^a').search(s, pos=2)
None
match makes it possible to write a tokenizer, and ensure that characters are never skipped. search has no way of... |
Different ways of deleting lists | I want to understand why:
a = [];
del a; and
del a[:];
behave so differently.
I ran a test for each to illustrate the differences I witnessed:
>>> # Test 1: Reset with a = []
...
>>> a = [1,2,3]
>>> b = a
>>> a = []
>>> a
[]
>>> b
[1, 2, 3]
>>>
>>> # Test 2: Reset with del a
...
>>> a = [1,2,3]
>>> b = a
>>> del a... | Test 1
>>> a = [1,2,3] # set a to point to a list [1, 2, 3]
>>> b = a # set b to what a is currently pointing at
>>> a = [] # now you set a to point to an empty list
# Step 1: A --> [1 2 3]
# Step 2: A --> [1 2 3] <-- B
# Step 3: A --> [ ] [1 2 3] <-- B
# at this point a points to a new empty list
# whereas b p... |
finding needle in haystack, what is a better solution? | so given "needle" and "there is a needle in this but not thisneedle haystack"
I wrote
def find_needle(n,h):
count = 0
words = h.split(" ")
for word in words:
if word == n:
count += 1
return count
This is O(n) but wondering if there is a better approach? maybe not by using split at a... | I don't think it's possible to get bellow O(n) with this (because you need to iterate trough the string at least once). You can do some optimizations.
I assume you want to match "whole words", for example looking up foo should match like this:
foo and foo, or foobar and not foo.
^^^ ^^^ ^^^
So s... |
How to add a title to Seaborn Facet Plot | How do I add a title to this Seaborne plot? Let's give it a title 'I AM A TITLE'.
tips = sns.load_dataset("tips")
g = sns.FacetGrid(tips, col="sex", row="smoker", margin_titles=True)
g.map(sns.plt.scatter, "total_bill", "tip")
| After those lines:
plt.subplots_adjust(top=0.9)
g.fig.suptitle('THIS IS A TITLE, YOU BET') # can also get the figure from plt.gcf()
If you add a suptitle without adjusting the axis, the seaborn facet titles overlap it.
(With different data):
|
Pandas DataFrame to List of Dictionaries (Dics) | I have the following DataFrame:
customer item1 item2 item3
1 apple milk tomato
2 water orange potato
3 juice mango chips
which I want to translate it to list of dictionaries per row
rows = [{'customer': 1, 'item1': 'apple', 'item2': 'milk', 'item3': 'to... | Use df.to_dict('records') -- gives the output without having to transpose externally.
In [2]: df.to_dict('records')
Out[2]:
[{'customer': 1L, 'item1': 'apple', 'item2': 'milk', 'item3': 'tomato'},
{'customer': 2L, 'item1': 'water', 'item2': 'orange', 'item3': 'potato'},
{'customer': 3L, 'item1': 'juice', 'item2': 'ma... |
django.db.utils.ProgrammingError: relation already exists | I'm trying to set up the tables for a new django project (that is, the tables do NOT already exist in the database); the django version is 1.7 and the db back end is PostgreSQL. The name of the project is crud. Results of migration attempt follow:
python manage.py makemigrations crud
Migrations for 'crud':
0001_init... | This works pretty fine
./manage.py migrate --fake default
Source: -https://github.com/nijel/weblate/issues/587
|
Numpy 1-hot array | Let's say I have a 1d numpy array
a=[1,0,3]
I would like to encode this as a 2d 1-hot array
b=[[0,1,0,0], [1,0,0,0], [0,0,0,1]]
Is there a quick way to do this? Quicker than just looping over a to set elements of b, that is.
| Your array a defines the columns, you just need to define the rows and then use fancy indexing:
>>> a = np.array([1, 0, 3])
>>> b = np.zeros((3, 4))
>>> b[np.arange(3), a] = 1
>>> b
array([[ 0., 1., 0., 0.],
[ 1., 0., 0., 0.],
[ 0., 0., 0., 1.]])
>>>
This is just for illustration. You may want t... |
Optimize the performance of dictionary membership for a list of Keys | I am trying to write a code which should return true if any element of list is present in a dictionary. Performance of this piece is really important. I know I can just loop over list and break if I find the first search hit. Is there any faster or more Pythonic way for this than given below?
for x in someList:
if... | Use of builtin any can have some performance edge over two loops
any(x in someDict for x in someList)
but you might need to measure your mileage. If your list and dict remains pretty static and you have to perform the comparison multiple times, you may consider using set
someSet = set(someList)
someDict.viewkeys() & ... |
How to write a function which takes a slice? | I would like to write a function in Python which takes a slice as a parameter. Ideally a user would be to be able to call the function as follows:
foo(a:b:c)
Unfortunately, this syntax is not permitted by Python - the use of a:b:c is only allowed within [], not ().
I therefore see three possibilities for my function:
... | Don't surprise your users.
If you use the slicing syntax consistently with what a developer expects from a slicing syntax, that same developer will expect square brackets operation, i.e. a __getitem__() method.
If instead the returned object is not somehow a slice of the original object, people will be confused if you ... |
Python - multiprocessing for matplotlib griddata | Following my former question [1], I would like to apply multiprocessing to matplotlib's griddata function. Is it possible to split the griddata into, say 4 parts, one for each of my 4 cores? I need this to improve performance.
For example, try the code below, experimenting with different values for size:
import numpy a... | I ran the example code below in Python 3.4.2, with numpy version 1.9.1 and matplotlib version 1.4.2, on a Macbook Pro with 4 physical CPUs (i.e., as opposed to "virtual" CPUs, which the Mac hardware architecture also makes available for some use cases):
import numpy as np
import matplotlib.mlab as mlab
import time
impo... |
Why is it valid to assign to an empty list but not to an empty tuple? | This came up in a recent PyCon talk.
The statement
[] = []
does nothing meaningful, but it does not throw an exception either. I have the feeling this must be due to unpacking rules. You can do tuple unpacking with lists too, e.g.,
[a, b] = [1, 2]
does what you would expect. As logical consequence, this also should w... | The comment by @user2357112 that this seems to be coincidence appears to be correct. The relevant part of the Python source code is in Python/ast.c:
switch (e->kind) {
# several cases snipped
case List_kind:
e->v.List.ctx = ctx;
s = e->v.List.elts;
break;
case Tuple_kind:
if ... |
How to mock asyncio coroutines? | The following code fails with TypeError: 'Mock' object is not iterable in ImBeingTested.i_call_other_coroutines because I've replaced ImGoingToBeMocked by a Mock object.
How can I mock coroutines?
class ImGoingToBeMocked:
@asyncio.coroutine
def yeah_im_not_going_to_run(self):
yield from asyncio.sleep(... | Since mock library doesn't support coroutines I create mocked coroutines manually and assign those to mock object. A bit more verbose but it works.
Your example may look like this:
import asyncio
import unittest
from unittest.mock import Mock
class ImGoingToBeMocked:
@asyncio.coroutine
def yeah_im_not_going_t... |
Operate on a list in a pythonic way when output depends on other elements | I have a task requiring an operation on every element of a list, with the outcome of the operation depending on other elements in the list.
For example, I might like to concatenate a list of strings conditional on them starting with a particular character:
This code solves the problem:
x = ['*a', 'b', 'c', '*d', 'e', '... | A few relevant excerpts from import this (the arbiter of what is Pythonic):
Simple is better than complex
Readability counts
Explicit is better than implicit.
I would just use code like this, and not worry about replacing the for loop with something "flatter".
x = ['*a', 'b', 'c', '*d', 'e', '*f', '*g']
partials = []... |
Microsoft Visual C++ Compiler for Python 3.4 | I know that there is a "Microsoft Visual C++ Compiler for Python 2.7" but is there, currently or planned, a Microsoft Visual C++ Compiler for Python 3.4 or eve Microsoft Visual C++ Compiler for Python 3.x for that matter? It would be supremely beneficial if I didn't have to install a different version of visual studio... | Unfortunately to be able to use the extension modules provided by others you'll be forced to use the official compiler to compile Python. These are:
Visual Studio 2008 for Python 2.7.
See: https://docs.python.org/2.7/using/windows.html#compiling-python-on-windows
Visual Studio 2010 for Python 3.4.
See: https://docs.p... |
Upgrading from Django 1.6 (with south) to 1.8 doesn't modify 'last_login' on the user table | I have upgraded from Django 1.6.5 (with south migrations) to Django 1.8. I have followed the instructions here:
https://docs.djangoproject.com/en/1.8/topics/migrations/#upgrading-from-south
So, I remove South, delete my previous migrations and run python manage.py makemigrations which makes a new migration file. Then I... | As noted in the 1.8 release notes:
If you are using a custom user model that inherits from AbstractUser, youâll need to run makemigrations and generate a migration for your app that contains that model.
|
Change user agent for selenium driver | I have the following code in Python:
from selenium.webdriver import Firefox
from contextlib import closing
with closing(Firefox()) as browser:
browser.get(url)
I would like to print the user-agent HTTP header and
possibly change it. Is it possible?
| There is no way in Selenium to read the request or response headers. You could do it by instructing your browser to connect through a proxy that records this kind of information.
Setting the User Agent in Firefox
The usual way to change the user agent for Firefox is to set the variable "general.useragent.override" in y... |
Find the column name which has maximum value for each row [pandas] | I have a dataframe like this one:
In [7]:
frame.head()
Out[7]:
Communications and Search Business General Lifestyle
0 0.745763 0.050847 0.118644 0.084746
0 0.333333 0.000000 0.583333 0.083333
0 0.617021 0.042553 0.297872 0.042553
0 0.435897 0.000000 0.410256 0.153846
0 ... | You can use idxmax() to find the column with the greatest value on each row:
>>> df.idxmax(axis=1)
0 Communications
1 Business
2 Communications
3 Communications
4 Business
dtype: object
To create the new column use df['Max'] = df.idxmax(axis=1).
|
Function decorated using functools.wraps raises TypeError with the name of the wrapper. Why? How to avoid? | def decorated(f):
@functools.wraps(f)
def wrapper():
return f()
return wrapper
@decorated
def g():
pass
functools.wraps does its job at preserving the name of g:
>>> g.__name__
'g'
But if I pass an argument to g, I get a TypeError containing the name of the wrapper:
>>> g(1)
Traceback (most r... | The name comes from the code object; both the function and the code object (containing the bytecode to be executed, among others) contain that name:
>>> g.__name__
'g'
>>> g.__code__.co_name
'wrapper'
The attribute on the code object is read-only:
>>> g.__code__.co_name = 'g'
Traceback (most recent call last):
File ... |
Extract cow number from image | every now and then my mom has to shift through these type of photos to extract the number from the image and rename it to the number.
I'm trying to use OpenCV, Python, Tesseract to get the process done. I'm really lost trying to extract the portion of the image with the numbers. How could I do this? Any suggestions ... | I have been having another look at this, and had a couple of inspirations along the way....
Tesseract can accept custom dictionaries, and if you dig a little more, it appears that from v3.0, it accepts the command-line parameter digits to make it recognise digits only - seems a useful idea for your needs.
It may not b... |
Why variable = object doesn't work like variable = number | These variable assignments work as I expect:
>>> a = 3
>>> b = a
>>> print(a, b)
(3, 3)
>>> b=4
>>> print(a, b)
(3, 4)
However, these assignments behave differently:
>>> class number():
... def __init__(self, name, number):
... self.name = name
... self.number = number
...
>>> c = number("one", 1)... | These lines:
c = number("one", 1)
d = c
...are effectively:
Create a new instance of number and assign it to c
Assign the existing reference called c to a new variable d
You haven't changed or modified anything about c; d is another name that points to the same instance.
Without cloning the instance or creating a ne... |
Calculating the averages for each KEY in a Pairwise (K,V) RDD in Spark with Python | I want to share this particular Apache Spark with Python solution because documentation for it is quite poor.
I wanted to calculate the average value of K/V pairs (stored in a Pairwise RDD), by KEY. Here is what the sample data looks like:
>>> rdd1.take(10) # Show a small sample.
[(u'2013-10-09', 7.60117302052786),
(u'... | Now a much better way to do this is to use the rdd.aggregateByKey() method. Because that method is so poorly documented in the Apache Spark with Python documentation (which is why I'm writing this), until recently I had been using the above code sequence. But again, it's less efficient, so don't do it that way unless y... |
Why is `if` so much faster when checked before a statement than after a statement? | Here's an example of what I mean:
s = """
if x > 10:
x -= 10
else:
x = 0
"""
import timeit
print(timeit.timeit(s, setup="x=5", number=99999999))
Outputs approximately 3 seconds on my computer, regardless of the setup (x=5 vs x=15, no difference)
If I were to use much shorter code, one that first decreases x -... | Your premise is wrong. setup only gets run once for the entire timeit. If you make sure that x stays above 10 then the symptoms disappear:
>>> s1 = """
... if x > 10:
... x -= 10
... else:
... x = 0
... """
>>> s2 = """
... x -= 10
... if x < 0:
... x = 0
... """
>>> import timeit
>>> print(timeit.timeit(s1... |
Multikey Multivalue Non Deterministic python dictionary | There is already a multi key dict in python and also a multivalued dict. I needed a python dictionary which is both:
example:
# probabilistically fetch any one of baloon, toy or car
d['red','blue','green']== "baloon" or "car" or "toy"
Probability of d['red']==d['green'] is high and Probability of d['red']!=d['red']... |
the single output value should be probabilistically determined (fuzzy) based on a rule from keys eg:in above case rule could be if keys have both "red" and "blue" then return "baloon" 80% of time if only blue then return "toy" 15% of time else "car" 5% of time.
Bare in mind your case analysis is not complete, and it'... |
Set debugger breakpoint at end of a function without return | I am debugging method f() that has no return in it.
class A(object):
def __init__(self):
self.X = []
def f(self):
for i in range(10):
self.X.append(i)
I need to see how this method modifies variable X right after it is called. To do that, I insert a return at the end ... | You can add a conditional breakpoint on the last line and set the condition to be something that occurs only in the last iteration.
In this instance the condition is very easy since it's just i == 9, but it may be a lot more complex depending on your loop condition so sometimes adding a statement at the end will be the... |
Renaming downloaded images in Scrapy 0.24 with content from an item field while avoiding filename conflicts? | I'm attempting to rename the images that are downloaded by my Scrapy 0.24 spider. Right now the downloaded images are stored with a SHA1 hash of their URLs as the file names. I'd like to instead name them the value I extract with item['model']. This question from 2011 outlines what I want, but the answers are for previ... | The pipelines.py:
from scrapy.contrib.pipeline.images import ImagesPipeline
from scrapy.http import Request
from scrapy.exceptions import DropItem
from scrapy import log
class MyImagesPipeline(ImagesPipeline):
#Name download version
def file_path(self, request, response=None, info=None):
image_guid = ... |
What is the relationship between virtualenv and pyenv? | I recently learned how to use virtualenv and virtualenvwrapper in my workflow but I've seen pyenv mentioned in a few guides but I can't seem to get an understanding of what pyenv is and how it is different/similar to virtualenv. Is pyenv a better/newer replacement for virtualenv or a complimentary tool? If the latter w... | Pyenv and virtualenv are very different tools that work in different ways to do different things:
Pyenv is a bash extension - will not work on Windows - that intercepts your calls to python, pip, etc., to direct them to one of several of the system python tool-chains. So you always have all the libraries that you hav... |
DRF: Simple foreign key assignment with nested serializers? | With Django REST Framework, a standard ModelSerializer will allow ForeignKey model relationships to be assigned or changed by POSTing an ID as an Integer.
What's the simplest way to get this behavior out of a nested serializer?
Note, I am only talking about assigning existing database objects, not nested creation.
I ha... | The best solution here is to use two different fields: one for reading and the other for writing. Without doing some heavy lifting, it is difficult to get what you are looking for in a single field.
The read-only field would be your nested serializer (ChildSerializer in this case) and it will allow you to get the same ... |
Finding substring (nonconsecutive) | In Python if I have string needle and I want to see if it exists (contiguously) as a substring in haystack, I only need to check if needle in haystack.
What happens in the case of a subsequence?
Example:
haystack = "qabcdzzzefgyyyh"
needle = "acgh"
"acgh" is a subsequence of qabcdzzzefgyyyh -- does not exist contiguou... | I don't know if there's builtin function, but it is rather simple to do manually
def exists(a, b):
"""checks if b exists in a as a subsequence"""
pos = 0
for ch in a:
if pos < len(b) and ch == b[pos]:
pos += 1
return pos == len(b)
>>> exists("moo", "mo")
True
>>> exists("moo", "oo")... |
What does this notation do for lists in Python: "someList[:]"? | I sometimes get across this way of printing or returning a list - someList[:].
I don't see why people use it, as it returns the full list.
Why not simply write someList, whithout the [:] part?
| [:] creates a slice, usually used to get just a part of a list. Without any minimum/maximum index given, it creates a copy of the entire list. Here's a Python session demonstrating it:
>>> a = [1,2,3]
>>> b1 = a
>>> b2 = a[:]
>>> b1.append(50)
>>> b2.append(51)
>>> a
[1, 2, 3, 50]
>>> b1
[1, 2, 3, 50]
>>> b2
[1, 2, 3, ... |
Finding all keys in a dictionary from a given list QUICKLY | I have a (potentially quite big) dictionary and a list of 'possible' keys. I want to quickly find which of the keys have matching values in the dictionary. I've found lots of discussion of single dictionary values here and here, but no discussion of speed or multiple entries.
I've come up with four ways, and for the th... | Of a couple of additional methods I've tried, the fastest was a simple list comprehension:
def way6(theList, theDict):
return [item for item in theList if item in theDict]
This runs the same process as your fastest approach, way1, but more quickly. For comparison, the quickest set-based way was
def way5(theList, ... |
Count number of non-NaN entries in every column of Dataframe | I have a really big DataFrame and I was wondering if there was short (one or two liner) way to get the a count of non-NaN entries in a DataFrame. I don't want to do this one column at a time as I have close to 1000 columns.
df1 = pd.DataFrame([(1,2,None),(None,4,None),(5,None,7),(5,None,None)],
co... | The count() method returns the number of non-NaN values in each column:
>>> df1.count()
a 3
b 2
d 1
dtype: int64
Similarly, count(axis=1) returns the number of non-NaN values in each row.
|
Python theano with index computed inside the loop | I have installed the Theano library for increasing the speed of a computation, so that I can use the power of a GPU.
However, inside the inner loop of the computation a new index is calculated, based on the loop index and corresponding values of a couple of arrays.
That calculated index is then used to access an elemen... | No, I see nothing which cannot be done using Tensors instead of a for-loop. This should mean that you might see an increase in speed, but this will really depend on the application. You have an overhead of python+theano as well, especially coming from c-like code.
So, instead of
for (m = 0; m < M; ++m)
{
unsigned i... |
Why might Python's `from` form of an import statement bind a module name? | I have a Python project with the following structure:
testapp/
âââ __init__.py
âââ api
â  âââ __init__.py
â  âââ utils.py
âââ utils.py
All of the modules are empty except testapp/api/__init__.py which has the following code:
from testapp import utils
print "a", utils
from test... | From the import system documentation:
When a submodule is loaded using any mechanism (e.g. importlib APIs,
the import or import-from statements, or built-in __import__())
a binding is placed in the parent moduleâs namespace to the submodule
object. For example, if package spam has a submodule foo, after
impo... |
How to execute Python code from within Visual Studio Code | Visual Studio Code was recently released and I liked the look of it and the features it offered, so I figured I would give it a go.
I downloaded the application from the downloads page
fired it up, messed around a bit with some of the features ... and then realized I had no idea how to actually execute any of my Pyth... | Here is how to Configure Task Runner in Visual Studio Code to run a py file.
In your console press Ctrl+Shift+P (Windows) or Cmd+Shift+P (Apple) and this brings up a search box where you search for "Configure Task Runner"
EDIT: If this is the first time you open the "Task: Configure Task Runner", you need to select "o... |
Problems obtaining most informative features with scikit learn? | Im triying to obtain the most informative features from a textual corpus. From this well answered question I know that this task could be done as follows:
def most_informative_feature_for_class(vectorizer, classifier, classlabel, n=10):
labelid = list(classifier.classes_).index(classlabel)
feature_names = vecto... | To solve this specifically for linear SVM, we first have to understand the formulation of the SVM in sklearn and the differences that it has to MultinomialNB.
The reason why the most_informative_feature_for_class works for MultinomialNB is because the output of the coef_ is essentially the log probability of features g... |
How to find the first index of any of a set of characters in a string | I'd like to find the index of the first occurrence of any âspecialâ character in a string, like so:
>>> "Hello world!".index([' ', '!'])
5
â¦except that's not valid Python syntax. Of course, I can write a function that emulates this behavior:
def first_index(s, characters):
i = []
for c in characters:
... | You can use enumerate and next with a generator expression, getting the first match or returning None if no character appears in s:
s = "Hello world!"
st = {"!"," "}
ind = next((i for i, ch in enumerate(s) if ch in st),None)
print(ind)
You can pass any value you want to next as a default return value if there is no... |
Interleave list with fixed element | I know that I can interleave two python lists with:
[elem for pair in zip(*lists) for elem in pair]
Now I need to interleave a list with a fixed element like:
list = [1, 2, 3, 4]
# í ½í° python magic í ½í°
output = [1, 0, 2, 0, 3, 0, 4]
| You can try the following itertools magic:
>>> from itertools import repeat, chain, izip
>>> l = [1, 2, 3, 4]
>>> list(chain.from_iterable(izip(l[:-1], repeat(0)))) + l[-1:]
[1, 0, 2, 0, 3, 0, 4]
|
What are the differences between Conda and Anaconda | I first installed Anaconda on my ubuntu at ~/anaconda, when I was trying to update my anaconda, according to the documentation from Continuum Analytics, I should use the following commands:
conda update conda
conda update anaconda
Then I realized that I did not have conda installed, so I installed it using the documen... | conda is the package manager. Anaconda is a set of about a hundred packages including conda, numpy, scipy, ipython notebook, and so on.
You installed Miniconda, which is a smaller alternative to Anaconda that is just conda and its dependencies (as opposed to Anaconda, which is conda and a bunch of other packages like ... |
Python self and super in multiple inheritance | In Raymond Hettinger's talk "Super considered super speak" at PyCon 2015 he explains the advantages of using super in Python in multiple inheritance context. This is one of the examples that Raymond used during his talk:
class DoughFactory(object):
def get_dough(self):
return 'insecticide treated wheat doug... | Just to clarify, there are four cases, based on changing the second line in Pizza.order_pizza and the definition of OrganicPizza:
super(), (Pizza, OrganicDoughFactory) (original): 'Making pie with pure untreated wheat dough'
self, (Pizza, OrganicDoughFactory): 'Making pie with pure untreated wheat dough'
super(), (Org... |
Is there a way to compare Arabic characters without regard to their initial/medial/final form? | In Latin script, letters have an upper case and a lower case form. In Python, if you want to compare two strings without regard to their case, you can convert them to the same case using 'string'.upper() or 'string'.lower()
In Arabic script, letters can have an initial, medial, or final form. Is there a similar way to ... | There are two parts to this, which should work for all languages:*
Your strings must be into NFKD normalization to guarantee that two equal strings have equal code units.
To ignore case in comparing two NFKD strings, use the Unicode case-folding algorithm.
Between the two, this handles English upper and lower case, A... |
Truth value of numpy array with one falsey element seems to depend on dtype | import numpy as np
a = np.array([0])
b = np.array([None])
c = np.array([''])
d = np.array([' '])
Why should we have this inconsistency:
>>> bool(a)
False
>>> bool(b)
False
>>> bool(c)
True
>>> bool(d)
False
| I'm pretty sure the answer is, as explained in Scalars, that:
Array scalars have the same attributes and methods as ndarrays. [1] This allows one to treat items of an array partly on the same footing as arrays, smoothing out rough edges that result when mixing scalar and array operations.
So, if it's acceptable to ca... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.