instruction stringlengths 12 148 | input stringlengths 16 30.2k | output stringlengths 11 27.3k |
|---|---|---|
Difference between variable_scope and name_scope in TensorFlow | What is the difference between variable_scope and name_scope? The variable scope tutorial talks about variable_scope implicitly opening name_scope. I also noticed that creating a variable in a name_scope automatically expands its name with the scope name as well. So what is the difference?
| When you create a variable with tf.get_variable instead of tf.Variable, Tensorflow will start checking the names of the vars created with the same method to see if they collide. If they do, an exception will be raised. If you created a var with tf.get_variable and you try to change the prefix of your variable names by ... |
Flask-restful API Authorization. Access current_identity inside decorator | I use flask-restful to create my APIs. I have used flask-jwt for enabling authentication based on JWT. Now I need to do authorization.
I have tried putting my authorization decorator.
test.py (/test api)
from flask_restful import Resource
from flask_jwt import jwt_required
from authorization_helper import authorized_... | Here is the combination of quickstarts of both Flask-JWT and Flask-Restful.
from flask import Flask
from flask_restful import Resource, Api, abort
from functools import wraps
app = Flask(__name__)
api = Api(app)
from flask_jwt import JWT, jwt_required, current_identity
from werkzeug.security import safe_str_cmp
cla... |
Installing custom builds heroku and issue with Library paths | I'm attempting to install a custom build on heroku, so I'm using a variety of ways to attempt a third part installing using the buildpacks. In my .buildpacks file I have:
https://github.com/ddollar/heroku-buildpack-apt
https://github.com/heroku/heroku-buildpack-python.git
and in my Aptfile I have the following: libgeo... | https://github.com/heroku/heroku-buildpack-python/blob/master/bin/compile#L99-L107
# Prepend proper path buildpack use.
export PATH=$BUILD_DIR/.heroku/python/bin:$BUILD_DIR/.heroku/vendor/bin:$PATH
export PYTHONUNBUFFERED=1
export LANG=en_US.UTF-8
export C_INCLUDE_PATH=/app/.heroku/vendor/include:$BUILD_DIR/.heroku/ven... |
How to assign value to a tensorflow variable? | I am trying to assign a new value to a tensorflow variable in python.
import tensorflow as tf
import numpy as np
x = tf.Variable(0)
init = tf.initialize_all_variables()
sess = tf.InteractiveSession()
sess.run(init)
print(x.eval())
x.assign(1)
print(x.eval())
But the output I get is
0
0
So the value has not changed... | The statement x.assign(1) does not actually assign the value 1 to x, but rather creates a tf.Operation that you have to explicitly run to update the variable.* A call to Operation.run() or Session.run() can be used to run the operation:
assign_op = x.assign(1)
sess.run(assign_op) # or `assign_op.op.run()`
print(x.eval... |
Difference between np.mean and tf.reduce_mean (numpy | tensorflow)? | In the following tutorial: https://www.tensorflow.org/versions/master/tutorials/mnist/beginners/index.html
There is accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
tf.cast basically changes the type of tensor the object is...but what is the difference between tf.reduce_mean and np.mean?
Here is the do... | The functionality of numpy.mean and tensorflow.reduce_mean are the same. They do the same thing. From the documentation, for numpy and tensorflow, you can see that. Lets look at an example,
c = np.array([[3.,4], [5.,6], [6.,7]])
print(np.mean(c,1))
Mean = tf.reduce_mean(c,1)
with tf.Session() as sess:
result = ses... |
difference between tensorflow tf.nn.softmax and tf.nn.softmax_cross_entropy_with_logits | I was going through the tensorflow api docs here. In tensorflow docs they used a keyword called logits. What is it? In a lot of methods in the api docs it is written like,
tf.nn.softmax(logits, name=None)
Now what it is written is that logits are only Tensors. Well why keep a different name like logits? I almost thoug... | Logits simply means that the function operates on the unscaled output of earlier layers and that the relative scale to understand the units is linear. It means, in particular, the sum of the inputs may not equal 1, that the values are not probabilities (you might have an input of 5).
tf.nn.softmax produces just the re... |
Acessing POST field data without a form (REST api) using Django | In the django documentation, it says:
HttpRequest.POST
A dictionary-like object containing all given HTTP POST parameters, providing that the request contains form data. See the QueryDict documentation below. If you need to access raw or non-form data posted in the request, access this through the HttpRequest.body att... | As far as I understand the field method from Unirest just uses normal application/x-www-form-urlencoded data like a HTML form. So you should be able to just use response.POST["field1"] like you suggested.
|
Patch __call__ of a function | I need to patch current datetime in tests. I am using this solution:
def _utcnow():
return datetime.datetime.utcnow()
def utcnow():
"""A proxy which can be patched in tests.
"""
# another level of indirection, because some modules import utcnow
return _utcnow()
Then in my tests I do something lik... | [EDIT]
Maybe the most interesting part of this question is Why I cannot patch somefunction.__call__?
Because the function don't use __call__'s code but __call__ (a method-wrapper object) use function's code.
I don't find any well sourced documentation about that, but I can prove it (Python2.7):
>>> def f():
... re... |
Find "one letter that appears twice" in a string | I'm trying to catch if one letter that appears twice in a string using RegEx (or maybe there's some better ways?), for example my string is:
ugknbfddgicrmopn
The output would be:
dd
However, I've tried something like:
re.findall('[a-z]{2}', 'ugknbfddgicrmopn')
but in this case, it returns:
['ug', 'kn', 'bf', 'dd', '... | You need use capturing group based regex and define your regex as raw string.
>>> re.search(r'([a-z])\1', 'ugknbfddgicrmopn').group()
'dd'
>>> [i+i for i in re.findall(r'([a-z])\1', 'abbbbcppq')]
['bb', 'bb', 'pp']
or
>>> [i[0] for i in re.findall(r'(([a-z])\2)', 'abbbbcppq')]
['bb', 'bb', 'pp']
Note that , re.findal... |
Adding lambda functions with the same operator in python | I have a rather lengthy equation that I need to integrate over using scipy.integrate.quad and was wondering if there is a way to add lambda functions to each other. What I have in mind is something like this
y = lambda u: u**(-2) + 8
x = lambda u: numpy.exp(-u)
f = y + x
int = scipy.integrate.quad(f, 0, numpy.inf)
The... | In Python, you'll normally only use a lambda for very short, simple functions that easily fit inside the line that's creating them. (Some languages have other opinions.)
As @DSM hinted in their comment, lambdas are essentially a shortcut to creating functions when it's not worth giving them a name.
If you're doing more... |
Error in function to return 3 largest values from a list of numbers | I have this data file and I have to find the 3 largest numbers it contains
24.7 25.7 30.6 47.5 62.9 68.5 73.7 67.9 61.1 48.5 39.6 20.0
16.1 19.1 24.2 45.4 61.3 66.5 72.1 68.4 60.2 50.9 37.4 31.1
10.4 21.6 37.4 44.7 53.2 68.0 73.7 68.... | Your data contains float numbers not integer.
You can use sorted:
>>> data = '''24.7 25.7 30.6 47.5 62.9 68.5 73.7 67.9 61.1 48.5 39.6 20.0
... 16.1 19.1 24.2 45.4 61.3 66.5 72.1 68.4 60.2 50.9 37.4 31.1
... 10.4 21.6 37.4 44.7 53.2 68.0 ... |
Install python3-venv module on linux mint | I was able to move to Linux mint 17.3 64 bit version from my Linux mint 16. This was long awaited migration.
After moving to Linux Mint 17.3, I am not able to the install python3-venv module, which is said to be the replacement for virtualenv in python 3.x. In my linux mint 16 I had access to pyvenv-3.4 tool. I dont k... | Try running this command:
sudo apt-get install python3.4-venv
Then use this:
python3 -m venv test
the package name is python3.4-venv and not python3-venv.
|
Why is str.translate faster in Python 3.5 compared to Python 3.4? | I was trying to remove unwanted characters from a given string using text.translate() in Python 3.4.
The minimal code is:
import sys
s = 'abcde12345@#@$#%$'
mapper = dict.fromkeys(i for i in range(sys.maxunicode) if chr(i) in '@#$')
print(s.translate(mapper))
It works as expected. However the same program when execut... | TL;DR - ISSUE 21118
The long Story
Josh Rosenberg found out that the str.translate() function is very slow compared to the bytes.translate, he raised an issue, stating that:
In Python 3, str.translate() is usually a performance pessimization, not optimization.
Why was str.translate() slow?
The main reason for str.tr... |
standard deviation and errors bars in seaborn tsplot function in Python | How does Seaborn compute its error bars? example:
import numpy as np; np.random.seed(22)
import seaborn as sns; sns.set(color_codes=True)
x = np.linspace(0, 15, 31)
data = np.sin(x) + np.random.rand(10, 31) + np.random.randn(10, 1)
ax = sns.tsplot(data=data, err_style="ci_bars")
plt.show()
how are the ci_bars (or ci_b... | Another workaround for plotting standard deviation could be to use matplotlib errorbar on top of seaborn tsplot:
import numpy as np;
import seaborn as sns;
import pandas as pd
# create a group of time series
num_samples = 90
group_size = 10
x = np.linspace(0, 10, num_samples)
group = np.sin(x) + np.linspace(0, 2, num_... |
Disable special "class" attribute handling | The Story:
When you parse HTML with BeautifulSoup, class attribute is considered a multi-valued attribute and is handled in a special manner:
Remember that a single tag can have multiple values for its âclassâ attribute. When you search for a tag that matches a certain CSS class, youâre matching against any of i... |
What I don't like in this approach is that it is quite "unnatural" and "magical" involving importing "private" internal _htmlparser. I hope there is a simpler way.
Yes, you can import it from bs4.builder instead:
from bs4 import BeautifulSoup
from bs4.builder import HTMLParserTreeBuilder
class MyBuilder(HTMLParserTr... |
How to cache reads? | I am using python/pysam to do analyze sequencing data. In its tutorial (pysam - An interface for reading and writing SAM files) for the command mate it says:
'This method is too slow for high-throughput processing. If a read needs to be processed with its mate, work from a read name sorted file or, better, cache reads.... | Caching is a typical approach to speed up long running operations. It sacrifices memory for the sake of computational speed.
Let's suppose you have a function which given a set of parameters always returns the same result. Unfortunately this function is very slow and you need to call it a considerable amount of times s... |
"Failed building wheel for psycopg2" - MacOSX using virtualenv and pip | I'm attempting to make a website with a few others for the first time, and have run into a weird error when trying to use Django/Python/VirtualEnv. I've found solutions to this problem for other operating systems, such as Ubuntu, but can't find any good solutions for Mac.
This is the relevant code being run:
virtualen... | I had the same problem on Arch linux. I think that it's not an OS dependant problem. Anyway, I fixed this by finding the outdated packages and updating then.
pip uninstall psycopg2
pip list --outdated
pip install --upgrade wheel
pip install --upgrade setuptools
pip install psycopg2
hope this helps...
|
Why values of an OrderedDict are not equal? | With Python 3:
>>> from collections import OrderedDict
>>> d1 = OrderedDict([('foo', 'bar')])
>>> d2 = OrderedDict([('foo', 'bar')])
I want to check equality:
>>> d1 == d2
True
>>> d1.keys() == d2.keys()
True
But:
>>> d1.values() == d2.values()
False
Do you know why values are not equal?
Tested with Python 3.4 and ... | In Python 3, dict.keys() and dict.values() return special iterable classes - respectively a collections.abc.KeysView and a collections.abc.ValuesView. The first one inherit it's __eq__ method from set, the second uses the default object.__eq__ which tests on object identity.
|
Indexing a list with an unique index | I have a list say l = [10,10,20,15,10,20]. I want to assign each unique value a certain "index" to get [1,1,2,3,1,2].
This is my code:
a = list(set(l))
res = [a.index(x) for x in l]
Which turns out to be very slow.
l has 1M elements, and 100K unique elements. I have also tried map with lambda and sorting, which did n... | You can do this in O(N) time using a defaultdict and a list comprehension:
>>> from itertools import count
>>> from collections import defaultdict
>>> lst = [10, 10, 20, 15, 10, 20]
>>> d = defaultdict(count(1).next)
>>> [d[k] for k in lst]
[1, 1, 2, 3, 1, 2]
In Python 3 use __next__ instead of next.
If you're wonder... |
Haystack says âModel could not be found for SearchResultâ | After updating my Django from 1.7 to 1.9, search engine, which is based on Haystack and Solr, stopped working. This is what I get:
./manage.py shell
Python 2.7.6 (default, Jun 22 2015, 17:58:13)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from ha... | I was able to fix the issue by including a missing commit to the 2.4.1 release. The commit that fixed this issue was https://github.com/django-haystack/django-haystack/commit/f1ed18313777005dd77ed724ecbfb27c0b03cad8
so you can do
pip install git+ssh://git@github.com/django-haystack/django-haystack.git@f1ed18313777005d... |
Setting group permissions with python | That is my setup:
I have a VirtualMachine (Ubuntu 14.04. LTS), where there is running a PostgreSQL/PostGIS database.
With Windows 7 in QGIS I connect to this database and load feature layer into my GIS project.
With some python code I create a file with a tile ID and some information.
import os
import io
import time
l... | From the os module documentation:
Note: Although Windows supports chmod(), you can only set the fileâs read-only flag with it (via the stat.S_IWRITE and stat.S_IREAD constants or a corresponding integer value). All other bits are ignored.
For Windows permissions, you manage the ACLs. Adapting from another answer, y... |
Tensorflow read images with labels | I am building a standard image classification model with Tensorflow. For this I have input images, each assigned with a label (number in {0,1}). The Data can hence be stored in a list using the following format:
/path/to/image_0 label_0
/path/to/image_1 label_1
/path/to/image_2 label_2
...
I want to use TensorFlow's q... | There are three main steps to solving this problem:
Populate the tf.train.string_input_producer() with a list of strings containing the original, space-delimited string containing the filename and the label.
Use tf.read_file(filename) rather than tf.WholeFileReader() to read your image files. tf.read_file() is a state... |
Sending JSON data over WebSocket from Matlab using Python Twisted and Autobahn | I'm trying to create a connection from Matlab to stream JSON frames over a WebSocket. I've tested my python installation of autobahn and twisted using the following.
Working Example
Matlab Code
Sample driver code that uses the JSONlab toolbox to convert Matlab data to JSON form and then I compress and Base64 encode the... | Setting up a WebSocket using Python and Matlab
Check Matlab is pointing at the correct version of python
First, you need to make sure you're using the correct python binary. On Mac you might be using the system standard version instead of the one that Homebrew installed for example. Check the location of your python in... |
Diffie-Hellman (to RC4) with Wincrypt From Python | I am currently working on a project written in C++ that leverages the CryptoAPI to perform a Diffie-Hellman key exchange. I'm having a bit of trouble getting this to work as the eventual RC4 session key I get cannot be used to encrypt the same text in Python (using pycrypto).
The C++ code to perform the Diffie-Hellman ... | Finally had some time to look over your code. When I run your code locally, I am able to export the session key and can use it successfully in pycrypto. My guess is that you are either not exporting the session key correctly (e.g. is what you posted what you are running?) or the data you are encrypting in C++ is not th... |
Cannot press button | I'm trying to code a bot for a game, and need some help to do it. Being a complete noob, I googled how to do it with python and started reading a bit about mechanize.
<div class="clearfix">
<a href="#" onclick="return Index.submit_login('server_br73');">
<span class="world_button_active"... | There is quite a lot of javascript involved when you perform different actions on a page, mechanize is not a browser and cannot execute javascript. One option to make your life easier here would be to automate a real browser. Here is an example code to log into the tribalwars using selenium and a headless PhantomJS:
fr... |
Extending CSS selectors in BeautifulSoup | The Question:
BeautifulSoup provides a very limited support for CSS selectors. For instance, the only supported pseudo-class is nth-of-type and it can only accept numerical values - arguments like even or odd are not allowed.
Is it possible to extend BeautifulSoup CSS selectors or let it use lxml.cssselect internally a... | After checking the source code, it seems that BeautifulSoup does not provide any convenient point in its interface to extend or monkey patch its existing functionality in this regard. Using functionality from lxml is not possible either since BeautifulSoup only uses lxml during parsing and uses the parsing results to c... |
SQLALchemy Many to Many model relationship configuration with polymorphic models | So, there are a few questions and answers that touch on this issue but I cannot reconcile them exactly with what I'm trying to achieve.
Here, here and here
I have a set of models that are self-referential and inherited. This is the basic design.
class BaseUser(db.Model):
id = db.Column(db.Integer, primary_key=True,... | It can be done using primaryjoin and secondaryjoin properties. Relevant documentation is here.
Example:
customer_organization = Table(
'base_user_customer_organization', ModelBase.metadata,
Column('user_id', Integer, ForeignKey('base_user.id')),
Column('org_id', Integer, ForeignKey('base_user.id'))
)
clas... |
Changing a variable inside a method with another method inside it | The following code raises an UnboundLocalError:
def foo():
i = 0
def incr():
i += 1
incr()
print(i)
foo()
Is there a way to accomplish this?
| Use nonlocal statement
def foo():
i = 0
def incr():
nonlocal i
i += 1
incr()
print(i)
foo()
For more information on this new statement added in python 3.x, go to https://docs.python.org/3/reference/simple_stmts.html#the-nonlocal-statement
|
Imports behave differently when in __init__.py that is imported | Imports in an __init__.py seem to behave differently when the file is run, to when it is imported.
If we have the following files:
run.py:
import test
test/b.py:
class B(object):
pass
test/__init__.py:
from b import B
print B
print b
If we run __init__.py we get an error as I expect:
% python test/__init__.py
<... | The situation is the following: you have a script (run.py), a package test and its submodule test.b.
Whenever you import a submodule in Python, the name of that submodule is automatically stored into the parent package. So that when you do import collections.abc (or from collections.abc import Iterable, or similar), th... |
Wrap an open stream with io.TextIOWrapper | How can I wrap an open binary stream â a Python 2 file, a Python 3 io.BufferedReader, an io.BytesIO â in an io.TextIOWrapper?
I'm trying to write code that will work unchanged:
Running on Python 2.
Running on Python 3.
With binary streams generated from the standard library (i.e. I can't control what type they are... | Use codecs.getreader to produce a wrapper object:
text_stream = codecs.getreader("utf-8")(bytes_stream)
Works on Python 2 and Python 3.
|
Replace single instances of a character that is sometimes doubled | I have a string with each character being separated by a pipe character (including the "|"s themselves), for example:
"f|u|n|n|y||b|o|y||a||c|a|t"
I would like to replace all "|"s which are not next to another "|" with nothing, to get the result:
"funny|boy|a|cat"
I tried using mytext.replace("|", ""), but that remov... | This can be achieved with a relatively simple regex without having to chain str.replace:
>>> import re
>>> s = "f|u|n|n|y||b|o|y||a||c|a|t"
>>> re.sub('\|(?!\|)' , '', s)
'funny|boy|a|cat'
Explanation: \|(?!\|) will look for a | character which is not followed by another | character. (?!foo) means negative lookahead, ... |
In py.test, what is the use of conftest.py files? | I recently discovered py.test. It seems great. However I feel the documentation could be better.
I'm trying to understand what conftest.py files are meant to be used for.
In my (currently small) test suite I have one conftest.py file at the project root. I use it to define the fixtures that I inject into my tests.
I ha... |
Is this the correct use of conftest.py?
Yes it is, Fixtures are a potential and common use of conftest.py. The
fixtures that you will define will be shared among all tests in your test suite. However defining fixtures in the root conftest.py might be useless and it would slow down testing if such fixtures are not us... |
Memory-efficient way to generate a large numpy array containing random boolean values | I need to create a large numpy array containing random boolean values without hitting the swap.
My laptop has 8 GB of RAM. Creating a (1200, 2e6) array takes less than 2 s and use 2.29 GB of RAM:
>>> dd = np.ones((1200, int(2e6)), dtype=bool)
>>> dd.nbytes/1024./1024
2288.818359375
>>> dd.shape
(1200, 2000000)
For a ... | One problem with using np.random.randint is that it generates 64-bit integers, whereas numpy's np.bool dtype uses only 8 bits to represent each boolean value. You are therefore allocating an intermediate array 8x larger than necessary.
A workaround that avoids intermediate 64-bit dtypes is to generate a string of rando... |
What is the currently correct way to dynamically update plots in Jupyter/iPython? | In the answers to how to dynamically update a plot in a loop in ipython notebook (within one cell), an example is given of how to dynamically update a plot inside a Jupyter notebook within a Python loop. However, this works by destroying and re-creating the plot on every iteration, and a comment in one of the threads n... | Here is an example that updates a plot in a loop. It updates the data in the figure and does not redraw the whole figure every time. It does block execution, though if you're interested in running a finite set of simulations and saving the results somewhere, it may not be a problem for you.
%matplotlib notebook
import... |
Issue warning for missing comma between list items bug | The Story:
When a list of strings is defined on multiple lines, it is often easy to forget a comma between list items, like in this example case:
test = [
"item1"
"item2"
]
The list test would now have a single item "item1item2".
Quite often the problem appears after rearranging the items in a list.
Sample Sta... | These are merely probable solutions since I'm not really apt with static-analysis.
With tokenize:
I recently fiddled around with tokenizing python code and I believe it has all the information needed to perform these kind of checks when sufficient logic is added. For your given list, the tokens generated with python -... |
python equality precedence | class L(object):
def __eq__(self, other):
print 'invoked L.__eq__'
return False
class R(object):
def __eq__(self, other):
print 'invoked R.__eq__'
return False
left = L()
right = R()
With this code, left side gets the first shot at comparison, as documented in the data model:
... | This is documented under the numeric operations, further down the page, with an explanation for why it works that way:
Note: If the right operandâs type is a subclass of the left operandâs type and that subclass provides the reflected method for the operation, this method will be called before the left operandâs... |
WebDriver click() vs JavaScript click() | The Story:
Here on StackOverflow, I've seen users reporting that they cannot click an element via selenium WebDriver "click" command and can workaround it with a JavaScript click by executing a script.
Example in Python:
element = driver.find_element_by_id("myid")
driver.execute_script("arguments[0].click();", element... | Contrarily to what the currently accepted answer suggests, there's nothing specific to PhantomJS when it comes to the difference between having WebDriver do a click and doing it in JavaScript.
The Difference
The essential difference between the two methods is common to all browsers and can be explained pretty simply:
... |
Why does Python allow function calls with wrong number of arguments? | Python is my first dynamic language. I recently coded a function call incorrectly supplying a wrong number of arguments. This failed with an exception at the time that function was called. I expected that even in a dynamic language, this kind of error can be detected when the source file is parsed.
I understand that th... | Python cannot know up-front what object you'll end up calling, because being dynamic, you can swap out the function object. At any time. And each of these objects can have a different number of arguments.
Here is an extreme example:
import random
def foo(): pass
def bar(arg1): pass
def baz(arg1, arg2): pass
the_funct... |
Labels for clustermap in seaborn? | I have several questions about labeling for clustermap in seaborn. First is it possible to extract the the distance values for the hierarchical clustering, and plot the value on the tree structure visualization (maybe only the first three levels).
Here is my example code for creating a clustermap plot:
import pandas as... | I had the exact same issue with the labels on the y-axis being rotated and found a solution.
The issue is that if you do plt.yticks(rotation=0) like suggested in the question you referenced, it will rotate the labels on your colobar due to the way ClusterGrid works.
To solve it and rotate the right labels, you need to ... |
What's the point of Django's collectstatic? | This is probably a stupid question, but it's just not clicking in my head.
In Django, the convention is to put all of your static files (i.e css, js) specific to your app into a folder called static. So the structure would look like this:
mysite/
manage.py
mysite/ --> (settings.py, etc)
myapp/ --> (models.... | Collect static files from multiple apps into a single path
Well, a single Django project may use several apps, so while there you only have one myapp, it may actually be myapp1, myapp2, etc
By copying them from inside the individual apps into a single folder, you can point your frontend web server (e.g. nginx) to that ... |
List comprehension as substitute for reduce() in Python | The following python tutorial says that:
List comprehension is a complete substitute for the lambda function as well as the functions map(), filter() and reduce().
http://python-course.eu/python3_list_comprehension.php
However, it does not mention an example how a list comprehension can substitute a reduce() and I ca... | Ideally, list comprehension is to create a new list. Quoting official documentation,
List comprehensions provide a concise way to create lists. Common applications are to make new lists where each element is the result of some operations applied to each member of another sequence or iterable, or to create a subsequenc... |
How to prefetch data using a custom python function in tensorflow | I am trying to prefetch training data to hide I/O latency. I would like to write custom Python code that loads data from disk and preprocesses the data (e.g. by adding a context window). In other words, one thread does data preprocessing and the other does training. Is this possible in TensorFlow?
Update: I have a work... | This is a common use case, and most implementations use TensorFlow's queues to decouple the preprocessing code from the training code. There is a tutorial on how to use queues, but the main steps are as follows:
Define a queue, q, that will buffer the preprocessed data. TensorFlow supports the simple tf.FIFOQueue that... |
Using Popen in a thread blocks every incoming Flask-SocketIO request | I have the following situation:
I receive a request on a socketio server. I answer it (socket.emit(..)) and then start something with heavy computation load in another thread.
If the heavy computation is caused by subprocess.Popen (using subprocess.PIPE) it totally blocks every incoming request as long as it is being e... | Thanks to this question I learned something new today. Eventlet does offer a greenlet friendly version of subprocess and its functions, but for some odd reason it does not monkey patch this module in the standard library.
Link to the eventlet implementation of subprocess: https://github.com/eventlet/eventlet/blob/maste... |
Are objects with the same id always equal when comparing them with ==? | If I have two objects o1 and o2, and we know that
id(o1) == id(o2)
returns true.
Then, does it follow that
o1 == o2
Or is this not always the case? The paper I'm working on says this is not the case, but in my opinion it should be true!
| Not always:
>>> nan = float('nan')
>>> nan is nan
True
or formulated the same way as in the question:
>>> id(nan) == id(nan)
True
but
>>> nan == nan
False
NaN is a strange thing. Per definition it is not equal nor less or greater than itself. But it is the same object. More details why all comparisons have to return... |
Recursively replace characters in a dictionary | How do I change all dots . to underscores (in the dict's keys), given an arbitrarily nested dictionary?
What I tried is write two loops, but then I would be limited to 2-level-nested dictionaries.
This ...
{
"brown.muffins": 5,
"green.pear": 4,
"delicious.apples": {
"green.apples": 2
{
}
... sh... | You can write a recursive function, like this
from collections.abc import Mapping
def rec_key_replace(obj):
if isinstance(obj, Mapping):
return {key.replace('.', '_'): rec_key_replace(val) for key, val in obj.items()}
return obj
and when you invoke this with the dictionary you have shown in the questio... |
Dict/Set Parsing Order Consistency | Containers that take hashable objects (such as dict keys or set items). As such, a dictionary can only have one key with the value 1, 1.0 or True etc. (note: simplified somewhat - hash collisions are permitted, but these values are considered equal)
My question is: is the parsing order well-defined and is the resulting... | dictionary-displays
If a comma-separated sequence of key/datum pairs is given, they are evaluated from left to right to define the entries of the dictionary: each key object is used as a key into the dictionary to store the corresponding datum. This means that you can specify the same key multiple times in the key/dat... |
Getting PKCS7 signer chain in python | I have PKCS7 message which is signed. It contains a data and a signing certificate (with the whole chain of trust).
I have a code which uses m2crypto to get a certificate out of it.
bio = BIO.MemoryBuffer(pkcs7message)
p7 = SMIME.PKCS7(m2.pkcs7_read_bio_der(bio._ptr()))
sk = X509.X509_Stack()
certStack = p7.get0_signer... | I guess you are making a confusion between signers and certificate chain of a signer. PKCS7_get0_signers return the list of signers.
In order to building a PKCS7 message with 2 signers, you can use following steps:
Build key and certificate for first signer:
openssl genrsa -out key1.pem
openssl req -new -key key1.pem ... |
Apply function to column before filtering | I have a column in my database called coordinates, now the coordinates column contains information on the range of time an object takes up within my graph. I want to allow the user to filter by the date, but the problem is I use a function to determine the date normally. Take:
# query_result is the result of some filte... | I think you should definitely parse strings to columns before storing it in the databases. Let the database do the job it was designed for!
CREATE TABLE [coordinates]
(
id INTEGER NOT NULL PRIMARY KEY,
tag VARCHAR2(32),
color VARCHAR2(32) default 'green',
time_begin ... |
pronoun resolution backwards | The usual coreference resolution works in the following way:
Provided
The man likes math. He really does.
it figures out that
he
refers to
the man.
There are plenty of tools to do this.
However, is there a way to do it backwards?
For example,
given
The man likes math. The man really does.
I want to do the prono... | This is perhaps not really an answer to be happy with, but I think the answer is that there's no such functionality built in anywhere, though you can code it yourself without too much difficulty. Giving an outline of how I'd do it with CoreNLP:
Still run coref. This'll tell you that "the man" and "the man" are corefer... |
Fail during installation of Pillow (Python module) in Linux | I'm trying to install Pillow (Python module) using pip, but it throws this error:
ValueError: jpeg is required unless explicitly disabled using --disable-jpeg, aborting
So as the error says, I tried:
pip install pillow --global-option="--disable-jpeg"
But it fails with:
error: option --disable-jpeg not recognized
An... | There is a bug reported for Pillow here, which indicates that libjpeg and zlib are now required as of Pillow 3.0.0.
The installation instructions for Pillow on Linux give advice of how to install these packages. Note that not all of the following packages may be missing on your machine (comments suggest that only libj... |
Relative import error with py2exe | I was trying to generate an executable for a simple Python script. My setup.py code looks like this:
from distutils.core import setup
import py2exe
setup(console=["script.py"])
However, I am getting the error shown in the screenshot. Is there something I could try to fix this? I am using Windows 10.
| It seems that in your mf3.py you are importing beyond the top level.
Let's suppose that your project structure is as follows:
folder/
main.py
mod/
__init__.py
components/
__init__.py
expander.py
language_id.py
utilities/
__init__.py
functions.py
First make sure that
... |
Tensorflow Strides Argument | I am trying to understand the strides argument in tf.nn.avg_pool, tf.nn.max_pool, tf.nn.conv2d.
The documentation repeatedly says
strides: A list of ints that has length >= 4. The stride of the sliding window for each dimension of the input tensor.
My questions are:
What do each of the 4+ integers represent?
Why m... | The pooling and convolutional ops slide a "window" across the input tensor. Using tf.nn.conv2d as an example: If the input tensor has 4 dimensions: [batch, height, width, channels], then the convolution operates on a 2D window on the height, width dimensions.
strides determines how much the window shifts by in each o... |
How can I split my Click commands, each with a set of sub-commands, into multiple files? | I have one large click application that I've developed, but navigating through the different commands/subcommands is getting rough. How do I organize my commands into separate files? Is it possible to organize commands and their subcommands into separate classes?
Here's an example of how I would like to separate it:
in... | I'm looking for something like this at the moment, in your case is simple because you have groups in each of the files, you can solve this problema as explained in the documentation:
In the init.py file:
import click
from command_cloudflare import cloudflare
from command_uptimerobot import uptimerobot
cli = click.Com... |
Psycopg2 Python SSL Support is not compiled in | I am trying to connect to my postgres database using psycopg2 with sslmode='required' param; however, I get the following error
psycopg2.OperationalError: sslmode value "require" invalid when SSL support is not compiled in
Heres a couple details about my system
Mac OS X El Capitan
Python 2.7
Installed psycopg2 via pi... | Since you're installing via pip, you should be using the most recent version of psycopg2 (2.6.1).
After a little digging through the code, it seems that the exception is being thrown in connection_int.c, which directly calls the postgresql-c-libraries to set up the db-connection. The call happens like so:
self->pgconn ... |
Insert 0s into 2d array | I have an array x:
x = [0, -1, 0, 3]
and I want y:
y = [[0, -2, 0, 2],
[0, -1, 0, 3],
[0, 0, 0, 4]]
where the first row is x-1, the second row is x, and the third row is x+1. All even column indices are zero.
I'm doing:
y=np.vstack(x-1, x, x+1)
y[0][::2] = 0
y[1][::2] = 0
y[2][::2] = 0
I was thinking the... | In two lines
>>> x = np.array([0, -1, 0, 3])
>>> y = np.vstack((x-1, x, x+1))
>>> y[:,::2] = 0
>>> y
array([[ 0, -2, 0, 2],
[ 0, -1, 0, 3],
[ 0, 0, 0, 4]])
Explanation
y[:, ::2]
gives the full first dimension. i.e all rows and every other entry form the second dimension, i.e. the columns:
array([... |
How to link PyCharm with PySpark? | I'm new with apache spark and apparently I installed apache-spark with homebrew in my macbook:
Last login: Fri Jan 8 12:52:04 on console
user@MacBook-Pro-de-User-2:~$ pyspark
Python 2.7.10 (default, Jul 13 2015, 12:05:58)
[GCC 4.2.1 Compatible Apple LLVM 6.1.0 (clang-602.0.53)] on darwin
Type "help", "copyright", "cre... | Create Run configuration:
Go to Run -> Edit configurations
Add new Python configuration
Set Script path so it points to the script you want to execute
Edit Environment variables field so it contains at least:
SPARK_HOME - it should point to the directory with Spark installation. It should contain directories such as ... |
for loops and iterating through lists | Here is a snippet of code which gives the output: 0 1 2 2. I had expected the output 3 3 3 3 since a[-1] accesses the number 3 in the list. The explanation given online says "The value of a[-1] changes in each iteration" but I don't quite understand how or why. Any explanations would be great!
a = [0, 1, 2, 3]
for a[-1... | While doing for a[-1] in a, you actually iterate through the list and temporary store the value of the current element into a[-1].
You can see the loop like these instructions:
a[-1] = a[0] # a = [0, 1, 2, 0]
print(a[-1]) # 0
a[-1] = a[1] # a = [0, 1, 2, 1]
print(a[-1]) # 1
a[-1] = a[2] # a = [0, 1, 2, 2]
print(a[-1]) ... |
Recursive factorial using dict causes RecursionError | A simple recursive factorial method works perfectly:
def fact(n):
if n == 0:
return 1
return n * fact(n-1)
But I wanted to experiment a little and use a dict instead. Logically, this should work, but a bunch of print statements tell me that n, instead of stopping at 0, glides down across the negative n... | Python doesn't lazily evaluate parameters.
The default value passed to dict.get call will also be evaluated before calling the dict.get.
So, in your case, the default value has a recursive call and since your condition is never met, it does infinite recursion.
You can confirm this, with this program
>>> def getter():
.... |
Avoid `logger=logging.getLogger(__name__)` | We set up logging like the django docs told us:
https://docs.djangoproject.com/en/1.9/topics/logging/#using-logging
# import the logging library
import logging
# Get an instance of a logger
logger = logging.getLogger(__name__)
def my_view(request, arg1, arg):
...
if bad_mojo:
# Log an error message
... | You can use logging.basicConfig to define the default interface available through logging as follows:
import logging
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s %(name)s.%(funcName)s +%(lineno)s: %(levelname)-8s [%(process)d] %(message)s',
)
This definition will... |
Calling list() empties my iterable object? | a = range(1, 3)
a = iter(a)
list(a)
a = list(a)
a evaluates to [ ].
a = range(1, 3)
a = iter(a)
a = list(a)
a evaluates to [1, 2].
The first result is unexpected to me. What semantics are going on here?
| The issue is not list() but iter() which as documented returns a single-use iterator. Once something has accessed the iterator's elements, the iterator is permanently empty. The more commonly used iterable type is (normally) reusable, and the two types shouldn't be confused.
Note that you don't need iter() in order to... |
Using moviepy, scipy and numpy in amazon lambda | I'd like to generate video using AWS Lambda feature.
I've followed instructions found here and here.
And I now have the following process to build my Lambda function:
Step 1
Fire a Amazon Linux EC2 instance and run this as root on it:
#! /usr/bin/env bash
# Install the SciPy stack on Amazon Linux and prepare it for AW... | I was also following your first link and managed to import numpy and pandas in a Lambda function this way (on Windows):
Started a (free-tier) t2.micro EC2 instance with 64-bit Amazon Linux AMI 2015.09.1 and used Putty to SSH in.
Tried the same commands you used and the one recommended by the Amazon article:
sudo yum ... |
Python with...as for custom context manager | I wrote a simple context manager in Python for handling unit tests (and to try to learn context managers):
class TestContext(object):
test_count=1
def __init__(self):
self.test_number = TestContext.test_count
TestContext.test_count += 1
def __enter__(self):
pass
def __exit__(se... | __enter__ needs to return self.
The with statement will bind this methodâs return value to the target(s) specified in the as clause of the statement, if any.
This will work.
class TestContext(object):
test_count=1
def __init__(self):
self.test_number = TestContext.test_count
TestContext.test... |
Difference between coroutine and future/task in Python 3.5? | Let's say we have a dummy function:
async def foo(arg):
result = await some_remote_call(arg)
return result.upper()
What's the difference between:
coros = []
for i in range(5):
coros.append(foo(i))
loop = get_event_loop()
loop.run_until_complete(wait(coros))
And:
from asyncio import ensure_future
futures... | A coroutine is a generator function that can both yield values and accept values from the outside. The benefit of using a coroutine is that we can pause the execution of a function and resume it later. In case of a network operation, it makes sense to pause the execution of a function while we're waiting for the respon... |
Most pythonic way to interleave two strings | What's the most pythonic way to mesh two strings together?
For example:
Input:
u = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
l = 'abcdefghijklmnopqrstuvwxyz'
Output:
'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz'
| For me, the most pythonic* way is the following which pretty much does the same thing but uses the + operator for concatenating the individual characters in each string:
res = "".join(i + j for i, j in zip(u, l))
print(res)
# 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz'
It is also faster than using two join(... |
Python: Splat/unpack operator * in python cannot be used in an expression? | Does anybody know the reasoning as to why the unary (*) operator cannot be used in an expression involving iterators/lists/tuples?
Why is it only limited to function unpacking? or am I wrong in thinking that?
For example:
>>> [1,2,3, *[4,5,6]]
File "<stdin>", line 1
[1,2,3, *[4,5,6]]
^
SyntaxError: invalid synt... | Not allowing unpacking in Python 2.x has noted and fixed in Python 3.5 which now has this feature as described in PEP 448:
Python 3.5.0 (v3.5.0:374f501f4567, Sep 13 2015, 02:27:37) on Windows (64 bits).
>>> [1, 2, 3, *[4, 5, 6]]
[1, 2, 3, 4, 5, 6]
Here are some explanations for the rationale behind this change.
|
matplotlib taking time when being imported | I just upgraded to the latest stable release of matplotlib (1.5.1) and everytime I import matplotlib I get this message:
/usr/local/lib/python2.7/dist-packages/matplotlib/font_manager.py:273: UserWarning: Matplotlib is building the font cache using fc-list. This may take a moment.
warnings.warn('Matplotlib is buildin... | As tom suggested in the comment above, deleting the files: fontList.cache, fontList.py3k.cache and tex.cache solve the problem. In my case the files were under ~/.matplotlib.
|
Anaconda Python installation error | I get the following error during Python 2.7 64-bit windows installation. I previously installed python 3.5 64-bit and it worked fine. But during python 2.7 installation i get this error:
Traceback (most recent call last):
File "C:\Anaconda2\Lib\_nsis.py", line 164, in <module> main()
File "C:\Anaconda2\Lib\_nsis.py", l... | I had the same problem today. I did the following to get this fixed:
First, open a DOS prompt and admin rights.
Then, go to your Anaconda2\Scripts folder.
Then, type in:
conda update conda
and allow all updates. One of the updates should be menuinst.
Then, change to the Anaconda2\Lib directory, and type in the foll... |
Updating a sliced list | I thought I understood Python slicing operations, but when I tried to update a sliced list, I got confused:
>>> foo = [1, 2, 3, 4]
>>> foo[:1] = ['one'] # OK, foo updated
>>> foo
['one', 2, 3, 4]
>>> foo[:][1] = 'two' # why foo not updated?
>>> foo
['one', 2, 3, 4]
>>> foo[:][2:] = ['three', 'four'] # Again, foo not ... | foo[:] is a copy of foo. You mutated the copy.
|
Python: optimal search for substring in list of strings | I have a particular problem where I want to search for many substrings in a list of many strings. The following is the gist of what I am trying to do:
listStrings = [ACDE, CDDE, BPLL, ... ]
listSubstrings = [ACD, BPI, KLJ, ...]
The above entries are just examples. len(listStrings) is ~ 60,000, len(listSubstrings) is ... | For the sort of thing you're trying (searching for a fixed set of a whole bunch of strings in a whole bunch of other strings), parallelizing and minor tweaks won't help much. You need algorithmic improvements.
For a start, I'd suggest using the Aho-Corasick string matching algorithm. Basically, in exchange for some pre... |
AttributeError: module 'html.parser' has no attribute 'HTMLParseError' |
This is the hints,how can I resolve it?
I use Python 3.5.1 created a virtual envirement by virtualenv
The source code works well on my friend's computer machine
Error:
Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "A:\Python3.5\lib\site-pac... | As you can read here this error is raised...
because HTMLParseError is deprecated from Python 3.3 onwards and removed in Python 3.5.
What you can do is downgrade your Python version or upgrade your Django version.
|
Comprehensions in Python to sample tuples from a list | I am trying to get the list of three-element tuples from the list [-4, -2, 1, 2, 5, 0] using comprehensions, and checking whether they fulfil the condition sum([] == 0). The following code works. However, there is no question that there ought to be an easier, much more elegant way of expressing these comprehensions:
[... | You can use itertools.product to hide the nested loops in your list comprehension. Use the repeat parameter to set the number of loops over the list (i.e. the number of elements in the tuple):
>>> import itertools
>>> lst = [-4, -2, 1, 2, 5, 0]
>>> [x for x in itertools.product(lst, repeat=3) if sum(x) == 0]
[(-4, 2, 2... |
What does "list comprehension" in Python mean? How does it work and how can I use it? | I have the following code:
[x**2 for x in range(10)]
When I run it in the Python Shell, it returns:
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
I've searched and it seems this is called a list comprehension, but how does it work?
| From the documentation:
List comprehensions provide a concise way to create lists. Common applications are to make new lists where each element is the result of some operations applied to each member of another sequence or iterable, or to create a subsequence of those elements that satisfy a certain condition.
About... |
Enumerating three variables in python list comprehension | I am trying to print all the possible enumerations of a list for three variables. For example if my input is:
x = 1
y = 1
z = 1
I want the output to be like:
[[0, 0, 0], [0, 0, 1], [0, 1, 0], [1, 0, 0], [1, 1, 0], [1, 0, 1], [0, 1, 1], [1, 1, 1]]
If any of the x,y,z variables are higher than 1, it would enumerate al... | You could use the product() function from itertools as follows:
from itertools import product
answer = list(list(x) for x in product([0, 1], repeat=3))
print(answer)
Output
[[0, 0, 0], [0, 0, 1], [0, 1, 0], [0, 1, 1], [1, 0, 0], [1, 0, 1], [1, 1, 0], [1, 1, 1]]
|
Is unsetting a single bit in flags safe with Python variable-length integers? | In my program (written in Python 3.4) I have a variable which contains various flags, so for example:
FLAG_ONE = 0b1
FLAG_TWO = 0b10
FLAG_THREE = 0b100
status = FLAG_ONE | FLAG_TWO | FLAG_THREE
Setting another flag can easily be done with
status |= FLAG_FOUR
But what if I explicitly want to clear a flag? I'd do
statu... | You should be safe using that approach, yes.
~ in Python is simply implemented as -(x+1) (cf. the CPython source) and negative numbers are treated as if they have any required number of 1s padding the start. From the Python Wiki:
Of course, Python doesn't use 8-bit numbers. It USED to use however many bits were native... |
What causes the '' in ['h', 'e', 'l', 'l', 'o', ''] when you do re.findall('[\w]?', 'hello') | What causes the '' in ['h', 'e', 'l', 'l', 'o', ''] when you do re.findall('[\w]?', 'hello'). I thought the result would be ['h', 'e', 'l', 'l', 'o'], without the last empty string.
| The question mark in your regex ('[\w]?') is responsible for the empty string being one of the returned results.
A question mark is a quantifier meaning "zero-or-one matches." You are asking for all occurrences of either zero-or-one "word characters". The letters satisfy the "-or-one word characters" match. The empty s... |
What is the proper way to determine if an object is a bytes-like object in Python? | I have code that expects str but will handle the case of being passed bytes in the following way:
if isinstance(data, bytes):
data = data.decode()
Unfortunately, this does not work in the case of bytearray. Is there a more generic way to test whether an object is either bytes or bytearray, or should I just check ... | There are a few approaches you could use here.
Duck typing
Since Python is duck typed, you could simply do as follows (which seems to be the way usually suggested):
try:
data = data.decode()
except AttributeError:
pass
You could use hasattr as you describe, however, and it'd probably be fine. This is, of cours... |
What does tf.nn.embedding_lookup function do? | tf.nn.embedding_lookup(params, ids, partition_strategy='mod', name=None)
I cannot understand the duty of this function. Is it like a lookup table? which means return the param corresponding for each id (in ids)?
For instance, in the skip-gram model if we use tf.nn.embedding_lookup(embeddings, train_inputs), then for e... | embedding_lookup function retrieves rows of the params tensor. The behavior is similar to using indexing with arrays in numpy. E.g.
matrix = np.random.random([1024, 64]) # 64-dimensional embeddings
ids = np.array([0, 5, 17, 33])
print matrix[ids] # prints a matrix of shape [4, 64]
params argument can be also a list... |
Seeking Elegant Python Dice Iteration | Is there an elegant way to iterate through possible dice rolls with up to five dice?
I want to replace this hacky Python:
self.rolls[0] = [str(a) for a in range(1,7)]
self.rolls[1] = [''.join([str(a), str(b)])
for a in range(1, 7)
for b in range(1, 7)
if a <= b]
self.r... | You can use itertools' combinations_with_replacement.
For example with 3 4-sided dice (just because the output isn't too large):
>>> from itertools import combinations_with_replacement
>>> dice = 3
>>> faces = 4
>>> list(combinations_with_replacement(range(1, faces+1), dice))
[(1, 1, 1),
(1, 1, 2),
(1, 1, 3),
(1, 1... |
Dump data from malformed SQLite in Python | I have a malformed database. When I try to get records from any of two tables, it throws an exception:
DatabaseError: database disk image is malformed
I know that through commandline I can do this:
sqlite3 ".dump" base.db | sqlite3 new.db
Can I do something like this from within Python?
| As far as i know you cannot do that (alas, i might be mistaken), because the sqlite3 module for python is very limited.
Only workaround i can think of involves calling the os command shell (e.g. terminal, cmd, ...) (more info) via pythons call-command:
Combine it with the info from here to do something like this:
This ... |
What happens in degenerate case of multiple assignment? | I'm teaching myself algorithms. I needed to swap two items in a list. Python makes all things easy:
def swap(A, i, j):
A[i], A[j] = A[j], A[i]
This works a treat:
>>> A = list(range(5))
>>> A
[0, 1, 2, 3, 4]
>>> swap(A, 0, 1)
>>> A
[1, 0, 2, 3, 4]
Note the function is resilient to the degenerate case i = j. As yo... | cycle is doing exactly what you ask it to: assigning to the left hand values the right hand values.
def cycle(A, i, j, k):
A[i], A[j], A[k] = A[j], A[k], A[i]
is functionally equivalent to
def cycle(A, i, j, k):
new_values = A[j], A[k], A[i]
A[i], A[j], A[k] = new_values
So when you do cycle(A, 1, 0, 1) ... |
When and why socket.send() returns 0 in python? | The python3 socket programming howto presents this code snippet
class MySocket:
"""demonstration class only
- coded for clarity, not efficiency
"""
def __init__(self, sock=None):
if sock is None:
self.sock = socket.socket(
socket.AF_INET, socket.SOCK_ST... | Upon seeing the question I was somehow stunned, because a send C call can return 0 bytes and the connection is of course still alive (the socket cannot simply send more bytes at that given moment in time)
https://github.com/python/cpython/blob/master/Modules/socketmodule.c
I decided to "use the source" and unless I a... |
How can I convert an absolutely massive number to a string in a reasonable amount of time? | This is quite an odd problem I know, but I'm trying to get a copy of the current largest prime number in a file. Getting the number in integer form is fairly easy. I just run this.
prime = 2**74207281 - 1
It takes about half a second and it works just fine. Operations are fairly quick as well. Dividing it by 10 (witho... | Repeated string concatenation is notoriously inefficient since Python strings are immutable. I would go for
strprime = str(prime)
In my benchmarks, this is consistently the fastest solution. Here's my little benchmark program:
import decimal
def f1(x):
''' Definition by OP '''
strprime = ""
while x > 0:
... |
gitpython list changed files since last commit | Folks,
I need to have the python script read in the files that have changed since the last git commit. Using GitPython, how would I get the same output as running from cli:
$ git diff --name-only HEAD~1 HEAD
I can do something like the following, however, I only need the file names:
hcommit = repo.head.commit
for d... | You need to pass the name_only keyword argument - it would automatically be used as --name-only command-line option when a git command would be issued.
The following is the equivalent of git diff --name-only HEAD~1..HEAD:
diff = repo.git.diff('HEAD~1..HEAD', name_only=True)
print(diff)
|
static openCL class not properly released in python module using boost.python | EDIT: Ok, all the edits made the layout of the question a bit confusing so I will try to rewrite the question (not changing the content, but improving its structure).
The issue in short
I have an openCL program that works fine, if I compile it as an executable. Now I try to make it callable from Python using boost.pyth... | I came across similar problem in the past.
clRetain* functions are supported from OpenCL1.2.
When getting devices for the first GPU platform (platforms[0].getDevices(...) for CL_DEVICE_TYPE_GPU) in your case it must happen to be a platform pre OpenCL1.2 hence you get a crash. When getting devices of any type (GPU/CPU/.... |
Robust endless loop for server written in Python | I write a server which handles events and uncaught exceptions during handling the event must not terminate the server.
The server is a single non-threaded python process.
I want to terminate on these errors types:
KeyboardInterrupt
MemoryError
...
The list of built in exceptions is long: https://docs.python.org/2/lib... | I would do this in a similar way you're thinking of, using the 'you shall not pass' Gandalf exception handler except Exception to catch all non-system-exiting exceptions while creating a black-listed set of exceptions that should pass and end be re-raised.
Using the Gandalf handler will make sure GeneratorExit, SystemE... |
Softmax function - python | From the Udacity's deep learning class, the softmax of y_i is simply the exponential divided by the sum of exponential of the whole Y vector:
Where S(y_i) is the softmax function of y_i and e is the exponentia and j is the no. of columns in the input vector Y.
I've tried the following:
import numpy as np
def softmax(... | They're both correct but yours has an unnecessary term.
You start with
e ^ (x - max(x)) / sum(e^(x - max(x))
By using the fact that a^(b - c) = (a^b)/(a^c) we have
= e ^ x / e ^ max(x) * sum(e ^ x / e ^ max(x))
= e ^ x / sum(e ^ x)
Which is what the other answer says. You could replace max(x) with any variable and it w... |
Why does range(0) == range(2, 2, 2) equal True in Python 3? | Why do range objects which are initialized with different values compare equal to one another in Python 3 (this doesn't happen in Python 2)?
When I execute the following commands in my interpreter:
>>> r1 = range(0)
>>> r2 = range(2, 2, 2)
>>> r1 == r2
True
>>>
The result is True. Why is this so? Why are two differe... | The range objects are special:
Python will compare range objects as Sequences. What that essentially means is that the comparison doesn't evaluate how they represent a given sequence but rather what they represent.
The fact that the start, stop and step parameters are completely different plays no difference here becau... |
Why is max slower than sort in Python? | I've found that max is slower than the sort function in Python 2 and 3.
Python 2
$ python -m timeit -s 'import random;a=range(10000);random.shuffle(a)' 'a.sort();a[-1]'
1000 loops, best of 3: 239 usec per loop
$ python -m timeit -s 'import random;a=range(10000);random.shuffle(a)' 'max(a)'
1000 loops, best of 3:... | You have to be very careful when using the timeit module in Python.
python -m timeit -s 'import random;a=range(10000);random.shuffle(a)' 'a.sort();a[-1]'
Here the initialisation code runs once to produce a randomised array a. Then the rest of the code is run several times. The first time it sorts the array, but every ... |
How do I transform a multi-level list into a list of strings in Python? | I have a list that looks something like this:
a = [('A', 'V', 'C'), ('A', 'D', 'D')]
And I want to create another list that transforms a into:
['AVC', 'ADD']
How would I go on to do this?
| Use str.join() in a list comprehension (works in both Python 2.x and 3.x):
>>> a = [('A', 'V', 'C'), ('A', 'D', 'D')]
>>> [''.join(x) for x in a]
['AVC', 'ADD']
|
Python - Plotting velocity and acceleration vectors at certain points | Here, i have a parametric equation.
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
t = np.linspace(0,2*np.pi, 40)
# Position Equation
def rx(t):
return t * np.cos(t)
def ry(t):
return t * np.sin(t)
# Velocity Vectors
def vx(t):
return np.cos(t) - t*np.sin(t)... | I feel like this is close... Even got the colors to match the sample picture :)
I'm not too experienced with plotting on polar coordinates, though (mostly confused on the third-dimension t coordinate).
Hopefully this will help and you could figure out how to extend it
I took what you had, added the Arrow3D class fro... |
Difference between a -= b and a = a - b in Python | I have recently applied this solution for averaging every N rows of matrix.
Although the solution works in general I had problems when applied to a 7x1 array. I have noticed that the problem is when using the -= operator.
To make a small example:
import numpy as np
a = np.array([1,2,3])
b = np.copy(a)
a[1:] -= a[:-1]... | Mutating arrays while they're being used in computations can lead to unexpected results!
In the example in the question, subtraction with -= modifies the second element of a and then immediately uses that modified second element in the operation on the third element of a.
Here is what happens with a[1:] -= a[:-1] step ... |
Performance degradation of matrix multiplication of single vs double precision arrays on multi-core machine | UPDATE
Unfortunately, due to my oversight, I had an older version of MKL (11.1) linked against numpy. Newer version of MKL (11.3.1) gives same performance in C and when called from python.
What was obscuring things, was even if linking the compiled shared libraries explicitly with the newer MKL, and pointing through L... | I suspect this is due to unfortunate thread scheduling. I was able to reproduce an effect similar to yours. Python was running at ~2.2 s, while the C version was showing huge variations from 1.4-2.2 s.
Applying:
KMP_AFFINITY=scatter,granularity=thread
This ensures that the 28 threads are always running on the same proc... |
Subtraction over a list of sets | Given a list of sets:
allsets = [set([1, 2, 4]), set([4, 5, 6]), set([4, 5, 7])]
What is a pythonic way to compute the corresponding list of sets of elements having no overlap with other sets?
only = [set([1, 2]), set([6]), set([7])]
Is there a way to do this with a list comprehension?
| To avoid quadratic runtime, you'd want to make an initial pass to figure out which elements appear in more than one set:
import itertools
import collections
element_counts = collections.Counter(itertools.chain.from_iterable(allsets))
Then you can simply make a list of sets retaining all elements that only appear once:... |
Adding data to Pandas Dataframe from a CSV file causing Value Errors | I am trying to add an int to an existing value in a Pandas DataFrame with
>>> df.ix['index 5','Total Dollars'] += 10
I get the error:
ValueError: Must have equal len keys and value when setting with an iterable.
I think the error comes from the datatype as gotten from:
>>> print type(df.ix['index 5','Total Dollars... | This looks like a bug for some earlier pandas versions, fixed at least with 0.16.2 if not earlier as discussed here and here.
With 0.17.1, this works fine:
df = pd.DataFrame(data=[5], columns=['Total Dollars'], index=['index 5'])
Total Dollars
index 5 5
df.ix['index 5', 'Total Dollars'] += 10
... |
Multi-threaded integer matrix multiplication in NumPy/SciPy | Doing something like
import numpy as np
a = np.random.rand(10**4, 10**4)
b = np.dot(a, a)
uses multiple cores, and it runs nicely.
The elements in a, though, are 64-bit floats (or 32-bit in 32-bit platforms?), and I'd like to multiply 8-bit integer arrays. Trying the following, though:
a = np.random.randint(2, size=(n... |
Option 5 - Roll a custom solution: Partition the matrix product in a few sub-products and perform these in parallel. This can be relatively easy implemented with standard Python modules. The sub-products are computed with numpy.dot, which releases the global interpreter lock. Thus, it is possible to use threads which ... |
NLTK ViterbiParser fails in parsing words that are not in the PCFG rule | import nltk
from nltk.parse import ViterbiParser
def pcfg_chartparser(grammarfile):
f=open(grammarfile)
grammar=f.read()
f.close()
return nltk.PCFG.fromstring(grammar)
grammarp = pcfg_chartparser("wsjp.cfg")
VP = ViterbiParser(grammarp)
print VP
for w in sent:
for tree in VP.parse(nltk.word_token... | Firstly, try to use (i) namespaces and (ii) unequivocal variable names, e.g.:
>>> from nltk import PCFG
>>> from nltk.parse import ViterbiParser
>>> import urllib.request
>>> response = urllib.request.urlopen('https://raw.githubusercontent.com/salmanahmad/6.863/master/Labs/Assignment5/Code/wsjp.cfg')
>>> wsjp = respons... |
Where should you update Celery settings? On the remote worker or sender? | Where should you update celery settings? On the remote worker or the sender?
For example, I have an API using Django and Celery. The API sends remote jobs to my remote workers via a broker (RabbitMQ). The workers are running a python script (not using Django) sometimes these works spawn sub tasks.
I've created celery ... | the django celery settings affects only workers running on the django server itself.
if all your workers are remote workers (the way as i do it), then on the sender side all you need is to put the configuration necessary to submit a task to the task queue.
and all the other settings need to be set on the remote workers... |
Dot notation string manipulation | Is there a way to manipulate a string in Python using the following ways?
For any string that is stored in dot notation, for example:
s = "classes.students.grades"
Is there a way to change the string to the following:
"classes.students"
Basically, remove everything up to and including the last period. So "restaurants... | you can use split and join together:
s = "classes.students.grades"
print '.'.join(s.split('.')[:-1])
You are splitting the string on . - it'll give you a list of strings, after that you are joining the list elements back to string separating them by .
[:-1] will pick all the elements from the list but the last one
To... |
Why do 3 backslashes equal 4 in a Python string? | Could you tell me why '?\\\?'=='?\\\\?' gives True? That drives me crazy and I can't find a reasonable answer...
>>> list('?\\\?')
['?', '\\', '\\', '?']
>>> list('?\\\\?')
['?', '\\', '\\', '?']
| Basically, because python is slightly lenient in backslash processing. Quoting from https://docs.python.org/2.0/ref/strings.html :
Unlike Standard C, all unrecognized escape sequences are left in the string unchanged, i.e., the backslash is left in the string.
(Emphasis in the original)
Therefore, in python, it isn't... |
Unable to run odoo properly in Mac OS X | I have installed Odoo 9 Community version from Git in my Mac OS X El Capitan 10.11.2, all my steps:
python --version
Python 2.7.10
git clone https://github.com/odoo/odoo.git
Checking out files: 100% (20501/20501), done.
Installed PostgresApp into Applications and added path in ~/.bash_profile, executed the same.
expo... | I just went through the setup on two systems, one is Mac OS X El Capitan 10.11.2 and another one is my primary OS - Ubuntu 15.04 (where things went much easier, but maybe it is just because I use Ubuntu on daily basis).
Below are installation steps for both systems. Make sure that every command finishes successfully (a... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.