instruction
stringlengths
12
148
input
stringlengths
16
30.2k
output
stringlengths
11
27.3k
takeOrdered descending Pyspark
i would like to sort K/V pairs by values and then take the biggest five values. I managed to do this with reverting K/V with first map, sort in descending order with FALSE, and then reverse key.value to the original (second map) and then take the first 5 that are the bigget, the code is this: RDD.map(lambda x:(x[1],x[0...
Sort by keys (ascending): RDD.takeOrdered(5, key = lambda x: x[0]) Sort by keys (descending): RDD.takeOrdered(5, key = lambda x: -x[0]) Sort by values (ascending): RDD.takeOrdered(5, key = lambda x: x[1]) Sort by values (descending): RDD.takeOrdered(5, key = lambda x: -x[1])
Test if dict contained in dict
Testing for equality works fine like this for python dicts: first = {"one":"un", "two":"deux", "three":"trois"} second = {"one":"un", "two":"deux", "three":"trois"} print(first == second) # Result: True But now my second dict contains some additional keys I want to ignore: first = {"one":"un", "two":"deux", "three"...
You can use a dictionary view: # Python 2 if first.viewitems() <= second.viewitems(): # true only if `first` is a subset of `second` # Python 3 if first.items() <= second.items(): # true only if `first` is a subset of `second` Dictionary views are the standard in Python 3, in Python 2 you need to prefix the s...
What does this: s[s[1:] == s[:-1]] do in numpy?
I've been looking for a way to efficiently check for duplicates in a numpy array and stumbled upon a question that contained an answer using this code. What does this line mean in numpy? s[s[1:] == s[:-1]] Would like to understand the code before applying it. Looked in the Numpy doc but had trouble finding this inform...
The slices [1:] and [:-1] mean all but the first and all but the last elements of the array: >>> import numpy as np >>> s = np.array((1, 2, 2, 3)) # four element array >>> s[1:] array([2, 2, 3]) # last three elements >>> s[:-1] array([1, 2, 2]) # first three elements therefore the comparison generates an array of ...
Multiprocessing IOError: bad message length
I get an IOError: bad message length when passing large arguments to the map function. How can I avoid this? The error occurs when I set N=1500 or bigger. The code is: import numpy as np import multiprocessing def func(args): i=args[0] images=args[1] print i return 0 N=1500 #N=1000 works fine i...
You're creating a pool and sending all the images at once to func(). If you can get away with working on a single image at once, try something like this, which runs to completion with N=10000 in 35s with Python 2.7.10 for me: import numpy as np import multiprocessing def func(args): i = args[0] img = args[1] ...
How to get the index of an integer from a list if the list contains a boolean?
I am just starting with Python. How to get index of integer 1 from a list if the list contains a boolean True object before the 1? >>> lst = [True, False, 1, 3] >>> lst.index(1) 0 >>> lst.index(True) 0 >>> lst.index(0) 1 I think Python considers 0 as False and 1 as True in the argument of the index method. How can I g...
The documentation says that Lists are mutable sequences, typically used to store collections of homogeneous items (where the precise degree of similarity will vary by application). You shouldn't store heterogeneous data in lists. The implementation of list.index only performs the comparison using Py_EQ (== opera...
Django DRF with oAuth2 using DOT (django-oauth-toolkit)
I am trying to make DRF work with oAuth2 (django-oauth-toolkit). I was focusing on http://httplambda.com/a-rest-api-with-django-and-oauthw-authentication/ First I followed that instruction, but later, after getting authentication errors, I setup this demo: https://github.com/felix-d/Django-Oauth-Toolkit-Python-Social-A...
I have tried demo you mentioned and everything was fine. $ curl -X POST -d "grant_type=password&username=superuser&assword=123qwe" -u"xLJuHBcdgJHNuahvER9pgqSf6vcrlbkhCr75hTCZ:nv9gzOj0BMf2cdxoxsnYZuRYTK5QwpKWiZc7USuJpm11DNtSE9X6Ob9KaVTKaQqeyQZh4KF3oZS4IJ7o9n4amzfqKJnoL7a2tYQiWgtYPSQpY6VKFjEazcqSacqTx9z8" http://127.0.0....
Installing new versions of Python on Cygwin does not install Pip?
While I am aware of the option of installing Pip from source, I'm trying to avoid going down that path so that updates to Pip will be managed by Cygwin's package management. I've recently learned that the latest versions of Python include Pip. However, even though I have recently installed the latest versions of Pytho...
cel self-answered this question in a comment above. For posterity, let's convert this helpfully working solution into a genuine answer. Unfortunately, Cygwin currently fails to: Provide pip, pip2, or pip3 packages. Install the pip and pip2 commands when the python package is installed. Install the pip3 command when th...
Creating deb or rpm with setuptools - data_files
I have a Python 3 project. MKC ├── latex │ ├── macros.tex │ └── main.tex ├── mkc │ ├── cache.py │ ├── __init__.py │ └── __main__.py ├── README.md ├── setup.py └── stdeb.cfg On install, I would like to move my latex files to known directory...
When creating a deb file (I guess the same counts for a rpm file), ./setup.py --command-packages=stdeb.command bdist_deb first creates a source distribution and uses that archive for further processing. But your LaTeX files are not included there, so they're not found. You need to add them to the source package. Such c...
Pandas: Add multiple empty columns to DataFrame
This may be a stupid question, but how do I add multiple empty columns to a DataFrame from a list? I can do: df["B"] = None df["C"] = None df["D"] = None But I can't do: df[["B", "C", "D"]] = None KeyError: "['B' 'C' 'D'] not in index"
You could use df.reindex to add new columns: In [18]: df = pd.DataFrame(np.random.randint(10, size=(5,1)), columns=['A']) In [19]: df Out[19]: A 0 4 1 7 2 0 3 7 4 6 In [20]: df.reindex(columns=list('ABCD')) Out[20]: A B C D 0 4 NaN NaN NaN 1 7 NaN NaN NaN 2 0 NaN NaN NaN 3 7 NaN NaN NaN 4 6 Na...
psycopg2: AttributeError: 'module' object has no attribute 'extras'
In my code I use the DictCursor from psycopg2.extras like this dict_cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor) However, all of the sudden I get the following error when I load the cursor: AttributeError: 'module' object has no attribute 'extras' Maybe something is dorked in my installation but I hav...
You need to explicitly import psycopg2.extras: import psycopg2.extras
Why does '12345'.count('') return 6 and not 5?
>>> '12345'.count('') 6 Why does this happen? If there are only 5 characters in that string, why is the count function returning one more? Also, is there a more effective way of counting characters in a string?
count returns how many times an object occurs in a list, so if you count occurrences of '' you get 6 because the empty string is at the beginning, end, and in between each letter. Use the len function to find the length of a string.
Why is globals() a function in Python?
Python offers the function globals() to access a dictionary of all global variables. Why is that a function and not a variable? The following works: g = globals() g["foo"] = "bar" print foo # Works and outputs "bar" What is the rationale behind hiding globals in a function? And is it better to call it only once and st...
Because it may depend on the Python implementation how much work it is to build that dictionary. In CPython, globals are kept in just another mapping, and calling the globals() function returns a reference to that mapping. But other Python implementations are free to create a separate dictionary for the object, as need...
Scrapy throws ImportError: cannot import name xmlrpc_client
After install Scrapy via pip, and having Python 2.7.10: scrapy Traceback (most recent call last): File "/usr/local/bin/scrapy", line 7, in <module> from scrapy.cmdline import execute File "/Library/Python/2.7/site-packages/scrapy/__init__.py", line 48, in <module> from scrapy.spiders import Spider File "/Library/Pyth...
I've just fixed this issue on my OS X. Please backup your files first. sudo rm -rf /Library/Python/2.7/site-packages/six* sudo rm -rf /System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/six* sudo pip install six Scrapy 1.0.0 is ready to go.
How does the class_weight parameter in scikit-learn work?
I am having a lot of trouble understanding how the class_weight parameter in scikit-learn's Logistic Regression operates. The Situation I want to use logistic regression to do binary classification on a very unbalanced data set. The classes are labelled 0 (negative) and 1 (positive) and the observed data is in a ratio ...
First off, it might not be good to just go by recall alone. You can simply achieve a recall of 100% by classifying everything as the positive class. I usually suggest using AUC for selecting parameters, and then finding a threshold for the operating point (say a given precision level) that you are interested in. For ho...
Convert Rust vector of tuples to a C compatible structure
Following these answers, I've currently defined a Rust 1.0 function as follows, in order to be callable from Python using ctypes: use std::vec; extern crate libc; use libc::{c_int, c_float, size_t}; use std::slice; #[no_mangle] pub extern fn convert_vec(input_lon: *const c_float, lon_size: ...
The most important thing to note is that there is no such thing as a tuple in C. C is the lingua franca of library interoperability, and you will be required to restrict yourself to abilities of this language. It doesn't matter if you are talking between Rust and another high-level language; you have to speak C. There ...
Weird numpy.sum behavior when adding zeros
I understand how mathematically-equivalent arithmentic operations can result in different results due to numerical errors (e.g. summing floats in different orders). However, it surprises me that adding zeros to sum can change the result. I thought that this always holds for floats, no matter what: x + 0. == x. Here's a...
Short answer: You are seeing the difference between a + b + c + d and (a + b) + (c + d) which because of floating point inaccuracies is not the same. Long answer: Numpy implements pair-wise summation as an optimization of both speed (it allows for easier vectorization) and rounding error. The numpy sum-implementation...
Check if a list is a rotation of another list that works with duplicates
I have this function for determining if a list is a rotation of another list: def isRotation(a,b): if len(a) != len(b): return False c=b*2 i=0 while a[0] != c[i]: i+=1 for x in a: if x!= c[i]: return False i+=1 return True e.g. >>> a = [1,2,3] >>> b = [2,3,1] >>> isRotation(a, b) ...
The following meta-algorithm will solve it. Build a concatenation of a, e.g., a = [3,1,2,3,4] => aa = [3,1,2,3,4,3,1,2,3,4]. Run any string adaptation of a string-matching algorithm, e.g., Boyer Moore to find b in aa. One particularly easy implementation, which I would first try, is to use Rabin Karp as the underl...
Stopping list selection in Python 2.7
Imagine that I have an order list of tuples: s = [(0,-1), (1,0), (2,-1), (3,0), (4,0), (5,-1), (6,0), (7,-1)] Given a parameter X, I want to select all the tuples that have a first element equal or greater than X up to but not including the first tuple that has -1 as the second element. For example, if X = 3, I want t...
You can simply filter the tuples from the list as a generator expression and then you can stop taking the values from the generator expression when you get the first tuple whose second element is -1, like this >>> s = [(0,-1), (1,0), (2,-1), (3,0), (4,0), (5,-1), (6,0), (7,-1)] >>> from itertools import takewhile >>> X...
Python: issue when using vars() dictionary
I have the following snippet: a, b = 1, 2 params = ['a', 'b'] res = {p: vars()[p] for p in params} Which gives me KeyError: 'a' whereas the following code works fine: a, b = 1, 2 params = ['a', 'b'] res = {} for p in params: res[p] = vars()[p] What's the difference here?
vars() without any argument acts like locals() and since a dictionary comprehension has its own scope it has no variable named a or b. You can use eval() here. Without any argument it will execute in LEGB manner, or specify globals() dict explicitly to eval: >>> res = {p: eval(p) for p in params} >>> res {'a': 1, 'b': ...
Python if not == vs if !=
What is the difference between these two lines of code: if not x == 'val': and if x != 'val': Is one more efficient than the other? Would it be better to use if x == 'val': pass else:
Using dis to look at the bytecode generated for the two versions: not == 4 0 LOAD_FAST 0 (foo) 3 LOAD_FAST 1 (bar) 6 COMPARE_OP 2 (==) 9 UNARY_NOT 10 RETURN_VALUE != 4 0 LOAD_FAST ...
Plotting categorical data with pandas and matplotlib
I have a data frame with categorical data: colour direction 1 red up 2 blue up 3 green down 4 red left 5 red right 6 yellow down 7 blue down and now I want to generate some graphs, like pie charts and histograns based on the categories. Is it possible without creating du...
You can simply use value_counts on the series: df.colour.value_counts().plot(kind='bar')
get the index of the last negative value in a 2d array per column
I'm trying to get the index of the last negative value of an array per column (in order to slice it after). a simple working example on a 1d vector is : import numpy as np A = np.arange(10) - 5 A[2] = 2 print A # [-5 -4 2 -2 -1 0 1 2 3 4] idx = np.max(np.where(A <= 0)[0]) print idx # 5 A[:idx] = 0 print A # [0...
You already have good answers, but I wanted to propose a potentially quicker variation using the function np.maximum.accumulate. Since your method for a 1D array uses max/where, you may also find this approach quite intuitive. (Edit: quicker Cython implementation added below). The overall approach is very similar to th...
Why is "1.real" a syntax error but "1 .real" valid in Python?
So I saw these two questions on twitter. How is 1.real a syntax error but 1 .real is not? >>> 1.real File "<stdin>", line 1 1.real ^ SyntaxError: invalid syntax >>> 1 .real 1 >>> 1. real File "<stdin>", line 1 1. real ^ SyntaxError: invalid syntax >>> 1 . real 1 >>> 1..real 1.0 >>> 1 ..re...
I guess that the . is greedily parsed as part of a number, if possible, making it the float 1., instead of being part of the method call. Spaces are not allowed around the decimal point, but you can have spaces before and after the . in a method call. If the number is followed by a space, the parse of the number is ter...
Python multi-line with statement
What is a clean way to create a multi-line with in python? I want to open up several files inside a single with, but it's far enough to the right that I want it on multiple lines. Like this: class Dummy: def __enter__(self): pass def __exit__(self, type, value, traceback): pass with Dummy() as a, Dummy() as b,...
Given that you've tagged this Python 3, if you need to intersperse comments with your context managers, I would use a contextlib.ExitStack: with ExitStack() as stack: a = stack.enter_context(Dummy()) # Relevant comment b = stack.enter_context(Dummy()) # Comment about b c = stack.enter_context(Dummy()) # Fur...
Insert element in Python list after every nth element
Say I have a Python list like this: letters = ['a','b','c','d','e','f','g','h','i','j'] I want to insert an 'x' after every nth element, let's say three characters in that list. The result should be: letters = ['a','b','c','x','d','e','f','x','g','h','i','x','j'] I understand that I can do that with looping and inser...
I've got two one liners. Given: >>> letters = ['a','b','c','d','e','f','g','h','i','j'] Use enumerate to get index, add 'x' every 3rd letter, eg: mod(n, 3) == 2, then concatenate into string and list() it. >>> list(''.join(l + 'x' * (n % 3 == 2) for n, l in enumerate(letters))) ['a', 'b', 'c', 'x', 'd', 'e', 'f', 'x...
How do I get authentication in a telegram bot?
Telegram Bots are ready now. If we use the analogy of web browser and websites, the telegram client applications are like the browser clients. The Telegram Chatrooms are like websites. Suppose we have some information we only want to restrict to certain users, on the websites, we will have authentication. How do we ach...
Forget about the webhook thingy. The deep linking explained: Let the user log in on an actual website with actual username-password authentication. Generate a unique hashcode (we will call it unique_code) Save unique_code->username to a database or key-value storage. Show the user the URL https://telegram.me/YOURBOTNA...
Define True, if not defined, causes syntax error
I have found the following construct today in someone elses code: try: True, False except NameError: True = 1==1; False = 1==0 As I understand this, it defines True and False if they are not defined already. So if they are defined it shouldn't throw the NameError-Exception, right? I have tryed this for myself in a s...
This code is written for Python 2.x and won't work on Python 3.x (in which True and False are true keywords). Since True and False are keywords in Python 3, you'll get a SyntaxError which you cannot catch. This code exists because of very old versions of Python. In Python 2.2 (released in 2001!), True and False did not...
What is the most pythonic way to iterate over OrderedDict
I have an OrderedDict and in a loop I want to get index, key and value. It's sure can be done in multiple ways, i.e. a = collections.OrderedDict({…}) for i,b,c in zip(range(len(a)), a.iterkeys(), a.itervalues()): … But I would like to avoid range(len(a)) and shorten a.iterkeys(), a.itervalues() to something lik...
You can use tuple unpacking in for statement: for i, (key, value) in enumerate(a.iteritems()): # Do something with i, key, value >>> d = {'a': 'b'} >>> for i, (key, value) in enumerate(d.iteritems()): ... print i, key, value ... 0 a b Side Note: In Python 3.x, use dict.items() which returns an iterable dict...
Simple line plots using seaborn
I'm trying to plot a ROC curve using seaborn (python). With matplotlib I simply use the function plot: plt.plot(one_minus_specificity, sensitivity, 'bs--') where one_minus_specificity and sensitivity are two lists of paired values. Is there a simple counterparts of the plot function in seaborn? I had a look at the gal...
Since seaborn also uses matplotlib to do its plotting you can easily combine the two. If you only what to adopt the styling of seaborn the set_style function should get you started: import matplotlib.pyplot as plt import numpy as np import seaborn as sns sns.set_style("darkgrid") plt.plot(np.cumsum(np.random.randn(100...
ImportError: No module named concurrent.futures.process
I have followed the procedure given in How to use valgrind with python? for checking memory leaks in my python code. I have my python source under the path /root/Test/ACD/atech I have given above path in PYTHONPATH. Everything is working fine if I run the code with default python binary, located under /usr/bin/. I n...
If you're using Python 2.7 you must install this module : pip install futures Futures feature has never included in Python 2.x core. However, it's present in Python 3.x since Python 3.2.
Efficiently build a graph of words with given Hamming distance
I want to build a graph from a list of words with Hamming distance of (say) 1, or to put it differently, two words are connected if they only differ from one letter (lol -> lot). so that given words = [ lol, lot, bot ] the graph would be { 'lol' : [ 'lot' ], 'lot' : [ 'lol', 'bot' ], 'bot' : [ 'lot' ] } The eas...
Assuming you store your dictionary in a set(), so that lookup is O(1) in the average (worst case O(n)). You can generate all the valid words at hamming distance 1 from a word: >>> def neighbours(word): ... for j in range(len(word)): ... for d in string.ascii_lowercase: ... word1 = ''.join(d if i...
Swapping two sublists in a list
Given the following list: my_list=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] I want to be able to swap the sub-list my_list[2:4] with the sub-list my_list[7:10] as quickly and as efficiently as possible, to get the new list: new_list=[0, 1, 7, 8, 9, 4, 5, 6, 2, 3, 10, 11, 12] Here's my attempt: def swap(s1, s2,...
Slices can be assigned. Two variables can be swapped with a, b = b, a. Combine the two above:: >>> my_list[7:10], my_list[2:4] = my_list[2:4], my_list[7:10] >>> my_list [0, 1, 7, 8, 9, 4, 5, 6, 2, 3, 10, 11, 12] Beware that - if slices have different sizes - the order is important: If you swap in the opposite order, ...
Virtualenv Command Not Found
I couldn't get virtualenv to work despite various attempts. I installed virtualenv on MAC OS X using: pip install virtualenv and have also added the PATH into my .bash_profile. Every time I try to run the virtualenv command, it returns: -bash: virtualenv: command not found Every time I run pip install virtualenv, it ...
I faced the same issue and this is how I solved it: The issue occurred to me because I installed virtualenv via pip as a regular user (not root). pip installed the packages into the directory ~/.local/lib/pythonX.X/site-packages When I ran pip as root or with admin privileges (sudo), it installed packages in /usr/lib/...
how do you create a linear regression forecast on time series data in python
I need to be able to create a python function for forecasting based on linear regression model with confidence bands on time series data: The function needs to take in an argument to how far out it forecasts. For example 1day, 7days, 30days, 90days etc. Depending on the argument, it will need to create holtwinters forc...
In the text of your question, you clearly state that you would like upper and lower bounds on your regression output, as well as the output prediction. You also mention using Holt-Winters algorithms for forecasting in particular. The packages suggested by other answerers are useful, but you might note that sklearn Line...
Logarithmic plot of a cumulative distribution function in matplotlib
I have a file containing logged events. Each entry has a time and latency. I'm interested in plotting the cumulative distribution function of the latencies. I'm most interested in tail latencies so I want the plot to have a logarithmic y-axis. I'm interested in the latencies at the following percentiles: 90th, 99th, 99...
Essentially you need to apply the following transformation to your Y values: -log10(1-y). This imposes the only limitation that y < 1, so you should be able to have negative values on the transformed plot. Here's a modified example from matplotlib documentation that shows how to incorporate custom transformations into ...
Is "__module__" guaranteed to be defined during class creation?
I was reading some code that looked basically like this: class Foo(object): class_name = __module__.replace('_', '-') To me, that looked really weird (__module__, what is that?) so I went and looked at the python data-model. A quick search shows that __module__ is a property of class objects and of function objec...
What the documentation does define is that classes will have a __module__ attribute. It seems the way CPython does this is that it defines a local variable __module__ at the beginning of the class block. This variable then becomes a class attribut like any other variable defined there. I can't find any documentation ...
How to send an array using requests.post (Python)? "Value Error: Too many values to unpack"
I'm trying to send an array(list) of requests to the WheniWork API using requests.post, and I keep getting one of two errors. When I send the list as a list, I get an unpacking error, and when I send it as a string, I get an error asking me to submit an array. I think it has something to do with how requests handles li...
You want to pass in JSON encoded data. See the API documentation: Remember — All post bodies must be JSON encoded data (no form data). The requests library makes this trivially easy: headers = {"W-Token": "Ilovemyboss"} data = [ { 'url': '/rest/shifts', 'params': {'user_id': 0, 'other_stuff': 'v...
getattr and setattr on nested objects?
this is probably a simple problem so hopefuly its easy for someone to point out my mistake or if this is even possible. I have an object that has multiple objects as properties. I want to be able to dynamically set the properties of these objects like so: class Person(object): def __init__(self): self.pet =...
You could use functools.reduce: import functools def rsetattr(obj, attr, val): pre, _, post = attr.rpartition('.') return setattr(rgetattr(obj, pre) if pre else obj, post, val) sentinel = object() def rgetattr(obj, attr, default=sentinel): if default is sentinel: _getattr = getattr else: ...
How to import all the environment variables in tox
I'm using following in setenv to import the environment variable from where I run, but is there a way to import all the variables so that I don't really need to import one by one. e.g: {env:TEMPEST_CONFIG:} and {env:TEMPEST_CONFIG_DIR:} used to import these 2 variables. [testenv:nosetests] setenv = TEMPEST_CONFIG={...
You can use passenv. If you pass the catch all wildcard * you have access to all environment variables from the parent environment: passenv=SPACE-SEPARATED-GLOBNAMES New in version 2.0. A list of wildcard environment variable names which shall be copied from the tox invocation environment to the test environment w...
Unexpected output from list(generator)
I have a list and a lambda function defined as In [1]: i = lambda x: a[x] In [2]: alist = [(1, 2), (3, 4)] Then I try two different methods to calculate a simple sum First method. In [3]: [i(0) + i(1) for a in alist] Out[3]: [3, 7] Second method. In [4]: list(i(0) + i(1) for a in alist) Out[4]: [7, 7] Both results a...
This behaviour has been fixed in python 3. When you use a list comprehension [i(0) + i(1) for a in alist] you will define a in its surrounding scope which is accessible for i. In a new session list(i(0) + i(1) for a in alist) will throw error. >>> i = lambda x: a[x] >>> alist = [(1, 2), (3, 4)] >>> list(i(0) + i(1) for...
sympy: order of result from solving a quadratic equation
I solved a quadratic equation using sympy: import sympy as sp q,qm,k,c0,c,vt,vm = sp.symbols('q qm k c0 c vt vm') c = ( c0 * vt - q * vm) / vt eq1 = sp.Eq(qm * k * c / (1 + k * c) ,q) q_solve = sp.solve(eq1,q) Based on some testing I figured out that only q_solve[0] makes physical sense. Will sympy always put (b - sqr...
A simple test to answer your question is to symbolically solve the quadratic equation using sympy per below: import sympy as sp a, b, c, x = sp.symbols('a b c x') solve( a*x**2 + b*x + c, x) this gives you the result: [(-b + sqrt(-4*a*c + b**2))/(2*a), -(b + sqrt(-4*a*c + b**2))/(2*a)] which leads me to believe that ...
What is the difference between "range(0,2)" and "list(range(0,2))"?
Need to understand the difference between range(0,2) and list(range(0,2)), using python2.7 Both return a list so what exactly is the difference?
In Python 3.x , range(0,3) returns a class of immutable iterable objects that lets you iterate over them, it does not produce lists, and they do not store all the elements in the range in memory, instead they produce the elements on the fly (as you are iterating over them) , whereas list(range(0,3)) produces a list (by...
What's the difference between select_related and prefetch_related in Django ORM?
In Django doc, select_related() “follow” foreign-key relationships, selecting additional related-object data when it executes its query. prefetch_related() does a separate lookup for each relationship, and does the ‘joining’ in Python. What does it mean by "doing the joining in python"? Can someone illustrat...
Your understanding is mostly correct. You use select_related when the object that you're going to be selecting is a single object, so OneToOneField or a ForeignKey. You use prefetch_related when you're going to get a "set" of things, so ManyToManyFields as you stated or reverse ForeignKeys. Just to clarify what I mean ...
Different behavior in python script and python idle?
In the python idle: >>> a=1.1 >>> b=1.1 >>> a is b False But when I put the code in a script and run it, I will get a different result: $cat t.py a=1.1 b=1.1 print a is b $python t.py True Why did this happen? I know that is compares the id of two objects, so why the ids of two objects are same/unique in python scrip...
When Python executes a script file, the whole file is parsed first. You can notice that when you introduce a syntax error somewhere: Regardless of where it is, it will prevent any line from executing. So since Python parses the file first, literals can be loaded effectively into the memory. Since Python knows that thes...
PEP 0492 - Python 3.5 async keyword
PEP 0492 adds the async keyword to Python 3.5. How does Python benefit from the use of this operator? The example that is given for a coroutine is async def read_data(db): data = await db.fetch('SELECT ...') According to the docs this achieves suspend[ing] execution of read_data coroutine until db.fetch awaita...
No, co-routines do not involve any kind of threads. Co-routines allow for cooperative multi-tasking in that each co-routine yields control voluntarily. Threads on the other hand switch between units at arbitrary points. Up to Python 3.4, it was possible to write co-routines using generators; by using yield or yield fro...
Doc2vec : How to get document vectors
How to get document vectors of two text documents using Doc2vec? I am new to this, so it would be helpful if someone could point me in right direction/help me with some tutorial I am using gensim python library. doc1=["This is a sentence","This is another sentence"] documents1=[doc.strip().split(" ") for doc in doc1 ] ...
doc=["This is a sentence","This is another sentence"] documents=[doc.strip().split(" ") for doc in doc1 ] model = doc2vec.Doc2Vec(documents, size = 100, window = 300, min_count = 10, workers=4) I got AttributeError: 'list' object has no attribute 'words' because the input documents to the Doc2vec() was not in correct...
Finding gradient of a Caffe conv-filter with regards to input
I need to find the gradient with regards to the input layer for a single convolutional filter in a convolutional neural network (CNN) as a way to visualize the filters. Given a trained network in the Python interface of Caffe such as the one in this example, how can I then find the gradient of a conv-filter with respec...
Caffe net juggles two "streams" of numbers. The first is the data "stream": images and labels pushed through the net. As these inputs progress through the net they are converted into high-level representation and eventually into class probabilities vectors (in classification tasks). The second "stream" holds the parame...
Cannot apply DjangoModelPermissions on a view that does not have `.queryset` property or overrides the `.get_queryset()` method
I am getting the error ".accepted_renderer not set on Response resp api django". I am following the django rest-api tutorial. Django version i am using 1.8.3 I followed the tutorial till first part. It worked properly. But when i continued the 2nd part in sending response, i got an error Cannot apply DjangoModelPermi...
You probably have set DjangoModelPermissions as a default permission class in your settings. Something like: REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.DjangoModelPermissions', ) } DjangoModelPermissions can only be applied to views that have a .queryset property or ...
MySQL Improperly Configured Reason: unsafe use of relative path
I'm using Django, and when I run python manage.py runserver I receive the following error: ImproperlyConfigured: Error loading MySQLdb module: dlopen(/Library/Python/2.7/site-packages/_mysql.so, 2): Library not loaded: libmysqlclient.18.dylib Referenced from: /Library/Python/2.7/site-packages/_mysql.so Reason: uns...
In OS X El Capitan (10.11), Apple added System Integrity Protection. This prevents programs in protected locations like /usr from calling a shared library that uses a relative reference to another shared library. In the case of _mysql.so, it contains a relative reference to the shared library libmysqlclient.18.dylib....
Portable way of detecting number of *usable* CPUs in Python
Per this question and answer -- Python multiprocessing.cpu_count() returns '1' on 4-core Nvidia Jetson TK1 -- the output of Python's multiprocessing.cpu_count() function on certain systems reflects the number of CPUs actively in use, as opposed to the number of CPUs actually usable by the calling Python program. A com...
I don't think you will get any truly portable answers, so I will give a correct one. The correct* answer for Linux is len(os.sched_getaffinity(pid)), where pid may be 0 for the current process. This function is exposed in Python 3.3 and later; if you need it in earlier, you'll have to do some fancy cffi coding. Edit: y...
Using Cloudfront with Django S3Boto
I have successfully set up my app to use S3 for storing all static and media files. However, I would like to upload to S3 (current operation), but serve from a cloudfront instance I have set up. I have tried adjusting settings to the cloudfront url but it does not work. How can I upload to S3 and serve from Cloudfront ...
Your code is almost complete except you are not adding your cloudfront domain to STATIC_URL/MEDIA_URL and your custom storages. In detail, you must first install the dependencies pip install django-storages-redux boto Add the required settings to your django settings file INSTALLED_APPS = ( ... 'storages', ...
Memory efficient sort of massive numpy array in Python
I need to sort a VERY large genomic dataset using numpy. I have an array of 2.6 billion floats, dimensions = (868940742, 3) which takes up about 20GB of memory on my machine once loaded and just sitting there. I have an early 2015 13' MacBook Pro with 16GB of RAM, 500GB solid state HD and an 3.1 GHz intel i7 processor....
At the moment each call to np.argsort is generating a (868940742, 1) array of int64 indices, which will take up ~7 GB just by itself. Additionally, when you use these indices to sort the columns of full_arr you are generating another (868940742, 1) array of floats, since fancy indexing always returns a copy rather than...
Celery chain not working with batches
At first glance I liked very much the "Batches" feature in Celery because I need to group an amount of IDs before calling an API (otherwise I may be kicked out). Unfortunately, when testing a little bit, batch tasks don't seem to play well with the rest of the Canvas primitives, in this case, chains. For example: @a.ta...
Looks like the behaviour of batch tasks is significantly different from normal tasks. Batch tasks are not even emitting signals like task_success. Since you need to call completed task after get_price, You can call it directly from get_price itself. @a.task(base=Batches, flush_every=10, flush_interval=5) def get_price(...
python dask DataFrame, support for (trivially parallelizable) row apply?
I recently found dask module that aims to be an easy-to-use python parallel processing module. Big selling point for me is that it works with pandas. After reading a bit on its manual page, I can't find a way to do this trivially parallelizable task: ts.apply(func) # for pandas series df.apply(func, axis = 1) # for pa...
map_partitions You can apply your function to all of the partitions of your dataframe with the map_partitions function. df.map_partitions(func, columns=...) Note that func will be given only part of the dataset at a time, not the entire dataset like with pandas apply (which presumably you wouldn't want if you want to ...
Reading JSON from SimpleHTTPServer Post data
I am trying to build a simple REST server with python SimpleHTTPServer. I am having problem reading data from the post message. Please let me know if I am doing it right. from SimpleHTTPServer import SimpleHTTPRequestHandler import SocketServer import simplejson class S(SimpleHTTPRequestHandler): def _set_headers(...
Thanks matthewatabet for the klein idea. I figured a way to implement it using BaseHTTPHandler. The code below. from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer import SocketServer import simplejson import random class S(BaseHTTPRequestHandler): def _set_headers(self): self.send_response(200) ...
Why doesn't the MySQLdb Connection context manager close the cursor?
MySQLdb Connections have a rudimentary context manager that creates a cursor on enter, either rolls back or commits on exit, and implicitly doesn't suppress exceptions. From the Connection source: def __enter__(self): if self.get_autocommit(): self.query("BEGIN") return self.cursor() def __exit__(self,...
To answer your question directly: I cannot see any harm whatsoever in closing at the end of a with block. I cannot say why it is not done in this case. But, as there is a dearth of activity on this question, I had a search through the code history and will throw in a few thoughts (guesses) on why the close() may not ...
How to cope with the performance of generating signed URLs for accessing private content via CloudFront?
A common use case of AWS S3 and CloudFront is serving private content. The common solution is using signed CloudFront URLs to access private files stored using S3. However, the generation of these URLs comes with a cost: computing the RSA signature of any given URL using a private key. For Python (or boto, AWS's Python...
Use Signed Cookies When I use CloudFront with many private URLs, I prefer to use Signed Cookies when all the restrictions are met. This does not speed up the generation of signed cookies but it reduces the number of signing requests to be one per user until they expire. Tuning RSA Signature Generation I can imagine you...
1 class inherits 2 different metaclasses (abcmeta and user defined meta)
I have a class1 that needs to inherit from 2 different metaclasses which is Meta1 and abc.ABCMeta Current implementation: Implementation of Meta1: class Meta1(type): def __new__(cls, classname, parent, attr): new_class = type.__new__(cls, classname, parent, attr) return super(Meta1, cls).__new__(cls...
In Python, every class can only have one metaclass, not many. However, it is possible to achieve similar behaviour (like if it would have multiple metaclasses) by mixing what these metaclasses do. Let's start simple. Our own metaclass, simply adds new attribute to a class: class SampleMetaClass(type): """Sample meta...
How to avoid building C library with my python package?
I'm building a python package using a C library with ctypes. I want to make my package portable (Windows, Mac and Linux). I found a strategy, using build_ext with pip to build the library during the installation of my package. It creates libfoo.dll or libfoo.dylib or libfoo.so depending on the target's platform. The pr...
You're certainly heading down the right path according to my research... As Daniel says, the only option you have is to build and distribute the binaries yourself. In general, the recommended way to install packages is covered well in the packaging user guide. I won't repeat advice there as you have clearly already f...
Error setting up Vagrant with VirtualBox in PyCharm under OS X 10.10
When setting up the remote interpreter and selecting Vagrant, I get the following error in PyCharm: Can't Get Vagrant Settings: [0;31mThe provider 'virtualbox' that was requested to back the machine 'default' is reporting that it isn't usable on this system. The reason is shown bellow: Vagrant could not detect VirtualB...
Another workaround: sudo ln -s /usr/local/bin/VBoxManage /usr/bin/VBoxManage Edit: Since it all worked some time ago, one of the following has to be cause of this problem: either update of VirtualBox changed location of it's executable or update of PyCharm changed PATH settings / executable location expectation for t...
ipython server can't launch: No module named notebook.notebookapp
I've been trying to setup an ipython server following several tutorials (since none was exactly my case). A couple days ago, I did manage to get it to the point where it was launching but then was not able to access it via url. Today it's not launching anymore and I can't find much about this specific error I get: Trac...
This should fix the issue: pip install jupyter
Determining implementation of Python at runtime?
I'm writing a piece of code that returns profiling information and it would be helpful to be able to dynamically return the implementation of Python in use. Is there a Pythonic way to determine which implementation (e.g. Jython, PyPy) of Python my code is executing on at runtime? I know that I am able to get version i...
You can use python_implementation from the platform module in Python 3 or Python 2. This returns a string that identifies the Python implementation. e.g. return_implementation.py import platform print(platform.python_implementation()) and iterating through some responses on the command line: $ for i in python pytho...
How to prepend a path to sys.path in Python?
Problem description: Using pip, I upgraded to the latest version of requests (version 2.7.0, with pip show requests giving the location /usr/local/lib/python2.7/dist-packages). When I import requests and print requests.__version__ in the interactive command line, though, I am seeing version 2.2.1. It turns out that Pyt...
You shouldn't need to mess with pip's path, python actually handles it's pathing automatically in my experience. It appears you have two pythons installed. If you type: which pip which python what paths do you see? If they're not in the same /bin folder, then that's your problem. I'm guessing that the python you're...
ImportError: cannot import name wraps
I'm using python 2.7.6 on Ubuntu 14.04.2 LTS. I'm using mock to mock some unittests and noticing when I import mock it fails importing wraps. Not sure if there's a different version of mock or six I should be using for it's import to work? Couldn't find any relevant answers and I'm not using virtual environments. mock ...
Installed mock==1.0.1 and that worked for some reason. (shrugs) edit: The real fix for me was to updated setuptools to the latest and it allowed me to upgrade mock and six to the latest. I was on setuptools 3.3. In my case I also had to remove said modules by hand because they were owned by OS in '/usr/local/lib/python...
Why does "not(True) in [False, True]" return False?
If I do this: >>> False in [False, True] True That returns True. Simply because False is in the list. But if I do: >>> not(True) in [False, True] False That returns False. Whereas not(True) is equal to False: >>> not(True) False Why?
Operator precedence 2.x, 3.x. The precedence of not is lower than that of in. So it is equivalent to: >>> not (True in [False, True]) False This is what you want: >>> (not True) in [False, True] True As @Ben points out: It's recommended to never write not(True), prefer not True. The former makes it look like a funct...
How to compute precision, recall, accuracy and f1-score for the multiclass case with scikit learn?
I'm working in a sentiment analysis problem the data looks like this: label instances 5 1190 4 838 3 239 1 204 2 127 So my data is unbalanced since 1190 instances are labeled with 5. For the classification Im using scikit's SVC. The problem is I do not know how to balance my data...
I think there is a lot of confusion about which weights are used for what. I am not sure I know precisely what bothers you so I am going to cover different topics, bear with me ;). Class weights The weights from the class_weight parameter are used to train the classifier. They are not used in the calculation of any of ...
What does the -> (dash-greater-than arrow symbol) mean in a Python method signature?
There is a ->, or dash-greater-than symbol at the end of a python method, and I'm not sure what it means. One might call it an arrow as well. Here is the example: @property def get_foo(self) -> Foo: return self._foo where self._foo is an instance of Foo. My guess is that it is some kind of static type declaration...
This is function annotations. It can be use to attach additional information to the arguments or a return values of functions. It is a useful way to say how a function must be use. Functions annotations are stored in a function's __annotations__ attribute. Use Cases (From documentation) Providing typing information T...
Why does Python 3 allow "00" as a literal for 0 but not allow "01" as a literal for 1?
Why does Python 3 allow "00" as a literal for 0 but not allow "01" as a literal for 1? Is there a good reason? This inconsistency baffles me. (And we're talking about Python 3, which purposely broke backward compatibility in order to achieve goals like consistency.) For example: >>> from datetime import time >>> time(1...
Per https://docs.python.org/3/reference/lexical_analysis.html#integer-literals: Integer literals are described by the following lexical definitions: integer ::= decimalinteger | octinteger | hexinteger | bininteger decimalinteger ::= nonzerodigit digit* | "0"+ nonzerodigit ::= "1"..."9" digit ::= ...
Why does my Sieve of Eratosthenes work faster with integers than with booleans?
I wrote a simple Sieve of Eratosthenes, which uses a list of ones and turns them into zeros if not prime, like so: def eSieve(n): #Where m is fixed-length list of all integers up to n '''Creates a list of primes less than or equal to n''' m = [1]*(n+1) for i in xrange(2,int((n)**0.5)+1): if m[i]: ...
This happens because True and False are looked up as globals in Python 2. The 0 and 1 literals are just constants, looked up by a quick array reference, while globals are dictionary lookups in the global namespace (falling through to the built-ins namespace): >>> import dis >>> def foo(): ... a = True ... b = 1...
Make a number more probable to result from random
I'm using x = numpy.random.rand(1) to generate a random number between 0 and 1. How do I make it so that x > .5 is 2 times more probable than x < .5?
That's a fitting name! Just do a little manipulation of the inputs. First set x to be in the range from 0 to 1.5. x = numpy.random.uniform(1.5) x has a 2/3 chance of being greater than 0.5 and 1/3 chance being smaller. Then if x is greater than 1.0, subtract .5 from it if x >= 1.0: x = x - 0.5
Fitting a closed curve to a set of points
I have a set of points pts which form a loop and it looks like this: This is somewhat similar to 31243002, but instead of putting points in between pairs of points, I would like to fit a smooth curve through the points (coordinates are given at the end of the question), so I tried something similar to scipy documentat...
Your problem is because you're trying to work with x and y directly. The interpolation function you're calling assumes that the x-values are in sorted order and that each x value will have a unique y-value. Instead, you'll need to make a parameterized coordinate system (e.g. the index of your vertices) and interpola...
Python 3 - Can pickle handle byte objects larger than 4GB?
Based on this comment and the referenced documentation, Pickle 4.0+ from Python 3.4+ should be able to pickle byte objects larger than 4 GB. However, using python 3.4.3 or python 3.5.0b2 on Mac OS X 10.10.4, I get an error when I try to pickle a large byte array: >>> import pickle >>> x = bytearray(8 * 1000 * 1000 * ...
To sum up what was answered in the comments: Yes, Python can pickle byte objects bigger than 4GB. The observed error is caused by a bug in the implementation (see Issue24658).
Python PIL Image in Label auto resize
I'm trying to make a widget to hold an image that will automatically resize to fit its container, e.g. if packed directly into a window, then expanding that window will expand the image. I have some code that is semi functional but I've had to add a couple of constants into one of the routines to prevent the auto resiz...
I believe I have now solved this, but it really needs a lot more testing with different parameters to ensure accurate results. The code I have use to test this is as follows: from tkinter import tix from PIL import Image, ImageTk def Resize_Image(image, maxsize): r1 = image.size[0]/maxsize[0] # width ratio r2 ...
Test if all values are in an iterable in a pythonic way
I am currently doing this: if x in a and y in a and z in a and q in a and r in a and s in a: print b Is there a more pythonic way to express this if statement?
Using the all function allows to write this in a nice and compact way: if all(i in a for i in (x, y, z, q, r, s)): print b This code should do almost exactly the same as your example, even if the objects are not hashable or if the a object has some funny __contains__ method. The all function also has similar short...
Flask CORS - no Access-control-allow-origin header present on a redirect()
I am implementing OAuth Twitter User-sign in (Flask API and Angular) I keep getting the following error when I click the sign in with twitter button and a pop up window opens: XMLHttpRequest cannot load https://api.twitter.com/oauth/authenticate?oauth_token=r-euFwAAAAAAgJsmAAABTp8VCiE. No 'Access-Control-Allow-Origin'...
The problem is not yours. Your client-side application is sending requests to Twitter, so it isn't you that need to support CORS, it is Twitter. But the Twitter API does not currently support CORS, which effectively means that you cannot talk to it directly from the browser. A common practice to avoid this problem is t...
Python file open function modes
I have noticed that, in addition to the documented mode characters, Python 2.7.5.1 in Windows XP and 8.1 also accepts modes U and D at least when reading files. Mode U is used in numpy's genfromtxt. Mode D has the effect that the file is deleted, as per the following code fragment: f = open('text.txt','rD') print(f.n...
The D flag seems to be Windows specific. Windows seems to add several flags to the fopen function in its CRT, as described here. While Python does filter the mode string to make sure no errors arise from it, it does allow some of the special flags, as can be seen in the Python sources here. Specifically, it seems that ...
PIP install unable to find ffi.h even though it recognizes libffi
I have installed libffi on my Linux server as well as correctly set the PKG_CONFIG_PATH environment variable to the correct directory, as pip recognizes that it is installed; however, when trying to install pyOpenSSL, pip states that it cannot find file 'ffi.h'. I know both thatffi.h exists as well as its directory, so...
You need to install the development package as well. libffi-dev on Debian/Ubuntu, libffi-devel on Redhat/Centos/Fedora.
How can I pass arguments to a docker container with a python entry-point script using command?
So I've got a docker image with a python script as the entry-point and I would like to pass arguments to the python script when the container is run. I've tried to get the arguments using sys.argv and sys.stdin, but neither has worked. I'm trying to run the container using: docker run image argument
It depends how the entrypoint was set up. If it was set up in "exec form" then you simply pass the arguments after the docker run command, like this: docker run image -a -b -c If it was set up in "shell form" then you have to override the entrypoint, unfortunately. $ docker run --entrypoint echo image hi hi You can c...
AttributeError: '_socketobject' object has no attribute 'set_tlsext_host_name'
In python, on a Ubuntu server, I am trying to get the requests library to make https requests, like so: import requests requests.post("https://example.com") At first, I got the following: /usr/local/lib/python2.7/dist-packages/requests/packages/urllib3/util/ssl_.py:90: InsecurePlatformWarning: A true SSLContext obj...
The fix for me was the following: sudo apt-get purge python-openssl sudo pip install pyopenssl
Monkey patching a @property
Is it at all possible to monkey patch the value of a @property of an instance of a class that I do not control? class Foo: @property def bar(self): return here().be['dragons'] f = Foo() print(f.bar) # baz f.bar = 42 # MAGIC! print(f.bar) # 42 Obviously the above would produce an error when trying...
Subclass the base class (Foo) and change single instance's class to match the new subclass using __class__ attribute: >>> class Foo: ... @property ... def bar(self): ... return 'Foo.bar' ... >>> f = Foo() >>> f.bar 'Foo.bar' >>> class _SubFoo(Foo): ... bar = 0 ... >>> f.__class__ = _SubFoo >>> f.bar...
pandas iloc vs ix vs loc explanation?
Can someone explain how these three methods of slicing are different? I've seen the docs, and I've seen these answers, but I still find myself unable to explain how the three are different. To me, they seem interchangeable in large part, because they are at the lower levels of slicing. For example, say we want to get...
First, a recap: loc works on labels in the index. iloc works on the positions in the index (so it only takes integers). ix usually tries to behave like loc but falls back to behaving like iloc if the label is not in the index. It's important to note some subtleties that can make ix slightly tricky to use: if the in...
Scrapy spider memory leak
My spider have a serious memory leak.. After 15 min of run its memory 5gb and scrapy tells (using prefs() ) that there 900k requests objects and thats all. What can be the reason for this high number of living requests objects? Request only goes up and doesnt goes down. All other objects are close to zero. My spider l...
There are a few possible issues I see right away. Before starting though, I wanted to mention that prefs() doesn't show the number of requests queued, it shows the number of Request() objects that are alive. It's possible to reference a request object and keep it alive, even if it's no longer queued to be downloaded. ...
How to copy/paste DataFrame from StackOverflow into Python
In questions and answers, users very often post an example DataFrame which their question/answer works with: In []: x Out[]: bar foo 0 4 1 1 5 2 2 6 3 It'd be really useful to be able to get this DataFrame into my Python interpreter so I can start debugging the question, or testing the answer. H...
Pandas is written by people that really know what people want to do. Since version 0.13 there's a function pd.read_clipboard which is absurdly effective at making this "just work". Copy and paste the part of the code in the question that starts bar foo, (i.e. the DataFrame) and do this in a Python interpreter: In [53]:...
How to place xaxis grid over spectrogram in Python?
I have the following plot, which provides the spectrogram of a pressure signal along with the signal placed on it for comparison. I was able to draw the y-axis grids on the spectrogram, but could not place the x-axis grid on it. The data used to generate the spectrogram is available here. Reproducible code from __futu...
As others have noted - it is very difficult to replicate your issue with the code you have provided. In particular - I have tried on Windows 8.1, Ubuntu 14.04 (on Virtualbox VM), matplotlib versions 1.3.1 and 1.4.3, with and without text.usetex set and with Python 2.7.6 and Python 3. None of them reproduce your proble...
Pythonic and efficient way to do an elementwise "in" using numpy
I'm looking for a way to efficiently get an array of booleans, where given two arrays with equal size a and b, each element is true if the corresponding element of a appears in the corresponding element of b. For example, the following program: a = numpy.array([1, 2, 3, 4]) b = numpy.array([[1, 2, 13], [2, 8, 9], [5, 6...
To take advantage of NumPy's broadcasting rules you should make array b squared first, which can be achieved using itertools.izip_longest: from itertools import izip_longest c = np.array(list(izip_longest(*b))).astype(float) resulting in: array([[ 1., 2., 5., 7.], [ 2., 8., 6., nan], [ 13.,...
python elasticsearch client set mappings during create index
I can set mappings of index being created in curl command like this: { "mappings":{ "logs_june":{ "_timestamp":{ "enabled":"true" }, "properties":{ "logdate":{ "type":"date", "format":"dd/MM/yyy HH:mm:ss" } } } } } But I need t...
You can simply add the mapping in the create call like this: from elasticsearch import Elasticsearch self.elastic_con = Elasticsearch([host], verify_certs=True) mapping = ''' { "mappings":{ "logs_june":{ "_timestamp":{ "enabled":"true" }, "properties":{ "logdate":{ ...
How to package a linked DLL and a pyd file into one self contained pyd file?
I am building a python module with Cython that links against a DLL file. In order to succesfully import my module I need to have the DLL in the Windows search path. Otherwise, the typical error message is: ImportError: DLL load failed: The specified module could not be found. Is there a way to packaged the DLL directly...
Python's packaging & deployment is still a pain point for many of us. There is just not a silver bullet. Here are several methods: 1. OpenCV build method The method is decribed here : https://opencv-python-tutroals.readthedocs.org/en/latest/py_tutorials/py_bindings/py_bindings_basics/py_bindings_basics.html#bindings-b...
Python - list comprehension in this case is efficient?
The is the input "dirty" list in python input_list = [' \n ',' data1\n ',' data2\n',' \n','data3\n'.....] each list element contains either empty spaces with new line chars or data with newline chars Cleaned it up using the below code.. cleaned_up_list = [data.strip() for data in input_list if data.strip()] giv...
Using your list comp strip is called twice, use a gen exp if you want to only call strip once and keep the comprehension: input_list[:] = [x for x in (s.strip() for s in input_list) if x] Input: input_list = [' \n ',' data1\n ',' data2\n',' \n','data3\n'] Output: ['data1', 'data2', 'data3'] input_list[:] will...
Vagrant Not Starting Up. User that created VM doesn't match current user
I was trying to start up my vagrant machine, so I navigated to the folder where my vagrantfile is, and used: vagrant up && vagrant ssh but I got the following error message: The VirtualBox VM was created with a user that doesn't match the current user running Vagrant. VirtualBox requires that the same user be use...
I ran into the same problem today. I edited my UID by opening the file .vagrant/machines/default/virtualbox/creator_uid and changing the 501 to a 0. After I saved the file, the command vagrant up worked like a champ.
python requests ssl handshake failure
Every time I try to do: requests.get('https://url') I got this message: import requests >>> requests.get('https://reviews.gethuman.com/companies') Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python2.7/dist-packages/requests/api.py", line 55, in get return reques...
I resolve the problem in the end i updated my ubuntu from 14.04 to 14.10 and the problem was solved but in the older version of ubuntu and python I install those lib and it seems to fix all my problems sudo apt-get install python-dev libssl-dev libffi-dev sudo pip2.7 install -U pyopenssl==0.13.1 pyasn1 ndg-httpsclient...
Python: Feed and parse stream of data to and from external program with additional input and output files
The problem: I have a poorly designed Fortran program (I cannot change it, I'm stuck with it) which takes text input from stdin and other input files, and writes text output results to stdout and other output files. The size of input and out is quite large, and I would like to avoid writing to the hard drive (slow oper...
You should use named pipes for all input and output to the Fortran program to avoid writing to disk. Then, in your consumer, you can use threads to read from each of the program's output sources and add the information to a Queue for in-order processing. To model this, I created a python app daemon.py that reads from s...
How do I properly use connection pools in redis?
It's not clear to me how connections pools work, and how to properly use them. I was hoping someone could elaborate. I've sketched out my use case below: settings.py: import redis def get_redis_connection(): return redis.StrictRedis(host='localhost', port=6379, db=0) task1.py import settings connection = setting...
Redis-py provides a connection pool for you from which you can retrieve a connection. Connection pools create a set of connections which you can use as needed (and when done - the connection is returned to the connection pool for further reuse). Trying to create connections on the fly without discarding them (i.e. no...
What is a Pythonic way for Dependency Injection?
Introduction For Java, Dependency Injection works as pure OOP, i.e. you provide an interface to be implemented and in your framework code accept an instance of a class that implements the defined interface. Now for Python, you are able to do the same way, but I think that method was too much overhead right in case of P...
See Raymond Hettinger - Super considered super! - PyCon 2015 for an argument about how to use super and multiple inheritance instead of DI. If you don't have time to watch the whole video, jump to minute 15 (but I'd recommend watching all of it). Here is an example of how to apply what's described in this video to you...
Making SVM run faster in python
Using the code below for svm in python: from sklearn import datasets from sklearn.multiclass import OneVsRestClassifier from sklearn.svm import SVC iris = datasets.load_iris() X, y = iris.data, iris.target clf = OneVsRestClassifier(SVC(kernel='linear', probability=True, class_weight='auto')) clf.fit(X, y) proba = clf...
If you want to stick with SVC as much as possible and train on the full dataset, you can use ensembles of SVCs that are trained on subsets of the data to reduce the number of records per classifier (which apparently has quadratic influence on complexity). Scikit supports that with the BaggingClassifier wrapper. That sh...
How to use Java/Scala function from an action or a transformation?
Background My original question here was Why using DecisionTreeModel.predict inside map function raises an exception? and is related to How to generate tuples of (original lable, predicted label) on Spark with MLlib? When we use Scala API a recommended way of getting predictions for RDD[LabeledPoint] using DecisionTree...
Communication using default Py4J gateway is simply not possible. To understand why we have to take a look at the following diagram from the PySpark Internals document [1]: Since Py4J gateway runs on the driver it is not accessible to Python interpreters which communicate with JVM workers through sockets (See for examp...
Trade off between code duplication and performance
Python, being the dynamic language that it is, offer multiple ways to implement the same feature. These options may vary in readability, maintainability and performance. Even though the usual scripts that I write in Python are of a disposable nature, I now have a certain project that I am working on (academic) that mus...
Very broadly speaking, there are two types of optimization: macro optimizations and micro optimizations. Macro optimizations include things like your choice of algorithms, deciding between different data structures, and the like. Things that can have a big impact on performance and often have large ripple effects on yo...
Lost important .py file (overwritten as 0byte file), but the old version still LOADED IN IPYTHON as module -- can it be retrieved?
Due to my stupidity, while managing several different screen sessions with vim open in many of them, in the process of trying to "organize" my sessions I somehow managed to overwrite a very important .py script with a 0Byte file. HOWEVER, I have an ipython instance open that, when running that same .py file as a modul...
As noted in comments, inspect.getsource will not work because it depends on the original file (ie, module.__file__). Best option: check to see if there's a .pyc file (ex, foo.pyc should be beside foo.py). If there is, you can use Decompile Python 2.7 .pyc to decompile it. The inspect modules also caches the source. You...
How to test Pl/Python PostgreSQL procedures with Travis CI?
I'm trying to set up CI for some PL/Python PostgreSQL procedures in Travis CI. I've tried several ways: 1) With the legacy infrastructure I've tried to just assume, that PL/Python is already installed, but it had not succeed: The command "psql -U postgres -c 'CREATE EXTENSION plpythonu;'" exited with 1. 0.01s$ psql -U ...
I was able to get the python-tempo build working with the following .travis.yml: sudo: required language: python before_install: - sudo apt-get -qq update - sudo /etc/init.d/postgresql stop - sudo apt-get install -y postgresql-9.4 - sudo apt-get install -y postgresql-contrib-9.4 postgresql-plpython-9.4 - sudo...
How to handle an exhausted iterator?
While searching the Python Documentation I found the equivalent python implementation of Pythons build-in zip() function. Instead of catching a StopIteration exception which signals that there are no further items produced by the iterator the author(s) use an if statement to check if the returned default value form nex...
you mean as opposed to this? def zip2(*iterables): # zip('ABCD', 'xy') --> Ax By iterators = [iter(it) for it in iterables] while iterators: result = [] for it in iterators: try: elem = next(it) except StopIteration: return ...
How do you install mysql-connector-python (development version) through pip?
I have a virtualenv in which I am running Django 1.8 with Python 3.4 I am trying to get support for MySQL however I am having trouble getting the different connectors to work. I have always used mysql-connector-python with django 1.7 and would like to continue using it. The development version of mysql-connector-python...
I agree, the debian packages appear to be broken for at least Ubuntu 14.04. The apt-get version and the pip version do not include the 2.1.x releases. To get it done, I had to grab the source: $ git clone https://github.com/mysql/mysql-connector-python.git $ cd mysql-connector-python $ python ./setup.py build $ sud...