instruction stringlengths 12 148 | input stringlengths 16 30.2k | output stringlengths 11 27.3k |
|---|---|---|
Boto3, python and how to handle errors | I just picked up python as my go-to scripting language and I am trying to figure how to do proper error handling with boto3.
I am trying to create an IAM user:
def create_user(username, iam_conn):
try:
user = iam_conn.create_user(UserName=username)
return user
except Exception as e:
retu... | Use the response contained within the exception. Here is an example:
import boto3
import botocore
try:
iam = boto3.client('iam')
user = iam.create_user(UserName='fred')
print "Created user: %s" % user
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'EntityAlreadyExists':
... |
Fast linear interpolation in Numpy / Scipy "along a path" | Let's say that I have data from weather stations at 3 (known) altitudes on a mountain. Specifically, each station records a temperature measurement at its location every minute. I have two kinds of interpolation I'd like to perform. And I'd like to be able to perform each quickly.
So let's set up some data:
import n... | A linear interpolation between two values y1, y2 at locations x1 and x2, with respect to point xi is simply:
yi = y1 + (y2-y1) * (xi-x1) / (x2-x1)
With some vectorized Numpy expressions we can select the relevant points from the dataset and apply the above function:
I = np.searchsorted(altitudes, location)
x1 = altit... |
How does this Python 3 quine work? | Found this example of quine:
s='s=%r;print(s%%s)';print(s%s)
I get that %s and %r do the str and repr functions, as pointed here, but what exactly means the s%s part and how the quine works?
| s is set to:
's=%r;print(s%%s)'
so the %r gets replaced by exactly that (keeping the single quotes) in s%s and the final %% with a single %, giving:
s='s=%r;print(s%%s)';print(s%s)
and hence the quine.
|
Losslessly compressing images on django | I'm doing optimization and Google recommends Lossless compression to images, looking for a way to implement this in Django.
Here's the images they specified, I think for it to be done effectively it needs to implemented systemwide possibly using a middleware class wondering if anyone has done this before. Here's the li... |
Losslessly compressing http://www.kenyabuzz.com/media/uploads/clients/kenya_buzz_2.jpg could save 594.3KiB (92% reduction).
First of all, the information in the logs is rather misleading because it is impossible to compress images by 92% using a lossless format (except for some cases like single-colour images, basic ... |
Mapping dictionary value to list | Given the following dictionary:
dct = {'a':3, 'b':3,'c':5,'d':3}
How can I apply these values to a list such as:
lst = ['c', 'd', 'a', 'b', 'd']
in order to get something like:
lstval = [5, 3, 3, 3, 3]
| Using map:
>>> map(dct.get, lst)
[5, 3, 3, 3, 3]
Using a list comprehension:
>>> [dct[k] for k in lst]
[5, 3, 3, 3, 3]
|
HTTPError: HTTP Error 503: Service Unavailable goslate language detection request : Python | I have just started using the goslate library in python to detect the language of the words in a text but after testing it for 7-8 inputs, I gave the input which had the words written in two languages arabic and english. After which, it started giving me the error.
Traceback (most recent call last):
File "<pyshell#0... | maybe looking for this: https://pypi.python.org/pypi/textblob it is better than goslate,
since textblob is blocked as of now, maybe py-translate could do the trick,
https://pypi.python.org/pypi/py-translate/#downloads
http://pythonhosted.org/py-translate/devs/api.html
from translate import translator
translator('en', '... |
How to set class attribute with await in __init__ | How can I define a class with await in the constructor or class body?
For example what I want:
import asyncio
# some code
class Foo(object):
async def __init__(self, settings):
self.settings = settings
self.pool = await create_pool(dsn)
foo = Foo(settings)
# it raises:
# TypeError: __init__() s... | Most magic methods aren't designed to work with async def/await - in general, you should only be using await inside the dedicated asynchronous magic methods - __aiter__, __anext__, __aenter__, and __aexit__. Using it inside other magic methods either won't work at all (as is the case with __init__), or will force you t... |
Addition of list and NumPy number | If you add an integer to a list, you get an error raised by the __add__ function of the list (I suppose):
>>> [1,2,3] + 3
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only concatenate list (not "int") to list
If you add a list to a NumPy array, I assume that the __add__ funct... | list does not know how to handle addition with NumPy arrays. Even in [1,2,3] + np.array([3]), it's NumPy arrays that handle the addition.
As documented in the data model:
For objects x and y, first x.__op__(y) is tried. If this is not implemented or returns NotImplemented, y.__rop__(x) is tried. If
this is also not... |
Getting only element from a single-element list in Python? | When a Python list is known to always contain a single item, is there way to access it other than:
mylist[0]
You may ask, 'Why would you want to?'. Curiosity alone. There seems to be an alternative way to do everything in Python.
| Sequence unpacking:
singleitem, = mylist
# Identical in behavior (byte code produced is the same),
# but arguably more readable since a lone trailing comma could be missed:
[singleitem] = mylist
Explicit use of iterator protocol:
singleitem = next(iter(mylist))
Destructive pop:
singleitem = mylist.pop()
Negative ind... |
Assigning to vs. from a slice | When reading profile.py of python standard library I came across the assignment statement sys.argv[:] = args, which is used to modify sys.argv to make the program being profiled see the correct command line arguments. I understand that this is different from sys.argv = args[:] in the actual operations, but in effect t... | The difference is, when you use a[:] = b it means you will override whatever is already on a. If you have something else with a reference to a it will change as well, as it keeps referencing the same location.
In the other hand, a = b[:] creates a new reference and copy all the values from b to this new reference. So e... |
On OS X El Capitan I can not upgrade a python package dependent on the six compatibility utilities NOR can I remove six | I am trying to use scrape, but I have a problem.
from six.moves import xmlrpc_client as xmlrpclib
ImportError: cannot import name xmlrpc_client
Then, I tried pip install --upgrade six scrape, but:
Found existing installation: six 1.4.1
DEPRECATION: Uninstalling a distutils installed project (six) has been depre... | I just got around what I think was the same problem. You might consider trying this (sudo, if necessary):
pip install scrape --upgrade --ignore-installed six
Github is ultimately where I got this answer (and there are a few more suggestions you may consider if this one doesn't solve your problem). It also seems as thou... |
Can a website detect when you are using selenium with chromedriver? | I've been testing out Selenium with Chromedriver and I noticed that some pages can detect that you're using Selenium even though there's no automation at all. Even when I'm just browsing manually just using chrome through Selenium and Xephyr I often get a page saying that suspicious activity was detected. I've checked ... | As we've already figured out in the question and the posted answers, there is an anti Web-scraping and a Bot detection service called "Distil Networks" in play here. And, according to the company CEO's interview:
Even though they can create new bots, we figured out a way to identify
Selenium the a tool theyâre usi... |
Getting signals working on PulseAudio's DBus interface? | I'm trying to get a D-Bus signal handler to be called whenever the state of a sink changes in PulseAudio (e.g. becomes inactive). Unfortunately, it isn't being called and I frankly am not sure why.
import dbus
import dbus.mainloop.glib
from gi.repository import GObject
dbus.mainloop.glib.DBusGMainLoop(set_as_default=... | Try this, works for me.
import dbus
import os
from dbus.mainloop.glib import DBusGMainLoop
import gobject
def pulse_bus_address():
if 'PULSE_DBUS_SERVER' in os.environ:
address = os.environ['PULSE_DBUS_SERVER']
else:
bus = dbus.SessionBus()
server_lookup = bus.get_object("org.PulseAudio1... |
max([x for x in something]) vs max(x for x in something): why is there a difference and what is it? | I was working on a project for class where my code wasn't producing the same results as the reference code.
I compared my code with the reference code line by line, they appeared almost exactly the same. Everything seemed to be logically equivalent. Eventually I began replacing lines and testing until I found the lin... | Are you leaking a local variable which is affecting later code?
# works
action = 'something important'
max_q = max(self.getQValue(nextState, action) for action in legal_actions)
assert action == 'something important'
# doesn't work (i.e., provides different results)
max_q = max([self.getQValue(nextState, action) for a... |
Trie tree match performance in word search | I have debugging a few similar solutions, but wondering if we could improve Trie Tree to partial match prefix (in search method of class Trie, current search method only check if a full word is matched or not) to even improve performance, which could return from a wrong path earlier? I am not very confident for the ide... | I don't see anything wrong from the Trie part in your code.
But I think the trie's original design already has early returning when detecting any mismatch.
Actually, I usually only use regular dict as a trie instead of defaultDict + TrieNode to avoid making the problem over-complicated. You just need to set a "#" key ... |
Force compiler when running python setup.py install | Is there a way to explicitly force the compiler for building Cython extensions when running python setup.py install? Where setup.py is of the form:
import os.path
import numpy as np
from setuptools import setup, find_packages, Extension
from Cython.Distutils import build_ext
setup(name='test',
packages=find_packages... | You can provide (default) command line arguments for distutils in a separate file called setup.cfg (placed parallel to your setup.py). See the docs for more information. To set the compiler use something like:
[build]
compiler=msvc
Now calling python setup.py build is equivalent to calling python setup.py build --com... |
SyntaxError with passing **kwargs and trailing comma | I wonder why this is a SyntaxError in Python 3.4:
some_function(
filename = "foobar.c",
**kwargs,
)
It works when removing the trailing comma after **kwargs.
| As pointed out by vaultah (who for some reason didnât bother to post an answer), this was reported on the issue tracker and has been changed since. The syntax will work fine starting with Python 3.6.
To be explicit, yes, I want to allow trailing comma even after *args or **kwds. And that's what the patch does. âGu... |
Mysterious interaction between Python's slice bounds and "stride" | I understand that given an iterable such as
>>> it = [1, 2, 3, 4, 5, 6, 7, 8, 9]
I can turn it into a list and slice off the ends at arbitrary points with, for example
>>> it[1:-2]
[2, 3, 4, 5, 6, 7]
or reverse it with
>>> it[::-1]
[9, 8, 7, 6, 5, 4, 3, 2, 1]
or combine the two with
>>> it[1:-2][::-1]
[7, 6, 5, 4, 3... | This is because in a slice like -
list[start:stop:step]
start is inclusive, resultant list starts at index start.
stop is exclusive, that is the resultant list only contains elements till stop - 1 (and not the element at stop).
So for your caseit[1:-2] - the 1 is inclusive , that means the slice result starts at inde... |
String character identity paradox | I'm completely stuck with this
>>> s = chr(8263)
>>> x = s[0]
>>> x is s[0]
False
How is this possible? Does this mean that accessing a string character by indexing create a new instance of the same character? Let's experiment:
>>> L = [s[0] for _ in range(1000)]
>>> len(set(L))
1
>>> ids = map(id, L)
>>> len(set(ids)... | There are two point to make here.
First, Python does indeed create a new character with the __getitem__ call, but only if that character has ordinal value greater than 256.
Observe:
>>> s = chr(256)
>>> s[0] is s
True
>>> t = chr(257)
>>> t[0] is t
False
This is because internally, the compiled getitem function check... |
Getting Spark, Python, and MongoDB to work together | I'm having difficulty getting these components to knit together properly. I have Spark installed and working succesfully, I can run jobs locally, standalone, and also via YARN. I have followed the steps advised (to the best of my knowledge) here and here
I'm working on Ubuntu and the various component versions I have a... | Updates:
2016-07-04
Since the last update MongoDB Spark Connector matured quite a lot. It provides up-to-date binaries and data source based API but it is using SparkConf configuration so it is subjectively less flexible than the Stratio/Spark-MongoDB.
2016-03-30
Since the original answer I found two different ways to ... |
python Ubuntu error install Pillow 3.0.0 | I recently failed trying to install Pillow 3.0.0 on my Ubuntu 14.04.
No matter what I do (download and try to "sudo python setup.py install" or "sudo -H pip install Pillow==3.0.0 --no-cache-dir") everytime I get error:
copying PIL/TiffImagePlugin.py -> build/lib.linux-x86_64-2.7/PIL
running egg_info
writing P... | Did you install the dependencies for pillow ? You can install them by
$ sudo apt-get build-dep python-imaging
$ sudo apt-get install libjpeg8 libjpeg62-dev libfreetype6 libfreetype6-dev
|
Django ignores router when running tests? | I have a django application that uses 2 database connections:
To connect to the actual data the app is to produce
To a reference master data system, that is maintained completely outside my control
The issue that I'm having, is that my webapp can absolutely NOT touch the data in the 2nd database. I solved most of th... | I solved this by changing the DATABASES.TEST definition. I added the TEST['MIRROR'] = 'default' to the mdm_db database entry.
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.oracle',
'NAME': '(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=%s)(PORT=1521)))(CONNECT_DATA=(SID=%s)))'
... |
How to check if Celery/Supervisor is running using Python | How to write a script in Python that outputs if celery is running on a machine (Ubuntu)?
My use-case. I have a simple python file with some tasks. I'm not using Django or Flask. I use supervisor to run the task queue. For example,
tasks.py
from celery import Celery, task
app = Celery('tasks')
@app.task()
def add_togeth... | You can run the celery status command via code by importing the celery.bin.celery package:
import celery
import celery.bin.base
import celery.bin.celery
import celery.platforms
app = celery.Celery('tasks', broker='redis://')
status = celery.bin.celery.CeleryCommand.commands['status']()
status.app = status.get_app()
... |
Create and import helper functions in tests without creating packages in test directory using py.test | Question
How can I import helper functions in test files without creating packages in the test directory?
Context
I'd like to create a test helper function that I can import in several tests. Say, something like this:
# In common_file.py
def assert_a_general_property_between(x, y):
# test a specific relationship... | my option is to create an extra dir in tests dir and add it to pythonpath in the conftest so.
tests/
helpers/
utils.py
...
conftest.py
setup.cfg
in the conftest.py
import sys
import os
sys.path.append(os.path.join(os.path.dirname(__file__), 'helpers')
in setup.cfg
[pytest]
norecursedirs=tests/help... |
Read cell content in an ipython notebook | I have an ipython notebook with mixed markdown and python cells.
And I'd like some of my python cells to read the adjacent markdown cells and process them as input.
An example of the desired situation:
CELL 1 (markdown): SQL Code to execute
CELL 2 (markdown): select * from tbl where x=1
CELL 3 (python) : mysql.query(... | I think you are trying to attack the problem the wrong way.
First yes, it is possible to get the adjacent markdown cell in really hackish way that would not work in headless notebook execution.
What you want to do is use IPython cell magics, that allow arbitrary syntax as long as the cell starts with 2 percent signs f... |
What does the built-in function sum do with sum(list, [])? | When I want to unfold a list, I found a way like below:
>>> a = [[1, 2], [3, 4], [5, 6]]
>>> a
[[1, 2], [3, 4], [5, 6]]
>>> sum(a, [])
[1, 2, 3, 4, 5, 6]
I don't know what happened in these lines, and the documentation states:
sum(iterable[, start])
Sums start and the items of an iterable from left to right and
ret... |
Don't you think that start should be a number?
start is a number, by default; 0, per the documentation you've quoted. Hence when you do e.g.:
sum((1, 2))
it is evaluated as 0 + 1 + 2 and it equals 3 and everyone's happy. If you want to start from a different number, you can supply that instead:
>>> sum((1, 2), 3)
6
... |
The similar method from the nltk module produces different results on different machines. Why? | I have taught a few introductory classes to text mining with Python, and the class tried the similar method with the provided practice texts. Some students got different results for text1.similar() than others.
All versions and etc. were the same.
Does anyone know why these differences would occur? Thanks.
Code use... | In your example there are 40 other words which have exactly one context in common with the word 'monstrous'.
In the similar function a Counter object is used to count the words with similar contexts and then the most common ones (default 20) are printed. Since all 40 have the same frequency the order can differ.
From t... |
Distribution of Number of Digits of Random Numbers | I encounter this curious phenomenon trying to implement a UUID generator in JavaScript.
Basically, in JavaScript, if I generate a large list of random numbers with the built-in Math.random() on Node 4.2.2:
var records = {};
var l;
for (var i=0; i < 1e6; i += 1) {
l = String(Math.random()).length;
if (records[l]) {
... | The reason is indeed related to floating point representation. A floating point number representation has a maximum number of (binary) digits it can represent, and a limited exponent value range. Now when you print this out without using scientific notation, you might in some cases need to have some zeroes after the de... |
Random number in the range 1 to sys.maxsize is always 1 mod 2^10 | I am trying to find the statistical properties of the PRNGs available in Python (2.7.10) by using the frequency test, runs test and the chi squared test.
For carrying out the frequency test, I need to convert the generated random number to its binary representation and then count the distribution of 1's and 0's. I was ... | @roeland hinted at the cause: in Python 2, sample() uses int(random.random() * n) repeatedly. Look at the source code (in your Python's Lib/random.py) for full details. In short, random.random() returns no more than 53 significant (non-zero) leading bits; then int() fills the rest of the low-order bits with zeroes (... |
In TensorFlow, what is the difference between Session.run() and Tensor.eval()? | TensorFlow has two ways to evaluate part of graph: Session.run on a list of variables and Tensor.eval. Is there a difference between these two?
| If you have a Tensor t, calling t.eval() is equivalent to calling tf.get_default_session().run(t).
You can make a session the default as follows:
t = tf.constant(42.0)
sess = tf.Session()
with sess.as_default(): # or `with sess:` to close on exit
assert sess is tf.get_default_session()
assert t.eval() == sess... |
Speeding-up "for-loop" in image analysis when iterations are up to 40,000 | The details of the prerequisites of this code are quite long so I'll try my best to summarize. WB/RG/BYColor is the base image, FIDO is an overlay of this base image which is applied to it. S_wb/rg/by are the final output images. WB/RG/BYColor are the same size as FIDO.
For each unique element in FIDO, we want to calcu... | By my timing, this is about 10 times faster than your original method. I tested with these arrays:
import numpy as np
sX=200
sY=200
FIDO = np.random.randint(0, sX*sY, (sX, sY))
WBColor = np.random.randint(0, sX*sY, (sX, sY))
RGColor = np.random.randint(0, sX*sY, (sX, sY))
BYColor = np.random.randint(0, sX*sY, (sX, sY... |
tensorflow -- is it or will it (sometime soon) be compatible with a windows workflow? | I haven't seen anything about Windows compatibility--is this on the way or currently available somwhere if I put forth some effort? (I have a mac and an ubuntu box but the windows machine is the one with the discrete graphics card that I currently use with theano)
| We haven't tried to build TensorFlow on Windows so far: the only supported platforms are Linux (Ubuntu) and Mac OS X, and we've only built binaries for those platforms.
For now, on Windows, the easiest way to get started with TensorFlow would be to use Docker: http://tensorflow.org/get_started/os_setup.md#docker-based_... |
How do I use distributed DNN training in TensorFlow? | Google released TensorFlow today.
I have been poking around in the code, and I don't see anything in the code or API about training across a cluster of GPU servers.
Does it have distributed training functionality yet?
| Updated: The initial release of Distributed TensorFlow occurred on 2/26/2016. The release was announced by coauthor Derek Murray in the original issue here and uses gRPC for inter-process communication.
Previous: A distributed implementation of TensorFlow has not been released yet. Support for a distributed implementat... |
Where is the folder for Installing tensorflow with pip, Mac OSX? | just installed tensorflow using pip with the command:
$ pip install tensorflow
On the "Getting Started" for Tensorflow they have an example for convolutional neural networks
$ python tensorflow/models/image/mnist/convolutional.py
Where is that directory located when installing with pip?
| Installing with pip, installs the packages to the directory "site-packages".
The following code shows the location of tensorflow as well as where pip installs the packages:
$ pip show tensorflow
Which return:
Metadata-Version: 2.0
Name: tensorflow
Version: 0.5.0
Summary: TensorFlow helps the tensors flow
Home-page: ht... |
Fail to run word embedding example in tensorflow tutorial with GPUs | I am trying to run the word embedding example code at https://github.com/tensorflow/tensorflow/tree/master/tensorflow/g3doc/tutorials/word2vec (installed with GPU version of tensorflow under Ubuntu 14.04), but it returns the following error message:
Found and verified text8.zip
Data size 17005207
Most common words (+UN... | It seems a whole bunch of operations used in this example aren't supported on a GPU. A quick workaround is to restrict operations such that only matrix muls are ran on the GPU.
There's an example in the docs: http://tensorflow.org/api_docs/python/framework.md
See the section on tf.Graph.device(device_name_or_function)
... |
Anaconda3 2.4 with python 3.5 installation error (procedure entry not found; Windows 10) | I have just made up my mind to change from python 2.7 to python 3.5 and therefore tried to reinstall Anaconda (64 bit) with the 3.5 environment. When I try to install the package I get several errors in the form of (translation from German, so maybe not exact):
The procedure entry "__telemetry_main_return_trigger" cou... | Finally I have found the reason. So, if anybody else has this problem:
Here the entry points are an issue as well and Michael Sarahan gives the solution. Install the Visual C++ Redistributable for Visual Studio 2015, which is used by the new version of python, first. After that install the Anaconda-package and it shoul... |
How to print the value of a Tensor object in TensorFlow? | I have been using the introductory example of matrix multiplication in TensorFlow.
matrix1 = tf.constant([[3., 3.]])
matrix2 = tf.constant([[2.],[2.]])
product = tf.matmul(matrix1, matrix2)
And when I print the product, it is displaying it as a TensorObject(obviously).
product
<tensorflow.python.framework.ops.Tensor o... | The easiest* way to evaluate the actual value of a Tensor object is to pass it to the Session.run() method, or call Tensor.eval() when you have a default session (i.e. in a with tf.Session(): block, or see below). In general,** you cannot print the value of a tensor without running some code in a session.
If you are ex... |
why is "any()" running slower than using loops? | I've been working in a project that manage big lists and pass the lists trough a lot of tests in order to validate or not each word of the list. The funny thing is that each time that I've used the "faster" tools or generators (like the itertools module) and I make some tests, they seem to be slower.
Finally I decided ... | Actually the any() function is equal to following function :
def any(iterable):
for element in iterable:
if element:
return True
return False
which is like your second function, but since the any() returns a boolean value by itself, you don't need to check for the result and then return a n... |
How to do Xavier initialization on TensorFlow | I'm porting my Caffe network over to TensorFlow but it doesn't seem to have xavier initialization. I'm using truncated_normal but this seems to be making it a lot harder to train.
| Now TensorFlow 0.8 has the xavier initializer implementation.
https://www.tensorflow.org/versions/r0.8/api_docs/python/contrib.layers.html#xavier_initializer
You can use something like this:
W = tf.get_variable("W", shape=[784, 256],
initializer=tf.contrib.layers.xavier_initializer())
|
Why does TensorFlow example fail when increasing batch size? | I was looking at the Tensorflow MNIST example for beginners and found that in this part:
for i in range(1000):
batch_xs, batch_ys = mnist.train.next_batch(100)
sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})
changing the batch size from 100 to be above 204 causes the model to fail to converge. It works... | You're using the very basic linear model in the beginners example?
Here's a trick to debug it - watch the cross-entropy as you increase the batch size (the first line is from the example, the second I just added):
cross_entropy = -tf.reduce_sum(y_*tf.log(y))
cross_entropy = tf.Print(cross_entropy, [cross_entropy], "Cro... |
Tensorflow image reading & display | I've got a bunch of images in a format similar to Cifar10 (binary file, size = 96*96*3 bytes per image), one image after another (STL-10 dataset). The file I'm opening has 138MB.
I tried to read & check the contents of the Tensors containing the images to be sure that the reading is done right, however I have two quest... | Just to give a complete answer:
filename_queue = tf.train.string_input_producer(['/Users/HANEL/Desktop/tf.png']) # list of files to read
reader = tf.WholeFileReader()
key, value = reader.read(filename_queue)
my_img = tf.image.decode_png(value) # use png or jpg decoder based on your files.
init_op = tf.initialize_al... |
Error while importing Tensorflow in python2.7 in Ubuntu 12.04. 'GLIBC_2.17 not found' | I have installed the Tensorflow bindings with python successfully. But when I try to import Tensorflow, I get the follwoing error.
ImportError: /lib/x86_64-linux-gnu/libc.so.6: version `GLIBC_2.17' not
found (required by
/usr/local/lib/python2.7/dist-packages/tensorflow/python/_pywrap_tensorflow.so)
I have tried ... | Okay so here is the other solution I mentionned in my previous answer, it's more tricky, but should always work on systems with GLIBC>=2.12 and GLIBCXX>=3.4.13.
In my case it was on a CentOS 6.7, but it's also fine for Ubuntu 12.04.
We're going to need a version of gcc that supports c++11, either on another machine or ... |
Randomly change the prompt in the Python interpreter | It's kind of boring to always see the >>> prompt in Python. What would be the best way to go about randomly changing the prompt prefix?
I imagine an interaction like:
This is a tobbaconist!>> import sys
Sorry?>> import math
Sorry?>> print sys.ps1
Sorry?
What?>>
| According to the docs, if you assign a non-string object to sys.ps1 then it will evaluate the str function of it each time:
If a non-string object is assigned to either variable, its str() is
re-evaluated each time the interpreter prepares to read a new
interactive command; this can be used to implement a dynamic ... |
Use attribute and target matrices for TensorFlow Linear Regression Python | I'm trying to follow this tutorial.
TensorFlow just came out and I'm really trying to understand it. I'm familiar with penalized linear regression like Lasso, Ridge, and ElasticNet and its usage in scikit-learn.
For scikit-learn Lasso regression, all I need to input into the regression algorithm is DF_X [an M x N di... | Softmax is an only addition function (in logistic regression for example), it is not a model like
model = LassoCV()
model.fit(DF_X,SR_y)
Therefore you can't simply give it data with fit method. However, you can simply create your model with the help of TensorFlow functions.
First of all, you have to create a computat... |
Converting large XML file to relational database | I'm trying to figure out the best way to accomplish the following:
Download a large XML (1GB) file on daily basis from a third-party website
Convert that XML file to relational database on my server
Add functionality to search the database
For the first part, is this something that would need to be done manually, or ... | All steps could certainly be accomplished using node.js. There are modules available that will help you with each of these tasks:
node-cron: lets you easily set up cron tasks in your node program. Another option would be to set up a cron task on your operating system (lots of resources available for your favourite OS... |
Why is this TensorFlow implementation vastly less successful than Matlab's NN? | As a toy example I'm trying to fit a function f(x) = 1/x from 100 no-noise data points. The matlab default implementation is phenomenally successful with mean square difference ~10^-10, and interpolates perfectly.
I implement a neural network with one hidden layer of 10 sigmoid neurons. I'm a beginner at neural network... | I tried training for 50000 iterations it got to 0.00012 error. It takes about 180 seconds on Tesla K40.
It seems that for this kind of problem, first order gradient descent is not a good fit (pun intended), and you need LevenbergâMarquardt or l-BFGS. I don't think anyone implemented them in TensorFlow yet.
Edit
Use ... |
How can numpy be so much faster than my Fortran routine? | I get a 512^3 array representing a Temperature distribution from a simulation (written in Fortran). The array is stored in a binary file that's about 1/2G in size. I need to know the minimum, maximum and mean of this array and as I will soon need to understand Fortran code anyway, I decided to give it a go and came up ... | Your Fortran implementation suffers two major shortcomings:
You mix IO and computations (and read from the file entry by entry).
You don't use vector/matrix operations.
This implementation does perform the same operation as yours and is faster by a factor of 20 on my machine:
program test
integer gridsize,unit
... |
sampling multinomial from small log probability vectors in numpy/scipy | Is there a function in numpy/scipy that lets you sample multinomial from a vector of small log probabilities, without losing precision? example:
# sample element randomly from these log probabilities
l = [-900, -1680]
the naive method fails because of underflow:
import scipy
import numpy as np
# this makes a all zeroe... | First of all, I believe the problem you're encountering is because you're normalizing your probabilities incorrectly. This line is incorrect:
a = np.exp(l) / scipy.misc.logsumexp(l)
You're dividing a probability by a log probability, which makes no sense. Instead you probably want
a = np.exp(l - scipy.misc.logsumexp(... |
How do I know if I can disable SQLALCHEMY_TRACK_MODIFICATIONS? | Every time I run my app that uses Flask-SQLAlchemy I get the following warning that the SQLALCHEMY_TRACK_MODIFICATIONS option will be disabled.
/home/david/.virtualenvs/flask-sqlalchemy/lib/python3.5/site-packages/flask_sqlalchemy/__init__.py:800: UserWarning: SQLALCHEMY_TRACK_MODIFICATIONS adds significant overhead an... | Most likely your application doesn't use the Flask-SQLAlchemy event system, so you're probably safe to turn off. You'll need to audit the code to verify--you're looking for anything that hooks into models_committed or before_models_committed. If you do find that you're using the Flask-SQLAlchemy event system, you proba... |
What does from __future__ import absolute_import actually do? | I have answered a question regarding absolute imports in Python, which I thought I understood based on reading the Python 2.5 changelog and accompanying PEP. However, upon installing Python 2.5 and attempting to craft an example of properly using from __future__ import absolute_import, I realize things are not so clear... | The changelog is sloppily worded. from __future__ import absolute_import does not care about whether something is part of the standard library, and import string will not always give you the standard-library module with absolute imports on.
from __future__ import absolute_import means that if you import string, Python ... |
How to install xgboost package in python (windows platform)? | http://xgboost.readthedocs.org/en/latest/python/python_intro.html
On the homepage of xgboost(above link), it says:
To install XGBoost, do the following steps:
You need to run make in the root directory of the project
In the python-package directory run
python setup.py install
However, when I did it, for step 1 the fo... | Note that as of the most recent release the Microsoft Visual Studio instructions no longer seem to apply as this link returns a 404 error:
https://github.com/dmlc/xgboost/tree/master/windows
You can read more about the removal of the MSVC build from Tianqi Chen's comment here.
So here's what I did to finish a 64-bit bu... |
Tensorflow: How to restore a previously saved model (python) | I want to make a prediction with a model already saved by tensorflow, so I need to restore the model first.
The code I have fails because I can't call Saver() without the variables of the model, but that is exactly what I want to load! Do I need to create a dummy model with the same variables first and then restore my ... | The checkpoints that are saved contain values for the Variables in your model, not the model/graph itself, which means that the graph should be the same when you restore the checkpoint.
Here's an example for a linear regression where there's a training loop that saves variable checkpoints and an evaluation section that... |
How can I visualize the weights(variables) in cnn in Tensorflow? | After training the cnn model, I want to visualize the weight or print out the weights, what can I do?
I cannot even print out the variables after training.
Thank you!
| To visualize the weights, you can use a tf.image_summary() op to transform a convolutional filter (or a slice of a filter) into a summary proto, write them to a log using a tf.train.SummaryWriter, and visualize the log using TensorBoard.
Let's say you have the following (simplified) program:
filter = tf.Variable(tf.tru... |
How is `min` of two integers just as fast as 'bit hacking'? | I was watching a lecture series on 'Bit Hacking' and came across the following optimization for finding the minimum of two integers:
return x ^ ((y ^ x) & -(x > y))
Which said to be faster than:
if x < y:
return x
else:
return y
Since the min function can handle more than just two integers (floats, strings, l... | This is likely due to how the min function is implemented in python.
Many python builtins are actually implemented in low level languages such as C or assembly and use the python apis in order to be callable in python.
Your bit fiddling technique is likely very fast in C but in python the interpretation overhead of the... |
Getting "Could not find function xmlCheckVersion in library libxml2. Is libxml2 installed?" when installing lxml through pip | I'm getting an error Could not find function xmlCheckVersion in library libxml2. Is libxml2 installed? when trying to install lxml through pip.
c:\users\f\appdata\local\temp\xmlXPathInitqjzysz.c(1) : fatal error C1083: Cannot open include file: 'libxml/xpath.h': No such file or directory
***************************... | I had this issue and realised that whilst I did have libxml2 installed, I didn't have the necessary development libraries required by the python package. Installing them solved the problem:
sudo apt-get install libxml2-dev libxslt1-dev
sudo pip install lxml
|
TensorFlow Error found in Tutorial | Dare I even ask? This is such a new technology at this point that I can't find a way to solve this seemingly simple error. The tutorial I'm going over can be found here- http://www.tensorflow.org/tutorials/mnist/pros/index.html#deep-mnist-for-experts
I literally copied and pasted all of the code into IPython Notebook a... | I figured it out. As you see in the value error, it says No default session is registered. Use 'with DefaultSession(sess)' or pass an explicit session to eval(session=sess) so the answer I came up with is to pass an explicit session to eval, just like it says. Here is where I made the changes.
if i%100 == 0:
tr... |
Tensorflow: Using Adam optimizer | I am experimenting with some simple models in tensorflow, including one that looks very similar to the first MNIST for ML Beginners example, but with a somewhat larger dimensionality. I am able to use the gradient descent optimizer with no problems, getting good enough convergence. When I try to use the ADAM optimizer,... | The AdamOptimizer class creates additional variables, called "slots", to hold values for the "m" and "v" accumulators.
See the source here if you're curious, it's actually quite readable:
https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/training/adam.py#L39 . Other optimizers, such as Momentum and... |
Why are log2 and log1p so much faster than log and log10? | Whilst playing around with this question I noticed something I couldn't explain regarding the relative performance of np.log2, np.log and np.log10:
In [1]: %%timeit x = np.random.rand(100000)
....: np.log2(x)
....:
1000 loops, best of 3: 1.31 ms per loop
In [2]: %%timeit x = np.random.rand(100000)
np.log(x)
... | This is just a note, but longer than a comment. Apparently this has to do with your particular install:
import numpy as np
import numexpr as ne
x = np.random.rand(100000)
I get the same timings with numpy 1.10 from conda and a version compiled with icc:
%timeit np.log2(x)
1000 loops, best of 3: 1.24 ms per loop
%time... |
check if a key exists in a bucket in s3 using boto3 | I would like to know if a key exists in boto3. I can loop the bucket contents and check the key if it matches.
But that seems longer and an overkill. Boto3 official docs explicitly state how to do this.
May be I am missing the obvious. Can anybody point me how I can achieve this.
| Boto 2's boto.s3.key.Key object used to have an exists method that checked if the key existed on S3 by doing a HEAD request and looking at the the result, but it seems that that no longer exists. You have to do it yourself:
import boto3
import botocore
s3 = boto3.resource('s3')
exists = False
try:
s3.Object('my-b... |
Demystifying sharedctypes performance | In python it is possible to share ctypes objects between multiple processes. However I notice that allocating these objects seems to be extremely expensive.
Consider following code:
from multiprocessing import sharedctypes as sct
import ctypes as ct
import numpy as np
n = 100000
l = np.random.randint(0, 10, size=n)
d... | Sample Code
I rewrote your sample code a little bit to look into this issue. Here's where I landed, I'll use it in my answer below:
so.py:
from multiprocessing import sharedctypes as sct
import ctypes as ct
import numpy as np
n = 100000
l = np.random.randint(0, 10, size=n)
def sct_init():
sh = sct.RawArray(ct.c_... |
Generate random number outside of range in python | I'm currently working on a pygame game and I need to place objects randomly on the screen, except they cannot be within a designated rectangle. Is there an easy way to do this rather than continuously generating a random pair of coordinates until it's outside of the rectangle?
Here's a rough example of what the screen ... |
Partition the box into a set of sub-boxes.
Among the valid sub-boxes, choose which one to place your point in with probability proportional to their areas
Pick a random point uniformly at random from within the chosen sub-box.
This will generate samples from the uniform probability distribution on the valid region,... |
Correct way of "Absolute Import" in Python 2.7 |
Python 2.7.10
In virtualenv
Enable from __future__ import absolute_import in each module
The directory tree looks like:
Project/
prjt/
__init__.py
pkg1/
__init__.py
module1.py
tests/
__init__.py
test_module1.py
pkg2/
... | How python find module
python will find module from sys.path, and the first entry sys.path[0] is '' means, python will find module from the current working directory
import sys
print sys.path
and python find third-party module from site-packages
so to absolute import, you can
append your package to the sys.path
import... |
Precedence of "in" in Python | This is a bit of a (very basic) language-lawyer kind of question. I understand what the code does, and why, so please no elementary explanations.
In an expression, in has higher precedence than and. So if I write
if n in "seq1" and "something":
...
it is interpreted just like
if (n in "seq1") and "something":
... | In the context of a for statement, the in is just part of the grammar that makes up that compound statement, and so it is distinct from the operator in. The Python grammar specification defines a for statement like this:
for_stmt ::= "for" target_list "in" expression_list ":" suite
["else" ":" suite]
Th... |
Count number of non-NaN entries in each column of Spark dataframe with Pyspark | I have a very large dataset that is loaded in Hive. It consists of about 1.9 million rows and 1450 columns. I need to determine the "coverage" of each of the columns, meaning, the fraction of rows that have non-NaN values for each column.
Here is my code:
from pyspark import SparkContext
from pyspark.sql import HiveC... | Let's start with a dummy data:
from pyspark.sql import Row
row = Row("x", "y", "z")
df = sc.parallelize([
row(0, 1, 2), row(None, 3, 4), row(None, None, 5)]).toDF()
## +----+----+---+
## | x| y| z|
## +----+----+---+
## | 0| 1| 2|
## |null| 3| 4|
## |null|null| 5|
## +----+----+---+
All you need is... |
Check constraint for mutually exclusive columns in SQLAlchemy | If I have a SQLAlchemy declarative model like below:
class Test(Model):
__tablename__ = 'tests'
id = Column(Integer, Sequence('test_id_seq'), primary_key=True)
...
Atest_id = Column(Integer, ForeignKey('Atests.id'), nullable=True)
Btest_id = Column(Integer, ForeignKey('Btests.id'), nullable=True)
... | Well, considering your requisites "The data model has interaction outside of SQLAlchemy, so preferably it would be a database-level check (MySQL)" and 'ensure that only one [..] is not null'. I think the best approach is to write a trigger like this:
DELIMITER $$
CREATE TRIGGER check_null_insert BEFORE INSERT
ON my_ta... |
How to set adaptive learning rate for GradientDescentOptimizer? | I am using TensorFlow to train a neural network. This is how I am initializing the GradientDescentOptimizer:
init = tf.initialize_all_variables()
sess = tf.Session()
sess.run(init)
mse = tf.reduce_mean(tf.square(out - out_))
train_step = tf.train.GradientDescentOptimizer(0.3).minimize(mse)
The thing here is th... | First of all, tf.train.GradientDescentOptimizer is designed to use a constant learning rate for all variables in all steps. TensorFlow also provides out-of-the-box adaptive optimizers including the tf.train.AdagradOptimizer and the tf.train.AdamOptimizer, and these can be used as drop-in replacements.
However, if you w... |
What's the purpose of tf.app.flags in TensorFlow? | I am reading some example codes in Tensorflow, I found following code
flags = tf.app.flags
FLAGS = flags.FLAGS
flags.DEFINE_float('learning_rate', 0.01, 'Initial learning rate.')
flags.DEFINE_integer('max_steps', 2000, 'Number of steps to run trainer.')
flags.DEFINE_integer('hidden1', 128, 'Number of units in hidden l... | The tf.app.flags module is presently a thin wrapper around python-gflags, so the documentation for that project is the best resource for how to use it argparse, which implements a subset of the functionality in python-gflags.
Note that this module is currently packaged as a convenience for writing demo apps, and is not... |
How to specify multiple return types using type-hints | I have a function in python that can either return a bool or a list. Is there a way to specify the return types using type hints.
For example, Is this the correct way to do it?
def foo(id) -> list or bool:
...
| From the documentation
class typing.Union
Union type; Union[X, Y] means either X or Y.
Hence the proper way to represent more than one return data type is
def foo(client_id: str) -> Union[list,bool]
But do note that typing is not enforced in Python3.5
>>> def foo(a:str) -> list:
... return("Works")
...
>>> f... |
How could I use Batch Normalization in TensorFlow? | I would like to use Batch Normalization in TensorFlow, since I found it in the source code core/ops/nn_ops.cc. However, I did not find it documented on tensorflow.org.
BN has different semantics in MLP and CNN, so I am not sure what exactly this BN does.
I did not find a method called MovingMoments either.
The C++ code... | Update July 2016 The easiest way to use batch normalization in TensorFlow is through the higher-level interfaces provided in either contrib/layers, tflearn, or slim.
Previous answer if you want to DIY:
The documentation string for this has improved since the release - see the docs comment in the master branch instead ... |
How to convert column with dtype as object to string in Pandas Dataframe | When I read a csv file to pandas dataframe, each column will be casted to datatypes on it's own. I have a column that was converted to object. I want to perform string operations for that column like splitting the values and creating a list. But no such operation is being performed because of it's dtype being object. C... | Did you try assigning it back to the column?
df['column'] = df['column'].astype('str')
Referring to this question, the pandas dataframe stores the pointers to the strings and hence it is of type
'object'. As per the docs ,You could try:
df['column_new'] = df['column'].str.split(',')
|
Subclassing matplotlib Text: manipulate properties of child artist | I am working on an implementation of a class for inline labeling of line objects. For this purpose I have made a subclass of the Text class which as a Line2D object as an attribute. The code in my previous post was maybe a bit lengthy, so I have isolated the problem here:
from matplotlib.text import Text
from matplotli... | The issue is that you're not updating the line until it is redrawn, I think this should work:
class LineText(Text):
def __init__(self,line,*args,**kwargs):
x_pos = line.get_xdata().mean()
y_pos = line.get_ydata().mean()
Text.__init__(self,x=x_pos,y=y_pos,*args,**kwargs)
self.line = line
self.lin... |
Can Pickle handle files larger than the RAM installed on my machine? | I'm using pickle for saving on disk my NLP classifier built with the TextBlob library.
I'm using pickle after a lot of searches related to this question. At the moment I'm working locally and I have no problem loading the pickle file (which is 1.5Gb) with my i7 and 16gb RAM machine. But the idea is that my program, in ... | Unfortunately this is difficult to accurately answer without testing it on your machine.
Here are some initial thoughts:
There is no inherent size limit that the Pickle module enforces, but you're pushing the boundaries of its intended use. It's not designed for individual large objects. However, you since you're usi... |
What's the difference between loop.create_task, asyncio.async/ensure_future and Task? | I'm a little bit confused by some asyncio functions. I see there is BaseEventLoop.create_task(coro) function to schedule a co-routine. The documentation for create_task says its a new function and for compatibility we should use asyncio.async(coro) which by referring to docs again I see is an alias for asyncio.ensure_f... | As you've noticed, they all do the same thing.
asyncio.async had to be replaced with asyncio.ensure_future because in Python >= 3.5, async has been made a keyword[1].
create_task's raison d'etre[2]:
Third-party event loops can use their own subclass of Task for interoperability. In this case, the result type is a subc... |
Hash for lambda function in Python | I'm trying to get the hash of a lambda function. Why do I get two values (8746164008739 and -9223363290690767077)? Why is the hash from the lambda function not always one value?
>>> fn = lambda: 1
>>> hash(fn)
-9223363290690767077
>>> fn = lambda: 1
>>> hash(fn)
8746164008739
>>> fn = lambda: 1
>>> hash(fn)
-9223363290... | Two objects are not guaranteed to hash to the same value unless they compare equal [1].
Python functions (including lambdas) don't compare equal even if they have identical code [2]. For example:
>>> (lambda: 1) == (lambda: 1)
False
Implementation-wise, this behaviour is due to the fact that function objects don't pro... |
Is this time complexity actually O(n^2)? | I am working on a problem out of CTCI.
The third problem of chapter 1 has you take a string such as
'Mr John Smith '
and asks you to replace the intermediary spaces with %20:
'Mr%20John%20Smith'
The author offers this solution in Python, calling it O(n):
def urlify(string, length):
'''function replaces single s... | In CPython, the standard implementation of Python, there's an implementation detail that makes this usually O(n), implemented in the code the bytecode evaluation loop calls for + or += with two string operands. If Python detects that the left argument has no other references, it calls realloc to attempt to avoid a copy... |
Is "x < y < z" faster than "x < y and y < z"? | From this page, we know that:
Chained comparisons are faster than using the and operator.
Write x < y < z instead of x < y and y < z.
However, I got a different result testing the following code snippets:
$ python -m timeit "x = 1.2" "y = 1.3" "z = 1.8" "x < y < z"
1000000 loops, best of 3: 0.322 usec per loop
$ py... | The difference is that in x < y < z y is only evaluated once. This does not make a large difference if y is a variable, but it does when it is a function call, which takes some time to compute.
from time import sleep
def y():
sleep(.2)
return 1.3
%timeit 1.2 < y() < 1.8
10 loops, best of 3: 203 ms per loop
%tim... |
SKlearn import MLPClassifier fails | I am trying to use the multilayer perceptron from scikit-learn in python. My problem is, that the import is not working. All other modules from scikit-learn are working fine.
from sklearn.neural_network import MLPClassifier
Import Error: cannot import name MLPClassifier
I'm using the Python Environment Python64-bit... | MLPClassifier is not yet available in scikit-learn v0.17 (as of 1 Dec 2015). If you really want to use it you could clone 0.18dev (however, I don't know how stable this branch currently is).
|
How does the min/max function on a nested list work? | Lets say, there is a nested list, like:
my_list = [[1, 2, 21], [1, 3], [1, 2]]
When the function min() is called on this:
min(my_list)
The output received is
[1, 2]
Why and How does it work? What are some use cases of it?
| How are lists and other sequences compared in Python?
Lists (and other sequences) in Python are compared lexicographically and not based on any other parameter.
Sequence objects may be compared to other objects with the same sequence type. The comparison uses lexicographical ordering: first the first two items are com... |
Number list with no repeats and ordered | This code returns a list [0,0,0] to [9,9,9], which produces no repeats and each element is in order from smallest to largest.
def number_list():
b=[]
for position1 in range(10):
for position2 in range(10):
for position3 in range(10):
if position1<=position2 and position2<=pos... | On the same note as the other itertools answer, there is another way with combinations_with_replacement:
list(itertools.combinations_with_replacement(range(10), 3))
|
how to set different PYTHONPATH variables for python3 and python2 respectively | I want to add a specific library path only to python2. After adding export PYTHONPATH="/path/to/lib/" to my .bashrc, however, executing python3 gets the error: Your PYTHONPATH points to a site-packages dir for Python 2.x but you are running Python 3.x!
I think it is due to that python2 and python3 share the common PYTH... | PYTHONPATH is somewhat of a hack as far as package management is concerned. A "pretty" solution would be to package your library and install it.
This could sound more tricky than it is, so let me show you how it works.
Let us assume your "package" has a single file named wow.py and you keep it in /home/user/mylib/wow.p... |
How to change dataframe column names in pyspark? | I come from pandas background and am used to reading data from CSV files into a dataframe and then simply changing the column names to something useful using the simple command:
df.columns = new_column_name_list
However, the same doesn't work in pyspark dataframes created using sqlContext.
The only solution I could f... | There are many ways to do that:
Option 1. Using selectExpr.
data = sqlContext.createDataFrame([("Alberto", 2), ("Dakota", 2)],
["Name", "askdaosdka"])
data.show()
data.printSchema()
# Output
#+-------+----------+
#| Name|askdaosdka|
#+-------+----------+
#|Alberto| 2|
#|... |
Send email task with correct context | This code is my celery worker script:
from app import celery, create_app
app = create_app('default')
app.app_context().push()
When I try to run the worker I will get into this error:
File "/home/vagrant/myproject/venv/app/mymail.py", line 29, in send_email_celery
msg.html = render_template(template + '.html', **k... | Finally found what is the reason of the problem after some debug with this code.
I have a app_context_processor that will not return any result.
@mod.app_context_processor
def last_reputation_changes():
if current_user:
#code
return dict(reputation='xxx')
When sending the email the current_user wi... |
Why does heroku local:run wants to use the global python installation instead of the currently activated virtual env? | Using Heroku to deploy our Django application, everything seems to work by the spec, except the heroku local:run command.
We oftentimes need to run commands through Django's manage.py file. Running them on the remote, as one-off dynos, works flawlessly.
To run them locally, we try:
heroku local:run python manage.py the... | After contacting Heroku's support, we understood the problem.
The support confirmed that heroku local:run should as expected use the currently active virtual env.
The problem is a local configuration problem, due to our .bashrc content: heroku local:run sources .bashrc (and in our case, this was prepending $PATH with t... |
Django: Support for string view arguments to url() is deprecated and will be removed in Django 1.10 | New python/Django user (and indeed new to SO):
When trying to migrate my Django project, I get an error:
RemovedInDjango110Warning: Support for string view arguments to url() is deprecated
and will be removed in Django 1.10 (got main.views.home). Pass the callable instead.
url(r'^$', 'main.views.home')
Apparently... | I have found the answer to my question. It was indeed an import error. For Django 1.10, you now have to import the app's view.py, and then pass the second argument of url() without quotes. Here is my code now in urls.py:
from django.conf.urls import url
from django.contrib import admin
import main.views
urlpatterns = ... |
Identifier normalization: Why is the micro sign converted into the Greek letter mu? | I just stumbled upon the following odd situation:
>>> class Test:
µ = 'foo'
>>> Test.µ
'foo'
>>> getattr(Test, 'µ')
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
getattr(Test, 'µ')
AttributeError: type object 'Test' has no attribute 'µ'
>>> 'µ'.encode(), dir(Test)[-1].e... | There are two different characters involved here. One is the MICRO SIGN, which is the one on the keyboard, and the other is GREEK SMALL LETTER MU.
To understand whatâs going on, we should take a look at how Python defines identifiers in the language reference:
identifier ::= xid_start xid_continue*
id_start ::... |
How can I convert a tensor into a numpy array in TensorFlow? | I know how to convert a numpy array into a tensor object with the function tf.convert_to_tensor(img.eval()).
My problem is that after I apply some preprocessing to this tensors in terms of brightness, contrast, etc, I would like to view the resulting transformations to evaluate and tweak my parameters.
How can I conve... | To convert back from tensor to numpy array you can simply run .eval() on the transformed tensor.
|
How can a Python list be sliced such that a column is moved to being a separate element column? | I have a list of the following form:
[[0, 5.1, 3.5, 1.4, 0.2],
[0, 4.9, 3.0, 1.4, 0.2],
[0, 4.7, 3.2, 1.3, 0.2],
[1, 4.6, 3.1, 1.5, 0.2],
[1, 5.0, 3.6, 1.4, 0.2],
[1, 5.4, 3.9, 1.7, 0.4],
[1, 4.6, 3.4, 1.4, 0.3]]
I want to slice out the first column and add it as a new element to each row of data (so at each odd... | Try indexing and then get flattened list- i used list comprehension for flattening.
>>>l=[[0, 5.1, 3.5, 1.4, 0.2],
[0, 4.9, 3.0, 1.4, 0.2],
[0, 4.7, 3.2, 1.3, 0.2],
[1, 4.6, 3.1, 1.5, 0.2],
[1, 5.0, 3.6, 1.4, 0.2],
[1, 5.4, 3.9, 1.7, 0.4],
[1, 4.6, 3.4, 1.4, 0.3]]
>>>[[i[1:],[i[0]]] for i in l]#get sliced list of... |
Why does Python "preemptively" hang when trying to calculate a very large number? | I've asked this question before about killing a process that uses too much memory, and I've got most of a solution worked out.
However, there is one problem: calculating massive numbers seems to be untouched by the method I'm trying to use. This code below is intended to put a 10 second CPU time limit on the process.
i... | TLDR: Python precomputes constants in the code. If any very large number is calculated with at least one intermediate step, the process will be CPU time limited.
It took quite a bit of searching, but I have discovered evidence that Python 3 does precompute constant literals that it finds in the code before evaluating ... |
Django upgrading to 1.9 error "AppRegistryNotReady: Apps aren't loaded yet." | When upgraded to django 1.9 from 1.8 I got this error. I checked answers for similar questions, but I didn't think this is an issue with any 3rd party packages or apps.
Traceback (most recent call last):
File "manage.py", line 10, in <module> execute_from_command_line(sys.argv)
File "/home/kishore/.virtualenvs/andone/l... | Try to add this lines to the top of your settings file:
import django
django.setup()
And if this will not help you try to remove third-party applications from your installed apps list one-by-one.
|
Difference between numpy dot() and Python 3.5+ matrix multiplication @ | I recently moved to Python 3.5 and noticed the new matrix multiplication operator (@) sometimes behaves differently from the numpy dot operator. In example, for 3d arrays:
import numpy as np
a = np.random.rand(8,13,13)
b = np.random.rand(8,13,13)
c = a @ b # Python 3.5+
d = np.dot(a, b)
The @ operator returns an arr... | The @ operator calls the array's __matmul__ method, not dot. This method is also present in the API as the function np.matmul.
>>> a = np.random.rand(8,13,13)
>>> b = np.random.rand(8,13,13)
>>> np.matmul(a, b).shape
(8, 13, 13)
From the documentation:
matmul differs from dot in two important ways.
Multiplication by... |
'is' operator behaves unexpectedly with non-cached integers | When playing around with the Python interpreter, I stumbled upon this conflicting case regarding the is operator:
If the evaluation takes place in the function it returns True, if it is done outside it returns False.
>>> def func():
... a = 1000
... b = 1000
... return a is b
...
>>> a = 1000
>>> b = 1000
... | tl;dr:
As the reference manual states:
A block is a piece of Python program text that is executed as a unit.
The following are blocks: a module, a function body, and a class definition.
Each command typed interactively is a block.
This is why, in the case of a function, you have a single code block which contains... |
Why do many examples use "fig, ax = plt.subplots()" in Matplotlib/pyplot/python | I'm learning to use matplotlib by studying examples, and a lot of examples seem to include a line like the following before creating a single plot...
fig, ax = plt.subplots()
Here are some examples...
Modify tick label text
http://matplotlib.org/examples/pylab_examples/boxplot_demo2.html
I see this function used a l... | plt.subplots() is a function that returns a tuple containing a figure and axes object(s). Thus when using fig, ax = plt.subplots() you unpack this tuple into the variables fig and ax. Having fig is useful if you want to change figure-level attributes or save the figure as an image file later (e.g. with fig.savefig('you... |
Did something about `namedtuple` change in 3.5.1? | On Python 3.5.0:
>>> from collections import namedtuple
>>> cluster = namedtuple('Cluster', ['a', 'b'])
>>> c = cluster(a=4, b=9)
>>> c
Cluster(a=4, b=9)
>>> vars(c)
OrderedDict([('a', 4), ('b', 9)])
On Python 3.5.1:
>>> from collections import namedtuple
>>> cluster = namedtuple('Cluster', ['a', 'b'])
>>> c = cluster... | Per Python bug #24931:
[__dict__] disappeared because it was fundamentally broken in Python 3, so it had to be removed. Providing __dict__ broke subclassing and produced odd behaviors.
Revision that made the change
Specifically, subclasses without __slots__ defined would behave weirdly:
>>> Cluster = namedtuple('Clu... |
What are the differences between mysql-connector-python, mysql-connector-python-rf and mysql-connector-repackaged? | I'd like to use the mysql-connector library for python 3. I could use pymysql instead, but mysql-connector already has a connection pool implementation, while pymysql doesn't seem to have one. So this would be less code for me to write.
However, when I do
$ pip3 search mysql-connector
I find that these 3 libraries are... | The main differences between them are:
mysql-connector-repackaged: is old, do not use it
mysql-connector-python 2.0.4: is the original uploaded by MySQL. But it has the problem that does not works with Django >= 1.8. MySQL did not upload yet their stable version 2.1.3 to this repo.
mysql-connector-python-rf 2.1.3: is ... |
Normal equation and Numpy 'least-squares', 'solve' methods difference in regression? | I am doing linear regression with multiple variables/features. I try to get thetas (coefficients) by using normal equation method (that uses matrix inverse), Numpy least-squares numpy.linalg.lstsq tool and np.linalg.solve tool. In my data I have n = 143 features and m = 13000 training examples.
For normal equation met... | Don't calculate matrix inverse to solve linear systems
The professional algorithms don't solve for the matrix inverse. It's slow and introduces unnecessary error. It's not a disaster for small systems, but why do something suboptimal?
Basically anytime you see the math written as:
x = A^-1 * b
you instead want:
x = np... |
Tuple unpacking order changes values assigned | I think the two are identical.
nums = [1, 2, 0]
nums[nums[0]], nums[0] = nums[0], nums[nums[0]]
print nums # [2, 1, 0]
nums = [1, 2, 0]
nums[0], nums[nums[0]] = nums[nums[0]], nums[0]
print nums # [2, 2, 1]
But the results are different.
Why are the results different? (why is the second one that re... | Prerequisites - 2 important Points
Lists are mutable
The main part in lists is that lists are mutable. It means that the
values of lists can be changed. This is one of the reason why you are
facing the trouble. Refer the docs for more info
Order of Evaluation
The other part is that while unpacking a tuple, the evaluat... |
Can you fool isatty AND log stdout and stderr separately? | Problem
So you want to log the stdout and stderr (separately) of a process or subprocess, without the output being different from what you'd see in the terminal if you weren't logging anything.
Seems pretty simple no? Well unfortunately, it appears that it may not be possible to write a general solution for this proble... | Like this?
% ./challenge.py >stdout 2>stderr
% cat stdout
This is a real tty :)
standard output data
% cat stderr
standard error data
Because I cheated a little bit. ;-)
% echo $LD_PRELOAD
/home/karol/preload.so
Like so...
% gcc preload.c -shared -o preload.so -fPIC
I feel dirty now, but it was fun. :D
% cat prelo... |
Cannot import name _uuid_generate_random in heroku django | I am working on a project which scans user gmail inbox and provides a report. I have deployed it in heroku with following specs:
Language: Python 2.7
Framework: Django 1.8
Task scheduler: Celery (Rabbitmq-bigwig for broker url)
Now when heroku execute it the celery is not giving me the output. On Heroku push its showi... | You are coming across this issue, which affects Python 2.7.11 (Kombu is required by Celery).
The issue is fixed in Kombu 3.0.30.
|
How to prevent tensorflow from allocating the totality of a GPU memory? | I work in an environment in which computational resources are shared, i.e., we have a few server machines equipped with a few Nvidia Titan X GPUs each.
For small to moderate size models, the 12GB of the Titan X are usually enough for 2-3 people to run training concurrently on the same GPU. If the models are small enoug... | You can set the fraction of GPU memory to be allocated when you construct a tf.Session by passing a tf.GPUOptions as part of the optional config argument:
# Assume that you have 12GB of GPU memory and want to allocate ~4GB:
gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.333)
sess = tf.Session(config=tf.... |
Call another function and optionally keep default arguments | I have a function with one optional argument, like this:
def funA(x, a, b=1):
return a+b*x
I want to write a new function that calls funA and also has an optional argument, but if no argument is passed, I want to keep the default in funA.
I was thinking something like this:
def funB(x, a, b=None):
if b:
ret... | I would replace if b with if b is not None, so that if you pass b=0 (or any other "falsy" value) as argument to funB it will be passed to funA.
Apart from that it seems pretty pythonic to me: clear and explicit. (albeit maybe a bit useless, depending on what you're trying to do!)
A little more cryptic way that relies o... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.