instruction stringlengths 12 148 | input stringlengths 16 30.2k | output stringlengths 11 27.3k |
|---|---|---|
How (in what form) to share (deliver) a Python function? | The final outcome of my work should be a Python function that takes a JSON object as the only input and return another JSON object as output. To keep it more specific, I am a data scientist, and the function that I am speaking about, is derived from data and it delivers predictions (in other words, it is a machine lear... | You have the right idea with using a socket but there are tons of frameworks doing exactly what you want. Like hleggs, I suggest you checkout Flask to build a microservice. This will let the other team post JSON objects in an HTTP request to your flask application and receive JSON objects back. No knowledge of the unde... |
How do I turn a dataframe into a series of lists? | I have had to do this several times and I'm always frustrated. I have a dataframe:
df = pd.DataFrame([[1, 2, 3, 4], [5, 6, 7, 8]], ['a', 'b'], ['A', 'B', 'C', 'D'])
print df
A B C D
a 1 2 3 4
b 5 6 7 8
I want to turn df into:
pd.Series([[1, 2, 3, 4], [5, 6, 7, 8]], ['a', 'b'])
a [1, 2, 3, 4]
b ... | You can first convert DataFrame to numpy array by values, then convert to list and last create new Series with index from df if need faster solution:
print (pd.Series(df.values.tolist(), index=df.index))
a [1, 2, 3, 4]
b [5, 6, 7, 8]
dtype: object
Timings with small DataFrame:
In [76]: %timeit (pd.Series(df.valu... |
Understanding Keras LSTMs | I am trying to reconcile my understand of LSTMs and pointed out here: http://colah.github.io/posts/2015-08-Understanding-LSTMs/ with the LSTM implemented in Keras. I am following the blog written http://machinelearningmastery.com/time-series-prediction-lstm-recurrent-neural-networks-python-keras/ for the Keras tutorial... | First of all, you choose great tutorials(1,2) to start.
What Time-step means: Time-steps==3 in X.shape (Describing data shape) means there are three pink boxes. Since in Keras each step requires an input, therefore the number of the green boxes should usually equal to the number of red boxes. Unless you hack the struct... |
Returning string matches between two lists for a given number of elements in a third list | I've got a feeling that I will be told to go to the 'beginner's guide' or what have you but I have this code here that goes
does = ['my','mother','told','me','to','choose','the']
it = ['my','mother','told','me','to','choose','the']
work = []
while 5 > len(work):
for nope in it:
if nope in does:
... | You could try something like this:
for nope in it:
if len(work) < 5 and nope in does:
work.append(nope)
else:
break
The problem with your code is that it does the check of the work's length, after having looped through all the items of it and having added all of them that are in does.
|
How to make this Block of python code short and efficient | I am total newbie to programming and python. I was solving a problem. I found the solution but it seems like too slow.
if n % 2 == 0 and n % 3 == 0 and\
n % 4 == 0 and n % 5 == 0 and\
n % 6 == 0 and n % 7 == 0 and\
n % 8 == 0 and n % 9 == 0 and\
n % 10 == 0 and n % 11 == 0 and\
n ... | There's a trade-off between short and efficient.
The Short way is if all(n % i == 0 for i in range(2, 21)):
The Efficient way is to notice that things like n % 20 == 0 also mean that n % f == 0 where f is any factor of 20. For example, you can drop n % 2 == 0. So you'll end up with fewer comparisons which will run fast... |
Slow equality evaluation for identical objects (x == x) | Is there any reason x == x is not evaluated quickly? I was hoping __eq__ would check if its two arguments are identical, and if so return True instantly. But it doesn't do it:
s = set(range(100000000))
s == s # this doesn't short-circuit, so takes ~1 sec
For built-ins, x == x always returns True I think? For user-defi... | As you say, someone could quite easily define an __eq__ that you personally don't happen to approve of ... for example, the Institute of Electrical and Electronics Engineers might be so foolish as to do that:
>>> float("NaN") == float("NaN")
False
Another "unreasonable use case":
>>> bool(numpy.ma.masked == numpy.ma.m... |
Passing a "pointer to a virtual function" as argument in Python | Compare the following code in C++:
#include <iostream>
#include <vector>
struct A
{
virtual void bar(void) { std::cout << "one" << std::endl; }
};
struct B : public A
{
virtual void bar(void) { std::cout << "two" << std::endl; }
};
void test(std::vector<A*> objs, void (A::*fun)())
{
for (auto o = objs.begin();... | Regarding your edit, one thing you could do is use a little wrapper lambda that calls the method you want to reference. This way the method call looks like "regular python code" instead of being something complicated based on string-based access.
In your example, the only part that would need to change is the call to t... |
Convert float to string without scientific notation and false precision | I want to print some floating point numbers so that they're always written in decimal form (e.g. 12345000000000000000000.0 or 0.000000000000012345, not in scientific notation, yet I'd want to keep the 15.7 decimal digits of precision and no more.
It is well-known that the repr of a float is written in scientific notati... | Unfortunately it seems that not even the new-style formatting with float.__format__ supports this. The default formatting of floats is the same as with repr; and with f flag there are 6 fractional digits by default:
>>> format(0.0000000005, 'f')
'0.000000'
However there is a hack to get the desired result - not the f... |
How to Bind and Send from Google Cloud Forwarding Rule IP Address? | I've followed the instructions for Using Protocol Forwarding on the Google Cloud Platform. So I now have something like this:
$ gcloud compute forwarding-rules list
NAME REGION IP_ADDRESS IP_PROTOCOL TARGET
x-fr-1 us-west1 104.198.?.?? TCP us-west1-a/targetInstances/x-target-instance
x-fr-2 u... |
it's not in the local routing table ('ip route show table local')
[ you could of course add it (e.g. 'ip address add x.x.x.x/32 dev ens4'),
but doing so wouldn't do you much good, since no packets will be
delivered to your VM using that as the destination address - see
below... ]
because the forwarded addresses have b... |
Splitting a list into uneven groups? | I know how to split a list into even groups, but I'm having trouble splitting it into uneven groups.
Essentially here is what I have: some list, let's call it mylist, that contains x elements.
I also have another file, lets call it second_list, that looks something like this:
{2, 4, 5, 9, etc.}
Now what I want to do ... | You can create an iterator and itertools.islice:
mylist = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
seclist = [2,4,6]
from itertools import islice
it = iter(mylist)
sliced =[list(islice(it, 0, i)) for i in seclist]
Which would give you:
[[1, 2], [3, 4, 5, 6], [7, 8, 9, 10, 11, 12]]
Once i elements are consumed they a... |
How to optimize multiprocessing in Python | EDIT:
I've had questions about what the video stream is, so I will offer more clarity. The stream is a live video feed from my webcam, accessed via OpenCV. I get each frame as the camera reads it, and send it to a separate process for processing. The process returns text based on computations done on the image. The tex... |
I want my program to read in images from a video stream in the main process
In producer/consumer implementations, which is what you have above, the producer, what puts tasks into the queue to be executed by the consumers, needs to be separate from the main/controlling process so that it can add tasks in parallel with... |
Îpposite of any() function | The Python built-in function any(iterable) can help to quickly check if any bool(element) is True in a iterable type.
>>> l = [None, False, 0]
>>> any(l)
False
>>> l = [None, 1, 0]
>>> any(l)
True
But is there an elegant way or function in Python that could achieve the opposite effect of any(iterable)? That is, if any... | There is also the all function which does the opposite of what you want, it returns True if all are True and False if any are False. Therefore you can just do:
not all(l)
|
Debugging Python and C++ exposed by boost together | I can debug Python code using ddd -pydb prog.py. All the python command line arguments can be passed too after prog.py. In my case, many classes have been implemented in C++ that are exposed to python using boost-python. I wish I could debug python code and C++ together. For example I want to set break points like this... | I found out how to debug the C++ part while running python. (realized it while reading about process ID detection in Python book..).
First you run the python program which includes C++ programs. At the start of the python program, use raw_input() to make the program wait for you input. But just before that do print os.... |
TensorFlow REST Frontend but not TensorFlow Serving | I want to deploy a simple TensorFlow model and run it in REST service like Flask.
Did not find so far good example on github or here.
I am not ready to use TF Serving as suggested in other posts, it is perfect solution for Google but it overkill for my tasks with gRPC, bazel, C++ coding, protobuf...
| There are different ways to do this. Purely, using tensorflow is not very flexible, however relatively straightforward. The downside of this approach is that you have to rebuild the graph and initialize variables in the code where you restore the model. There is a way shown in tensorflow skflow/contrib learn which is m... |
Compute first order derivative with MongoDB aggregation framework | Is it possible to calculate a first order derivative using the aggregate framework?
For example, I have the data :
{time_series : [10,20,40,70,110]}
I'm trying to obtain an output like:
{derivative : [10,20,30,40]}
| We can do this using the aggregation framework in MongoDB 3.2 or newer because what we really need is a way to keep tracking of the index of the current and previous element in our array and fortunately starting from MongoDB 3.2 we can use the $unwind operator to deconstruct our array and include the index of each elem... |
How to keep track of players' rankings? | I have a Player class with a score attribute:
class Player(game_engine.Player):
def __init__(self, id):
super().__init__(id)
self.score = 0
This score increases/decreases as the player succeeds/fails to do objectives. Now I need to tell the player his rank out of the total amount of players with s... | Redis sorted sets help with this exact situation (the documentation uses leader boards as the example usage) http://redis.io/topics/data-types-intro#redis-sorted-sets
The key commands you care about are ZADD (update player rank) and ZRANK (get rank for specific player). Both operations are O(log(N)) complexity.
Redis... |
Active tasks is a negative number in Spark UI | When using spark-1.6.2 and pyspark, I saw this:
where you see that the active tasks are a negative number (the difference of the the total tasks from the completed tasks).
What is the source of this error?
Node that I have many executors. However, it seems like there is a task that seems to have been idle (I don't se... | It is a Spark issue. It occurs when executors restart after failures. The JIRA issue for the same is already created. You can get more details about the same from https://issues.apache.org/jira/browse/SPARK-10141 link.
|
Remove first encountered elements from a list | I have two Python lists with the same number of elements. The elements of the first list are unique, the ones in the second list - not necessarily so. For instance
list1 = ['e1', 'e2', 'e3', 'e4', 'e5', 'e6', 'e7']
list2 = ['h1', 'h2', 'h1', 'h3', 'h1', 'h2', 'h4']
I want to remove all the "first encountered" elements... | Just use a set object to lookup if the current value is already seen, like this
>>> list1 = ['e1', 'e2', 'e3', 'e4', 'e5', 'e6', 'e7']
>>> list2 = ['h1', 'h2', 'h1', 'h3', 'h1', 'h2', 'h4']
>>>
>>> def filterer(l1, l2):
... r1 = []
... r2 = []
... seen = set()
... for e1, e2 in zip(l1, l2):
... ... |
Text based data format which supports multiline strings | I search a text based data format which supports multiline strings.
JSON does not allow multiline strings:
>>> import json
>>> json.dumps(dict(text='first line\nsecond line'))
'{"text": "first line\\nsecond line"}'
My desired output:
{"text": "first line
second line"}
This question is about input and output. The data... | I think you should consider YAML format. It supports block notation which is able to preserve newlines like this
data: |
There once was a short man from Ealing
Who got on a bus to Darjeeling
It said on the door
"Please don't spit on the floor"
So he carefully spat on the ceiling
Also there is a ... |
Function chaining in Python | On codewars.com I encountered the following task:
Create a function add that adds numbers together when called in succession. So add(1) should return 1, add(1)(2) should return 1+2, ...
While I'm familiar with the basics of Python, I've never encountered a function that is able to be called in such succession, i.e. a... | I don't know whether this is function chaining as much as it's callable chaining, but, since functions are callables I guess there's no harm done. Either way, there's two ways I can think of doing this:
Sub-classing int and defining __call__:
The first way would be with a custom int subclass that defines __call__ which... |
How can I slice each element of a numpy array of strings? | Numpy has some very useful string operations, which vectorize the usual Python string operations.
Compared to these operation and to pandas.str, the numpy strings module seems to be missing a very important one: the ability to slice each string in the array. For example,
a = numpy.array(['hello', 'how', 'are', 'you'])
... | Here's a vectorized approach -
def slicer_vectorized(a,start,end):
b = a.view('S1').reshape(len(a),-1)[:,start:end]
return np.fromstring(b.tostring(),dtype='S'+str(end-start))
Sample run -
In [68]: a = np.array(['hello', 'how', 'are', 'you'])
In [69]: slicer_vectorized(a,1,3)
Out[69]:
array(['el', 'ow', 're'... |
Coding style (PEP8) - Module level "dunders" | Definition of "Dunder" (Double underscore): http://www.urbandictionary.com/define.php?term=Dunder
I have a question according the placement of module level "dunders" (like __all__, __version__, __author__ etc.) in Python code.
The question came up to me while reading through PEP8 and seeing this Stack Overflow questio... | PEP 8 recently was updated to put the location before the imports. See revision cf8e888b9555, committed on June 7th, 2016:
Relax __all__ location.
Put all module level dunders together in the same location, and remove
the redundant version bookkeeping information.
Closes #27187. Patch by Ian Lee.
The text was furt... |
NumPy performance: uint8 vs. float and multiplication vs. division? | I have just noticed that the execution time of a script of mine nearly halves by only changing a multiplication to a division.
To investigate this, I have written a small example:
import numpy as np ... | The problem is your assumption, that you measure the time needed for division or multiplication, which is not true. You are measuring the overhead needed for a division or multiplication.
One has really to look at the exact code to explain every effect, which can vary from version to version. This answer can only give... |
Matching Unicode word boundaries in Python | In order to match the Unicode word boundaries [as defined in the Annex #29] in Python, I have been using the regex package with flags regex.WORD | regex.V1 (regex.UNICODE should be default since the pattern is a Unicode string) in the following way:
>>> s="here are some words"
>>> regex.findall(r'\w(?:\B\S)*', s, flags... | 1- RIGHT SINGLE QUOTATION MARK â seems to be just simply missed in source file:
/* Break between apostrophe and vowels (French, Italian). */
/* WB5a */
if (pos_m1 >= 0 && char_at(state->text, pos_m1) == '\'' &&
is_unicode_vowel(char_at(state->text, text_pos)))
return TRUE;
2- Unicode vowels are determined wit... |
Imported a Python module; why does a reassigning a member in it also affect an import elsewhere? | I am seeing Python behavior that I don't understand. Consider this layout:
project
| main.py
| test1.py
| test2.py
| config.py
main.py:
import config as conf
import test1
import test2
print(conf.test_var)
test1.test1()
print(conf.test_var)
test2.test2()
test1.py:
import config as conf
def test1():
conf.... | Python caches imported modules. The second import call doesn't reload the file.
|
How to get a python script to invoke "python -i" when called normally? | I have a python script that I like to run with python -i script.py, which runs the script and then enters interactive mode so that I can play around with the results.
Is it possible to have the script itself invoke this option, such that I can just run python script.py and the script will enter interactive mode after r... | From within script.py, set the PYTHONINSPECT environment variable to any nonempty string. Python will recheck this environment variable at the end of the program and enter interactive mode.
import os
# This can be placed at top or bottom of the script, unlike code.interact
os.environ['PYTHONINSPECT'] = 'TRUE'
|
interactive conditional histogram bucket slicing data visualization | I have a df that looks like:
df.head()
Out[1]:
A B C
city0 40 12 73
city1 65 56 10
city2 77 58 71
city3 89 53 49
city4 33 98 90
An example df can be created by the following code:
df = pd.DataFrame(np.random.randint(100,size=(1000000,3)), columns=list('ABC'))
indx = ['city'+str(x) for... | In order to get the interaction effect you're looking for, you must bin all the columns you care about, together.
The cleanest way I can think of doing this is to stack into a single series then use pd.cut
Considering your sample df
df_ = pd.cut(df[['A', 'B']].stack(), 5, labels=list(range(5))).unstack()
df_.columns =... |
Better way to swap elements in a list? | I have a bunch of lists that look like this one:
l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
I want to swap elements as follows:
final_l = [2, 1, 4, 3, 6, 5, 8, 7, 10, 9]
The size of the lists may vary, but they will always contain an even number of elements.
I'm fairly new to Python and am currently doing it like this:
l = ... | No need for complicated logic, simply rearrange the list with slicing and step:
In [1]: l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
In [2]: l[::2], l[1::2] = l[1::2], l[::2]
In [3]: l
Out[3]: [2, 1, 4, 3, 6, 5, 8, 7, 10, 9]
 TLDR;
Edited with explanation
I believe most viewers are already familiar with list slicing and mu... |
Can a line of Python code know its indentation nesting level? | From something like this:
print(get_indentation_level())
print(get_indentation_level())
print(get_indentation_level())
I would like to get something like this:
1
2
3
Can the code read itself in this way?
All I want is the output from the more nested parts of the code to be more nested. In the same way t... | If you want indentation in terms of nesting level rather than spaces and tabs, things get tricky. For example, in the following code:
if True:
print(
get_nesting_level())
the call to get_nesting_level is actually nested one level deep, despite the fact that there is no leading whitespace on the line of the get_nes... |
Find all n-dimensional lines and diagonals with NumPy | Using NumPy, I would like to produce a list of all lines and diagonals of an n-dimensional array with lengths of k.
Take the case of the following three-dimensional array with lengths of three.
array([[[ 0, 1, 2],
[ 3, 4, 5],
[ 6, 7, 8]],
[[ 9, 10, 11],
[12, 13, 14],
[15, ... | This solution generalized over n
Lets rephrase this problem as "find the list of indices".
We're looking for all of the 2d index arrays of the form
array[i[0], i[1], i[2], ..., i[n-1]]
Let n = arr.ndim
Where i is an array of shape (n, k)
Each of i[j] can be one of:
The same index repeated n times, ri[j] = [j, ..., j]... |
How `[System.Console]::OutputEncoding/InputEncoding` with Python? | Under Powershell v5, Windows 8.1, Python 3. Why these fails and how to fix?
[system.console]::InputEncoding = [System.Text.Encoding]::UTF8;
[system.console]::OutputEncoding = [System.Text.Encoding]::UTF8;
chcp;
"import sys
print(sys.stdout.encoding)
print(sys.stdin.encoding)
sys.stdout.write(sys.stdin.readline())
" ... | You are piping data into Python; at that point Python's stdin is no longer attached to a TTY (your console) and won't guess at what the encoding might be. Instead, the default system locale is used; on your system that's cp1251 (the Windows Latin-1-based codepage).
Set the PYTHONIOENCODING environment variable to overr... |
How to subclass list and trigger an event whenever the data change? | I would like to subclass list and trigger an event (data checking) every time any change happens to the data. Here is an example subclass:
class MyList(list):
def __init__(self, sequence):
super().__init__(sequence)
self._test()
def __setitem__(self, key, value):
super().__setitem__(key... | As you say, this is not the best way to go about it. To correctly implement this, you'd need to know about every method that can change the list.
The way to go is to implement your own list (or rather a mutable sequence). The best way to do this is to use the abstract base classes from Python which you find in the coll... |
Why does list(next(iter(())) for _ in range(1)) == []? | Why does list(next(iter(())) for _ in range(1)) return an empty list rather than raising StopIteration?
>>> next(iter(()))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
>>> [next(iter(())) for _ in range(1)]
Traceback (most recent call last):
File "<stdin>", line 1, in <module... | assuming all goes well, the generator comprehension x() for _ in range(1) should raise StopIteration when it is finished iterating over range(1) to indicate that there are no more items to pack into the list.
However because x() raises StopIteration it ends up exiting early meaning this behaviour is a bug in python tha... |
Build 2 lists in one go while reading from file, pythonically | I'm reading a big file with hundreds of thousands of number pairs representing the edges of a graph. I want to build 2 lists as I go: one with the forward edges and one with the reversed.
Currently I'm doing an explicit for loop, because I need to do some pre-processing on the lines I read. However, I'm wondering if t... | I would keep your logic as it is the Pythonic approach just not split/rstrip the same line multiple times:
with open('SCC.txt') as data:
for line in data:
spl = line.split()
if spl:
i, j = map(int, spl)
edge_list.append((i, j))
reversed_edge_list.append((j, i))
C... |
How to parse an HTML table with rowspans in Python? | The problem
I'm trying to parse an HTML table with rowspans in it, as in, I'm trying to parse my college schedule.
I'm running into the problem where if the last row contains a rowspan, the next row is missing a TD where the rowspan is now that TD that is missing.
I have no clue how to account for this and I hope to be... | You'll have to track the rowspans on previous rows, one per column.
You could do this simply by copying the integer value of a rowspan into a dictionary, and subsequent rows decrement the rowspan value until it drops to 1 (or we could store the integer value minus 1 and drop to 0 for ease of coding). Then you can adjus... |
Is there any reason for giving self a default value? | I was browsing through some code, and I noticed a line that caught my attention. The code is similar to the example below
class MyClass:
def __init__(self):
pass
def call_me(self=''):
print(self)
This looks like any other class that I have seen, however a str is being passed in as default valu... | Not really, it's just an odd way of making it not raise an error when called via the class:
MyClass.call_me()
works fine since, even though nothing is implicitly passed as with instances, the default value for that argument is provided. If no default was provided, when called, this would of course raise the TypeError ... |
Why is ''.join() faster than += in Python? | I'm able to find a bevy of information online (on Stack Overflow and otherwise) about how it's a very inefficient and bad practice to use + or += for concatenation in Python.
I can't seem to find WHY += is so inefficient. Outside of a mention here that "it's been optimized for 20% improvement in certain cases" (still n... | Let's say you have this code to build up a string from three strings:
x = 'foo'
x += 'bar' # 'foobar'
x += 'baz' # 'foobarbaz'
In this case, Python first needs to allocate and create 'foobar' before it can allocate and create 'foobarbaz'.
So for each += that gets called, the entire contents of the string and whateve... |
Mimicing glib.spawn_async with Popen⦠| The function glib.spawn_async allows you to hook three callbacks which are called on event on stdout, stderr, and on process completion.
How can I mimic the same functionality with subprocess with either threads or asyncio?
I am more interested in the functionality rather than threading/asynio but an answer that contai... | asyncio has subprocess_exec, there is no need to use the subprocess module at all:
import asyncio
class Handler(asyncio.SubprocessProtocol):
def pipe_data_received(self, fd, data):
# fd == 1 for stdout, and 2 for stderr
print("Data from /bin/ls on fd %d: %s" % (fd, data.decode()))
def pipe_con... |
Why does Python's set difference method take time with an empty set? | Here is what I mean:
> python -m timeit "set().difference(xrange(0,10))"
1000000 loops, best of 3: 0.624 usec per loop
> python -m timeit "set().difference(xrange(0,10**4))"
10000 loops, best of 3: 170 usec per loop
Apparently python iterates through the whole argument, even if the result is known to be the empty ... | IMO it's a matter of specialisation, consider:
In [18]: r = range(10 ** 4)
In [19]: s = set(range(10 ** 4))
In [20]: %time set().difference(r)
CPU times: user 387 µs, sys: 0 ns, total: 387 µs
Wall time: 394 µs
Out[20]: set()
In [21]: %time set().difference(s)
CPU times: user 10 µs, sys: 8 µs, total: 18 µs
Wall... |
How do I make a custom model Field call to_python when the field is accessed immediately after initialization (not loaded from DB) in Django >=1.10? | After upgrading from Django 1.9 to 1.10, I've experienced a change in behaviour with a field provided by the django-geolocation package.
This is the change that was made for 1.10 compatibility that broke the behaviour: https://github.com/philippbosch/django-geoposition/commit/689ff1651a858d81b2d82ac02625aae8a125b9c9
Pr... | After lots of digging it turns out that in 1.8 the behaviour of custom fields was changed in such a way that to_python is no longer called on assignment to a field.
https://docs.djangoproject.com/en/1.10/releases/1.8/#subfieldbase
The new approach doesnât call the to_python() method on assignment as was the case wit... |
When should I use list.count(0), and how do I to discount the "False" item? | a.count(0) always returns 11, so what should I do to discount the False and return 10?
a = ["a",0,0,"b",None,"c","d",0,1,False,0,1,0,3,[],0,1,9,0,0,{},0,0,9]
| Python 2.x interprets False as 0 and vice versa. AFAIK even None and "" can be considered False in conditions.
Redefine count as follows:
sum(1 for item in a if item == 0 and type(item) == int)
or (Thanks to Kevin, and Bakuriu for their comments):
sum(1 for item in a if item == 0 and type(item) is type(0))
or as ... |
How to traverse cyclic directed graphs with modified DFS algorithm | OVERVIEW
I'm trying to figure out how to traverse directed cyclic graphs using some sort of DFS iterative algorithm. Here's a little mcve version of what I currently got implemented (it doesn't deal with cycles):
class Node(object):
def __init__(self, name):
self.name = name
def start(self):
p... | Before I start, Run the code on CodeSkulptor! I also hope that the comments elaborate what I have done enough. If you need more explanation, look at my explanation of the recursive approach below the code.
# If you don't want global variables, remove the indentation procedures
indent = -1
MAX_THRESHOLD = 10
INF = 1 <<... |
What's the closest I can get to calling a Python function using a different Python version? | Say I have two files:
# spam.py
import library_Python3_only as l3
def spam(x,y)
return l3.bar(x).baz(y)
and
# beans.py
import library_Python2_only as l2
...
Now suppose I wish to call spam from within beans. It's not directly possible since both files depend on incompatible Python versions. Of course I can Pope... | Here is a complete example implementation using subprocess and pickle that I actually tested. Note that you need to use protocol version 2 explicitly for pickling on the Python 3 side (at least for the combo Python 3.5.2 and Python 2.7.3).
# py3bridge.py
import sys
import pickle
import importlib
import io
import trace... |
How to break conversation data into pairs of (Context , Response) | I'm using Gensim Doc2Vec model, trying to cluster portions of a customer support conversations. My goal is to give the support team an auto response suggestions.
Figure 1: shows a sample conversations where the user question is answered in the next conversation line, making it easy to extract the data:
during the con... | To train a model I would start by concatenating consecutive sequences of messages. What I would do is, using the timestamps, concatenate the messages without any message in between from the other entity.
For instance:
Hello
I have a problem
I cannot install software X
Hi
... |
How do you organise a python project that contains multiple packages so that each file in a package can still be run individually? | TL;DR
Here's an example repository that is set up as described in the first diagram (below): https://github.com/Poddster/package_problems
If you could please make it look like the second diagram in terms of project organisation and can still run the following commands, then you've answered the question:
$ git clone htt... | Once you move to your desired configuration, the absolute imports you are using to load the modules that are specific to my_tool no longer work.
You need three modifications after you create the my_tool subdirectory and move the files into it:
Create my_tool/__init__.py. (You seem to already do this but I wanted to me... |
ImportError: cannot import name 'QtCore' | I am getting the below error with the following imports.
It seems to be related to pandas import. I am unsure how to debug/solve this.
Imports:
import pandas as pd
import numpy as np
import pdb, math, pickle
import matplotlib.pyplot as plt
Error:
In [1]: %run NN.py
-----------------------------------------------------... | Downgrading pyqt version 5.6.0 to 4.11.4, and qt from version 5.6.0 to 4.8.7 fixes this:
$ conda install pyqt=4.11.4
$ conda install qt=4.8.7
The issue itself is being resolved here: https://github.com/ContinuumIO/anaconda-issues/issues/1068
|
Remove the first N items that match a condition in a Python list | If I have a function matchCondition(x), how can I remove the first n items in a Python list that match that condition?
One solution is to iterate over each item, mark it for deletion (e.g., by setting it to None), and then filter the list with a comprehension. This requires iterating over the list twice and mutates the... | One way using itertools.filterfalse and itertools.count:
from itertools import count, filterfalse
data = [1, 10, 2, 9, 3, 8, 4, 7]
output = filterfalse(lambda L, c=count(): L < 5 and next(c) < 3, data)
Then list(output), gives you:
[10, 9, 8, 4, 7]
|
Short-circuit evaluation like Python's "and" while storing results of checks | I have multiple expensive functions that return results. I want to return a tuple of the results of all the checks if all the checks succeed. However, if one check fails I don't want to call the later checks, like the short-circuiting behavior of and. I could nest if statements, but that will get out of hand if ther... | Just use a plain old for loop:
results = {}
for function in [check_a, check_b, ...]:
results[function.__name__] = result = function()
if not result:
break
The results will be a mapping of the function name to their return values, and you can do what you want with the values after the loop breaks.
Use... |
Why does the floating-point value of 4*0.1 look nice in Python 3 but 3*0.1 doesn't? | I know that most decimals don't have an exact floating point representation (Is floating point math broken?).
But I don't see why 4*0.1 is printed nicely as 0.4, but 3*0.1 isn't, when
both values actually have ugly decimal representations:
>>> 3*0.1
0.30000000000000004
>>> 4*0.1
0.4
>>> from decimal import Decimal
>>> ... | The simple answer is because 3*0.1 != 0.3 due to quantization (roundoff) error (whereas 4*0.1 == 0.4 because multiplying by a power of two is usually an "exact" operation).
You can use the .hex method in Python to view the internal representation of a number (basically, the exact binary floating point value, rather tha... |
Python vectorizing nested for loops | I'd appreciate some help in finding and understanding a pythonic way to optimize the following array manipulations in nested for loops:
def _func(a, b, radius):
"Return 0 if a>b, otherwise return 1"
if distance.euclidean(a, b) < radius:
return 1
else:
return 0
def _make_mask(volume, roi, ra... | Approach #1
Here's a vectorized approach -
m,n,r = volume.shape
x,y,z = np.mgrid[0:m,0:n,0:r]
X = x - roi[0]
Y = y - roi[1]
Z = z - roi[2]
mask = X**2 + Y**2 + Z**2 < radius**2
Possible improvement : We can probably speedup the last step with numexpr module -
import numexpr as ne
mask = ne.evaluate('X**2 + Y**2 + Z**... |
Not nesting version of @atomic() in Django? | From the docs of atomic()
atomic blocks can be nested
This sound like a great feature, but in my use case I want the opposite: I want the transaction to be durable as soon as the block decorated with @atomic() gets left successfully.
Is there a way to ensure durability in django's transaction handling?
Background
Tra... | You can't do that through any API.
Transactions can't be nested while retaining all ACID properties, and not all databases support nested transactions.
Only the outermost atomic block creates a transaction. Inner atomic blocks create a savepoint inside the transaction, and release or roll back the savepoint when exitin... |
PYTHONPATH order on Ubuntu 14.04 | I have two computers running Ubuntu 14.04 server (let's call them A and B). B was initially a 10.04 but it has received two upgrades to 12.04 and 14.04. I do not understand why the python path is different on the two computers.
As you can see on the two paths below, the pip installation path /usr/local/lib/python2.7/di... | As we cannot explore into your system, I am trying to analysis your first question by illustrating how sys.path is initialized. Available references are where-does-sys-path-starts and pyco-reverse-engineering(python2.6).
The sys.path comes from the following variables(in order):
$PYTHONPATH (highest priority)
sys.pref... |
Re-compose a Tensor after tensor factorization | I am trying to decompose a 3D matrix using python library scikit-tensor. I managed to decompose my Tensor (with dimensions 100x50x5) into three matrices. My question is how can I compose the initial matrix again using the decomposed matrix produced with Tensor factorization? I want to check if the decomposition has any... | The CP product of, for example, 4 matrices
can be expressed using Einstein notation as
or in numpy as
numpy.einsum('az,bz,cz,dz -> abcd', A, B, C, D)
so in your case you would use
numpy.einsum('az,bz->ab', P.U[0], P.U[1])
or, in your 3-matrix case
numpy.einsum('az,bz,cz->abc', P.U[0], P.U[1], P.U[2])
sktensor.kten... |
How to get lineno of "end-of-statement" in Python ast | I am trying to work on a script that manipulates another script in Python, the script to be modified has structure like:
class SomethingRecord(Record):
description = 'This records something'
author = 'john smith'
I use ast to locate the description line number, and I use some code to change the original file w... | I looked at the other answers; it appears people are doing backflips to get around the problems of computing line numbers, when your real problem is one of modifying the code. That suggests the baseline machinery is not helping you the way you really need.
If you use a program transformation system (PTS), you could a... |
Python button functions oddly not doing the same | I currently have 2 buttons hooked up to my Raspberry Pi (these are the ones with ring LED's in them) and I'm trying to perform this code
#!/usr/bin/env python
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(17, GPIO.OUT) #green LED
GPIO.setup(18, GPIO.OUT) #red LED
GPIO.se... | I was able to reproduce your problem on my Raspberry Pi 1, Model B by running your script and connecting a jumper cable between ground and GPIO27 to simulate red button presses. (Those are pins 25 and 13 on my particular Pi model.)
The python interpreter is crashing with a Segmentation Fault in the thread dedicated ... |
Regular Expression Matching First Non-Repeated Character | TL;DR
re.search("(.)(?!.*\1)", text).group() doesn't match the first non-repeating character contained in text (it always returns a character at or before the first non-repeated character, or before the end of the string if there are no non-repeated characters. My understanding is that re.search() should return None if... | Well let's take your tooth example - here is what the regex-engine does (a lot simplified for better understanding)
Start with t then look ahead in the string - and fail the lookahead, as there is another t.
tooth
^ °
Next take o, look ahead in the string - and fail, as there is another o.
tooth
^°
Next take the ... |
How to use the `pos` argument in `networkx` to create a flowchart-style Graph? (Python 3) | I am trying create a linear network graph using Python (preferably with matplotlib and networkx although would be interested in bokeh) similar in concept to the one below.
How can this graph plot be constructed efficiently (pos?) in Python using networkx? I want to use this for more complicated examples so I feel t... | Networkx has decent plotting facilities for exploratory data
analysis, it is not the tool to make publication quality figures,
for various reason that I don't want to go into here. I hence
rewrote that part of the code base from scratch, and made a
stand-alone drawing module called netgraph that can be found
here (lik... |
Stuck implementing simple neural network | I've been bashing my head against this brick wall for what seems like an eternity, and I just can't seem to wrap my head around it. I'm trying to implement an autoencoder using only numpy and matrix multiplication. No theano or keras tricks allowed.
I'll describe the problem and all its details. It is a bit complex at ... | OK, here's a suggestion. In the vector case, if you have x as a vector of length n, then g(x) is also a vector of length n. However, g'(x) is not a vector, it's the Jacobian matrix, and will be of size n X n. Similarly, in the minibatch case, where X is a matrix of size m X n, g(X) is m X n but g'(X) is n X n. Try:... |
cryptography AssertionError: sorry, but this version only supports 100 named groups | I'm installing several python packages via pip install on travis,
language: python
python:
- '2.7'
install:
- pip install -r requirements/env.txt
Everything worked fine, but today I started getting following error:
Running setup.py install for cryptography
Traceback (most recent call last):
File "<string>", line 1... | There is a bug with PyCParser - See https://github.com/pyca/cryptography/issues/3187
The work around is to use another version or to not use the binary distribution.
pip install git+https://github.com/eliben/pycparser@release_v2.14
or
pip install --no-binary pycparser
|
How does one add an item to GTK's "recently used" file list from Python? | I'm trying to add to the "recently used" files list from Python 3 on Ubuntu.
I am able to successfully read the recently used file list like this:
from gi.repository import Gtk
recent_mgr = Gtk.RecentManager.get_default()
for item in recent_mgr.get_items():
print(item.get_uri())
This prints out the same list of fi... | A Gtk.RecentManager needs to emit the changed signal for the update to be written in a private attribute of the C++ class. To use a RecentManager object in an application, you need to start the event loop by calling Gtk.main:
from gi.repository import Gtk
recent_mgr = Gtk.RecentManager.get_default()
uri = r'file:/path... |
How to make an integer larger than any other integer? | Note: while the accepted answer achieves the result I wanted, and @ecatmur answer provides a more comprehensive option, I feel it's very important to emphasize that my use case is a bad idea in the first place. This is explained very well in @Jason Orendorff answer below.
Note: this question is not a duplicate of the q... | Since python integers are unbounded, you have to do this with a custom class:
import functools
@functools.total_ordering
class NeverSmaller(object):
def __le__(self, other):
return False
class ReallyMaxInt(NeverSmaller, int):
def __repr__(self):
return 'ReallyMaxInt()'
Here I've used a mix-in... |
Is there a more Pythonic way to combine an Else: statement and an Except:? | I have a piece of code that searches AutoCAD for text boxes that contain certain keywords (eg. "overall_weight" in this case) and replaces it with a value from a dictionary. However, sometimes the dictionary key is assigned to an empty string and sometimes, the key doesn't exist altogether. In these cases, the "overall... | Use dict.get() which will return the value associated with the given key if it exists otherwise None. (Note that '' and None are both falsey values.) If s is true then assign it to nObject.TextString otherwise give it a value of "N/A".
if nObject.TextString == "overall_weight":
nObject.TextString = self.var.jobDeta... |
Is there a way to compile python application into static binary? | What I'm trying to do is ship my code to a remote server, that may have different python version installed and/or may not have packages my app requires.
Right now to achieve such portability I have to build relocatable virtualenv with interpreter and code. That approach has some issues (for example, you have to manuall... | There are two ways you could go about to solve your problem
Use a static builder, like freeze, or pyinstaller, or py2exe
Compile using cython
I will explain how you can go about doing it using the second, since the first method is not cross platform and version, and has been explained in other answers. Also, using pr... |
What are variable annotations in Python 3.6? | Python 3.6 is about to be released. PEP 494 -- Python 3.6 Release Schedule mentions the end of December, so I went through What's New in Python 3.6 to see they mention the variable annotations:
PEP 484 introduced standard for type annotations of function parameters, a.k.a. type hints. This PEP adds syntax to Python fo... | Everything between : and the = is a type hint, so primes is indeed defined as List[int], and initially set to an empty list (and stats is an empty dictionary initially, defined as Dict[str, int]).
List[int] and Dict[str, int] are not part of the next syntax however, these were already defined in the Python 3.5 typing h... |
Dictionaries are ordered in Python 3.6 | Dictionaries are ordered in Python 3.6, unlike in previous Python incarnations. This seems like a substantial change, but it's only a short paragraph in the documentation. It is described as an implementation detail rather than a language feature, but also implies this may become standard in the future.
How does the Py... |
How does the Python 3.6 dictionary implementation perform better than the older one while preserving element order?
Essentially by keeping two arrays, one holding the entries for the dictionary in the order that they were inserted and the other holding a list of indices.
In the previous implementation a sparse array ... |
Why does map return a map object instead of a list in Python 3? | I am interested in understanding the new language design of Python 3.x.
I do enjoy, in Python 2.7, the function map:
Python 2.7.12
In[2]: map(lambda x: x+1, [1,2,3])
Out[2]: [2, 3, 4]
However, in Python 3.x things have changed:
Python 3.5.1
In[2]: map(lambda x: x+1, [1,2,3])
Out[2]: <map at 0x4218390>
I understand th... | Because it returns an iterator, it omit storing the full list in the memory. So that you can easily iterate over it in the future not making pain to memory. Possibly you even don't need a full list, but the part of it, until your condition is matched.
You can find this docs useful, because iterators are awesome.
An ob... |
list() uses more memory than list comprehension | So i was playing with list objects and found little strange thing that if list is created with list() it uses more memory, than list comprehension? I'm using Python 3.5.2
In [1]: import sys
In [2]: a = list(range(100))
In [3]: sys.getsizeof(a)
Out[3]: 1008
In [4]: b = [i for i in range(100)]
In [5]: sys.getsizeof(b)
Ou... | I think you're seeing over-allocation patterns this is a sample from the source:
/* This over-allocates proportional to the list size, making room
* for additional growth. The over-allocation is mild, but is
* enough to give linear-time amortized behavior over a long
* sequence of appends() in the presence of a poo... |
Removing elements from an array that are in another array | Say I have these 2D arrays A and B.
How can I remove elements from A that are in B.
A=np.asarray([[1,1,1], [1,1,2], [1,1,3], [1,1,4]])
B=np.asarray([[0,0,0], [1,0,2], [1,0,3], [1,0,4], [1,1,0], [1,1,1], [1,1,4]])
#output = [[1,1,2], [1,1,3]]
To be more precise, I would like to do something like this.
data = some nump... | Here is a Numpythonic approach with broadcasting:
In [83]: A[np.all(np.any((A-B[:, None]), axis=2), axis=0)]
Out[83]:
array([[1, 1, 2],
[1, 1, 3]])
Here is a timeit with other answer:
In [90]: def cal_diff(A, B):
....: A_rows = A.view([('', A.dtype)] * A.shape[1])
....: B_rows = B.view([('', B.dt... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.