title stringlengths 10 172 | question_id int64 469 40.1M | question_body stringlengths 22 48.2k | question_score int64 -44 5.52k | question_date stringlengths 20 20 | answer_id int64 497 40.1M | answer_body stringlengths 18 33.9k | answer_score int64 -38 8.38k | answer_date stringlengths 20 20 | tags list |
|---|---|---|---|---|---|---|---|---|---|
Get most informative features from very simple scikit-learn SVM classifier | 39,095,116 | <p>I tried to build the a very simple SVM predictor that I would understand with my basic python knowledge. As my code looks so different from this <a href="http://stackoverflow.com/questions/30017491/problems-obtaining-most-informative-features-with-scikit-learn">question</a> and also this <a href="http://stackoverflow.com/questions/11116697/how-to-get-most-informative-features-for-scikit-learn-classifiers">question</a> I don't know how I can find the most important features for SVM prediction in my example.</p>
<p>I have the following 'sample' containing features and class (status):</p>
<pre><code>A B C D E F status
1 5 2 5 1 3 1
1 2 3 2 2 1 0
3 4 2 3 5 1 1
1 2 2 1 1 4 0
</code></pre>
<p>I saved the feature names as 'features': </p>
<pre><code>A B C D E F
</code></pre>
<p>The features 'X':</p>
<pre><code>1 5 2 5 1 3
1 2 3 2 2 1
3 4 2 3 5 1
1 2 2 1 1 4
</code></pre>
<p>And the status 'y':</p>
<pre><code>1
0
1
0
</code></pre>
<p>Then I build X and y arrays out of the sample, train & test on half of the sample and count the correct predictions.</p>
<pre><code>import pandas as pd
import numpy as np
from sklearn import svm
X = np.array(sample[features].values)
X = preprocessing.scale(X)
X = np.array(X)
y = sample['status'].values.tolist()
y = np.array(y)
test_size = int(X.shape[0]/2)
clf = svm.SVC(kernel="linear", C= 1)
clf.fit(X[:-test_size],y[:-test_size])
correct_count = 0
for x in range(1, test_size+1):
if clf.predict(X[-x].reshape(-1, len(features)))[0] == y[-x]:
correct_count += 1
accuracy = (float(correct_count)/test_size) * 100.00
</code></pre>
<p>My problem is now, that I have no idea, how I could implement the code from the questions above so that I could also see, which ones are the most important features.</p>
<p>I would be grateful if you could tell me, if that's even possible for my simple version? And if yes, any tipps on how to do it would be great.</p>
| 0 | 2016-08-23T07:38:07Z | 39,097,242 | <p>From all feature set, the set of variables which produces the lowest values for square of norm of vector must be chosen as variables of high importance in order</p>
| 0 | 2016-08-23T09:21:36Z | [
"python",
"scikit-learn",
"svm"
] |
Creating another chapter in python game | 39,095,258 | <p>I am creating a game from some code which I got from another question on here and I need help creating another chapter after I kill the bear with sword. How and where do I insert the <strong>goto command</strong> to start working on another chapter. Also if you have any advice or comments that would also be helpful.
Here is the code. Feel free to tweak it and show me how.</p>
<pre><code>p = 30
print 'You enter a dark room with two doors. Do you want to enter door #1 or door #2?'
door = raw_input('> ')
if door == "1":
print 'Theres a giant bear eating what appears to be a human arm, though its so damaged it\'s hard to be sure'
print 'what do you want to do?'
print '#1 try to take the arm'
print '#2 scream at the bear'
print '#3 swing sword of death upon him'
bear = raw_input('> ')
if bear == "1":
print 'You approach the bear slowly, never breaking eye contact. After what feel like a thousand years you are finally face to face with the bear. \nYou grab the arm and pull. of course the bear responds by eating you face. well done!'
elif bear == "2":
print 'You scream at the bear, a decent sound as well. The bear however was not impressed it would seem \nas he insantly eats your face. Well done!'
elif bear == "3":
print ' You swing the sword with all your might chopping the bears head completely off while blood drips to the floor'
else:
print 'Well, doing %s is probably better. Bear runs away.' % bear
elif door == "2":
print 'You stare into the endless abyss of Bollofumps retina.'
print 'Oh dear, seems the insanity of Bollofumps existence had driven you quite insane.'
print '#1. drool'
print '#2. scream and drool'
print '#3. Understand the fabrics of molecula toy crafting'
insanity = raw_input('> ')
if insanity == "1" or "2":
print 'Your body survives, powered by pure insanity!'
else:
print 'your mind melts into green flavoured jello! mmm!'
else:
print 'you think for a while but suddenly a troll weilding a terrible looking knife comes through a trap door and shanks you!'
</code></pre>
| -6 | 2016-08-23T07:46:04Z | 39,096,191 | <p>I think if you carry on down this route, you wont need to add many more rooms/scenarios before the code becomes unmanageable. It will also contain a lot of almost duplicated code to do with presenting the numbered options, reading the response, and presenting the outcome (mostly it seems unpleasant death.....).</p>
<p>if you really want to continue doing it all yourself, consider perhaps some structured data that describes the location, the questions and the next location each response takes you to. That could be a dictionary containing various elements. e.g. descripition, choices (an array of choices to allow different numbers of choices for each scenario), next_location (an array of the same size as choices providing the loction of the next scenario your adventurer arrives at based on the choice). You then need a dictionary to hold alll these dictionaries where the key is the name of the location. To try and give you an example of what I mean, here are (slightly cut down) versions of 'dark room' and 'endless abyss'</p>
<pre><code>game_dict ={}
sample_location_1 = { 'description' : 'You enter a dark room with two doors. Do you want to',
'choices' : ['enter door #1','enter door #2','dark_room_invalid'],
'next_location' :['bear_room', 'endless_abyss', 'dark_room'] }
game_dict['dark_room'] = sample_location_1
sample_location_2 = { 'description' : 'You stare into the endless abyss of Bollofumps retina.\nOh dear, seems the insanity of Bollofumps existence had driven you quite insane. What do you want to do ?',
'choices' : ['drool','scream and drool', 'Understand the fabrics of molecula toy crafting', 'endless_abyss_invalid'],
'next_location' :['death', 'death', 'death_by_troll', 'death_by_witty_reposte'] }
game_dict['endless_abyss'] = sample_location_2
</code></pre>
<p>Then you need code which reads and acts upon the data in a single location and presents the next location after action has been taken :</p>
<pre><code>current_location = 'dark_room'
while current_location != 'death':
print(game_dict[current_location]['description'])
for num, option in enumerate(game_dict[current_location]['choices'][:-1]):
print option
action = int(raw_input('> ')) -1
if action < len(game_dict[current_location]['choices']) -1:
current_location = game_dict[current_location]['next_location'][action]
else:
current_location = game_dict[current_location]['next_location'][-1]
print "you are now dead....... consider this."
</code></pre>
<p>This is an oversimplified code example, you'll possibly want to put error handling around getting the response from the user. possibly error habndling around accidentally specifying a 'next_location' you haven't defined yet and you're going to need a monstrous dictionary of all the locations you might want.</p>
<p>Coding the game with ifs and gotos will just get out of hand very quicky. Think structured data and single routines to handle that data and get you to the next location, which is then handled by the same routine....</p>
<p>Doing it this way, you can then investigate writing routines to help you create the data interactively (i.e. prompting you for descriptions, choices and outcomes). That daqta could then be written to disk and possibly read in from file allowing you to have many adventures based around one re-usable 'engine'.</p>
<p>I hope that's been of some use.</p>
| 3 | 2016-08-23T08:34:33Z | [
"python"
] |
Override __repr__ or pprint for int | 39,095,294 | <p>Is there any way of changing the way a <code>int</code>-type object is converted to string when calling <code>repr</code> or <code>pprint.pformat</code>, such that</p>
<pre><code>repr(dict(a=5, b=100))
</code></pre>
<p>will give <code>"{a: 0x5, b: 0x64}"</code> instead of <code>"{a: 5, b: 100}"</code>?</p>
<p>I suppose subclassing the <code>int</code> type would be an option:</p>
<pre><code>class IntThatPrintsAsHex(int):
def __repr__(self):
return hex(self)
def preprocess_for_repr(obj):
if isinstance(obj, dict):
return {preprocess_for_repr(k): preprocess_for_repr(v) for k, v in obj.items()}
elif isinstance(obj, list):
return [preprocess_for_repr(e) for e in obj]
elif isinstance(obj, tuple):
return tuple(preprocess_for_repr(e) for e in obj)
elif isinstance(obj, int) and not isinstance(obj, bool):
return IntThatPrintsAsHex(obj)
elif isinstance(obj, set):
return {preprocess_for_repr(e) for e in obj}
elif isinstance(obj, frozenset):
return frozenset(preprocess_for_repr(e) for e in obj)
else: # I hope I didn't forget any.
return obj
print(repr(preprocess_for_repr(dict(a=5, b=100))))
</code></pre>
<p>But as you can see, the <code>preprocess_for_repr</code> function is rather unpleasant to keep "as-complete-as-needed" and to work with. Also, the obvious performance implications.</p>
| 1 | 2016-08-23T07:47:46Z | 39,096,085 | <p><code>int</code> is a builtin type and you can't set attributes of built-in/extension types (you can not override nor add new methods to these types). You could however subclass <code>int</code> and override the <code>__repr__</code> method like this:</p>
<pre class="lang-py prettyprint-override"><code> class Integer(int):
def __repr__(self):
return hex(self)
x = Integer(3)
y = Integer(100)
# prints "[0x3, 0x64]"
print [x,y]
</code></pre>
<p><code>Integer</code> will behave exactly like an int, except for the <code>__repr__</code> method. You can use it index lists, do math and so on. However unless you override them, math operations will return regular <code>int</code> results:</p>
<pre class="lang-py prettyprint-override"><code>>>> print [x,y,x+1,y-2, x*y]
[0x3, 0x64, 4, 98, 300]
</code></pre>
| 2 | 2016-08-23T08:29:34Z | [
"python",
"python-3.x",
"built-in"
] |
Override __repr__ or pprint for int | 39,095,294 | <p>Is there any way of changing the way a <code>int</code>-type object is converted to string when calling <code>repr</code> or <code>pprint.pformat</code>, such that</p>
<pre><code>repr(dict(a=5, b=100))
</code></pre>
<p>will give <code>"{a: 0x5, b: 0x64}"</code> instead of <code>"{a: 5, b: 100}"</code>?</p>
<p>I suppose subclassing the <code>int</code> type would be an option:</p>
<pre><code>class IntThatPrintsAsHex(int):
def __repr__(self):
return hex(self)
def preprocess_for_repr(obj):
if isinstance(obj, dict):
return {preprocess_for_repr(k): preprocess_for_repr(v) for k, v in obj.items()}
elif isinstance(obj, list):
return [preprocess_for_repr(e) for e in obj]
elif isinstance(obj, tuple):
return tuple(preprocess_for_repr(e) for e in obj)
elif isinstance(obj, int) and not isinstance(obj, bool):
return IntThatPrintsAsHex(obj)
elif isinstance(obj, set):
return {preprocess_for_repr(e) for e in obj}
elif isinstance(obj, frozenset):
return frozenset(preprocess_for_repr(e) for e in obj)
else: # I hope I didn't forget any.
return obj
print(repr(preprocess_for_repr(dict(a=5, b=100))))
</code></pre>
<p>But as you can see, the <code>preprocess_for_repr</code> function is rather unpleasant to keep "as-complete-as-needed" and to work with. Also, the obvious performance implications.</p>
| 1 | 2016-08-23T07:47:46Z | 39,096,331 | <p>You should be able to monkey patch the <code>pprint</code> module to have integers print the way you want, but this isn't really a good approach.</p>
<p>If you're just looking for a better representation of integers for debugging, IPython has its own pretty printer that is easily customizable through its <a href="https://ipython.readthedocs.io/en/stable/api/generated/IPython.lib.pretty.html" rel="nofollow"><code>pretty</code></a> module:</p>
<pre><code>In [1]: from IPython.lib import pretty
In [2]: pretty.for_type(int, lambda n, p, cycle: p.text(hex(n)))
Out[2]: <function IPython.lib.pretty._repr_pprint>
In [3]: 123
Out[3]: 0x7b
In [4]: x = [12]
In [5]: x
Out[5]: [0xc]
In [6]: pretty.pretty(x)
Out[6]: '[0xc]'
</code></pre>
<p>You can read more about the three parameters in the linked documentation.</p>
| 1 | 2016-08-23T08:40:36Z | [
"python",
"python-3.x",
"built-in"
] |
finding the average of values in a column that matches the condition in pythonic way | 39,095,324 | <p>suppose i have the data like this</p>
<pre><code>mpg cylinder
14 4
26 6
45 4
20 4
23 8
21 8
</code></pre>
<p>and my output should be like this</p>
<pre><code>cylinder 4= 14+45+20/3
</code></pre>
<p>and so on</p>
<pre><code>dataset=[]
f= open('auto-mpg-data.csv')
csv_f=csv.reader(f)
for row in csv_f:
dataset.append(row)
#reading mpg column
mpg=[]
for row in dataset:
mpg.append(float(row[0]))
#reading cylinder column
cylinder=[]
for row in dataset:
cylinder.append(float[row[1])
#calculating average with condition
</code></pre>
| -5 | 2016-08-23T07:49:35Z | 39,095,534 | <p>Calculating an average from a condition is easy with <code>sum</code> and <code>len</code> after using a list comprehension to filter. For example, to calculate the average <code>mpg</code> where there are four <code>cylinders</code>, you could do:</p>
<pre><code>mpg4cylinder = [m for m, c in zip(mpg, cylinder) if c == 4]
# For greater precision with float summing, you may want to use math.fsum
cylinder4avg = sum(mpg4cylinder) / len(mpg4cylinder)
</code></pre>
<p>If you're using modern Python (3.4+), it's even easier with <a href="https://docs.python.org/3/library/statistics.html" rel="nofollow">the <code>statistics</code> module</a>:</p>
<pre><code>cylinder4avg = statistics.mean(m for m, c in zip(mpg, cylinder) if c == 4)
</code></pre>
<p>which is even more accurate than <code>math.fsum</code> approaches and more concise, in exchange for being slower.</p>
<p>This is somewhat inefficient if you are calculating stats for all cylinders, not just one or two. You could improve on this by grouping them by cylinder as you go:</p>
<pre><code>from collections import defaultdict
cyl_to_mpgs = defaultdict(list)
for m, c in zip(mpg, cylinder):
cyl_to_mpgs[c].append(m)
</code></pre>
<p>Now you can get the averages for any given cylinder count without needing to search through the whole list of data to filter out the bits you want, you just do:</p>
<pre><code>statistics.mean(cyl_to_mpgs[4.0])
</code></pre>
<p>which gets the pre-filtered <code>list</code> cheaply (having prefiltered all cylinder combinations in a single pass up front).</p>
<p>FYI, Python can do a lot of the work for you more succinctly. The creation and population of <code>dataset</code> could be just:</p>
<pre><code># newline='' is the correct way to do csv in Py3; on Py2, you'd get rid of it
# but provide a mode argument of "rb"
with open('auto-mpg-data.csv', newline='') as f:
dataset = list(csv.reader(f))
</code></pre>
<p><code>mpg</code> would be:</p>
<pre><code>mpg = [float(row[0]) for row in dataset]
</code></pre>
<p>with the same pattern for <code>cylinder</code>. Loops that do nothing but <code>append</code> values one by one are usually best replaced with the <code>list</code> constructor or a list comprehension (if the <code>list</code> already has values, you'd call <code>extend</code> with the same arguments or comprehension as <code>list</code>/listcomps).</p>
| 0 | 2016-08-23T08:01:17Z | [
"python",
"csv"
] |
How to create a singleton class that implements an abstract class, without getting into metaclass conflict? | 39,095,392 | <p>I've read a bunch of useful information on SO as well as the article at <a href="http://www.phyast.pitt.edu/~micheles/python/metatype.html" rel="nofollow">http://www.phyast.pitt.edu/~micheles/python/metatype.html</a></p>
<p>However, I think I still did not find the answer. Hence a new question.</p>
<p>I'm creating a library of functions/classes for in-house use. As part of that I would like to create a Singleton class. Any other class should be able to inherit it and become Singleton. These classes should be sub-classable.</p>
<p>Per SO post at <a href="http://stackoverflow.com/questions/6760685/creating-a-singleton-in-python">Creating a singleton in Python</a>, I implemented:</p>
<pre><code>class _Singleton(type):
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = super(
_Singleton, cls).__call__(*args, **kwargs)
return cls._instances[cls]
class Singleton(_Singleton('SingletonMeta', (object,), {})):
pass
</code></pre>
<p>It works. It helps create a singleton class that can be sub-classed.</p>
<p>There would be some classes in my library that would implement an abstract class using abc. Such class or a class implementing this abstract class can likely be Singleton.</p>
<p>So,</p>
<pre><code>import abc
class Foo(metaclass=abc.ABCMeta):
@abc.abstractmethod
def bar(self): pass
class Bar(Singleton, Foo): # This generates the meta-class conflict
def bar(self):
return 'implemented'
def bat(self):
return 'something else'
</code></pre>
<p>I am looking for inputs/help to help implement such a scenario.</p>
<p>**</p>
<p>Summary Requirements:</p>
<p>**</p>
<ul>
<li>A mechanism to create a Singleton class.</li>
<li>A class implemented as
Singleton (via the above mechanism) should be sub-classable. The sub-
class my have additional/new methods than the base class.</li>
<li>A mechanism to create an abstract class (abc helps with this).</li>
<li>An implementation of this abstract class that acts as a Singleton. It<br>
may have additional methods than the abstract class itself.</li>
</ul>
<p>Any inputs/help/pointers will be appreciated.</p>
<p>Regards</p>
<p>Sharad</p>
| 2 | 2016-08-23T07:52:55Z | 39,289,901 | <p>Instead of resorting to a metaclass to register your singletons, you can do that on the Base class for your hierarchy - just put the singleton logic on the <code>__new__</code> method instead. That way, you don't have to change the metaclass just due to this aditional behaviors, and abc.metaclasses will just work.</p>
<pre><code>import abc
class Foo(metaclass=abc.ABCMeta):
_singleton_registry = {}
def __new__(cls, *args, **kw):
if cls in in __class__._singleton_registry:
return __class__._singleton_registry[cls]
singleton = super().__new__(*args, **kw)
__class__._singleton_registry[cls] = singleton
return singleton
@abc.abstractmethod
def bar(self): pass
</code></pre>
| 0 | 2016-09-02T10:13:11Z | [
"python",
"python-3.x",
"singleton",
"abstract"
] |
Addition and multiplication of python using single coefficient | 39,095,435 | <p>I would like to add and multiply polynomials using python .
For example, if the Question is: </p>
<pre><code>addpoly([(4,3),(3,0)],[(-4,3),(2,1)])
[(2, 1),(3, 0)] (answer)
</code></pre>
<p>my Code:</p>
<pre><code>def addpoly( x, y):
min_len = min( len(x), len(y))
return x[: -min_len] + y[: -min_len] + [ x[i] + y[i] for i in range(-min_len,0)
</code></pre>
<p>my output</p>
<pre><code>addpoly([(4,3),(3,0)],[(-4,3),(2,1)])
[(4, 3, -4, 3), (3, 0, 2, 1)]
</code></pre>
<p>Required Output:</p>
<pre><code>[(2, 1), (3, 0)]
</code></pre>
<p>I would like to recieve any suggestions if possible.
Thank you.</p>
| 0 | 2016-08-23T07:55:39Z | 39,095,771 | <p>The simplest way is to convert your polynomial into a <code>dict</code> with <code>power -> coefficient</code> items:</p>
<pre><code>In [1]: p1 = [(4,3),(3,0)]
In [2]: p2 = [(-4,3),(2,1)]
In [3]: from collections import Counter
In [4]: p1_c = Counter(dict((degree, coef) for (coef, degree) in p1))
In [5]: p2_c = Counter(dict((degree, coef) for (coef, degree) in p2))
In [6]: p1_c, p2_c
Out[6]: (Counter({0: 3, 3: 4}), Counter({1: 2, 3: -4}))
</code></pre>
<p>Then you could add these dictionaries:</p>
<pre><code>In [7]: p1_c + p2_c
Out[7]: Counter({0: 3, 1: 2})
</code></pre>
<p>And convert them back into a list:</p>
<pre><code>In [8]: [(c, d) for (d, c) in (p1_c + p2_c).items()]
Out[8]: [(3, 0), (2, 1)]
</code></pre>
<p>You may also sort them by the degree (to fit your expected output)</p>
<pre><code>In [9]: from operator import itemgetter
In [10]: sorted(((c, d) for (d, c) in (p1_c + p2_c).items()), key=itemgetter(1), reverse=True)
Out[10]: [(2, 1), (3, 0)]
</code></pre>
<p>You may also find useful <a href="http://docs.sympy.org/dev/modules/polys/reference.html" rel="nofollow"><code>sympy</code></a> library, it allows you to work with symbolic expressions (i.e. with polynomials too) in a very neat way.</p>
| 0 | 2016-08-23T08:12:42Z | [
"python",
"python-3.x"
] |
How can i use variable when i used def function [Python] | 39,095,439 | <p>I have small problem. When I make a new function with <code>def</code>, I want change <code>i</code> on the end of function according to some variable. Example:</p>
<pre><code>import time
i = 2
def Happy_1():
print("Happy Brithday to you")
time.sleep(1)
print("Happy Brithday to you")
time.sleep(1)
print("Happy Brithday dear Paul")
time.sleep(1)
print("Happy Brithday to you")
time.sleep(1)
print("END")
def Happy_2():
print("Happy Brithday to you")
time.sleep(1)
print("Happy Brithday to you")
time.sleep(1)
print("Happy Brithday dear Peter")
time.sleep(1)
print("Happy Brithday to you")
time.sleep(1)
print("END")
Happy_("i or some variable")()
</code></pre>
<p>Is it possible to do something?
Thank you</p>
| -3 | 2016-08-23T07:56:00Z | 39,095,482 | <p>You can use:</p>
<pre><code>locals()["Happy_" + i]()
</code></pre>
<p>or </p>
<pre><code>globals()["Happy_" + i]()
</code></pre>
<p><code>locals()["Happy_" + i]</code> will get the function from the locals, and the final <code>()</code> will call the function.</p>
| 0 | 2016-08-23T07:58:34Z | [
"python",
"python-3.x"
] |
How can i use variable when i used def function [Python] | 39,095,439 | <p>I have small problem. When I make a new function with <code>def</code>, I want change <code>i</code> on the end of function according to some variable. Example:</p>
<pre><code>import time
i = 2
def Happy_1():
print("Happy Brithday to you")
time.sleep(1)
print("Happy Brithday to you")
time.sleep(1)
print("Happy Brithday dear Paul")
time.sleep(1)
print("Happy Brithday to you")
time.sleep(1)
print("END")
def Happy_2():
print("Happy Brithday to you")
time.sleep(1)
print("Happy Brithday to you")
time.sleep(1)
print("Happy Brithday dear Peter")
time.sleep(1)
print("Happy Brithday to you")
time.sleep(1)
print("END")
Happy_("i or some variable")()
</code></pre>
<p>Is it possible to do something?
Thank you</p>
| -3 | 2016-08-23T07:56:00Z | 39,095,581 | <pre><code>import time
i = 2
def Happy_1():
print("Happy Brithday to you")
time.sleep(1)
print("Happy Brithday to you")
time.sleep(1)
print("Happy Brithday dear Paul")
time.sleep(1)
print("Happy Brithday to you")
time.sleep(1)
print("END")
def Happy_2():
print("Happy Brithday to you")
time.sleep(1)
print("Happy Brithday to you")
time.sleep(1)
print("Happy Brithday dear Peter")
time.sleep(1)
print("Happy Brithday to you")
time.sleep(1)
print("END")
def error():
print('No such function!')
print locals().get('Happy_{}'.format(i), error)()
</code></pre>
| 0 | 2016-08-23T08:03:27Z | [
"python",
"python-3.x"
] |
How can i use variable when i used def function [Python] | 39,095,439 | <p>I have small problem. When I make a new function with <code>def</code>, I want change <code>i</code> on the end of function according to some variable. Example:</p>
<pre><code>import time
i = 2
def Happy_1():
print("Happy Brithday to you")
time.sleep(1)
print("Happy Brithday to you")
time.sleep(1)
print("Happy Brithday dear Paul")
time.sleep(1)
print("Happy Brithday to you")
time.sleep(1)
print("END")
def Happy_2():
print("Happy Brithday to you")
time.sleep(1)
print("Happy Brithday to you")
time.sleep(1)
print("Happy Brithday dear Peter")
time.sleep(1)
print("Happy Brithday to you")
time.sleep(1)
print("END")
Happy_("i or some variable")()
</code></pre>
<p>Is it possible to do something?
Thank you</p>
| -3 | 2016-08-23T07:56:00Z | 39,095,798 | <p>I'm pretty sure others are missing the obvious solution here.</p>
<pre><code>def happy(i):
names = ['Paul', 'Peter']
...
print('Happy birthday to {}'.format(names(i)))
</code></pre>
| 2 | 2016-08-23T08:13:38Z | [
"python",
"python-3.x"
] |
How can i use variable when i used def function [Python] | 39,095,439 | <p>I have small problem. When I make a new function with <code>def</code>, I want change <code>i</code> on the end of function according to some variable. Example:</p>
<pre><code>import time
i = 2
def Happy_1():
print("Happy Brithday to you")
time.sleep(1)
print("Happy Brithday to you")
time.sleep(1)
print("Happy Brithday dear Paul")
time.sleep(1)
print("Happy Brithday to you")
time.sleep(1)
print("END")
def Happy_2():
print("Happy Brithday to you")
time.sleep(1)
print("Happy Brithday to you")
time.sleep(1)
print("Happy Brithday dear Peter")
time.sleep(1)
print("Happy Brithday to you")
time.sleep(1)
print("END")
Happy_("i or some variable")()
</code></pre>
<p>Is it possible to do something?
Thank you</p>
| -3 | 2016-08-23T07:56:00Z | 39,095,834 | <p>Thanks @ Daniel Roseman for pointing this.</p>
<p><strong>Zen of Python - Simple is better than complex.</strong></p>
<p>Please check this code.</p>
<ul>
<li>Function Happy takes one argument. So no need to write two functions.</li>
</ul>
<p></p>
<pre><code>import time
i = 2
def Happy(i):
if i == 1:
print("Happy Brithday to you")
time.sleep(1)
print("Happy Brithday to you")
time.sleep(1)
print("Happy Brithday dear Paul")
time.sleep(1)
print("Happy Brithday to you")
time.sleep(1)
print("END")
elif i == 2:
print("Happy Brithday to you")
time.sleep(1)
print("Happy Brithday to you")
time.sleep(1)
print("Happy Brithday dear Peter")
time.sleep(1)
print("Happy Brithday to you")
time.sleep(1)
print("END")
Happy(i)
</code></pre>
<p>Output:</p>
<pre><code>C:\Users\dinesh_pundkar\Desktop>python demo.Py
Happy Brithday to you
Happy Brithday to you
Happy Brithday dear Peter
Happy Brithday to you
END
</code></pre>
| 0 | 2016-08-23T08:15:42Z | [
"python",
"python-3.x"
] |
group clusters of numbers in array | 39,095,536 | <p>I have an array like:</p>
<pre><code>A = [1,3,8,9,3,7,2,1,3,9,6,8,3,8,8,1,2]
</code></pre>
<p>And I want to count the number of "entry clusters" that are <code>>5</code>. In this case the result should be <code>4</code>, because:</p>
<pre><code>[1, 3, (8,9), 3, (7), 2, 1, 3, (9,6,8), 3, (8,8), 1, 2]
</code></pre>
<p>Given <code>L</code> length of the array, I can do:</p>
<pre><code>A = [1,3,8,9,3,7,2,1,3,9,6,8,3,8,8,1,2]
A = np.array(A)
for k in range(0,L):
if A[k]>5:
print k, A[k]
</code></pre>
<p>and this gives me all entries greater than <code>5</code>. But how could I group every cluster of numbers?</p>
| 3 | 2016-08-23T08:01:21Z | 39,095,826 | <p>You could use the <code>groupby</code> function from <code>itertools</code>.</p>
<pre><code>from itertools import groupby
A = [1,3,8,9,3,7,2,1,3,9,6,8,3,8,8,1,2]
result = [tuple(g) for k, g in groupby(A, lambda x: x > 5) if k]
print(result)
# [(8, 9), (7,), (9, 6, 8), (8, 8)]
print(len(result))
# 4
</code></pre>
| 5 | 2016-08-23T08:15:31Z | [
"python",
"arrays",
"group",
"cluster-computing"
] |
ImportError: No module named phpoob.bank | 39,095,559 | <pre><code>lcl
|
|----|
|----enterprise
|----phpoob
|----|----|
|----|----'bank.py'
|----|
|----'__init__.py'
|----'module.py'
</code></pre>
<p>this is my file structure</p>
<p><code>__init__.py</code>--></p>
<pre><code>from module import LCLModule
__all__ = ['LCLModule']
</code></pre>
<p><code>module.py</code>--></p>
<pre><code>from phpoob.bank import something
__all__ = ['LCLModule']
class LCLModule(something):
_code here_
</code></pre>
<p>these are my files</p>
<p>while firing the command <code>python __init__.py</code> i got following error <code>ImportError: No module named phpoob.bank</code> how shold i overcome this error</p>
<p>i also tried it <code>from .phpoob.bank import something</code> but it gives <code>ValueError: Attempted relative import in non-package</code> </p>
<p>what will be solution for it...?</p>
| 0 | 2016-08-23T08:02:33Z | 39,098,530 | <p>Looks like you are using Python 2.x. Folder <code>phpoob</code> is not treated as Python module. That's why you can't import <code>phpoob.bank</code>.</p>
<p><strong>Solution #1:</strong> Create empty file <code>phpoob/__init__.py</code> After that you will be able to import <code>phpoob</code> and import any file inside.</p>
<p><strong>Solution #2:</strong> Upgrate to Python 3.</p>
| 0 | 2016-08-23T10:22:50Z | [
"python",
"importerror"
] |
Why IMAP4.select() shows more number of mails than present in inbox | 39,095,727 | <p>IMAP4.select() returns more number of mails than present in inbox of gmail.</p>
<pre><code>def login_credentials():
db = MySQLdb.connect("192.168.140.38","admin_newsletter","zxax5575","admin_newsletter" )
cursor = db.cursor()
sql="SELECT email, password FROM readmail_account"
cursor.execute(sql)
details = cursor.fetchone()
return details
def connect_imap():
m = imaplib.IMAP4_SSL("imap.gmail.com") # server to connect to
print("{0} Connecting to mailbox via IMAP...".format(datetime.datetime.today().strftime("%Y-%m-%d %H:%M:%S")))
details = login_credentials()
m.login(details[0], details[1])
print m.select()
connect_imap()
</code></pre>
<p>This gives output </p>
<blockquote>
<p>('OK', ['22587'])</p>
</blockquote>
<p>But I have only 22,309 mails in my inbox, why so?</p>
| 0 | 2016-08-23T08:10:39Z | 39,096,282 | <p>The <code>select()</code> function returns count of all the messages.</p>
<blockquote>
<p>Select a mailbox. Returned data is the count of messages in mailbox (EXISTS response). The default mailbox is 'INBOX'. If the readonly flag is set, modifications to the mailbox are not allowed.</p>
</blockquote>
<p>What you usually see in the number of mails is the number of <strong>unread mails</strong> only, not the read ones. Use the search function.</p>
<pre><code>status, response = mail.search(None, 'ALL')
response = str( response[0], encoding='utf8' )
listresponse = response.split(" ")
print(len(listresponse),"new e-mails.")
</code></pre>
| 0 | 2016-08-23T08:38:49Z | [
"python",
"imap",
"imaplib"
] |
coloring issue - combination of open cv with matplotlib legend | 39,095,745 | <p>I'm currently trying to create a legend manually for several rectangles drawn in an image. But I get confused with the coloring.</p>
<pre><code> color_step = 255/(len(contours)+1)
patch =[]
for cnt_idx, cnt in enumerate(contours):
cnt_color = color_step * (cnt_idx+1)
cv2.rectangle(img,(cnt['x'],cnt['y']), \
(cnt['x']+cnt['w'], \
cnt['y']+cnt['h']),cnt_color,thickness)
patch.append(mpatches.Patch(color = (cnt_color/255.0,cnt_color/255.0,cnt_color/255.0 ), label='%d' %cnt_idx))
</code></pre>
<p>in the end I just call:</p>
<pre><code>patch = np.array(patch)
plt.legend(handles=patch)
plt.imshow(img, interpolation = 'none', cmap='gray')
</code></pre>
<p>I found out, that the cv2.rectangle method just assigns the value defined in cnt_color at the specific location of the rectangle. Unfortunately I don't know how to define the color for the patch.</p>
<p>The current result: <a href="http://i.stack.imgur.com/TaDmR.png" rel="nofollow"><img src="http://i.stack.imgur.com/TaDmR.png" alt="enter image description here"></a></p>
| 2 | 2016-08-23T08:11:33Z | 39,146,009 | <p>The problem was caused by the imshow function itself, as it normalizeses the result before showing the image.
setting of vmax and vmin helped</p>
| 0 | 2016-08-25T12:57:45Z | [
"python",
"opencv",
"matplotlib"
] |
I'm trying to know how I can use 'extent' in matplotlib to make my background image look decent | 39,095,784 | <p>No matter what values I change it's always distorting it, or it's too far on the left.</p>
<p>Here's an example:</p>
<p><img src="http://i.stack.imgur.com/HDRPt.png" alt="Plot with background image"></p>
<pre><code>barchart = pd.read_csv('barchart.csv')
df = pd.DataFrame(barchart)
var1 = df['col1'].head(7).tolist()
var2 = df['col2'].head(7).tolist()
sometitle = df['sometitle'][0]
var2 = [ float(x) for x in var2 ]
y_pos = np.arange(len(var1))
datafile = cbook.get_sample_data('/path/to/watch.jpg', asfileobj=False)
im = image.imread(datafile)
plt.imshow(im, zorder=0, extent=[0.5, 8.0, 1.0, 7.0])
barlist = plt.barh(y_pos, var2, align='center', alpha=0.5)
colors = ["red", "green", "blue", "orange", "pink", "cyan", "yellow"]
for a, b in zip(range(6), colors):
barlist[a].set_color(b)
plt.yticks(y_pos, var1)
plt.xlabel('a label', color="green", fontsize=9)
plt.title(sometitle + " " + str(now))
plt.show()
</code></pre>
| 2 | 2016-08-23T08:13:14Z | 39,107,584 | <p>From the documentation,</p>
<blockquote>
<p>extent : scalars (left, right, bottom, top), optional, default: None</p>
<p>The location, in data-coordinates, of the lower-left and upper-right corners. If None, the image is positioned such that the pixel centers fall on zero-based (row, column) indices.</p>
</blockquote>
<p>So if you want to put the image at a given <code>x</code>, <code>y</code> with <code>size</code> all in data-coordinates, get the ratio of <code>im.shape</code> and use this to scale. For example,</p>
<pre><code>import matplotlib.pyplot as plt
import numpy as np
val = 3+10*np.random.random(7)
pos = np.arange(7)+.5
fig,ax = plt.subplots(1,1)
colors = ["red", "green", "blue", "orange", "pink", "cyan", "yellow"]
barlist = ax.barh(pos, val, align='center',alpha=0.5)
for a, b in zip(range(6), colors):
barlist[a].set_color(b)
im = plt.imread('/path/to/watch.jpg')
x = 4.; y = 0.; size = 7.; xyratio = im.shape[1]/im.shape[0]
ax.imshow(im, zorder=0, extent=[x, x+size , y, y+size*xyratio])
ax.set_xlim([0.,np.max(val)+1.])
ax.set_ylim([0.,np.max(pos)+1.])
plt.show()
</code></pre>
<p>which looks like,</p>
<p><a href="http://i.stack.imgur.com/CXUcC.png" rel="nofollow"><img src="http://i.stack.imgur.com/CXUcC.png" alt="enter image description here"></a></p>
<p>Note there is also the issue of whitespace around the image which will cause it to appear away from extents.</p>
<p>You can also do something like set <code>aspect="equal"</code> but must remove the <code>extents</code>. </p>
| 0 | 2016-08-23T17:39:52Z | [
"python",
"matplotlib"
] |
How can I evaluate a View context variable as a Template variable in Django? | 39,095,793 | <p>I'd like to pass a context variable from a view into my template to direct what the template should display.</p>
<p>I have a context list variable <code>column_headers</code> that dictates the number of columns in a list page table, along with the header text that should be used.</p>
<pre><code>context['column_list'] = [
_('Animal'),
_('Owner'),
_('Reason'),
_('Time'),
_('Vet'),
_('Status')
]
</code></pre>
<p>I'd like to include a related list variable that tells the template which variable to include for each cell in the corresponding column, for example:</p>
<pre><code>context['cell_vars'] = [
'patient',
'client',
'reason',
'start_time',
'attending_staff',
'status'
]
</code></pre>
<p>such that the variable <code>FOO.client</code> would appear in the <code>'Owner'</code> column, and <code>FOO.attending_staff</code> would appear in the <code>'Vet'</code> column, etc.</p>
<p>Doing this allows me have a single list.html page to handle all of my lists.</p>
<p>So, my question is whether this is a good idea, and if so, how would I go about evaluating a 'string' presented as a context variable i.e.</p>
<pre><code>{% for row in rows %} #loop over list data
{{ row.attending_staff }} #work fine, but...
{{ row.SOME_VARIABLE_THAT_HAS_VALUE_OF_'attending_staff' }} #doesn't
{% endfor %}
</code></pre>
<p>So, if <code>x='attending_staff'</code> I need to be able to evaluate the variable <code>row.x</code> such that it actually evaluates <code>row.attending_staff</code> </p>
<p>The use case for this is very defined and involves display logic only (not data retrieval since the data is already in the loop variable <code>row</code>) so IMO could be a good fit for a template. </p>
<p>It would allow me to have a single 'list.hml' template to handle pretty much all of my lists, rather than what I have currently which is 10 x foo_list.html pages, all being very similar to each other (table structure, looping logic, icons, links, css class names etc).</p>
| 0 | 2016-08-23T08:13:29Z | 39,095,967 | <p>I think <a href="https://docs.djangoproject.com/en/1.10/howto/custom-template-tags/" rel="nofollow">custom tags or filters</a> would be a solution</p>
<p>e.g.: the following</p>
<pre><code>@register.filter
def settings_value(name):
return getattr(settings, name, "")
</code></pre>
<p>could be used in the templates like</p>
<pre><code>{% load your_filters %}
{{ "MY_SETTINGS_NAME"|settings_value }}
</code></pre>
| 0 | 2016-08-23T08:22:58Z | [
"python",
"django",
"django-templates",
"django-views"
] |
How can I evaluate a View context variable as a Template variable in Django? | 39,095,793 | <p>I'd like to pass a context variable from a view into my template to direct what the template should display.</p>
<p>I have a context list variable <code>column_headers</code> that dictates the number of columns in a list page table, along with the header text that should be used.</p>
<pre><code>context['column_list'] = [
_('Animal'),
_('Owner'),
_('Reason'),
_('Time'),
_('Vet'),
_('Status')
]
</code></pre>
<p>I'd like to include a related list variable that tells the template which variable to include for each cell in the corresponding column, for example:</p>
<pre><code>context['cell_vars'] = [
'patient',
'client',
'reason',
'start_time',
'attending_staff',
'status'
]
</code></pre>
<p>such that the variable <code>FOO.client</code> would appear in the <code>'Owner'</code> column, and <code>FOO.attending_staff</code> would appear in the <code>'Vet'</code> column, etc.</p>
<p>Doing this allows me have a single list.html page to handle all of my lists.</p>
<p>So, my question is whether this is a good idea, and if so, how would I go about evaluating a 'string' presented as a context variable i.e.</p>
<pre><code>{% for row in rows %} #loop over list data
{{ row.attending_staff }} #work fine, but...
{{ row.SOME_VARIABLE_THAT_HAS_VALUE_OF_'attending_staff' }} #doesn't
{% endfor %}
</code></pre>
<p>So, if <code>x='attending_staff'</code> I need to be able to evaluate the variable <code>row.x</code> such that it actually evaluates <code>row.attending_staff</code> </p>
<p>The use case for this is very defined and involves display logic only (not data retrieval since the data is already in the loop variable <code>row</code>) so IMO could be a good fit for a template. </p>
<p>It would allow me to have a single 'list.hml' template to handle pretty much all of my lists, rather than what I have currently which is 10 x foo_list.html pages, all being very similar to each other (table structure, looping logic, icons, links, css class names etc).</p>
| 0 | 2016-08-23T08:13:29Z | 39,096,013 | <p>Did you try to do it in this way? Or maybe you don't have option for that:</p>
<pre><code># Python script
context['column_list'] = [
_('Animal'),
_('Owner'),
_('Reason'),
_('Time'),
_('Vet'),
_('Status')
]
context['cell_vars'] = [
'patient',
'client',
'reason',
'start_time',
'attending_staff',
'status'
]
g_context = zip(context['column_list'], context['cell_vars'])
# HTML
{% for column, var in g_context %}
{{ column }}
{{ var }}
{% endfor %}
</code></pre>
<p>Is it what you're asking for?</p>
| 0 | 2016-08-23T08:25:24Z | [
"python",
"django",
"django-templates",
"django-views"
] |
Fast conversion of Java array to NumPy array (Py4J) | 39,095,994 | <p>There are some nice examples how to convert NumPy array to Java array, but not vice versa - how to convert data from Java object back to NumPy array. I have a Python script like this:</p>
<pre><code> from py4j.java_gateway import JavaGateway
gateway = JavaGateway() # connect to the JVM
my_java = gateway.jvm.JavaClass(); # my Java object
....
int_array=my_java.doSomething(int_array); # do something
my_numpy=np.zeros((size_y,size_x));
for jj in range(size_y):
for ii in range(size_x):
my_numpy[jj,ii]=int_array[jj][ii];
</code></pre>
<p><code>my_numpy</code> is the Numpy array, <code>int_array</code> is the Java array of integers - <code>int[ ][ ]</code> kind of array. Initialized in Python script as:</p>
<pre><code> int_class=gateway.jvm.int # make int class
double_class=gateway.jvm.double # make double class
int_array = gateway.new_array(int_class,size_y,size_x)
double_array = gateway.new_array(double_class,size_y,size_x)
</code></pre>
<p>Although, it works as it is, it is not the fastest way and works rather slowly - for ~1000x1000 array, the conversion took more than 5 minutes. </p>
<p>Is there any way how to make this with reasonable time?</p>
<p>If I try:</p>
<pre><code> test=np.array(int_array)
</code></pre>
<p>I get:</p>
<pre><code> ValueError: invalid __array_struct__
</code></pre>
| 1 | 2016-08-23T08:24:19Z | 39,726,480 | <p>I've had a similar issue, just trying to plot spectral vectors (Java arrays) I got from the Java side via py4j.
Here, the conversion from the Java Array to a Python list is achieved by the list() function. This might give some clues as how to use it to fill NumPy arrays ...</p>
<pre><code>vectors = space.getVectorsAsArray(); # Java array (MxN)
wvl = space.getAverageWavelengths(); # Java array (N)
wavelengths = list(wvl)
import matplotlib.pyplot as mp
mp.hold
for i, dataset in enumerate(vectors):
mp.plot(wavelengths, list(dataset))
</code></pre>
<p>Whether this is faster than the nested for loops you used I cannot say, but it also does the trick:</p>
<pre><code>import numpy
from numpy import array
x = array(wavelengths)
v = array(list(vectors))
mp.plot(x, numpy.rot90(v))
</code></pre>
| 0 | 2016-09-27T13:50:19Z | [
"java",
"python",
"numpy",
"py4j"
] |
How to Sort list of list as per user input? | 39,096,075 | <p>I want to sort list of list according to the user input.</p>
<pre><code>output = [[1,2],[3,4],[5,6],[7,8]] # input
# ^ ^ ^ ^
# A B C D
A = output[0] ; B = output[1] ; C = output[2] ; D = output[3] # initialization
userin = input('Enter sequence')
seq_list = userin.split(',')
print(seq_list)
>>> Enter sequence B,C,D,A
>>> ['B', 'C', 'D', 'A']
</code></pre>
<p>Python interprets input values as string, whereas i want those corresponding list to be reflected.</p>
<p>Expected output : </p>
<pre><code>>>> Enter sequence B,C,D,A
>>> [[3, 4], [5, 6], [7, 8], [1, 2]]
</code></pre>
| 1 | 2016-08-23T08:29:07Z | 39,096,281 | <p>EDIT:
I've re-written the <code>output</code> variable as a dictionary using the stated letters as keys. Then it uses a list comprehension on <code>seq_list</code> to access the dictionary in the order the user has supplied.</p>
<pre><code>output = {"A": [1,2], "B": [3,4],"C": [5,6],"D": [7,8]}
userin = input('Enter sequence')
seq_list = userin.split(',')
temp_list = [output[key] for key in seq_list]
print(temp_list)
</code></pre>
| 0 | 2016-08-23T08:38:48Z | [
"python",
"list"
] |
How to Sort list of list as per user input? | 39,096,075 | <p>I want to sort list of list according to the user input.</p>
<pre><code>output = [[1,2],[3,4],[5,6],[7,8]] # input
# ^ ^ ^ ^
# A B C D
A = output[0] ; B = output[1] ; C = output[2] ; D = output[3] # initialization
userin = input('Enter sequence')
seq_list = userin.split(',')
print(seq_list)
>>> Enter sequence B,C,D,A
>>> ['B', 'C', 'D', 'A']
</code></pre>
<p>Python interprets input values as string, whereas i want those corresponding list to be reflected.</p>
<p>Expected output : </p>
<pre><code>>>> Enter sequence B,C,D,A
>>> [[3, 4], [5, 6], [7, 8], [1, 2]]
</code></pre>
| 1 | 2016-08-23T08:29:07Z | 39,096,324 | <p>It would be easier to make user input numbers instead of letters. However, if you want to stick to letters you can just map them in a dictionary. My example approach looks like this:</p>
<pre><code>output = [[1,2],[3,4],[5,6],[7,8]]
output_dict = {i:elem for i, elem in enumerate(output)}
user_input = input('Enter sequence - numbers from 1 to 4 separated by comma')
print [output_dict[elem - 1] for elem in user_input]
</code></pre>
| 0 | 2016-08-23T08:40:24Z | [
"python",
"list"
] |
How to Sort list of list as per user input? | 39,096,075 | <p>I want to sort list of list according to the user input.</p>
<pre><code>output = [[1,2],[3,4],[5,6],[7,8]] # input
# ^ ^ ^ ^
# A B C D
A = output[0] ; B = output[1] ; C = output[2] ; D = output[3] # initialization
userin = input('Enter sequence')
seq_list = userin.split(',')
print(seq_list)
>>> Enter sequence B,C,D,A
>>> ['B', 'C', 'D', 'A']
</code></pre>
<p>Python interprets input values as string, whereas i want those corresponding list to be reflected.</p>
<p>Expected output : </p>
<pre><code>>>> Enter sequence B,C,D,A
>>> [[3, 4], [5, 6], [7, 8], [1, 2]]
</code></pre>
| 1 | 2016-08-23T08:29:07Z | 39,096,349 | <p>You can use a dictionary comprehension and the <code>zip</code> function to convert your <code>output</code> list of lists into a dict of lists.</p>
<pre><code>output = [[1, 2], [3, 4], [5, 6], [7, 8]]
d = {c: u for c, u in zip('ABCD', output)}
print(d)
userin = 'B,C,D,A'
seq_list = [d[c] for c in userin.split(',')]
print(seq_list)
</code></pre>
<p><strong>typical output</strong></p>
<pre><code>{'C': [5, 6], 'B': [3, 4], 'A': [1, 2], 'D': [7, 8]}
[[3, 4], [5, 6], [7, 8], [1, 2]]
</code></pre>
<p>Python dictionaries are unordered, and in Python 3 the order that items of the dict <code>d</code> are printed in will change each time you run my code. Of course, that won't affect the order of sub-lists in <code>seq_list</code> </p>
| 1 | 2016-08-23T08:41:26Z | [
"python",
"list"
] |
int input with a string and a variable | 39,096,337 | <p>I'm somewhat new to python and am working on an assignment with a friend for school.
We wanted to ask for a swimmer's name, followed by asking what time they managed to achieve.
We wanted the program to work like this:</p>
<pre><code>Name = input('Input swimmers name: ')
Time = int(input('What time did',Name,'achieve? ')
</code></pre>
<p>However it isn't working. What could we use here that will allow us to ask the swimmer's time by using the swimmer's name in the question?</p>
| 0 | 2016-08-23T08:41:00Z | 39,096,376 | <p>You have to pass a single string to <code>input</code>, you can do it by first concatenating your 3 strings:</p>
<pre><code>Time = int(input('What time did' + Name + 'achieve? ')
</code></pre>
<p>BTW: "achieve" with an "e" ;-)</p>
| 3 | 2016-08-23T08:43:00Z | [
"python",
"input"
] |
int input with a string and a variable | 39,096,337 | <p>I'm somewhat new to python and am working on an assignment with a friend for school.
We wanted to ask for a swimmer's name, followed by asking what time they managed to achieve.
We wanted the program to work like this:</p>
<pre><code>Name = input('Input swimmers name: ')
Time = int(input('What time did',Name,'achieve? ')
</code></pre>
<p>However it isn't working. What could we use here that will allow us to ask the swimmer's time by using the swimmer's name in the question?</p>
| 0 | 2016-08-23T08:41:00Z | 39,096,437 | <p>You can also use %s for concatenation </p>
<pre><code>Time = int(input('What time did %s achive? ' % Name ))
</code></pre>
| 2 | 2016-08-23T08:45:35Z | [
"python",
"input"
] |
How do I add the path to a directory to the environment variables using python | 39,096,384 | <p>I want to know if it is possible to add the path to a directory to the environment variables permanently using python. I have seen other questions that relate to mine but the answers there only add the path temporarily,I want to know if there's a way to add it permanently</p>
| 0 | 2016-08-23T08:43:07Z | 39,096,747 | <p>While using bash add this
<code>~/.bashrc</code>
<code>export PYTHONPATH="${PYTHONPATH}:/Home/dev/path</code></p>
<p>Make sure the directory you point to has at the topmost <code>init.py</code> file in your directory structure</p>
| 1 | 2016-08-23T09:00:08Z | [
"python",
"environment-variables"
] |
Loop until a specific user input is received in Python | 39,096,424 | <p>Hello Im doing a assessment for school. Im quite a newbie to python and I really have no idea on how to loop this</p>
<pre><code> achieved=50 #predefined variables for grade input
merit=70
excellence=85
max=100
import re #imports re an external modeule which defines re
studentfname = input("Input Student first name in lowercase")
if any( [ i>'z' or i<'a' for i in studentfname]):#checks if is in lowercase letters
print ("Invalid input must be letter and in lowercase")
import re
studentlname = input("Input Student last name in lowercase")
if any( [ i>'z' or i<'a' for i in studentlname]):
print ("Invalid input must be letter and in lowercase")
import sys
raise SystemExit
print(studentfname)
elif len(studentlname)>30:
print ("Very long string")
raise SystemExit
import re
teacherfname = input("Input your first name in lowercase")
if any( [ i>'z' or i<'a' for i in teacherfname]):
print ("Invalid input must be letter and in lowercase")
import sys
raise SystemExit
print(teacherfname)
elif len(teacherfname)>30:
print ("Very long string")
raise SystemExit
print(teacherfname)
teacherlname = input("Input your last name in lowercase")
if any( [ i>'z' or i<'a' for i in teacherlname]):
print ("Invalid input must be letter and in lowercase")
import sys
raise SystemExit
print(teacherlname)
elif len(teacherlname)>30:
print ("Very long string")
raise SystemExit
print(teachercode)
teachercode = input("Input your teacher code in lowercase")
if any( [ i>'z' or i<'a' for i in teachercode]):
print ("Invalid input must be letter and in lowercase")
import sys
raise SystemExit
print(teachercode)
elif len(teachercode)>30:
print ("Very long string")
raise SystemExit
print(teachercode)
while True: #inputs student depending on the input prints out results id achieved, merit and excellence
try:
grade = int(input("Enter student's grade"))
print(str(grade))
break
except ValueError:
continue
#prints if not a number stops letters
if grade >merit>excellence>= achieved:
print("Achieved")
if grade < achieved:
print("not achieved")
if grade >=merit>excellence < excellence:
print("merit")
if grade >= excellence > merit:
print("excellence")
if grade < 0:
print("can't be negative")
raise SystemExit
if grade > max:
print("Cannot be more than 100")
raise SystemExit
print("student's details")#last print of variablesa
print(studentfname,studentlname)
print("teacher's details")
print(teacherfname,teacherlname,teachercode)
print("student's grade")
print(grade)
if grade >merit>excellence>= achieved:
print("Achieved")
if grade < achieved:
print("not achieved")
if grade >=merit>excellence < excellence:
print("merit")
if grade >= excellence > merit:
print("excellence")
if grade < 0:
print("can't be negative")
raise SystemExit
if grade > max:
print("Cannot be more than 100")
raise SystemExit
print("Thanks for adding in the grades")
break
</code></pre>
<p>Im trying to make it so that it will ask the user if they would like to input more student data after they have done one student. eg like if they wish to continue and basically repeat the coding again. I would really love some help</p>
| -7 | 2016-08-23T08:45:07Z | 39,096,498 | <p>You just loop it</p>
<pre><code>achieved=50 #predefined variables for grade input
merit=70
excellence=85
max=100
import sys
import re #imports re an external modeule which defines re
while(1):
studentfname = input("Input Student first name in lowercase")
if any( [ i>'z' or i<'a' for i in studentfname]):#checks if is in lowercase letters
print ("Invalid input must be letter and in lowercase")
raise SystemExit
print(studentfname)
studentlname = input("Input Student last name in lowercase")
if any( [ i>'z' or i<'a' for i in studentlname]):
print ("Invalid input must be letter and in lowercase")
raise SystemExit
elif len(studentlname)>30:
print ("Very long string")
raise SystemExit
print(studentlname)
teacherfname = input("Input your first name in lowercase")
if any( [ i>'z' or i<'a' for i in teacherfname]):
print ("Invalid input must be letter and in lowercase")
raise SystemExit
elif len(teacherfname)>30:
print ("Very long string")
raise SystemExit
print(teacherfname)
teacherlname = input("Input your last name in lowercase")
if any( [ i>'z' or i<'a' for i in teacherlname]):
print ("Invalid input must be letter and in lowercase")
raise SystemExit
elif len(teacherlname)>30:
print ("Very long string")
raise SystemExit
print(teacherlname)
teachercode = input("Input your teacher code in lowercase")
if any( [ i>'z' or i<'a' for i in teachercode]):
print ("Invalid input must be letter and in lowercase")
raise SystemExit
elif len(teachercode)>30:
print ("Very long string")
raise SystemExit
print(teachercode)
while True: #inputs student depending on the input prints out results id achieved, merit and excellence
try:
grade = int(input("Enter student's grade"))
print(str(grade))
except ValueError:
continue
if grade >merit>excellence>= achieved:
graden = "Achieved"
print("Achieved")
if grade < achieved:
print("not achieved")
if grade >=merit>excellence < excellence:
graden = "merit"
print("merit")
if grade >= excellence > merit:
graden = "excellence"
print("excellence")
if grade < 0:
print("can't be negative")
raise SystemExit
if grade > max:
print("Cannot be more than 100")
raise SystemExit
print(grade)
print("Student")
print(studentfname)
print(studentlname)
print("Teacher")
print(teacherfname)
print(teacherlname)
print(teachercode)
print("Grade")
print(str(grade))
print(graden)
print("Thanks for adding in the grades")
break
if input('More?')=='no': break
</code></pre>
<p>Now it works. Just remember quotation marks in input. Or fix it.</p>
| 0 | 2016-08-23T08:48:35Z | [
"python",
"loops"
] |
Loop until a specific user input is received in Python | 39,096,424 | <p>Hello Im doing a assessment for school. Im quite a newbie to python and I really have no idea on how to loop this</p>
<pre><code> achieved=50 #predefined variables for grade input
merit=70
excellence=85
max=100
import re #imports re an external modeule which defines re
studentfname = input("Input Student first name in lowercase")
if any( [ i>'z' or i<'a' for i in studentfname]):#checks if is in lowercase letters
print ("Invalid input must be letter and in lowercase")
import re
studentlname = input("Input Student last name in lowercase")
if any( [ i>'z' or i<'a' for i in studentlname]):
print ("Invalid input must be letter and in lowercase")
import sys
raise SystemExit
print(studentfname)
elif len(studentlname)>30:
print ("Very long string")
raise SystemExit
import re
teacherfname = input("Input your first name in lowercase")
if any( [ i>'z' or i<'a' for i in teacherfname]):
print ("Invalid input must be letter and in lowercase")
import sys
raise SystemExit
print(teacherfname)
elif len(teacherfname)>30:
print ("Very long string")
raise SystemExit
print(teacherfname)
teacherlname = input("Input your last name in lowercase")
if any( [ i>'z' or i<'a' for i in teacherlname]):
print ("Invalid input must be letter and in lowercase")
import sys
raise SystemExit
print(teacherlname)
elif len(teacherlname)>30:
print ("Very long string")
raise SystemExit
print(teachercode)
teachercode = input("Input your teacher code in lowercase")
if any( [ i>'z' or i<'a' for i in teachercode]):
print ("Invalid input must be letter and in lowercase")
import sys
raise SystemExit
print(teachercode)
elif len(teachercode)>30:
print ("Very long string")
raise SystemExit
print(teachercode)
while True: #inputs student depending on the input prints out results id achieved, merit and excellence
try:
grade = int(input("Enter student's grade"))
print(str(grade))
break
except ValueError:
continue
#prints if not a number stops letters
if grade >merit>excellence>= achieved:
print("Achieved")
if grade < achieved:
print("not achieved")
if grade >=merit>excellence < excellence:
print("merit")
if grade >= excellence > merit:
print("excellence")
if grade < 0:
print("can't be negative")
raise SystemExit
if grade > max:
print("Cannot be more than 100")
raise SystemExit
print("student's details")#last print of variablesa
print(studentfname,studentlname)
print("teacher's details")
print(teacherfname,teacherlname,teachercode)
print("student's grade")
print(grade)
if grade >merit>excellence>= achieved:
print("Achieved")
if grade < achieved:
print("not achieved")
if grade >=merit>excellence < excellence:
print("merit")
if grade >= excellence > merit:
print("excellence")
if grade < 0:
print("can't be negative")
raise SystemExit
if grade > max:
print("Cannot be more than 100")
raise SystemExit
print("Thanks for adding in the grades")
break
</code></pre>
<p>Im trying to make it so that it will ask the user if they would like to input more student data after they have done one student. eg like if they wish to continue and basically repeat the coding again. I would really love some help</p>
| -7 | 2016-08-23T08:45:07Z | 39,096,523 | <p>To answer your question what you need is to loop until a given input is given.
So you would use:</p>
<pre><code>while True: # infinite loop
user_input = raw_input("Want to continue? ")
if user_input == "No":
break # stops the loop
else:
# do whatever computations you need
</code></pre>
| 2 | 2016-08-23T08:50:03Z | [
"python",
"loops"
] |
How to know size of python module? | 39,096,604 | <p>When I install the module using <code>pip install module_name</code>, I am able to see the size of either wheel or the package.</p>
<p>so the question is, is it possible to know just the size of each module?</p>
<p>something like this.</p>
<pre><code>import pip
for dist in pip.get_installed_distributions():
print(distribution_size_only of dist)
</code></pre>
<p>I want to know estimated size of the distribution so that I can remove them from winpython distribution.</p>
| 1 | 2016-08-23T08:53:42Z | 39,096,975 | <pre><code>import os
import pip
def calc_container(path):
total_size = 0
for dirpath, dirnames, filenames in os.walk(path):
for f in filenames:
fp = os.path.join(dirpath, f)
total_size += os.path.getsize(fp)
return total_size
for dist in pip.get_installed_distributions():
try:
path = os.path.join(dist.location, dist.project_name)
size = calc_container(path)
if size:
print path
print size
except OSError:
'{} no longer exists'.format(dist.project_name)
</code></pre>
<p>If you're in virtualenv, you can use first option to get more:</p>
<blockquote>
<p>get_installed_distributions(local_only=True, skip=('python', 'wsgiref', 'argparse'), include_editables=True, editables_only=False, user_only=False)
Return a list of installed Distribution objects.</p>
<p>If <code>local_only</code> is True (default), only return installations
local to the current virtualenv, if in a virtualenv.</p>
</blockquote>
| 1 | 2016-08-23T09:10:22Z | [
"python"
] |
How to know size of python module? | 39,096,604 | <p>When I install the module using <code>pip install module_name</code>, I am able to see the size of either wheel or the package.</p>
<p>so the question is, is it possible to know just the size of each module?</p>
<p>something like this.</p>
<pre><code>import pip
for dist in pip.get_installed_distributions():
print(distribution_size_only of dist)
</code></pre>
<p>I want to know estimated size of the distribution so that I can remove them from winpython distribution.</p>
| 1 | 2016-08-23T08:53:42Z | 39,099,602 | <p>I know this is vague but this is what I wanted:</p>
<pre><code>import re
import requests
import json
def regexsubstring(s, p):
p = re.compile(p, flags=re.IGNORECASE)
return p.search(s)
def wf(data,path,mode):
with open(path, mode, encoding='utf-8') as out:
out.write(data)
return
import pip
dists_size_info = {}
for dist in pip.get_installed_distributions():
url = "https://pypi.python.org/pypi/" + dist.key + "/" + dist.version
r = requests.get(url)
size = regexsubstring(r.text, """<td style="text-align: right;">(\w+)</td>""").group(1)
dists_size_info[dist.key] = [dist.version, size]
print(dists_size_info)
wf(json.dumps(dists_size_info),'dists_size_info.txt','w')
</code></pre>
<p>or you can get list at:</p>
<p><a href="http://hastebin.com/qiconesoje.apache" rel="nofollow">http://hastebin.com/qiconesoje.apache</a></p>
| 0 | 2016-08-23T11:12:33Z | [
"python"
] |
Django error: unsupported operand type(s) for *: 'NoneType' and 'float' | 39,096,659 | <p><br>I have some problem with my code. I was looking have to solve it, but I didn't find similar problem. I want to multiple and then sum some field values, but I get error from a title. Have to solve this problem? I suppose that is problem with data type, but I don't know how to define equation. Please help me.</p>
<pre><code>class Bill(models.Model):
date = models.DateField(default=datetime.now())
tax = models.FloatField(default=0.20)
priceNoTax = models.IntegerField()#integer that I get from other class
priceTax = models.FloatField()
idAccount = models.ForeignKey(Account, on_delete=models.CASCADE, verbose_name="Account")
def save(self, *args, **kwargs):
if self.priceTax is None:
self.priceTax = self.priceNoTax+(self.priceNoTax*self.tax)#here is an error
super(Bill, self).save(*args, **kwargs)
def __str__(self):
return self.date
</code></pre>
<p>Thanks a lot!</p>
| 0 | 2016-08-23T08:56:17Z | 39,096,786 | <p>The order of the arguments in the error message corresponds to the code:</p>
<p><code>'NoneType' and 'float'</code> <=> <code>self.priceNoTax*self.tax</code></p>
<p><code>self.priceNoTax</code> has not been initialised, or if you loaded this from the database then it contained <code>NULL</code>. You can verify this with a <code>print</code> of the contents of <code>self.priceNoTax</code> on the line before the multiplication takes place.</p>
<p>Double check how <code>self.priceNoTax</code> is being set.</p>
| 0 | 2016-08-23T09:01:45Z | [
"python",
"django"
] |
Raspberry Pi 3 Python and Opencv for facial recognition | 39,096,755 | <p>I am receiving this message when trying to execute script whether in virtual environment or a normal Python shell. </p>
<pre><code>File "/home/pi/facesample1.py", line 10, in <module>
gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
error: /home/pi/opencv-3.1.0/modules/imgproc/src/color.cpp:8000: error: (-215) scn == 3 || scn == 4 in function cvtColor
</code></pre>
<p>Here is my code:</p>
<pre><code>import cv2
#Load an image from file
image = cv2.imread("fronthead.jpg", 1)
#Load a cascade file for detecting faces
face_cascade = cv2.CascadeClassifier('/usr/share/opencv/haarcascades/haarcascade_frontalface_alt.xml')
#Convert to grayscale
gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
#Look for faces in the image using the loaded cascade file
faces = face_cascade.detectMultiScale(gray, 1.1, 5)
print "Found "+str(len(faces))+" face(s)"
#Draw a rectangle around every found face
for (x,y,w,h) in faces:
cv2.rectangle(image,(x,y),(x+w,y+h),(255,0,0),2)
#Save the result image
cv2.imwrite('camresult.jpg',image)
</code></pre>
<p>Why am I getting this error?</p>
| 0 | 2016-08-23T09:00:24Z | 39,097,751 | <p>Your <code>image</code> variable is apparently not a 3 or 4 channel image.
Thus, <code>cvtColor()</code> is unable to transform it to grayscale.</p>
<p>Check <code>image.shape</code> and see that it returns something with the right dimensions (i.e. a 3D array with last dimension 3 or 4).</p>
<p>It is also quite possible that <code>image</code> is <code>None</code>, which usually means that the path to the file is wrong.</p>
| 0 | 2016-08-23T09:45:43Z | [
"python",
"c++",
"opencv",
"raspberry-pi3"
] |
what is the Tensorflow batch size when you use high-level API tf.contrib.learn.DNNClassifier | 39,096,757 | <pre><code>def binaryClassify_DNN(units,steps,trainingFilePath,testingFilePath,modelPath):
# Data sets
# Load datasets.
training_set = tf.contrib.learn.datasets.base.load_csv(filename=trainingFilePath,target_dtype=np.float)
test_set = tf.contrib.learn.datasets.base.load_csv(filename=testingFilePath,target_dtype=np.float)
# Build 3 layer DNN with 10, 20, 10 units respectively.
classifier = tf.contrib.learn.DNNClassifier(hidden_units=units,n_classes=2,model_dir=modelPath,optimizer=tf.train.ProximalAdagradOptimizer(learning_rate=0.1))
# Fit model.
classifier.fit(x=training_set.data,
y=training_set.target,
steps=steps)
# Evaluate accuracy.
accuracy_score = classifier.evaluate(x=test_set.data,
y=test_set.target)["accuracy"]
print('Accuracy: {0:f}'.format(accuracy_score))
</code></pre>
<p>I've coded above source little changed from <a href="https://www.tensorflow.org/versions/r0.10/tutorials/tflearn/index.html#tf-contrib-learn-quickstart" rel="nofollow">https://www.tensorflow.org/versions/r0.10/tutorials/tflearn/index.html#tf-contrib-learn-quickstart</a></p>
<p>As you can see, I didn't add parameter for <code>batch_size</code> which I can add to <code>classifier.fi()</code></p>
<p>I tried executing this code and it seemed that it was looping without batch size.
I mean that it looks like training with the full size of data instead of mini batch.</p>
<p>Is it true?</p>
<p>I'd like to know what is the default setting for batch size.</p>
<p>Thanks in advance.</p>
| 0 | 2016-08-23T09:00:27Z | 39,096,855 | <p>I am sorry i should have looked into source code before posting</p>
<pre><code>def fit(self, x=None, y=None, input_fn=None, steps=None, batch_size=None,
monitors=None, max_steps=None):
"""Trains a model given training data `x` predictions and `y` targets.
Args:
x: Matrix of shape [n_samples, n_features...]. Can be iterator that
returns arrays of features. The training input samples for fitting the
model. If set, `input_fn` must be `None`.
y: Vector or matrix [n_samples] or [n_samples, n_outputs]. Can be
iterator that returns array of targets. The training target values
(class labels in classification, real numbers in regression). If set,
`input_fn` must be `None`.
input_fn: Input function. If set, `x`, `y`, and `batch_size` must be
`None`.
steps: Number of steps for which to train model. If `None`, train forever.
If set, `max_steps` must be `None`.
batch_size: minibatch size to use on the input, defaults to first
dimension of `x`. Must be `None` if `input_fn` is provided.
monitors: List of `BaseMonitor` subclass instances. Used for callbacks
inside the training loop.
max_steps: Number of total steps for which to train model. If `None`,
train forever. If set, `steps` must be `None`.
Two calls to `fit(steps=100)` means 200 training
iterations. On the other hand, two calls to `fit(max_steps=100)` means
that the second call will not do any iteration since first call did
all 100 steps.
Returns:
`self`, for chaining.
Raises:
ValueError: If `x` or `y` are not `None` while `input_fn` is not `None`.
ValueError: If both `steps` and `max_steps` are not `None`.
"""
</code></pre>
<p>As you can see, the default batch_size is the first dimension of 'x'</p>
| 0 | 2016-08-23T09:04:55Z | [
"python",
"neural-network",
"tensorflow",
"deep-learning"
] |
Python : How should I send data values to web-server and get result using python? | 39,096,775 | <p>I am trying to get the output page once we submit input on this page. <a href="http://batblob.com" rel="nofollow">http://batblob.com</a>
Below is my code but it is giving me the html code of same page rather than of output page.
I am on Python 2.7, Please suggest me how should I get there.
Thank you in advance.</p>
<pre><code>import requests
import sys
from BeautifulSoup import BeautifulSoup
url = 'http://batblob.com'
session = requests.Session()
form = {
'bitadd':'anybitcoinaddress',
'submit': 'submit',
}
r = requests.post( url, data=form)
response = session.get(url)
html = response.content
soup = BeautifulSoup(html)
print soup
</code></pre>
| 0 | 2016-08-23T09:01:12Z | 39,096,950 | <p>In this case the data you want is already in your <strong>r</strong> variable. I would assume the following will get what you are after.</p>
<pre><code>import requests
from BeautifulSoup import BeautifulSoup
url = 'http://batblob.com'
form = {
'bitadd':'anybitcoinaddress',
'submit': 'submit',
}
# Post form data and parse response
response = requests.post(url, data=form)
soup = BeautifulSoup(response.content)
print(soup)
</code></pre>
| 0 | 2016-08-23T09:09:23Z | [
"python",
"python-requests"
] |
Python XML DOM collecting elements data | 39,096,799 | <p>I was trying to retrieve some info of an XML tag with python, my achieve is to have a dictionary wich saves for each situation tag id, all child data, but I don´t know how to deal with the fact that extract data from text nodes , thanks.</p>
<p><strong>My code:</strong></p>
<pre><code>from xml.dom.minidom import *
import requests
print("GETTING XML...")
resp = requests.get('http://infocar.dgt.es/datex2/dgt/SituationPublication/all/content.xml', stream = True) #XML that I need
if resp.status_code != 200:
raise ApiError('GET /tasks/ {}'.format(resp.status_code))
print("XML RECIBIDO 200 OK")
#resp.raw.decode_content = True
print("GUARDANDO XML")
with open("DGT_DATEX.xml", "wb") as handle:
for data in (resp.iter_content()):
handle.write(data)
print("XML GUARDADO")
print("INICIANDO PARSEO..")
dom3 = parse("DGT_DATEX.xml")
print(dom3)#memory dir
print("DATEX PARSEADO")
def getText(nodelist):
dict = {}
listofdata = list()
for node in nodelistofPayloadTag:
if node.nodeType != node.TEXT_NODE:
dict[node.getAttribute('id')] = listofdata
listofdata = goDeep(node.childNodes ,listofdata)
print(str.format("El diccionario antes de ser retornado es {0}", dict))
return dict
def goDeep(childsOfElement, l):
for i in childsOfElement:
if i.nodeType != i.TEXT_NODE:
goDeep(i.childNodes, l)
else:
l.append(i.data)
return l
def getSituation(payloadTag):
getText(payloadTag.childNodes)
def getPayLoad(dom):
print(str.format("Tag to be processed:{0}",dom.getElementsByTagNameNS('*', 'payloadPublication')[0]))
getSituation(dom.getElementsByTagNameNS('*', 'payloadPublication')[0])
print(str.format("Verificando que el dato retornado es un diccionario, {0}, y contiene {1}", type(getPayLoad(dom3)), getPayLoad(dom3)))
</code></pre>
| 0 | 2016-08-23T09:02:35Z | 39,102,441 | <p>Here is the way which allow me to collect data from childs, thanks</p>
<pre><code>import xml.etree.ElementTree as ET
from xml.dom.minidom import *
import requests
print("GETTING XML...")
resp = requests.get('http://infocar.dgt.es/datex2/dgt/SituationPublication/all/content.xml', stream = True) #XML that I need
if resp.status_code != 200:
raise ApiError('GET /tasks/ {}'.format(resp.status_code))
print("XML RECIBIDO 200 OK")
#resp.raw.decode_content = True
print("GUARDANDO XML")
with open("DGT_DATEX.xml", "wb") as handle:
for data in (resp.iter_content()):
handle.write(data)
print("XML GUARDADO")
print("INICIANDO PARSEO..")
dom3 = parse("DGT_DATEX.xml")
print(dom3)#memory dir
print("DATEX PARSEADO")
def getAttributeID(element):
return element.getAttribute('id')
def getText(element):
return element.data
def getPayLoad(dom):
dict = {}
index = 1 #esto sirve para relacionar los atributos con el situation que les corresponde
indexRecord = 1 #esto sirve para relacionar los atributos con el situationRecord que les corresponde
for i in dom.getElementsByTagNameNS('*', 'situation'):
#Por cada situation del XML vamos a sacar el situation id y todos los campos que pertecen a este de la siguiente manera
print(str.format("Situation ID: {0} numero {1}", getAttributeID(i), index))
print(getText(dom.getElementsByTagNameNS('*','confidentiality')[index].firstChild))#por ejemplo aquÃ, se coge el first text de la lista de atributos confidentiality dado el index, que nos indica la relacion con el situation
print(getText(dom.getElementsByTagNameNS('*', 'informationStatus')[index].firstChild))
for record in dom.getElementsByTagNameNS('*', 'situation')[index].childNodes:#buscamos el hijo del corespondiente situation que tenga un ID, lo que nos deveulve elsituationRecord
if record.nodeType != record.TEXT_NODE:
print(str.format("SituationRecord ID: {0} numero {1}", getAttributeID(record), indexRecord))
print(getText(dom.getElementsByTagNameNS('*', 'situationRecordCreationReference')[indexRecord].firstChild))
print(getText(dom.getElementsByTagNameNS('*', 'situationRecordCreationTime')[indexRecord].firstChild))
print(getText(dom.getElementsByTagNameNS('*', 'situationRecordVersion')[indexRecord].firstChild))
print(getText(dom.getElementsByTagNameNS('*', 'situationRecordVersionTime')[indexRecord].firstChild))
print(getText(dom.getElementsByTagNameNS('*', 'situationRecordFirstSupplierVersionTime')[indexRecord].firstChild))
print(getText(dom.getElementsByTagNameNS('*', 'probabilityOfOccurrence')[indexRecord].firstChild))
print(getText(dom.getElementsByTagNameNS('*', 'sourceCountry')[indexRecord].firstChild))
print(getText(dom.getElementsByTagNameNS('*', 'sourceIdentification')[indexRecord].firstChild))
print(getText(dom.getElementsByTagNameNS('*', 'validityStatus')[indexRecord].firstChild))
print(getText(dom.getElementsByTagNameNS('*', 'overallStartTime')[indexRecord].firstChild))
print(getText(dom.getElementsByTagNameNS('*', 'overallEndTime')[indexRecord].firstChild))
print(getText(dom.getElementsByTagNameNS('*', 'impactOnTraffic')[indexRecord].firstChild))
print(getText(dom.getElementsByTagNameNS('*', 'locationDescriptor')[indexRecord].firstChild))
print(getText(dom.getElementsByTagNameNS('*', 'tpegDirection')[indexRecord].firstChild))
print(getText(dom.getElementsByTagNameNS('*', 'latitude')[indexRecord].firstChild))
print(getText(dom.getElementsByTagNameNS('*', 'longitude')[indexRecord].firstChild))
print(str.format("VALUE FIELD: {0}", getText(dom.getElementsByTagNameNS('*', 'descriptor')[indexRecord].firstChild)))
indexRecord = indexRecord + 1
index = index + 1
getPayLoad(dom3)
</code></pre>
| 0 | 2016-08-23T13:21:19Z | [
"python",
"xml"
] |
Python XML DOM collecting elements data | 39,096,799 | <p>I was trying to retrieve some info of an XML tag with python, my achieve is to have a dictionary wich saves for each situation tag id, all child data, but I don´t know how to deal with the fact that extract data from text nodes , thanks.</p>
<p><strong>My code:</strong></p>
<pre><code>from xml.dom.minidom import *
import requests
print("GETTING XML...")
resp = requests.get('http://infocar.dgt.es/datex2/dgt/SituationPublication/all/content.xml', stream = True) #XML that I need
if resp.status_code != 200:
raise ApiError('GET /tasks/ {}'.format(resp.status_code))
print("XML RECIBIDO 200 OK")
#resp.raw.decode_content = True
print("GUARDANDO XML")
with open("DGT_DATEX.xml", "wb") as handle:
for data in (resp.iter_content()):
handle.write(data)
print("XML GUARDADO")
print("INICIANDO PARSEO..")
dom3 = parse("DGT_DATEX.xml")
print(dom3)#memory dir
print("DATEX PARSEADO")
def getText(nodelist):
dict = {}
listofdata = list()
for node in nodelistofPayloadTag:
if node.nodeType != node.TEXT_NODE:
dict[node.getAttribute('id')] = listofdata
listofdata = goDeep(node.childNodes ,listofdata)
print(str.format("El diccionario antes de ser retornado es {0}", dict))
return dict
def goDeep(childsOfElement, l):
for i in childsOfElement:
if i.nodeType != i.TEXT_NODE:
goDeep(i.childNodes, l)
else:
l.append(i.data)
return l
def getSituation(payloadTag):
getText(payloadTag.childNodes)
def getPayLoad(dom):
print(str.format("Tag to be processed:{0}",dom.getElementsByTagNameNS('*', 'payloadPublication')[0]))
getSituation(dom.getElementsByTagNameNS('*', 'payloadPublication')[0])
print(str.format("Verificando que el dato retornado es un diccionario, {0}, y contiene {1}", type(getPayLoad(dom3)), getPayLoad(dom3)))
</code></pre>
| 0 | 2016-08-23T09:02:35Z | 39,119,543 | <p>I came to this code, is it what you were looking for?</p>
<pre><code>def getText(element):
return element.data.encode('utf-8').strip()
def getPayLoad(dom):
attrs = ['confidentiality', 'informationStatus', 'situationRecordCreationReference', 'situationRecordCreationTime', 'situationRecordVersion', 'situationRecordVersionTime', 'situationRecordFirstSupplierVersionTime', 'probabilityOfOccurrence', 'sourceCountry', 'sourceIdentification', 'validityStatus', 'overallStartTime', 'overallEndTime', 'impactOnTraffic', 'locationDescriptor', 'tpegDirection', 'latitude', 'longitude', 'tpegDescriptorType', 'from']
for index, node in enumerate(dom.getElementsByTagNameNS('*', 'situation'), 1):
print("\nSituation ID: {0} numero {1}".format(getAttributeID(node), index))
for attr in attrs:
key = node.getElementsByTagNameNS('*', attr)
if key:
value = getText(key[0].firstChild)
if value:
print('{0}: {1}'.format(attr, value))
</code></pre>
| 1 | 2016-08-24T09:34:51Z | [
"python",
"xml"
] |
Call Javascript from python | 39,096,901 | <p>I am looking for a way to call a js function from a python function. I am coming to you because I also need my js function to use DOM, so pyv8 for example is not a solution.. Do you guys have any idea? Is it even possible?</p>
<p>Thanks in advance.</p>
| 1 | 2016-08-23T09:06:48Z | 39,097,009 | <p>According to <a href="http://stackoverflow.com/a/30537286/6353933">http://stackoverflow.com/a/30537286/6353933</a>,</p>
<pre><code>import js2py
js = """
function escramble_758(){
var a,b,c
a='+1 '
b='84-'
a+='425-'
b+='7450'
c='9'
document.write(a+c+b)
}
escramble_758()
""".replace("document.write", "return ")
result = js2py.eval_js(js) # executing JavaScript and converting the result to python string
</code></pre>
<p>Advantages of Js2Py include portability and extremely easy integration with python (since basically JavaScript is being translated to python).</p>
<p>To install:</p>
<pre><code>pip install js2py
</code></pre>
| 2 | 2016-08-23T09:11:48Z | [
"javascript",
"python"
] |
Call Javascript from python | 39,096,901 | <p>I am looking for a way to call a js function from a python function. I am coming to you because I also need my js function to use DOM, so pyv8 for example is not a solution.. Do you guys have any idea? Is it even possible?</p>
<p>Thanks in advance.</p>
| 1 | 2016-08-23T09:06:48Z | 39,097,157 | <p>PyExecJS seems to be a good option.</p>
<pre><code>>>> import execjs
>>> execjs.eval("'red yellow blue'.split(' ')")
['red', 'yellow', 'blue']
>>> ctx = execjs.compile("""
... function add(x, y) {
... return x + y;
... }
... """)
>>> ctx.call("add", 1, 2)
3
</code></pre>
<p>to install:</p>
<pre><code>$ pip install PyExecJS
</code></pre>
| 1 | 2016-08-23T09:17:25Z | [
"javascript",
"python"
] |
Pandas dataframe pivot table and grouping | 39,096,924 | <p>I have a DataFrame which I made into a pivot table, but now I want to order the pivot table so that common values based on a particular column are aligned beside each other. For e.g. order DataFrame so that all common countries align to same row:</p>
<pre><code>data = {'dt': ['2016-08-22', '2016-08-21', '2016-08-22', '2016-08-21', '2016-08-21'],
'country':['uk', 'usa', 'fr','fr','uk'],
'number': [10, 21, 20, 10,12]
}
df = pd.DataFrame(data)
print df
country dt number
0 uk 2016-08-22 10
1 usa 2016-08-21 21
2 fr 2016-08-22 20
3 fr 2016-08-21 10
4 uk 2016-08-21 12
#pivot table by dt:
df['idx'] = df.groupby('dt')['dt'].cumcount()
df_pivot = df.set_index(['idx','dt']).stack().unstack([1,2])
print df_pivot
dt 2016-08-22 2016-08-21
country number country number
idx
0 uk 10 usa 21
1 fr 20 fr 10
2 NaN NaN uk 12
#what I really want:
dt 2016-08-22 2016-08-21
country number country number
0 uk 10 uk 12
1 fr 20 fr 10
2 NaN NaN usa 21
</code></pre>
<p>or even better:</p>
<pre><code> 2016-08-22 2016-08-21
country number number
0 uk 10 12
1 fr 20 10
2 usa NaN 21
</code></pre>
<p>i.e. <code>uk</code> values from both <code>2016-08-22</code> and <code>2016-08-21</code> are aligned on same row</p>
| 2 | 2016-08-23T09:08:02Z | 39,097,046 | <p>You can use:</p>
<pre><code>df_pivot = df.set_index(['dt','country']).stack().unstack([0,2]).reset_index()
print (df_pivot)
dt country 2016-08-22 2016-08-21
number number
0 fr 20.0 10.0
1 uk 10.0 12.0
2 usa NaN 21.0
#change first value of Multiindex from first to second level
cols = [col for col in df_pivot.columns]
df_pivot.columns = pd.MultiIndex.from_tuples([('','country')] + cols[1:])
print (df_pivot)
2016-08-22 2016-08-21
country number number
0 fr 20.0 10.0
1 uk 10.0 12.0
2 usa NaN 21.0
</code></pre>
<p>Another simplier solution is with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.pivot.html" rel="nofollow"><code>pivot</code></a>:</p>
<pre><code>df_pivot = df.pivot(index='country', columns='dt', values='number')
print (df_pivot)
dt 2016-08-21 2016-08-22
country
fr 10.0 20.0
uk 12.0 10.0
usa 21.0 NaN
</code></pre>
| 1 | 2016-08-23T09:13:22Z | [
"python",
"pandas",
"dataframe",
"alignment",
"pivot"
] |
Is there any shorter way to write this method? | 39,096,933 | <p>I have a list in python that should look like this for example:</p>
<pre><code>line = ['0', '1', '0', 'R', '1']
</code></pre>
<p>I wrote this function, but can this be done in the easier way?</p>
<pre><code>def checkCardCommands(line):
if line[0] == '0' or line[0] == '1':
if line[1] == '0' or line[1] == '1' or line[1] == 'None':
if line[2] == '0' or line[2] == '1' or line[2] == 'None':
if line[3] == 'R' or line[3] == 'L':
if line[4] == '0' or line[4] == '1':
if len(line) == 5:
return True
else:
return False
else:
return False
else:
return False
else:
return False
else:
return False
else:
return False
</code></pre>
| -2 | 2016-08-23T09:08:32Z | 39,097,029 | <p>You could write it as something like:</p>
<pre><code>def checkCardCommands(line):
return (len(line) == 5
and line[0] in ['0', '1']
and line[1] in ['0', '1', 'None']
and line[2] in ['0', '1', 'None']
and line[3] in ['R', 'L']
and line[4] in ['0', '1'])
</code></pre>
| 7 | 2016-08-23T09:12:32Z | [
"python",
"list"
] |
Is there any shorter way to write this method? | 39,096,933 | <p>I have a list in python that should look like this for example:</p>
<pre><code>line = ['0', '1', '0', 'R', '1']
</code></pre>
<p>I wrote this function, but can this be done in the easier way?</p>
<pre><code>def checkCardCommands(line):
if line[0] == '0' or line[0] == '1':
if line[1] == '0' or line[1] == '1' or line[1] == 'None':
if line[2] == '0' or line[2] == '1' or line[2] == 'None':
if line[3] == 'R' or line[3] == 'L':
if line[4] == '0' or line[4] == '1':
if len(line) == 5:
return True
else:
return False
else:
return False
else:
return False
else:
return False
else:
return False
else:
return False
</code></pre>
| -2 | 2016-08-23T09:08:32Z | 39,097,034 | <pre><code>def checkcards():
return line[0] in ['0','1'] and line[1] in ['0','1','None'] and line[2] in ['0','1','None'] and line[3] in ['R','L'] and line[4] in ['0','1'] and len(line)==5
</code></pre>
<p>'None' is a string, None is an object type. make sure you know which one you want to use. </p>
| 1 | 2016-08-23T09:12:51Z | [
"python",
"list"
] |
Is there any shorter way to write this method? | 39,096,933 | <p>I have a list in python that should look like this for example:</p>
<pre><code>line = ['0', '1', '0', 'R', '1']
</code></pre>
<p>I wrote this function, but can this be done in the easier way?</p>
<pre><code>def checkCardCommands(line):
if line[0] == '0' or line[0] == '1':
if line[1] == '0' or line[1] == '1' or line[1] == 'None':
if line[2] == '0' or line[2] == '1' or line[2] == 'None':
if line[3] == 'R' or line[3] == 'L':
if line[4] == '0' or line[4] == '1':
if len(line) == 5:
return True
else:
return False
else:
return False
else:
return False
else:
return False
else:
return False
else:
return False
</code></pre>
| -2 | 2016-08-23T09:08:32Z | 39,097,108 | <pre><code>def check(line):
spec = [
['0', '1'],
['0', '1', 'None'],
['0', '1', 'None'],
['R', 'L'],
['0', '1']
]
return len(line) == len(spec) and all(ln in spc for ln, spc in zip(line, spec))
</code></pre>
<p>Shorter, and way more readable and maintainable.</p>
| 4 | 2016-08-23T09:15:05Z | [
"python",
"list"
] |
Is there any shorter way to write this method? | 39,096,933 | <p>I have a list in python that should look like this for example:</p>
<pre><code>line = ['0', '1', '0', 'R', '1']
</code></pre>
<p>I wrote this function, but can this be done in the easier way?</p>
<pre><code>def checkCardCommands(line):
if line[0] == '0' or line[0] == '1':
if line[1] == '0' or line[1] == '1' or line[1] == 'None':
if line[2] == '0' or line[2] == '1' or line[2] == 'None':
if line[3] == 'R' or line[3] == 'L':
if line[4] == '0' or line[4] == '1':
if len(line) == 5:
return True
else:
return False
else:
return False
else:
return False
else:
return False
else:
return False
else:
return False
</code></pre>
| -2 | 2016-08-23T09:08:32Z | 39,097,207 | <p>If your validations are not too complicated you could write some validation helpers yourself:</p>
<pre><code>#!/usr/bin/env python3
# coding: utf-8
def validate(schema, seq):
"""
Validates a given iterable against a schema. Schema is a list
of callables, taking a single argument returning `True` if the
passed value is valid, `False` otherwise.
"""
if not len(schema) == len(seq):
raise ValueError('length mismatch')
for f, item in zip(schema, seq):
if not f(item):
raise ValueError('validation failed: %s' % (item))
return True
if __name__ == '__main__':
# two validation helper, add more here
isbool = lambda s: s == '0' or s == '1'
islr = lambda s: s == 'L' or s == 'R'
# define a schema
schema = [isbool, isbool, isbool, islr, isbool]
# example input
line = ['0', '1', '0', 'R', '1']
# this is valid
validate(schema, ['0', '1', '0', 'R', '1'])
# ValueError: validation failed: X
validate(schema, ['0', '1', '0', 'R', 'X'])
# ValueError: length mismatch
validate(schema, ['0', '1'])
</code></pre>
<p>For more advanced data structure schema validations, have a look at <a href="https://pypi.python.org/pypi/voluptuous" rel="nofollow">voluptuous</a>.</p>
<blockquote>
<p>Voluptuous, despite the name, is a Python data validation library. It is primarily intended for validating data coming into Python as JSON, YAML, etc.</p>
</blockquote>
| 4 | 2016-08-23T09:19:43Z | [
"python",
"list"
] |
Is there any shorter way to write this method? | 39,096,933 | <p>I have a list in python that should look like this for example:</p>
<pre><code>line = ['0', '1', '0', 'R', '1']
</code></pre>
<p>I wrote this function, but can this be done in the easier way?</p>
<pre><code>def checkCardCommands(line):
if line[0] == '0' or line[0] == '1':
if line[1] == '0' or line[1] == '1' or line[1] == 'None':
if line[2] == '0' or line[2] == '1' or line[2] == 'None':
if line[3] == 'R' or line[3] == 'L':
if line[4] == '0' or line[4] == '1':
if len(line) == 5:
return True
else:
return False
else:
return False
else:
return False
else:
return False
else:
return False
else:
return False
</code></pre>
| -2 | 2016-08-23T09:08:32Z | 39,097,456 | <p>The following code will help in case of dynamic list to be checked.</p>
<pre><code>line = ['0', '1', '0', 'R', '1']
check_list = [
['0', '1'],
['0', '1', 'None'],
['0', '1', 'None'],
['R', 'L'],
['0', '1']
]
def check():
for l, item in enumerate(line):
if not item in check_list[l]:
return False
elif l == 4:
### comes here only if each item in line is found in the check_list
return True
</code></pre>
| 1 | 2016-08-23T09:31:02Z | [
"python",
"list"
] |
Removing django default permissions from auth models | 39,096,973 | <p>guys im trying to remove default django permissions i'll never use in my project but with no success. When I make migration it states that migration is made with success but there's no effect, like it skipped the function. I'm pretty sure code is ok because i tested it in shell. Any ideas?
Here's code for migration: </p>
<pre><code>from django.db import migrations
def remove_redundant_permissions(apps, schema_editor):
Permission = apps.get_model('auth.Permission')
app_labels = ['admin', 'reversion', 'contenttypes', 'sessions', 'sites']
Permission.objects.filter(content_type__app_label__in=app_labels).delete()
class Migration(migrations.Migration):
dependencies = [
('users', '0014_auto_20160808_0738'),
]
operations = [
migrations.RunPython(remove_redundant_permissions),
]
</code></pre>
| 0 | 2016-08-23T09:10:19Z | 39,097,371 | <p>Django's permessions are generated with <code>post_migrate</code> signal. This means even if you delete them in migration they will be regenerated after migration completes. </p>
<p>Here is code from django</p>
<pre><code># django/contrib/auth/apps.py
from django.apps import AppConfig
from django.contrib.auth.checks import check_user_model
from django.core import checks
from django.db.models.signals import post_migrate
from django.utils.translation import ugettext_lazy as _
from .management import create_permissions
class AuthConfig(AppConfig):
name = 'django.contrib.auth'
verbose_name = _("Authentication and Authorization")
def ready(self):
post_migrate.connect(create_permissions,
dispatch_uid="django.contrib.auth.management.create_permissions")
checks.register(check_user_model, checks.Tags.models)
</code></pre>
<p>As you see <code>auth</code> app has this <code>AppConfig</code> which regenerates permissions with <code>create_permissions</code> function.</p>
<p>Why do you want to delete default django permissions? Do they block you from doing something?</p>
| 0 | 2016-08-23T09:27:24Z | [
"python",
"django",
"migration"
] |
writing in a text file with [ ] python | 39,097,004 | <p>I am trying to write in a text file with braces. </p>
<pre><code>output.write("{}\t{}\t{}\t{}\t{}\t".format(student_iD,user_id,First_name, Last_name,Other_name))
output.write("\n")
</code></pre>
<p>it writes in the text file with out the braces. What should I add such that I get something like this:</p>
<pre><code>[student_id] [user_id] [First_name] [Last_name] [other_name] in the text file.
</code></pre>
| -3 | 2016-08-23T09:11:35Z | 39,097,044 | <p>Surround those braces with <code>[]</code></p>
<pre><code>output.write("[{}]\t[{}]\t[{}]\t[{}]\t[{}]\t".format(student_iD,user_id,First_name, Last_name,Other_name))
output.write("\n")
</code></pre>
| 0 | 2016-08-23T09:13:18Z | [
"python",
"python-2.7"
] |
writing in a text file with [ ] python | 39,097,004 | <p>I am trying to write in a text file with braces. </p>
<pre><code>output.write("{}\t{}\t{}\t{}\t{}\t".format(student_iD,user_id,First_name, Last_name,Other_name))
output.write("\n")
</code></pre>
<p>it writes in the text file with out the braces. What should I add such that I get something like this:</p>
<pre><code>[student_id] [user_id] [First_name] [Last_name] [other_name] in the text file.
</code></pre>
| -3 | 2016-08-23T09:11:35Z | 39,097,075 | <p>As simple as that:</p>
<pre><code>output.write("[{}]\t[{}]\t[{}]\t[{}]\t[{}]\t".format(...)
</code></pre>
<p>Or place the brackets around the variable names themselves without changing the format string. Then you'll be printing lists, and each of them will consist of only one value.</p>
<pre><code>output.write("{}\t{}\t{}\t{}\t{}\t".format([student_iD],[user_id], [First_name], [Last_name], [Other_name]))
</code></pre>
| 0 | 2016-08-23T09:14:08Z | [
"python",
"python-2.7"
] |
writing in a text file with [ ] python | 39,097,004 | <p>I am trying to write in a text file with braces. </p>
<pre><code>output.write("{}\t{}\t{}\t{}\t{}\t".format(student_iD,user_id,First_name, Last_name,Other_name))
output.write("\n")
</code></pre>
<p>it writes in the text file with out the braces. What should I add such that I get something like this:</p>
<pre><code>[student_id] [user_id] [First_name] [Last_name] [other_name] in the text file.
</code></pre>
| -3 | 2016-08-23T09:11:35Z | 39,097,426 | <p>My code</p>
<pre><code>output = open('/home/vipul/Desktop/test_data.txt', 'a')
output.write("[{}]\t[{}]\t[{}]\t[{}]\t[{}]\t".format(222,2222,'test', 'test','test'))
output.write("\n")
</code></pre>
<p>output I got:
[222] [2222] [test] [test] [test] </p>
<p>Its working. If you get error paste your output here. </p>
| 0 | 2016-08-23T09:29:27Z | [
"python",
"python-2.7"
] |
Switch Alternative in python | 39,097,072 | <p>Am trying this small piece of code which can be alternative for switch. But i get weired Error.</p>
<pre><code>def main(x):
x = x.split(' ')
return {'Function1' : Function1(x),
'Function2' : Function2(x),
}[x[0]]
def Function1(x):
var1 = x[0]
var2 = x[1]
def Function2(x):
print x[0]
main("Function1 10")
</code></pre>
<p>Now the above code work fine. Problem is if i pass Function2 as key without any arguments to main function it automatically goes into Function1 and throws list out of range error.</p>
<pre><code>main("Function2")
</code></pre>
<p>Thanks in Advance.</p>
| 0 | 2016-08-23T09:14:08Z | 39,097,143 | <p>Your code doesn't work at all. You always call the functions when you define the dict. You should keep the callable in the dict and call the result.</p>
<pre><code>def main(x):
x = x.split(' ')
func = {'Function1' : Function1,
'Function2' : Function2,
}[x[0]]
return func(x[1])
</code></pre>
| 3 | 2016-08-23T09:16:52Z | [
"python",
"python-2.7"
] |
Switch Alternative in python | 39,097,072 | <p>Am trying this small piece of code which can be alternative for switch. But i get weired Error.</p>
<pre><code>def main(x):
x = x.split(' ')
return {'Function1' : Function1(x),
'Function2' : Function2(x),
}[x[0]]
def Function1(x):
var1 = x[0]
var2 = x[1]
def Function2(x):
print x[0]
main("Function1 10")
</code></pre>
<p>Now the above code work fine. Problem is if i pass Function2 as key without any arguments to main function it automatically goes into Function1 and throws list out of range error.</p>
<pre><code>main("Function2")
</code></pre>
<p>Thanks in Advance.</p>
| 0 | 2016-08-23T09:14:08Z | 39,097,204 | <p>What you really should do is use a string of <code>if/elif/else</code> statements:</p>
<pre><code>if x == 1:
Function1()
elif x == 2:
Function2()
else:
Function3()
</code></pre>
| 0 | 2016-08-23T09:19:39Z | [
"python",
"python-2.7"
] |
Switch Alternative in python | 39,097,072 | <p>Am trying this small piece of code which can be alternative for switch. But i get weired Error.</p>
<pre><code>def main(x):
x = x.split(' ')
return {'Function1' : Function1(x),
'Function2' : Function2(x),
}[x[0]]
def Function1(x):
var1 = x[0]
var2 = x[1]
def Function2(x):
print x[0]
main("Function1 10")
</code></pre>
<p>Now the above code work fine. Problem is if i pass Function2 as key without any arguments to main function it automatically goes into Function1 and throws list out of range error.</p>
<pre><code>main("Function2")
</code></pre>
<p>Thanks in Advance.</p>
| 0 | 2016-08-23T09:14:08Z | 39,097,293 | <p>The code block</p>
<pre><code> return {'Function1' : Function1(x),
'Function2' : Function2(x),
}[x[0]]
</code></pre>
<p>is evaluated first as</p>
<pre><code> return {'Function1' : Function1(x),
'Function2' : Function2(x),
}
</code></pre>
<p>Evaluating this will actually call both <code>Function1</code> and <code>Function2</code>.</p>
<p>What you want is to get a reference to the correct function without actually calling it until you know which one you want to call:</p>
<pre><code> return {'Function1' : Function1,
'Function2' : Function2,
}[x[0]](x)
</code></pre>
| 1 | 2016-08-23T09:24:03Z | [
"python",
"python-2.7"
] |
How to give a user a single session extra permission in Django | 39,097,148 | <h1>Background</h1>
<p>We have a service where a django super admin can login and view all the users in a specific org, and this super admin can "log in" in the place of that user. Ie suppose we have</p>
<pre><code>super admin = joe
users = mike, abe, tony
</code></pre>
<p>then joe can log into an org, see mike, abe and tony, then joe can login into the system as if they are mike. Everything they see and do will be as if Mike were doing it. So if the super admin has permission to create public events, but mike doesn't, when the super admin logs in as mike, they won't be able to create events either. </p>
<p>So far so good.</p>
<p>However we realized that in many cases we would like the super admin to login as mike, and still be recognized as a super admin in the system. This is useful for data migration purposes, ie sometimes the super admin should actually do stuff in the name of mike that mike can't do themselves. </p>
<h1>Problem</h1>
<p>the idea here is that I would like the system to recognize that super admin is logged in as mike. However all questions I saw online (such as <a href="http://stackoverflow.com/questions/20361235/django-set-user-permissions-when-user-is-automatically-created">this one</a>) are more about assigning permanent permissions (ie by storing them in the db), rather than temporary/ephemeral ones. </p>
<p>This is the code that gets called when the admin clicks on the login button beside mike:</p>
<pre><code>class LoginAsView(APIView):
permission_classes = []
def get(self, request, *args, **kwargs):
if request.user.is_superuser and 'username' in request.GET:
user = User.objects.get(email=request.GET['username'])
user.backend = settings.AUTHENTICATION_BACKENDS[0]
login(self.request, user)
return Response('/', 302, headers={'Location': '/'})
raise PermissionDenied('NO U')
</code></pre>
<p>so as you can see the user I'm retrieving behaves exactly as if that user (ie mike) logged in organically. I would like in this method to assign mike some temporary special permissions that allows mike to do things he normally cannot.</p>
| 0 | 2016-08-23T09:17:03Z | 39,103,612 | <p>enter <a href="https://github.com/arteria/django-hijack" rel="nofollow">https://github.com/arteria/django-hijack</a></p>
<p>for example django-hijack add extra flag to session for checking is user hijacked <a href="https://github.com/arteria/django-hijack/search?utf8=%E2%9C%93&q=is_hijacked_user" rel="nofollow">https://github.com/arteria/django-hijack/search?utf8=%E2%9C%93&q=is_hijacked_user</a></p>
| 0 | 2016-08-23T14:11:47Z | [
"python",
"django",
"django-models",
"django-admin",
"django-authentication"
] |
Python write edited NaNs in variable to .csv | 39,097,337 | <p>I'm trying to convert <code>NULL</code> values in a .csv to <code>NaN</code> and then save a file with these edits. <code>f</code> in the code below has the <code>NaN</code>values in the correct location in the data. However, I am unable to save this as a .csv. the error is printed below the code.</p>
<pre><code>#take .csv with NULL and replaces with NaN - write numerical and NaN values to .csv
import csv
import numpy as np
import pandas
f = pandas.read_csv('C:\Users\mmso2\Google Drive\MABL Wind\_Semester 2 2016\Wind Farm Info\DataB\DataB - Copy.csv')#convert file to variable so it can be edited
outfile = open('C:\Users\mmso2\Google Drive\MABL Wind\_Semester 2 2016\Wind Farm Info\DataB\DataB - NaN1.csv','wb')#create empty file to write to
writer = csv.writer(outfile)#writer will write when given the data to write below
result = f[f is 'NULL'] = np.nan
writer.writerows(f)
</code></pre>
<p>error:</p>
<pre><code> Traceback (most recent call last):
File "C:/Users/mmso2/Google Drive/MABL Wind/_Semester 2 2016/_PGR Training/CENTA/MATLAB/In class ex/SAR_data/gg_nan.py", line 12, in <module>
writer.writerows(f)
_csv.Error: sequence expected
</code></pre>
| 0 | 2016-08-23T09:25:37Z | 39,097,615 | <p><a href="https://docs.python.org/3/library/csv.html#csv.csvwriter.writerows" rel="nofollow"><code>csv.writer.writerows()</code></a> expects a sequence of sequences (a sequence of row objects), which a <code>pandas.DataFrame</code> is not, as it returns a sequence of column names when iterated over:</p>
<pre><code>In [23]: df = pd.DataFrame({'A': range(10)})
In [24]: for x in df:
print(x)
....:
A
</code></pre>
<p>This can bite you silently, as a sequence of strings is actually a sequence of sequences, so you'd end up with a CSV file that contains rows made up of the letters of your column names. In your case it fails because of how you tried to replace the 'NULL' strings, which ended up adding a column with the label <code>False</code> (a boolean value).</p>
<p>To iterate over row tuples, you'd use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.itertuples.html" rel="nofollow"><code>DataFrame.itertuples()</code></a>:</p>
<pre><code>In [27]: for x in df.itertuples(index=False):
print(x)
....:
(0,)
(1,)
(2,)
...
</code></pre>
<p>The easiest approach though is to simply use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_csv.html" rel="nofollow"><code>DataFrame.to_csv()</code></a>:</p>
<pre><code>filename = 'C:\Users\mmso2\Google Drive\MABL Wind\_Semester 2 2016\Wind Farm Info\DataB\DataB - NaN1.csv'
f.to_csv(filename, na_rep='NaN') # default representation for nans is ''
</code></pre>
<p>Note that to replace the <code>'NULL'</code> values you have to use the equality operator instead of the identity operator <code>is</code>:</p>
<pre><code>f[f == 'NULL'] = np.nan
</code></pre>
<p>Using the identity will effectively add a new column labeled <code>False</code> with all values set to nan:</p>
<pre><code>In [42]: df = pd.DataFrame({'A': ['NULL', 1] * 10})
In [43]: df[df is 'NULL'] = float('nan')
In [44]: df
Out[44]:
A False
0 NULL NaN
1 1 NaN
2 NULL NaN
3 1 NaN
...
</code></pre>
<p>because <code>f is 'NULL'</code> evaluates to <code>False</code> instead of a new <code>DataFrame</code>.</p>
| 1 | 2016-08-23T09:39:01Z | [
"python",
"python-2.7",
"csv",
null
] |
Html page cannot show properly in PyQt Qwebview | 39,097,359 | <p>I use PyQt4(4.11 version) and Python2.7 </p>
<p>I would like to embedded html page in pyqt GUI by using Qwebview ,
the html were generated from plotly offline,simply contains bar chart graph like this:
<a href="http://i.stack.imgur.com/7RlhS.png" rel="nofollow">bar chart</a></p>
<pre><code>self.webView = QtWebKit.QWebView(self.centralwidget)
self..webView.setUrl(QtCore.QUrl('file:///D:/Anaconda/Lib/site-packages/PyQt4/my-graph.html'))
</code></pre>
<p>however, the html display nothing in QwebView, while it can show the plotly bar chart properly in windows browser</p>
<p>I also tried to set Url to the plotly website
<code>self.load(QtCore.QUrl('https://plot.ly/python/axes/'))</code>
and found out that only the plotly image cannot display properly
<a href="http://i.stack.imgur.com/EAgZa.png" rel="nofollow">text and images display well</a></p>
<p>the same problem appears when i generated html by google chart</p>
<p>then i tried to set the following parameters, but it still not works</p>
<pre><code>self.webView = QtWebKit.QWebView(self.centralwidget)
s=self.webView.settings()
s.setAttribute(QtWebKit.QWebSettings.PluginsEnabled, True)
s.setAttribute(QtWebKit.QWebSettings.JavascriptEnabled, True)
s.setAttribute(QtWebKit.QWebSettings.JavascriptCanOpenWindows, True)
s.setAttribute(QtWebKit.QWebSettings.JavascriptCanAccessClipboard, True)
s.setAttribute(QtWebKit.QWebSettings.JavaEnabled, True)
s.setAttribute(QtWebKit.QWebSettings.AutoLoadImages, True)
s.setAttribute(QtWebKit.QWebSettings.DeveloperExtrasEnabled, True)
s.setAttribute(QtWebKit.QWebSettings.LocalStorageEnabled, True)
s.setAttribute(QtWebKit.QWebSettings.SpatialNavigationEnabled, True)
s.setAttribute(QtWebKit.QWebSettings.LocalContentCanAccessRemoteUrls, True)
s.setAttribute(QtWebKit.QWebSettings.LocalContentCanAccessFileUrls, True)
</code></pre>
<p>i have no idea now, does anyone can fix this? </p>
| 0 | 2016-08-23T09:26:53Z | 39,114,343 | <p>Both Qt4 (which you're using with PyQt4) and QtWebKit are unmaintained. </p>
<p>You'll also get a webkit which is probably around 4 years old. Such an old webkit version will struggle with modern web content (apart from the obvious security and stability issues).</p>
<p>I'd recommend to upgrade at least to PyQt5/Qt5, and ideally from QtWebKit to <a href="http://doc.qt.io/qt-5/qtwebengine-index.html" rel="nofollow">QtWebEngine</a></p>
| 0 | 2016-08-24T04:17:36Z | [
"python",
"html",
"pyqt",
"plotly"
] |
Check if variable is set in multiple scripts | 39,097,416 | <p>I have a python module with lots of python scripts in, I want to read these scripts and check if a variable is set.</p>
<p>I'm currently reading the files line by line, but as the scripts i'm reading are in python i'm guessing there is a better way?</p>
<pre><code>for filename in glob.glob(os.path.join(my_path, '*.py')):
with open(filename) as f:
for line in f:
if 'my_variable' in line:
variable_exists = True
</code></pre>
<p><strong>Edit</strong></p>
<p>I have a directory which has lots of classes, some have variables which affect how the script runs.
e.g.</p>
<pre><code>class Script1():
name = 'script1'
countrys = ['US', 'UK', 'AU']
class Script2():
name = 'script2'
countrys = ['US', 'CA']
</code></pre>
<p>From this i want to achieve</p>
<pre><code>[
{'name': 'script1', 'country': 'US'},
{'name': 'script1', 'country': 'UK'},
{'name': 'script1', 'country': 'AU'},
{'name': 'script2', 'country': 'US'},
{'name': 'script2', 'country': 'CA'}
]
</code></pre>
| 3 | 2016-08-23T09:28:56Z | 39,098,330 | <p>Here's a working example for your question:</p>
<pre><code>import glob
import inspect
import os
import sys
import importlib
def get_classes(module):
def pred(c):
if inspect.isclass(c) and hasattr(c, "countrys"):
return True
return False
for value in inspect.getmembers(module, pred):
yield value
def list_plugins(search_paths, my_path):
output = set()
for path in search_paths:
sys_path = list(sys.path)
sys.path.insert(0, path)
for f in glob.glob(my_path):
print f
location, ext = os.path.splitext(f)
mod_name = os.path.basename(location)
mod = importlib.import_module(mod_name)
print os.path.abspath(mod.__file__)
for c in get_classes(mod):
output.add(c)
sys.path[:] = sys_path
return output
if __name__ == "__main__":
output = []
for p in list_plugins(["test"], os.path.join("test","*.py")):
name, plugin = p[0], p[1]
for c in plugin.countrys:
output.append({
'name': name,
'country': c
})
print output
</code></pre>
<p>Some comments, to make it work, create a folder in the same script's folder called <code>test</code> containing an empty <code>__init__.py</code> file and one (or more) python files with the classes you've mentioned in your question.</p>
<p>The important bits of the code are the usage of <a href="https://docs.python.org/2/library/importlib.html#importlib.import_module" rel="nofollow">import_module</a> and <a href="https://docs.python.org/2/library/inspect.html" rel="nofollow">inspect</a></p>
<p>It's a little example but it should be a good starting point for you. Hope it helps.</p>
| 1 | 2016-08-23T10:13:30Z | [
"python"
] |
How to render tables in django-datatable-view? | 39,097,427 | <p>I can't figure out how to render an editable table using <code>Django-datatable-view</code>. I want to create a table exactly like this: <a href="http://django-datatable-view.appspot.com/x-editable-columns/" rel="nofollow">http://django-datatable-view.appspot.com/x-editable-columns/</a> from model <code>City</code> for example.</p>
<p>I've read the docs and tutorials but still can't figure out how to create the table. </p>
<p>This is what I've done so far:</p>
<pre><code>{% extends "base.html" %}
{% block head %}
{% load static %}e
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.12/css/dataTables.bootstrap.min.css">
<script src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.12/js/dataTables.bootstrap.min.js"></script>
<script src="{% static "datatable/js/datatableview.min.js" %}"></script>
<script>
datatableview.auto_initialize = false;
$(function () {
var xeditable_options = {};
datatableview.initialize($('.datatable'), {
fnRowCallback: datatableview.make_xeditable(xeditable_options),
});
})
</script>
{% endblock %}
{% block content %}
{{ datatable }}
{{ object_list }}
{% endblock %}
</code></pre>
<p>And my view is:</p>
<pre><code>class ZeroConfigurationDatatableView(dtv_views.XEditableDatatableView):
model = dolava_models.City
datatable_options = {
'columns': [
'id',
("Name", 'name', dtv_helpers.make_xeditable),
("Country", 'country', dtv_helpers.make_xeditable),
]
}
</code></pre>
<p>Unfortunately my code renders this:</p>
<p><a href="http://i.stack.imgur.com/iG7AQ.png" rel="nofollow"><img src="http://i.stack.imgur.com/iG7AQ.png" alt="enter image description here"></a></p>
| 1 | 2016-08-23T09:29:32Z | 39,101,030 | <pre><code>{% block content %}
{% if instances %}
<table class='datatable'>
<tr>
<th>ID</th>
<th>Name</th>
<th>Country</th>
</tr>
{% for row in instances %}
<tr>
<th> {{ row.id }}</th>
<th> {{ row.name }}</th>
<th> {{ row.country }}</th>
</tr>
{% endfor %}
</table>
{% else %}
<p>No data available</p>
{% endif %}
{% endblock %}
</code></pre>
| -1 | 2016-08-23T12:19:28Z | [
"python",
"django",
"datatable",
"html-table"
] |
How to render tables in django-datatable-view? | 39,097,427 | <p>I can't figure out how to render an editable table using <code>Django-datatable-view</code>. I want to create a table exactly like this: <a href="http://django-datatable-view.appspot.com/x-editable-columns/" rel="nofollow">http://django-datatable-view.appspot.com/x-editable-columns/</a> from model <code>City</code> for example.</p>
<p>I've read the docs and tutorials but still can't figure out how to create the table. </p>
<p>This is what I've done so far:</p>
<pre><code>{% extends "base.html" %}
{% block head %}
{% load static %}e
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.12/css/dataTables.bootstrap.min.css">
<script src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.12/js/dataTables.bootstrap.min.js"></script>
<script src="{% static "datatable/js/datatableview.min.js" %}"></script>
<script>
datatableview.auto_initialize = false;
$(function () {
var xeditable_options = {};
datatableview.initialize($('.datatable'), {
fnRowCallback: datatableview.make_xeditable(xeditable_options),
});
})
</script>
{% endblock %}
{% block content %}
{{ datatable }}
{{ object_list }}
{% endblock %}
</code></pre>
<p>And my view is:</p>
<pre><code>class ZeroConfigurationDatatableView(dtv_views.XEditableDatatableView):
model = dolava_models.City
datatable_options = {
'columns': [
'id',
("Name", 'name', dtv_helpers.make_xeditable),
("Country", 'country', dtv_helpers.make_xeditable),
]
}
</code></pre>
<p>Unfortunately my code renders this:</p>
<p><a href="http://i.stack.imgur.com/iG7AQ.png" rel="nofollow"><img src="http://i.stack.imgur.com/iG7AQ.png" alt="enter image description here"></a></p>
| 1 | 2016-08-23T09:29:32Z | 39,713,780 | <p>As the first step, try to run the example project that is buried in:</p>
<pre><code>django-datatable-view/datatableview/tests/example_project/example_project/example_app
</code></pre>
<p>To do this, follow the <a href="https://github.com/pivotal-energy-solutions/django-datatable-view#documentation-and-live-demos" rel="nofollow">Documentation and Live Demos</a> on the projects github page, but be sure to replace <code>django>=1.4</code> with <code>django==1.8</code> before you start. That is, it is not compatible with django1.9 or 1.10 in my experience. </p>
<p>Once you accomplish this, you will have a full set of working examples and the matching documentation which will ease things a bit. The link that you gave is out of date. Explore the examples (<code>example_app/views.py</code>), and the documentation. </p>
<p>When you are ready to get out of the sandbox, follow this route:</p>
<ol>
<li><p>Start a new virtualenv</p></li>
<li><p>Clone this branch: <code>https://github.com/jangeador/django-datatable-view/</code> (it has a few more commits that make it compatible with recent versions of django), and pip install (use the -e editable option if you plan to make changes). </p></li>
<li><p>Follow of this example <a href="http://localhost/configure-datatable-object/" rel="nofollow">Datatable object and Meta</a> from the example app that you run. In code: </p>
<pre><code>class MyDatatable(Datatable):
class Meta:
model = Entry
columns = ['id', 'headline', 'pub_date', 'n_comments', 'n_pingbacks']
ordering = ['-id']
page_length = 5
search_fields = ['blog__name']
unsortable_columns = ['n_comments']
hidden_columns = ['n_pingbacks']
structure_template = 'datatableview/default_structure.html'
class ConfigureDatatableObjectDatatableView(DatatableView):
model = Entry
datatable_class = MyDatatable
</code></pre></li>
</ol>
<p>You can delete all attributes in the <code>Datatable</code> class if you don't need (they are optional).</p>
<p>Apart from the documentation I had to override the following method on the <code>DataTableView</code> class to make it work. </p>
<pre><code>def get_template_names(self):
return "example_base.html"
</code></pre>
<p>This is your template file, which needs to contain:</p>
<pre><code><script src="{% static 'path-to/datatables.min.js' %}" type="text/javascript"></script>
<link href="{% static 'your-path-to/datatables.min.css' %}" rel="stylesheet">
<script type="text/javascript" src="{% static 'js/datatableview.js' %}"></script>
{{ datatable }}
<script>
// Page javascript
datatableview.auto_initialize = true;
</script>
</code></pre>
<p>What is noteworthy here is the inclusion of <code>datatableview.js</code> from the django-datatable-view module (and the accompanying <code>datatableview.auto_initialize = true;</code>). If you are comfortable with the datatables.js to begin with, you can go ahead and configure it by yourself, but given you are also new to django-datatable-view also, this is probably the easiest route. </p>
| 0 | 2016-09-26T23:16:50Z | [
"python",
"django",
"datatable",
"html-table"
] |
python3 script to compress directory and dynamically name the archive | 39,097,509 | <p>I am trying to write a python 3 script that will compress the contents of a directory <code>/home/pi/results</code> and copy it to another folder <code>/home/pi/backups</code>.<br>
I need to be able to run this script multiple times and each time, the resulting archive is named something based on the previous archives. So first run would create <code>backup001.tgz</code>, second run would create <code>backup002.tgz</code>, etc. Each backup will be a complete backup containing anything within that directory.</p>
<p>I've figured out how to compress the folder to a <code>.tgz</code>, I just can't figure out how to append a number to it based on previous backups.</p>
<pre><code>tar=tarfile.open(backupdir+'backup.tgz', "w:gz")
tar.add(resultspath, arcname=os.path.basename(resultspath))
tar.close()
</code></pre>
| 2 | 2016-08-23T09:33:44Z | 39,097,614 | <pre><code>import os
latest_file = sorted(os.listdir('/home/pi/backups'))[-1]
</code></pre>
<p>This should give you the latest file name. The next one could be figured out from this name.</p>
| 1 | 2016-08-23T09:38:58Z | [
"python",
"python-3.x"
] |
python3 script to compress directory and dynamically name the archive | 39,097,509 | <p>I am trying to write a python 3 script that will compress the contents of a directory <code>/home/pi/results</code> and copy it to another folder <code>/home/pi/backups</code>.<br>
I need to be able to run this script multiple times and each time, the resulting archive is named something based on the previous archives. So first run would create <code>backup001.tgz</code>, second run would create <code>backup002.tgz</code>, etc. Each backup will be a complete backup containing anything within that directory.</p>
<p>I've figured out how to compress the folder to a <code>.tgz</code>, I just can't figure out how to append a number to it based on previous backups.</p>
<pre><code>tar=tarfile.open(backupdir+'backup.tgz', "w:gz")
tar.add(resultspath, arcname=os.path.basename(resultspath))
tar.close()
</code></pre>
| 2 | 2016-08-23T09:33:44Z | 39,097,634 | <p>Maybe use timestamp? Then you will know at the first sight which specific backup you're looking for.</p>
<pre><code>import datetime
date = datetime.datetime.utcnow().isoformat()
filename = 'backup-{}.tgz'.format(date)
filepath = os.path.join(backupdir, filename)
tar=tarfile.open(filepath, "w:gz")
tar.add(resultspath, arcname=os.path.basename(resultspath))
tar.close()
</code></pre>
| 0 | 2016-08-23T09:40:01Z | [
"python",
"python-3.x"
] |
python3 script to compress directory and dynamically name the archive | 39,097,509 | <p>I am trying to write a python 3 script that will compress the contents of a directory <code>/home/pi/results</code> and copy it to another folder <code>/home/pi/backups</code>.<br>
I need to be able to run this script multiple times and each time, the resulting archive is named something based on the previous archives. So first run would create <code>backup001.tgz</code>, second run would create <code>backup002.tgz</code>, etc. Each backup will be a complete backup containing anything within that directory.</p>
<p>I've figured out how to compress the folder to a <code>.tgz</code>, I just can't figure out how to append a number to it based on previous backups.</p>
<pre><code>tar=tarfile.open(backupdir+'backup.tgz', "w:gz")
tar.add(resultspath, arcname=os.path.basename(resultspath))
tar.close()
</code></pre>
| 2 | 2016-08-23T09:33:44Z | 39,097,830 | <p>You could try a filtering/counting approach:</p>
<pre><code># we set the path, and the word key that we are looking for
path = '/home/user/backups'
word_key = 'backup-'
# we count the occurrences and generate a new filename from it
backups_count = len(filter(lambda x : word_key in x, os.listdir(path)))
filename = 'backup-{}.tgz'.format(backups_count)
</code></pre>
| 0 | 2016-08-23T09:49:16Z | [
"python",
"python-3.x"
] |
python3 script to compress directory and dynamically name the archive | 39,097,509 | <p>I am trying to write a python 3 script that will compress the contents of a directory <code>/home/pi/results</code> and copy it to another folder <code>/home/pi/backups</code>.<br>
I need to be able to run this script multiple times and each time, the resulting archive is named something based on the previous archives. So first run would create <code>backup001.tgz</code>, second run would create <code>backup002.tgz</code>, etc. Each backup will be a complete backup containing anything within that directory.</p>
<p>I've figured out how to compress the folder to a <code>.tgz</code>, I just can't figure out how to append a number to it based on previous backups.</p>
<pre><code>tar=tarfile.open(backupdir+'backup.tgz', "w:gz")
tar.add(resultspath, arcname=os.path.basename(resultspath))
tar.close()
</code></pre>
| 2 | 2016-08-23T09:33:44Z | 39,098,251 | <p>Use <a href="https://docs.python.org/2/library/glob.html" rel="nofollow">glob</a> to get a list of backups that already exist<br>
Use <code>max()</code> with <a href="http://stackoverflow.com/questions/18296755/python-max-function-using-key-and-lambda-expression">custom key</a> to find the last one<br>
Use <a href="http://stackoverflow.com/questions/339007/nicest-way-to-pad-zeroes-to-string">string formatting</a> to create the next filename</p>
<pre><code>import glob
filelist = glob.glob('Backup???.tgz')
last = max(filelist, key = lambda x: x[6:9])
filename = 'Backup{0:03d}.tgz'.format(int(last[6:9])+1)
print filename
</code></pre>
<p>(Outputs <code>Backup003.tgz</code> for a directory which contains <code>Backup001.tgz</code> & <code>Backup002.tgz</code>)</p>
| 0 | 2016-08-23T10:09:37Z | [
"python",
"python-3.x"
] |
Bioinformatics : Programmatic Access to the BacDive Database | 39,097,529 | <p>the resource at "BacDive" - ( <a href="http://bacdive.dsmz.de/" rel="nofollow">http://bacdive.dsmz.de/</a>) is a highly useful database for accessing bacterial knowledge, such as strain information, species information and parameters such as growth temperature optimums. </p>
<p>I have a scenario in which I have a set of organism names in a plain text file, and I would like to programmatically search them 1 by 1 against the Bacdive database (which doesnt allow a flat file to be downloaded) and retrieve the relevent information and populate my text file accordingly. </p>
<p>What are the main modules (such as beautifulsoups) that I would need to accomplish this? Is it straight forward? Is it allowed to programmatically access webpages ? Do I need permission?</p>
<p>A bacteria name would be "Pseudomonas putida" . Searching this would give 60 hits on bacdive. Clicking one of the hits, takes us to the specific page, where the line : "Growth temperature: [Ref.: #27] Recommended growth temperature : 26 °C " is the most important. </p>
<p>The script would have to access bacdive (which i have tried accessing using requests, but I feel they do not allow programmatic access, I have asked the moderator about this, and they said I should register for their API first).</p>
<hr>
<p>I now have the API access. This is the page (<a href="http://www.bacdive.dsmz.de/api/bacdive/" rel="nofollow">http://www.bacdive.dsmz.de/api/bacdive/</a>). This may seem quite simple to people who do HTML scraping, but I am not sure what to do now that I have access to the API. </p>
| 0 | 2016-08-23T09:34:51Z | 39,098,473 | <p>Here is the solution...</p>
<pre><code>import re
import urllib
from bs4 import BeautifulSoup
def get_growth_temp(url):
soup = BeautifulSoup(urllib.urlopen(url).read())
no_hits = int(map(float, re.findall(r'[+-]?[0-9]+',str(soup.find_all("span", class_="searchresultlayerhits"))))[0])
if no_hits > 1 :
letters = soup.find_all("li", class_="searchresultrow1") + soup.find_all("li", class_="searchresultrow2")
all_urls = []
for i in letters:
all_urls.append('http://bacdive.dsmz.de/index.php' + i.a["href"])
max_temp = []
for ind_url in all_urls:
soup = BeautifulSoup(urllib.urlopen(ind_url).read())
a = soup.body.findAll(text=re.compile('Recommended growth temperature :'))
if a:
max_temp.append(int(map(float, re.findall(r'[+-]?[0-9]+', str(a)))[0]))
print "Recommended growth temperature : %d °C:\t" % max(max_temp)
url = 'http://bacdive.dsmz.de/index.php?search=Pseudomonas+putida'
if __name__ == "__main__":
# TO Open file then iterate thru the urls/bacterias
# with open('file.txt', 'rU') as f:
# for url in f:
# get_growth_temp(url)
get_growth_temp(url)
</code></pre>
<h2>Edit:</h2>
<p>Here I am passing single url. if you want to pass multiple urls to get their growth temperature. call the function(url) by opening file. code is commented.</p>
<p>Hope it helped you..
Thanks</p>
| 2 | 2016-08-23T10:20:35Z | [
"python",
"database",
"webpage",
"bioinformatics"
] |
Deployment on Google App Engine - Django, Vagrant, Ansible | 39,097,545 | <p>I want to deploy <code>Django</code> project on <code>google app engine</code></p>
<p>Following are the current situations.</p>
<ol>
<li>I have a code on <code>GITHUB</code></li>
<li><code>Djnago</code> project has setup using <code>Vagrant</code>, <code>Ansible</code>, <code>VirtualBox</code></li>
</ol>
<p>I am completely new for <code>cloud base deployments</code>.</p>
<p>Need help to achieve this. </p>
<p>I checked <code>google docs</code> but there are couple of options for django related deployment, I am not sure which to pick for <code>vagrant</code> and <code>ansible</code>.</p>
| -5 | 2016-08-23T09:35:32Z | 39,097,936 | <p>Your question is a bit too generic as it stands - making it here rather than comment for clarity.</p>
<p>If you're talking about deploying to GAE (Google App Engine) then most likely you cannot re-use your Ansible scripts as you've been writing for vagrant. As it may be possible to use Ansible to deploy on GAE, most people I know are using standard google <a href="https://cloud.google.com/python/django/appengine" rel="nofollow">procedure</a> to deploy their app. </p>
<p>If you plan to use GCE (Google Compute Engine, a layer down in the infrastructure), you would be able to use your existing Ansible provisioning scripts (maybe with slight modification), follow along the <a href="http://docs.ansible.com/ansible/guide_gce.html" rel="nofollow">Ansible documentation</a> </p>
| 0 | 2016-08-23T09:54:45Z | [
"python",
"django",
"google-app-engine",
"vagrant",
"ansible"
] |
Django Rest Framework Without Database | 39,098,008 | <p>I'm trying to setup a simple API using Django Rest Framework, the problem is that my API does not have any database but the framework won't work without database setting.</p>
<p>Here is my Django Rest Framework configuration in <code>settings.py</code>:</p>
<pre class="lang-python prettyprint-override"><code>INSTALLED_APPS = [
'provider',
'django_nose',
'rest_framework',
'django.contrib.contenttypes',
]
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [],
'DEFAULT_PERMISSION_CLASSES': [],
}
</code></pre>
<p>The error which I got is:</p>
<blockquote>
<p>ImproperlyConfigured("settings.DATABASES is improperly configured.
"django.core.exceptions.ImproperlyConfigured: settings.DATABASES is
improperly configured. Please supply the ENGINE value. Check settings
documentation for more details.</p>
</blockquote>
<p>Is there any minimal settings which does not include <code>django.contrib.contenttypes</code> and <code>django.contrib.auth</code>?</p>
| 1 | 2016-08-23T09:58:14Z | 39,098,104 | <p>You don't have any option. <code>DATABASES</code> dict should be in <code>settings.py</code>. You can use this:</p>
<pre><code>DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
</code></pre>
| 0 | 2016-08-23T10:03:13Z | [
"python",
"django",
"django-rest-framework"
] |
Django Rest Framework Without Database | 39,098,008 | <p>I'm trying to setup a simple API using Django Rest Framework, the problem is that my API does not have any database but the framework won't work without database setting.</p>
<p>Here is my Django Rest Framework configuration in <code>settings.py</code>:</p>
<pre class="lang-python prettyprint-override"><code>INSTALLED_APPS = [
'provider',
'django_nose',
'rest_framework',
'django.contrib.contenttypes',
]
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [],
'DEFAULT_PERMISSION_CLASSES': [],
}
</code></pre>
<p>The error which I got is:</p>
<blockquote>
<p>ImproperlyConfigured("settings.DATABASES is improperly configured.
"django.core.exceptions.ImproperlyConfigured: settings.DATABASES is
improperly configured. Please supply the ENGINE value. Check settings
documentation for more details.</p>
</blockquote>
<p>Is there any minimal settings which does not include <code>django.contrib.contenttypes</code> and <code>django.contrib.auth</code>?</p>
| 1 | 2016-08-23T09:58:14Z | 39,098,414 | <p>[not tested] maybe you could use a dummy backend. I see there's one from django:</p>
<pre><code>DATABASES = {
'default': {
'ENGINE': 'django.db.backends.dummy',
}
}
</code></pre>
| 0 | 2016-08-23T10:17:41Z | [
"python",
"django",
"django-rest-framework"
] |
Django Rest Framework Without Database | 39,098,008 | <p>I'm trying to setup a simple API using Django Rest Framework, the problem is that my API does not have any database but the framework won't work without database setting.</p>
<p>Here is my Django Rest Framework configuration in <code>settings.py</code>:</p>
<pre class="lang-python prettyprint-override"><code>INSTALLED_APPS = [
'provider',
'django_nose',
'rest_framework',
'django.contrib.contenttypes',
]
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [],
'DEFAULT_PERMISSION_CLASSES': [],
}
</code></pre>
<p>The error which I got is:</p>
<blockquote>
<p>ImproperlyConfigured("settings.DATABASES is improperly configured.
"django.core.exceptions.ImproperlyConfigured: settings.DATABASES is
improperly configured. Please supply the ENGINE value. Check settings
documentation for more details.</p>
</blockquote>
<p>Is there any minimal settings which does not include <code>django.contrib.contenttypes</code> and <code>django.contrib.auth</code>?</p>
| 1 | 2016-08-23T09:58:14Z | 39,098,512 | <p>If you are really forced to use a database but you don't want to, you can use <code>:memory:</code> with the SQLite backend, like this:</p>
<pre><code>DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
}
}
</code></pre>
<p>This uses an in-memory database, so that your filesystem won't be touched.</p>
<p>Because memory is volatile, you might need to run migrations automatically every time your web app starts.</p>
| 1 | 2016-08-23T10:21:59Z | [
"python",
"django",
"django-rest-framework"
] |
Django Rest Framework Without Database | 39,098,008 | <p>I'm trying to setup a simple API using Django Rest Framework, the problem is that my API does not have any database but the framework won't work without database setting.</p>
<p>Here is my Django Rest Framework configuration in <code>settings.py</code>:</p>
<pre class="lang-python prettyprint-override"><code>INSTALLED_APPS = [
'provider',
'django_nose',
'rest_framework',
'django.contrib.contenttypes',
]
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [],
'DEFAULT_PERMISSION_CLASSES': [],
}
</code></pre>
<p>The error which I got is:</p>
<blockquote>
<p>ImproperlyConfigured("settings.DATABASES is improperly configured.
"django.core.exceptions.ImproperlyConfigured: settings.DATABASES is
improperly configured. Please supply the ENGINE value. Check settings
documentation for more details.</p>
</blockquote>
<p>Is there any minimal settings which does not include <code>django.contrib.contenttypes</code> and <code>django.contrib.auth</code>?</p>
| 1 | 2016-08-23T09:58:14Z | 39,101,018 | <p>The actual cause of the problem is that DRF trys to add a <code>user</code> attribute to the <code>request</code>. Briefly mentioned in the documentation, the mechanism is as follows:</p>
<blockquote>
<p><strong><a href="http://www.django-rest-framework.org/api-guide/authentication/#how-authentication-is-determined" rel="nofollow">How authentication is determined</a></strong></p>
<p>If no class authenticates, <code>request.user</code> will be set to an instance of
<code>django.contrib.auth.models.AnonymousUser</code></p>
</blockquote>
<p>So it needed the <code>django.contrib.auth</code> application to run correctly, consequently <code>django.contrib.auth</code> requires a working configuration of Database to be able to perform.</p>
<p>The solution to this problem is to set the settings <code>UNAUTHENTICATED_USER</code> property to <code>None</code>.</p>
<p>Configuration will be like this after the changes:</p>
<pre class="lang-python prettyprint-override"><code>INSTALLED_APPS = [
'provider',
'django_nose',
'rest_framework',
]
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [],
'DEFAULT_PERMISSION_CLASSES': [],
'UNAUTHENTICATED_USER': None,
}
</code></pre>
| 1 | 2016-08-23T12:19:05Z | [
"python",
"django",
"django-rest-framework"
] |
Firebase: limited and secure service access from Pyrebase? | 39,098,190 | <p>When using Firebase's server API, you can provide additional <code>databaseAuthVariableOverride</code> section to limit access of the service account, as described <a href="https://firebase.google.com/docs/database/server/start#authenticate-with-limited-privileges" rel="nofollow">in the docs</a>. I wanted to use <a href="https://github.com/thisbejim/Pyrebase" rel="nofollow">Pyrebase</a>, as it's in python and supports using service accounts. However, if I log in using a service account there, it has full access to the database -- the validation rules before write are not checked (while I do want them to be checked).</p>
<p>So, there are two parts to this question:</p>
<ol>
<li>Is it possible to add support for <code>databaseAuthVariableOverride</code> into Pyrebase at all? I see it uses Firebase REST API, and I don't know if that supports it, and where should I send that variable.</li>
<li>I can work around this issue by not using the service account, but a normal email/password account set to a particular email, and add root read/write rules checking <code>auth.email === '<my-email></code> and/or <code>auth.uid === '<my-account-uid>'</code>. Question here is: is this equally secure as using a service account with limited access (as linked on the top)?</li>
</ol>
| 0 | 2016-08-23T10:07:18Z | 39,102,831 | <p>There is no difference in the security rules between an auth.uid that you've set using <a href="https://firebase.google.com/docs/database/server/start#authenticate-with-limited-privileges" rel="nofollow">Authenticate with limited privileges</a> or one that is determined by <a href="https://firebase.google.com/docs/auth/android/password-auth" rel="nofollow">signing in with email&password</a>.</p>
| 1 | 2016-08-23T13:38:42Z | [
"python",
"firebase",
"firebase-database",
"firebase-security"
] |
AttributeError: 'NoneType' object has no attribute 'group' Can't Parse (Python) | 39,098,278 | <p>I am getting the following error when I am trying to parse "bloomberg" out of the self.web_url. type of self.web_url is unicode, so I am assuming that might be the reason why. However, I do not know how to implement type conversions if necessary or what to do</p>
<pre><code>self.web_url = "http://www.bloomberg.com"
start = "http:/www."
end = ".com")
print type(self.web_url)
web_name = re.search('%s(.*)%s' % (start, end), self.web_url).group(1)
</code></pre>
| 1 | 2016-08-23T10:11:05Z | 39,098,351 | <p>You are missing a <code>/</code> in <code>start</code>:</p>
<pre><code>start = 'http://www.'
</code></pre>
<p>Also note that, the <code>.</code> has a special meaning in Regex, its a Regex token that will match any single character, not literal <code>.</code>. You need to escape it to make it literal i.e. <code>\.</code>.</p>
<p>So you better do:</p>
<pre><code>start = "http://www\."
end = "\.com"
</code></pre>
| 1 | 2016-08-23T10:14:13Z | [
"python",
"regex",
"python-2.7"
] |
AttributeError: 'NoneType' object has no attribute 'group' Can't Parse (Python) | 39,098,278 | <p>I am getting the following error when I am trying to parse "bloomberg" out of the self.web_url. type of self.web_url is unicode, so I am assuming that might be the reason why. However, I do not know how to implement type conversions if necessary or what to do</p>
<pre><code>self.web_url = "http://www.bloomberg.com"
start = "http:/www."
end = ".com")
print type(self.web_url)
web_name = re.search('%s(.*)%s' % (start, end), self.web_url).group(1)
</code></pre>
| 1 | 2016-08-23T10:11:05Z | 39,098,561 | <p>You get the error because there is no match. Your pattern is incorrect since it matches a single <code>/</code>, while there are 2 <code>/</code>s after <code>http:</code>. You need to fix the pattern as heemayl suggests or use an alternative <code>urlparse</code> based solution to get the <code>netloc</code> part, and get the part in between the first and last dots (either with <code>find</code> and <code>rfind</code>, or regex):</p>
<pre><code>import urlparse, re
path = urlparse.urlparse("http://www.bloomberg.com")
print(path.netloc[path.netloc.find(".")+1:path.netloc.rfind(".")]) # => bloomberg
# or a regex:
print(re.sub(r"\A[^.]*\.(.*)\.[^.]*\Z", r"\1", path.netloc)) # => bloomberg
# or Regex 2:
mObj = re.search(r"\.(.*)\.", path.netloc);
if mObj:
print(mObj.group(1)) # => bloomberg
</code></pre>
<p>See <a href="http://ideone.com/lcitI2" rel="nofollow">Python demo</a></p>
<p>Regex 1 - <code>\A[^.]*\.(.*)\.[^.]*\Z</code> - will will match the start of string (<code>\A</code>), then 0+ non-<code>.</code>s (<code>[^.]*</code>), then a dot (<code>\.</code>), then will capture any 0+ chars other than a newline into Group 1, then will match <code>.</code> and 0+ non-<code>.</code>s up to the very end of the string (<code>\Z</code>).</p>
<p>Regex 2 will just match the first <code>.</code> followed with any 0+ chars up to the last <code>.</code> capturing what is in between <code>.</code>s into Group 1.</p>
| 1 | 2016-08-23T10:24:26Z | [
"python",
"regex",
"python-2.7"
] |
Override numpy.random to use cudamat | 39,098,284 | <p>I have a programm that uses np.random many times. Now I wan't the user to pass an argument <code>gpu=True/False</code>. How can I override np.random to return <code>cm.CUDAMatrix(np.random.uniform(low=low, high=high, size=size))</code> without ending in a recursion?
Or is there a better way to use cudamat with small code changes?</p>
<p>Thanks for your help.</p>
<p>If you need more code please comment.</p>
<pre><code>class FeedForwardNetwork():
def __init__(self, input_dim, hidden_dim, output_dim, dropout=False, dropout_prop=0.5, gpu=True):
np.random.seed(1)
self.input_layer = np.array([])
self.hidden_layer = np.array([])
self.output_layer = np.array([])
self.input_dim = input_dim
self.hidden_dim = hidden_dim
self.output_dim = output_dim
self.dropout = dropout
self.dropout_prop = dropout_prop
r_input_hidden = math.sqrt(6 / (input_dim + hidden_dim))
r_hidden_output = math.sqrt(6 / (hidden_dim + output_dim))
self.weights_input_hidden = np.random.uniform(low=-0.01, high=0.01, size=(input_dim, hidden_dim))
self.weights_hidden_output = np.random.uniform(low=-0.01, high=0.01, size=(hidden_dim, output_dim))
</code></pre>
| 0 | 2016-08-23T10:11:19Z | 39,098,650 | <pre><code>class FeedForwardNetwork():
def __init__(self, input_dim, hidden_dim, output_dim, dropout=False, dropout_prop=0.5, gpu=True):
np.random.seed(1)
self.input_layer = np.array([])
self.hidden_layer = np.array([])
self.output_layer = np.array([])
self.input_dim = input_dim
self.hidden_dim = hidden_dim
self.output_dim = output_dim
self.dropout = dropout
self.dropout_prop = dropout_prop
r_input_hidden = math.sqrt(6 / (input_dim + hidden_dim))
r_hidden_output = math.sqrt(6 / (hidden_dim + output_dim))
self.weights_input_hidden = np.random.uniform(low=-0.01, high=0.01, size=(input_dim, hidden_dim))
self.weights_hidden_output = np.random.uniform(low=-0.01, high=0.01, size=(hidden_dim, output_dim))
def np_random(self, gpu):
'''gpu:bool'''
if gpu:
return np.random.uniform(low=-0.01, high=0.01, size=(self.input_dim, self.hidden_dim))
else:
return np.random.uniform(low=-0.01, high=0.01, size=(self.hidden_dim, self.output_dim))
</code></pre>
<p>Then you can call it from your instance:</p>
<pre><code>instance = FeedForwardNetwork(**kwargs)
instance.np_random(True/False)
</code></pre>
| 1 | 2016-08-23T10:27:58Z | [
"python",
"numpy",
"cudamat"
] |
Inherit namedtuple from a base class in python | 39,098,452 | <p>Is it possible to produce a <code>namedtuple</code> which inherits from a base class? </p>
<p>What I want is that <code>Circle</code> and <code>Rectangle</code> are <code>namedtuple</code>s and are inherited from a common base class ('Shape'):</p>
<pre><code>from collections import namedtuple
class Shape:
def addToScene(self, scene):
...
Circle=namedtuple('Circle', 'x y radius')
Rectangle=namedtuple('Rectangle', 'x1 y1 x2 y2')
</code></pre>
<p>How would I do that?</p>
| 1 | 2016-08-23T10:19:27Z | 39,098,966 | <p>You can try this:</p>
<pre><code>class Circle(Shape, namedtuple('Circle', 'x y radius')):
pass
</code></pre>
<p>(You should consider adding <a href="https://docs.python.org/3/reference/datamodel.html#slots" rel="nofollow"><code>__slots__</code></a> to all your three classes to save memory and for sightly faster lookups.)</p>
| 1 | 2016-08-23T10:42:44Z | [
"python",
"inheritance",
"namedtuple"
] |
Lambda function translation | 39,098,549 | <p>I have been struggling with a piece of python code that i can not make sense of.
It's about a nested lambda function that looks like this:</p>
<pre><code>lambda l: lambda x: x[0] in [None if not i.object else i.object.key for i in l]
</code></pre>
<p>I have tried to translate it and i came up with this but i do not think this is right</p>
<pre><code> def f1(l):
def f2(x):
for i in l:
if not i.object:
return None
else
return x[0]
</code></pre>
| 1 | 2016-08-23T10:23:36Z | 39,098,827 | <p><strong>Step 1:</strong></p>
<pre><code>def f1(l):
def f2(x):
xs = [None if not i.object else i.object.key for i in l]
return x[0] in xs
return f2
</code></pre>
<p><strong>Step 2:</strong></p>
<pre><code>def f1(l):
def f2(x):
xs = []
for i in l:
if not i.object:
xs.append(None)
else:
xs.append(i.object.key)
return x[0] in xs
return f2
</code></pre>
| 2 | 2016-08-23T10:36:29Z | [
"python",
"lambda"
] |
Lambda function translation | 39,098,549 | <p>I have been struggling with a piece of python code that i can not make sense of.
It's about a nested lambda function that looks like this:</p>
<pre><code>lambda l: lambda x: x[0] in [None if not i.object else i.object.key for i in l]
</code></pre>
<p>I have tried to translate it and i came up with this but i do not think this is right</p>
<pre><code> def f1(l):
def f2(x):
for i in l:
if not i.object:
return None
else
return x[0]
</code></pre>
| 1 | 2016-08-23T10:23:36Z | 39,101,969 | <p>The accepted answer from @citaret is fine but one aspect of this hasn't been made clear so far and that is - why is it we have a function in a function, why not just have <code>f1(l, x)</code>?</p>
<p>The answer is that the function is likely used as an input to another function which takes exactly 1 argument and therefore we wish to 'capture' the list <code>l</code> in the function so we need only supply <code>x</code> when we invoke the function (this is referred to as a 'closure').</p>
<p>So for example we can create a function <code>f</code> which takes a list <code>l</code> as input and returns a new function (a closure) over <code>l</code> which accepts <code>x</code> and return True if <code>x</code> is in <code>l</code>:</p>
<pre><code>f = lambda l: lambda x: x in l
</code></pre>
<p>We can then create a function <code>f2</code> which is a closure over a list:</p>
<pre><code>f2 = f([1, 2, 3])
</code></pre>
<p>Now we can map <code>f2</code> to another list:</p>
<pre><code>print map(f2, [2, 3, 4])
</code></pre>
<p>Produces:</p>
<pre><code>[True, True, False]
</code></pre>
<p>Python's <code>functools</code> module provides a <a href="https://docs.python.org/2/library/functools.html#functools.partial" rel="nofollow">partial</a> function to help with this and perhaps make the intent of the inner lambda clearer, i.e. we could define <code>f3</code> as:</p>
<pre><code>f3 = functools.partial(lambda l, x: x in l, [1, 2, 3])
print map(f3, [2, 3, 4])
</code></pre>
<p>For a more comprehensive description of closures see <a href="http://stackoverflow.com/questions/4020419/why-arent-python-nested-functions-called-closures">this</a> answer.</p>
| 1 | 2016-08-23T13:00:13Z | [
"python",
"lambda"
] |
Splitting numbers between zeroes into separate lists in Python | 39,098,583 | <p>I'm not getting anywhere with google, as I don't think I can formulate this into a search query well.</p>
<p>I have this list:</p>
<pre><code>a = [0.0, 0.0, 0.0, 23.1, 23.1, ... , 23.1, 0.0, ... , 0.0, 34.5, ..., 34.5, 0.0, 0.0, 0.0]
</code></pre>
<p>I'd like to make it into this:</p>
<pre><code>asplit = [[23.1], [34.5]]
</code></pre>
<p>EDIT:</p>
<p>So I've change the code in the example above. I have a list that has, let's say, 234 zeroes at the front, then the number 23.1 repeated 90 time, then a 987 zeroes, then 65 occurrences of 34.5, then 34 zeroes.</p>
<p>The number of non-zero unique values will vary, as will the count of each unique value, and the number of zeroes between each unique number will also vary. It is even possible that the numbers will not be unique, but that is highly unlikely and I'm prepared to make the assumption that they are.</p>
<p>I need to preserve the order in which the unique numbers occur.</p>
<p>Sorry for the vagueness of my initial question. I find it hard to explain, but I'm fairly sure the answer will be simple.</p>
| -1 | 2016-08-23T10:25:22Z | 39,098,881 | <p>To get the first elements of all consecutive runs of non-zero numbers in the list <code>a</code>, you can use</p>
<pre><code>from itertools import groupby
result = [next(vals) for k, vals in groupby(a, bool) if k]
</code></pre>
<p>Edit: Code adapted to match the updated question.</p>
| 3 | 2016-08-23T10:38:45Z | [
"python"
] |
Splitting numbers between zeroes into separate lists in Python | 39,098,583 | <p>I'm not getting anywhere with google, as I don't think I can formulate this into a search query well.</p>
<p>I have this list:</p>
<pre><code>a = [0.0, 0.0, 0.0, 23.1, 23.1, ... , 23.1, 0.0, ... , 0.0, 34.5, ..., 34.5, 0.0, 0.0, 0.0]
</code></pre>
<p>I'd like to make it into this:</p>
<pre><code>asplit = [[23.1], [34.5]]
</code></pre>
<p>EDIT:</p>
<p>So I've change the code in the example above. I have a list that has, let's say, 234 zeroes at the front, then the number 23.1 repeated 90 time, then a 987 zeroes, then 65 occurrences of 34.5, then 34 zeroes.</p>
<p>The number of non-zero unique values will vary, as will the count of each unique value, and the number of zeroes between each unique number will also vary. It is even possible that the numbers will not be unique, but that is highly unlikely and I'm prepared to make the assumption that they are.</p>
<p>I need to preserve the order in which the unique numbers occur.</p>
<p>Sorry for the vagueness of my initial question. I find it hard to explain, but I'm fairly sure the answer will be simple.</p>
| -1 | 2016-08-23T10:25:22Z | 39,098,920 | <p>Here's a possible solution for the original question:</p>
<pre><code>import itertools
a = [0.0, 0.0, 0.0, 23.1, 23.2, 0.0, 0.0, 0.0, 34.5, 34.6, 0.0, 0.0, 0.0]
b = [list(x[1]) for x in itertools.groupby(a, lambda x: x == 0) if not x[0]]
print(b)
</code></pre>
<p>And here's the solution if you don't want to have duplicate elements in the sublists:</p>
<pre><code>import itertools
a = [0.0, 0.0, 0.0, 23.1, 23.2, 0.0, 0.0, 0.0, 34.5, 34.6, 0.0, 0.0, 0.0]
b = [list(set(x[1])) for x in itertools.groupby(a, lambda x: x == 0) if not x[0]]
print(b)
</code></pre>
| 2 | 2016-08-23T10:40:40Z | [
"python"
] |
Splitting numbers between zeroes into separate lists in Python | 39,098,583 | <p>I'm not getting anywhere with google, as I don't think I can formulate this into a search query well.</p>
<p>I have this list:</p>
<pre><code>a = [0.0, 0.0, 0.0, 23.1, 23.1, ... , 23.1, 0.0, ... , 0.0, 34.5, ..., 34.5, 0.0, 0.0, 0.0]
</code></pre>
<p>I'd like to make it into this:</p>
<pre><code>asplit = [[23.1], [34.5]]
</code></pre>
<p>EDIT:</p>
<p>So I've change the code in the example above. I have a list that has, let's say, 234 zeroes at the front, then the number 23.1 repeated 90 time, then a 987 zeroes, then 65 occurrences of 34.5, then 34 zeroes.</p>
<p>The number of non-zero unique values will vary, as will the count of each unique value, and the number of zeroes between each unique number will also vary. It is even possible that the numbers will not be unique, but that is highly unlikely and I'm prepared to make the assumption that they are.</p>
<p>I need to preserve the order in which the unique numbers occur.</p>
<p>Sorry for the vagueness of my initial question. I find it hard to explain, but I'm fairly sure the answer will be simple.</p>
| -1 | 2016-08-23T10:25:22Z | 39,099,179 | <p>another solution but without itertools
<strong>EDIT:</strong> As Op changed the question quite a bit, here another solution to fit OPs needs</p>
<pre><code># init the loop
i = 0
asplit = []
last = None
while i < len(a)-1:
# add non-zero number, that is new
cand = a[i]
if cand != last and cand != 0.0:
last = cand
asplit.append([last])
i += 1
</code></pre>
| 1 | 2016-08-23T10:53:18Z | [
"python"
] |
Splitting numbers between zeroes into separate lists in Python | 39,098,583 | <p>I'm not getting anywhere with google, as I don't think I can formulate this into a search query well.</p>
<p>I have this list:</p>
<pre><code>a = [0.0, 0.0, 0.0, 23.1, 23.1, ... , 23.1, 0.0, ... , 0.0, 34.5, ..., 34.5, 0.0, 0.0, 0.0]
</code></pre>
<p>I'd like to make it into this:</p>
<pre><code>asplit = [[23.1], [34.5]]
</code></pre>
<p>EDIT:</p>
<p>So I've change the code in the example above. I have a list that has, let's say, 234 zeroes at the front, then the number 23.1 repeated 90 time, then a 987 zeroes, then 65 occurrences of 34.5, then 34 zeroes.</p>
<p>The number of non-zero unique values will vary, as will the count of each unique value, and the number of zeroes between each unique number will also vary. It is even possible that the numbers will not be unique, but that is highly unlikely and I'm prepared to make the assumption that they are.</p>
<p>I need to preserve the order in which the unique numbers occur.</p>
<p>Sorry for the vagueness of my initial question. I find it hard to explain, but I'm fairly sure the answer will be simple.</p>
| -1 | 2016-08-23T10:25:22Z | 39,114,866 | <p>You may achieve it using <code>set</code>. Since, order of number is to be preserved, you can do:</p>
<pre><code> >>> my_list = [23.1, 23.1, 23.1, 0.0, 0.0, 34.5, 34.5, 0.0, 0.0, 0.0]
>>> seen = set()
>>> seen_add = seen.add
>>> [[x] for x in my_list if x and not (x in seen or seen_add(x))]
[[23.1], [34.5]]
</code></pre>
<p>Else, <em>if order was not necessary</em>, you can simply achieve it via:</p>
<pre><code>>>> my_list = [23.1, 23.1, 23.1, 0.0, 0.0, 34.5, 34.5, 0.0, 0.0, 0.0]
>>> map(lambda x: [x], set(x for x in my_list if x))
[[34.5], [23.1]]
</code></pre>
| 3 | 2016-08-24T05:10:58Z | [
"python"
] |
Celery and Flask in same docker-compose | 39,098,668 | <p>I'm trying to use <code>docker-compose</code> to spawn my Flask/Celery/Redis services.</p>
<p>Here's my <code>docker-compose.yml</code>:</p>
<pre><code>flask:
build: .
command: "python3 app.py"
ports:
- '5000:5000'
links:
- redis
volumes:
- .:/usr/src/app:ro
celery:
build: .
command: "celery -A app.celery worker --loglevel=info"
volumes:
- .:/usr/src/app:ro
redis:
image: redis
ports:
- '6379:6379'
</code></pre>
<p>When I run this <code>docker-compose</code>, both Flask and Redis start fine and function as expected. Regarding Celery, Docker reports: <code>flaskcelery_celery_1 exited with code 1</code>, with no other info.</p>
<p>If I run my three services without Docker, and start Celery with <code>celery -A app.celery worker --loglevel=info</code>, my app functions just fine.</p>
<p>Some more info, if necessary:</p>
<p>Dockerfile: (this image installs <code>requirements.txt</code> on build as well)</p>
<pre><code>FROM python:3.5-onbuild
EXPOSE 5000
</code></pre>
<p>requirements.txt:</p>
<pre><code>flask==0.11.1
celery==3.1.23
</code></pre>
<p><code>docker-compose up</code> output:</p>
<pre><code>Starting flaskcelery_celery_1
Starting flaskcelery_redis_1
Starting flaskcelery_flask_1
Attaching to flaskcelery_celery_1, flaskcelery_redis_1, flaskcelery_flask_1
redis_1 | _._
redis_1 | _.-``__ ''-._
redis_1 | _.-`` `. `_. ''-._ Redis 3.2.3 (00000000/0) 64 bit
redis_1 | .-`` .-```. ```\/ _.,_ ''-._
redis_1 | ( ' , .-` | `, ) Running in standalone mode
redis_1 | |`-._`-...-` __...-.``-._|'` _.-'| Port: 6379
redis_1 | | `-._ `._ / _.-' | PID: 1
redis_1 | `-._ `-._ `-./ _.-' _.-'
redis_1 | |`-._`-._ `-.__.-' _.-'_.-'|
redis_1 | | `-._`-._ _.-'_.-' | http://redis.io
redis_1 | `-._ `-._`-.__.-'_.-' _.-'
redis_1 | |`-._`-._ `-.__.-' _.-'_.-'|
redis_1 | | `-._`-._ _.-'_.-' |
redis_1 | `-._ `-._`-.__.-'_.-' _.-'
redis_1 | `-._ `-.__.-' _.-'
redis_1 | `-._ _.-'
redis_1 | `-.__.-'
redis_1 |
redis_1 | 1:M 23 Aug 10:23:08.409 # WARNING: The TCP backlog setting of 511 cannot be enforced because /proc/sys/net/core/somaxconn is set to the lower value of 128.
redis_1 | 1:M 23 Aug 10:23:08.409 # Server started, Redis version 3.2.3
redis_1 | 1:M 23 Aug 10:23:08.409 # WARNING overcommit_memory is set to 0! Background save may fail under low memory condition. To fix this issue add 'vm.overcommit_memory = 1' to /etc/sysctl.conf and then reboot or run the command 'sysctl vm.overcommit_memory=1' for this to take effect.
redis_1 | 1:M 23 Aug 10:23:08.409 # WARNING you have Transparent Huge Pages (THP) support enabled in your kernel. This will create latency and memory usage issues with Redis. To fix this issue run the command 'echo never > /sys/kernel/mm/transparent_hugepage/enabled' as root, and add it to your /etc/rc.local in order to retain the setting after a reboot. Redis must be restarted after THP is disabled.
redis_1 | 1:M 23 Aug 10:23:08.409 * The server is now ready to accept connections on port 6379
flaskcelery_celery_1 exited with code 1
flask_1 | * Running on http://0.0.0.0:5000/ (Press CTRL+C to quit)
flask_1 | * Restarting with stat
flask_1 | * Debugger is active!
flask_1 | * Debugger pin code: 196-119-737
</code></pre>
| 5 | 2016-08-23T10:28:58Z | 39,101,944 | <p>Solved my problem. I eventually figured out I could get a command prompt on the Docker image:</p>
<pre><code>docker build -t <image name> .
docker run -it <image name> /bin/bash
</code></pre>
<p>Then trying to run <code>celery</code> within the container revealed the problem:</p>
<pre><code>root@4a6edc5d7372:/usr/src/app# celery -A app.celery worker --loglevel=info
Running a worker with superuser privileges when the
worker accepts messages serialized with pickle is a very bad idea!
If you really want to continue then you have to set the C_FORCE_ROOT
environment variable (but please think about this before you do).
User information: uid=0 euid=0 gid=0 egid=0
</code></pre>
<p>Docker usually runs as root, and Celery doesn't like running as root for security reasons (I believe you can get code execution with pickle deserialization). The safer solution was to set the <code>celery</code> container to run as <code>nobody</code>. Working <code>docker-compose.yml</code>:</p>
<pre><code>flask:
build: .
command: "python3 app.py"
ports:
- '5000:5000'
links:
- redis
- celery
volumes:
- .:/usr/src/app:ro
celery:
build: .
command: "celery -A app.celery worker --loglevel=info"
user: nobody
links:
- redis
volumes:
- .:/usr/src/app:ro
redis:
image: redis
ports:
- '6379:6379'
</code></pre>
| 2 | 2016-08-23T12:59:05Z | [
"python",
"docker",
"redis",
"celery",
"docker-compose"
] |
Replacing a conditional with the negative (i.e. using not) causes error with pythons re.sub method | 39,098,761 | <p>I'm trying to replace all characters in a string that windows doesn't like in a file path (such as <code>%$£^</code>) with an empty string, using <code>re.sub</code>. When I use this:</p>
<pre><code> import string
import re
name= '*example -name_with^additional£$characters'
for j in name:
if j in string.ascii_letters+string.digits+'_-':
name=re.sub(j,'',name)
</code></pre>
<p>The regular expression works and replaces all the characters with an empty string. However, since I want to replace characters NOT in <code>string.ascii_letters+string.digits+'_-'</code> i need to use <code>not</code> instead...</p>
<pre><code> import string
import re
name= '*example -name_with^additional£$characters'
for j in name:
if j not in string.ascii_letters+string.digits+'_-':
name=re.sub(j,'',name)
</code></pre>
<p>However, this gives me an error: </p>
<pre><code> File "C:\Anaconda2\lib\re.py", line 155, in sub
return _compile(pattern, flags).sub(repl, string, count)
File "C:\Anaconda2\lib\re.py", line 251, in _compile
raise error, v # invalid expression
error: unexpected end of regular expression
</code></pre>
<p>Does anybody know what is going on? Thanks</p>
| 1 | 2016-08-23T10:32:49Z | 39,098,841 | <p>The issue arises because you are trying to <code>re.sub</code> with <code>*</code> pattern, and it is an invalid regex pattern since you cannot quantify nothing (empty location).</p>
<p>Use a simple <code>replace</code>:</p>
<pre><code>import string
name= '*example -name_with^additional£$characters'
for j in name:
if j not in string.ascii_letters+string.digits+'_-':
name=name.replace(j,'') # <- here
print(name)
</code></pre>
<p>See <a href="https://ideone.com/4CWyan" rel="nofollow">Python demo</a></p>
| 1 | 2016-08-23T10:36:56Z | [
"python",
"regex",
"string"
] |
Pandas: condition to string | 39,098,970 | <p>I have dataframe and I want to delete string from dataframe, if some column contain <code>avito</code> and doesn't contain <code>telefony</code>.
I can write condition</p>
<p><code>df1 = df[~df.url.str.contains(r"avito")]</code> </p>
<p>but I don't know how can I add condition with <code>telefony</code>
data:</p>
<pre><code>url
avito.ru/mytischi/telefony/sim_karty_s_nulevym_balansom_bonus_689217820
avito.ru/moskva/blackberry_z10_714072090
avito.ru/moskva/telefony/blackberry_bold_new_rost-test_original_697592392
avito.ru/moskva/telefony/blackberry_bold_blask_new_e._a._c._rost-test_696289049
avito.ru/moskva/blackberry_z30_lte_4g_714023258
vk.com
</code></pre>
<p>Desire output:</p>
<pre><code>url
avito.ru/mytischi/telefony/sim_karty_s_nulevym_balansom_bonus_689217820
avito.ru/moskva/telefony/blackberry_bold_new_rost-test_original_697592392
avito.ru/moskva/telefony/blackberry_bold_blask_new_e._a._c._rost-test_696289049
vk.com
</code></pre>
| -1 | 2016-08-23T10:43:11Z | 39,099,620 | <p>You want to compound your boolean conditions and negate it:</p>
<pre><code>In [18]:
df[~(df['url'].str.contains('avito') & ~df['url'].str.contains('telefony'))]
Out[18]:
url
0 avito.ru/mytischi/telefony/sim_karty_s_nulevym...
2 avito.ru/moskva/telefony/blackberry_bold_new_r...
3 avito.ru/moskva/telefony/blackberry_bold_blask...
5 vk.com
</code></pre>
<p>So the inner condition:</p>
<pre><code>df['url'].str.contains('avito') & ~df['url'].str.contains('telefony')
</code></pre>
<p>here we are looking for urls that contain 'avito' and don't contain 'telefony':</p>
<pre><code>In [19]:
df['url'].str.contains('avito') & ~df['url'].str.contains('telefony')
Out[19]:
0 False
1 True
2 False
3 False
4 True
5 False
Name: url, dtype: bool
</code></pre>
<p>we then invert the above by enclosing in parentheses and using <code>~</code> like in the first code snippet</p>
| 2 | 2016-08-23T11:13:41Z | [
"python",
"pandas"
] |
How to write CSV files into XLSX using Python Pandas? | 39,099,008 | <p>I have several .csv files and I want to write them into one .xlsx file as spreadsheets.</p>
<p>I've loaded these .csv files into Pandas.DataFrame using following code:</p>
<pre><code>df1 = pandas.read_csv('my_file1.csv')
df2 = pandas.read_csv('my_file2.csv')
......
df5 = pandas.read_csv('my_file5.csv')
</code></pre>
<p>But I couldn't find any functions in Pandas that can write these DataFrames into one .xlsx file as separated spreadsheets.</p>
<p>Can anyone help me with this? Many thanks.</p>
| 0 | 2016-08-23T10:44:49Z | 39,099,084 | <p>you can write Dataframes to CSV file and open it with Excel.</p>
<p>Use to_csv method to write it to a file.</p>
<pre><code>df1.to_csv(path_to_file)
</code></pre>
<p>You can read more here:</p>
<p><a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_csv.html" rel="nofollow">http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_csv.html</a></p>
| -1 | 2016-08-23T10:48:43Z | [
"python",
"csv",
"pandas",
"spreadsheet",
"xlsx"
] |
How to write CSV files into XLSX using Python Pandas? | 39,099,008 | <p>I have several .csv files and I want to write them into one .xlsx file as spreadsheets.</p>
<p>I've loaded these .csv files into Pandas.DataFrame using following code:</p>
<pre><code>df1 = pandas.read_csv('my_file1.csv')
df2 = pandas.read_csv('my_file2.csv')
......
df5 = pandas.read_csv('my_file5.csv')
</code></pre>
<p>But I couldn't find any functions in Pandas that can write these DataFrames into one .xlsx file as separated spreadsheets.</p>
<p>Can anyone help me with this? Many thanks.</p>
| 0 | 2016-08-23T10:44:49Z | 39,099,338 | <p>With recent enough pandas use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_excel.html" rel="nofollow"><code>DataFrame.to_excel()</code></a> with an existing <code>ExcelWriter</code> object and pass sheet names:</p>
<pre><code>from pandas.io.excel import ExcelWriter
import pandas
csv_files = ['my_file1.csv', 'my_file2.csv', ..., 'my_file5.csv']
with ExcelWriter('my_excel.xlsx') as ew:
for csv_file in csv_files:
pandas.read_csv(csv_file).to_excel(ew, sheet_name=csv_file)
</code></pre>
| 1 | 2016-08-23T11:00:32Z | [
"python",
"csv",
"pandas",
"spreadsheet",
"xlsx"
] |
Pycharm SqlAlchemy autocomplete not working | 39,099,117 | <p>I'm using SQLAlchemy and Pycharm, but PyCharm can't see methods of SQLAlchemy for autocomplete function.</p>
<p>Code:</p>
<pre><code>from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///data.sqlite3'
db = SQLAlchemy(app)
class User(db.Model):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(16), index=True, unique=True)
if __name__ == '__main__':
db.create_all()
app.run(debug=True)
</code></pre>
<p>For example, if I want call SQLAlchemy method of User class i must type full method name manually User.query.filter_by(username='peter').first()
<a href="http://i.stack.imgur.com/RP5QT.jpg" rel="nofollow">Autocomplete example</a></p>
<p><strong>How to make autocomplete work for SQLAlchemy?</strong></p>
<p>1) Yes, project was reloaded several times <br>
2) Yes, right interpreter in File | settings | Project <br>
3) Yes, PyCharm is not in Power Save Mode <br>
4) Yes, I have Professional edition. <br></p>
| 2 | 2016-08-23T10:50:12Z | 39,103,583 | <p>PyCharm (or any other IDE) can't find most methods (<code>query()</code>, <code>add()</code>, <code>commit()</code> etc) as they are not defined in <code>flask_sqlalchemy.SQLAlchemy</code> class. SQLAlchemy methods are added to <code>flask_sqlalchemy.SQLAlchemy</code> objects dynamically during initialization. You can find this initialization function in <a href="https://github.com/mitsuhiko/flask-sqlalchemy/blob/master/flask_sqlalchemy/__init__.py#L87" rel="nofollow">flask_sqlalchemy module</a>:</p>
<pre><code>def _include_sqlalchemy(obj):
for module in sqlalchemy, sqlalchemy.orm:
for key in module.__all__:
if not hasattr(obj, key):
setattr(obj, key, getattr(module, key))
</code></pre>
<p>Just for the testing: you can type <code>from sqlalchemy.orm import Query</code>. I think PyCharm will find it's objects just fine.</p>
<p>I can't suggest any solution, maybe someone else here know about possibility of dynamically added attributes autocompletion.</p>
| 0 | 2016-08-23T14:10:35Z | [
"python",
"autocomplete",
"sqlalchemy",
"pycharm",
"flask-sqlalchemy"
] |
In Python, how do I select the columns of a dataframe satisfying a condition on the number of NaN? | 39,099,143 | <p>I hope someone could help me. I'm new to Python, and I have a dataframe with 111 columns and over 40 000 rows. All the columns contain NaN values (some columns contain more NaN's than others), so I want to drop those columns having at least 80% of NaN values. How can I do this?</p>
<p>To solve my problem, I tried the following code</p>
<pre><code>df1=df.apply(lambda x : x.isnull().sum()/len(x) < 0.8, axis=0)
</code></pre>
<p>The function <code>x.isnull().sum()/len(x)</code> is to divide the number of NaN in the column x by the length of x, and the part < 0.8 is to choose those columns containing less than 80% of NaN. </p>
<p>The problem is that when I run this code I only get the names of the columns together with the boolean "True" but I want the entire columns, not just the names. What should I do?</p>
| 0 | 2016-08-23T10:51:45Z | 39,099,887 | <p>You could do this:</p>
<pre><code>filt = df.isnull().sum()/len(df) < 0.8
df1 = df.loc[:, filt]
</code></pre>
| 2 | 2016-08-23T11:26:58Z | [
"python",
"apply",
null
] |
In Python, how do I select the columns of a dataframe satisfying a condition on the number of NaN? | 39,099,143 | <p>I hope someone could help me. I'm new to Python, and I have a dataframe with 111 columns and over 40 000 rows. All the columns contain NaN values (some columns contain more NaN's than others), so I want to drop those columns having at least 80% of NaN values. How can I do this?</p>
<p>To solve my problem, I tried the following code</p>
<pre><code>df1=df.apply(lambda x : x.isnull().sum()/len(x) < 0.8, axis=0)
</code></pre>
<p>The function <code>x.isnull().sum()/len(x)</code> is to divide the number of NaN in the column x by the length of x, and the part < 0.8 is to choose those columns containing less than 80% of NaN. </p>
<p>The problem is that when I run this code I only get the names of the columns together with the boolean "True" but I want the entire columns, not just the names. What should I do?</p>
| 0 | 2016-08-23T10:51:45Z | 39,100,029 | <p>You want to achieve two things. First, you have to find the indices of all columns which contain at most 80% <code>NaN</code>s. Second, you want to discard them from your <code>DataFrame</code>.</p>
<p>To get a <code>pandas</code> <code>Series</code> indicating whether a row should be discarded by doing, you can do:</p>
<pre><code>df1 = df.isnull().sum(axis=0) < 0.8*df.shape[1]
</code></pre>
<p>(Btw. you have a typo in your question. You should drop the <code>==True</code> as it always tests whether <code>0.5==True</code>)</p>
<p>This will give <code>True</code> for all column indices to keep, as <code>.isnull()</code> gives <code>True</code> (or 1) if it is <code>NaN</code> and <code>False</code> (or 0) for a valid number for every element. Then the <code>.sum(axis=0)</code> sums along the columns giving the number of <code>NaN</code>s in each column. The comparison is then, if that number is bigger than 80% of the number of columns.</p>
<p>For the second task, you can use this to index your columns by using:</p>
<pre><code>df = df[df.columns[df1]]
</code></pre>
<p>or as suggested in the comments by doing:</p>
<pre><code>df.drop(df.columns[df1==False], axis=1, inplace=True)
</code></pre>
| 2 | 2016-08-23T11:32:50Z | [
"python",
"apply",
null
] |
Pandas reduce number of categorical variables | 39,099,217 | <p>New to pandas I want to perform something similar to <a href="http://stackoverflow.com/questions/39066382/reduce-number-of-levels-for-large-categorical-variables?noredirect=1#comment65482577_39066382">Reduce number of levels for large categorical variables</a> (binning of categorical variables in order to reduce their levels)
The following code works fine in R</p>
<pre><code>DTsetlvls <- function(x, newl)
setattr(x, "levels", c(setdiff(levels(x), newl), rep("other", length(newl))))
</code></pre>
<p>My dataframe:</p>
<pre><code>df = pd.DataFrame({'Color': 'Red Red Blue'.split(),
'Value': [100, 150, 50]})
df['Counts'] = df.groupby('Color')['Value'].transform('count')
print (df)
Color Value Counts
0 Red 100 2
1 Red 150 2
2 Blue 50 1
</code></pre>
<p>I manually would create an aggregate column and then based on that, label the less frequent groups e.g. "blue" as a single "other" group.
But compared to the concise R code this seems clumsy. What would be the right approach here?</p>
| 0 | 2016-08-23T10:55:00Z | 39,099,960 | <p>I think you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.value_counts.html" rel="nofollow"><code>value_counts</code></a> with <a href="http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.where.html" rel="nofollow"><code>numpy.where</code></a>, where is condition with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.isin.html" rel="nofollow"><code>isin</code></a>:</p>
<pre><code>df = pd.DataFrame({'Color':'Red Red Blue Red Violet Blue'.split(),
'Value':[11,150,50,30,10,40]})
print (df)
Color Value
0 Red 11
1 Red 150
2 Blue 50
3 Red 30
4 Violet 10
5 Blue 40
a = df.Color.value_counts()
print (a)
Red 3
Blue 2
Violet 1
Name: Color, dtype: int64
#get top 2 values of index
vals = a[:2].index
print (vals)
Index(['Red', 'Blue'], dtype='object')
</code></pre>
<hr>
<pre><code>df['new'] = np.where(df.Color.isin(vals), 0,1)
print (df)
Color Value new
0 Red 11 0
1 Red 150 0
2 Blue 50 0
3 Red 30 0
4 Violet 10 1
5 Blue 40 0
</code></pre>
<p>Or if need replace all not top values use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.where.html" rel="nofollow"><code>where</code></a>:</p>
<pre><code>df['new1'] = df.Color.where(df.Color.isin(vals), 'other')
print (df)
Color Value new1
0 Red 11 Red
1 Red 150 Red
2 Blue 50 Blue
3 Red 30 Red
4 Violet 10 other
5 Blue 40 Blue
</code></pre>
| 1 | 2016-08-23T11:30:08Z | [
"python",
"pandas",
"categorical-data",
"binning"
] |
Is it safe to inject context into a eventlet thread like this? | 39,099,325 | <p>I need to inject thread level context information for logging and debugging purposes. I've been told that this is potentially unsafe.</p>
<pre><code>greenthread = worker_pool.spawn(run_worker, args, handle_result)
# this logging_context attribute will be accessed by the logging library
greenthread.__dict__['logging_context'] = 'data for logging'
greenthread.link()
</code></pre>
<p>While certainly not something you would want to do often, it was the only way I could set a thread local global constant, which the logger could access.</p>
<p>This can then be accessed later by the logger via</p>
<pre><code>eventlet.getcurrent().logging_context
</code></pre>
<p>As far as my knowledge in python goes, I don't see how this is unsafe, why do others say this is potentially a recipe for disaster?</p>
<hr>
<p>While I see it as a rather ugly monkey patch, I am not creating global mutable state. I am creating a thread-local constant that is instantiated before the thread is even run.</p>
| 3 | 2016-08-23T10:59:42Z | 39,119,196 | <p>I agree, "safe/unsafe" is for obsessed parents. As programmers we can define expectancy for troubles in a much more strict and useful way.</p>
<ul>
<li>That approach works now, so while eventlet and greenlet versions are locked, it will work and everything is great.</li>
<li>You're changing Greenthread attributes after <code>spawn</code>. Right now it takes <code>sleep()</code> or other way to yield to "event loop" before newly spawned greenthread executes, but that behavior may change in future. Which means that <code>run_worker</code> may already be running. You can use <code>eventlet.pools.Pool()</code> to manage proper setup and link of greenthreads before allowing them to run.</li>
<li>In future it may break because greenthread would get <code>__slots__</code> to save memory, or particular <code>__setattr__</code> implementation for other reasons.</li>
<li>There is tested and supported API for what you're doing, it's called thread local storage. You use it like regular Python threadlocal object, but use patched version of <code>threading</code>[1].</li>
<li>You may like Logbook[2] more, it has cleaner way to do the same (using threadlocal under the hood).</li>
</ul>
<p>Sample code for <code>threadlocal</code> route:</p>
<pre><code>def add_logging_context(context, fun, *a, **kw):
tl = threading.local()
tl.logging_context = context
return fun(*a, **kw)
pool.spawn(add_logging_context, 'data for logging', run_worker, args, handle_result)
</code></pre>
<p>[1] <a href="http://eventlet.net/doc/patching.html" rel="nofollow">http://eventlet.net/doc/patching.html</a></p>
<p>[2] <a href="https://logbook.readthedocs.io/en/stable/" rel="nofollow">https://logbook.readthedocs.io/en/stable/</a></p>
| 1 | 2016-08-24T09:17:26Z | [
"python",
"multithreading",
"logging",
"eventlet"
] |
In python, apply path (URL) of unknown length to a JSON object | 39,099,591 | <p>Given paths (<em>foos</em>) of unknown length, and associated values (<em>bars</em>):</p>
<pre><code>foo1 = '/path/key1'
foo2 = '/path/node1/key2'
bar1 = 'value1'
bar2 = 'value2'
</code></pre>
<p>How can I recursively map these to a json structure, for example using python's json module? The above would become:</p>
<pre><code>{ 'path':
{ 'key1': 'value1',
'node1': { 'key2': 'value2' }
}
}
</code></pre>
<p>The aforementioned json module supports:</p>
<pre><code>json_data['path']['key1'] = bar1
json_data['path']['node1']['key2'] = bar2
</code></pre>
<p>But I don't know the depth of each path provided...?!</p>
| 0 | 2016-08-23T11:12:08Z | 39,100,568 | <p>To get a recursive dictionary, you can use this helper class</p>
<pre><code>class RecursiveDict(dict):
def __missing__(self, attr):
db = RecursiveDict()
super(RecursiveDict, self).__setitem__(attr, db)
return db
def __setitem__(self, attr, value):
if isinstance(attr, (tuple,list)):
cur = self[attr[0]]
for i in attr[1:-1]:
cur = cur[i]
cur[attr[-1]] = value
else:
super(RecursiveDict, self).__setitem__(attr, value)
def __getitem__(self, item):
if isinstance(item, (tuple, list)):
cur = self[item[0]]
for i in item[1:]:
cur = cur[i]
return cur
else:
return super(RecursiveDict, self).__getitem__(item)
def __delitem__(self, item):
if isinstance(item, (tuple, list)):
cur = self[item[0]]
for i in item[1:-1]:
cur = cur[i]
del cur[item[-1]]
else:
return super(RecursiveDict, self).__delitem__(item)
</code></pre>
<p>Use like:</p>
<pre><code>a=RecursiveDict()
path="/a/a/a"
path = path.strip("/").split("/")
a[path]="value"
a["a","b","c"]=1
a["b"]=2
print a
</code></pre>
<p>--> <code>{'a': {'a': {'a': 'value'}, 'b': {'c': 1}}, 'b': 2}</code></p>
| 2 | 2016-08-23T11:59:36Z | [
"python",
"json",
"dictionary",
"recursion"
] |
Confused how to extract value from a list of dictionaries | 39,099,608 | <pre><code>diction_a = {'x': {'zebra':'white', 'raptors':'bosh', 'teams' : [{'a': 0, 'b': '123456', 'c': 1, 'd': 'xuix'}, {'a': 0, 'b': '234567', 'c': 1, 'd': 'lebron?', 'owner': 'heat'}, {'a': 0, 'b': '7890324', 'c': 1, 'd': 'durant'}, ..{many more with similar format}]
</code></pre>
<p>So I'm given diction_a as the dictionary but I need to extract the value of 'b' from 'teams' from multiple dictionaries within the list. I have this code below, but when I print list_of_b its an empty list.</p>
<pre><code>search = diction_a ['x']['teams']
list_of_b = [a.get('b') for a in search if 'b' in a]
</code></pre>
| -2 | 2016-08-23T11:12:56Z | 39,100,145 | <p>You should confirm first your data structure is correct, here's a working example using exactly your code:</p>
<pre><code>diction_a = {
'x': {
'zebra': 'white',
'raptors': 'bosh',
'teams': [
{
'a': 0,
'b': '123456',
'c': 1,
'd': 'xuix'
}, {
'a': 0,
'b': '234567',
'c': 1,
'd': 'lebron?',
'owner': 'heat'
}, {
'a': 0,
'b': '7890324',
'c': 1,
'd': 'durant'
}
]
}
}
search = diction_a['x']['teams']
list_of_b = [a.get('b') for a in search if 'b' in a]
print list_of_b
</code></pre>
| -1 | 2016-08-23T11:38:38Z | [
"python",
"python-3.x",
"dictionary"
] |
Confused how to extract value from a list of dictionaries | 39,099,608 | <pre><code>diction_a = {'x': {'zebra':'white', 'raptors':'bosh', 'teams' : [{'a': 0, 'b': '123456', 'c': 1, 'd': 'xuix'}, {'a': 0, 'b': '234567', 'c': 1, 'd': 'lebron?', 'owner': 'heat'}, {'a': 0, 'b': '7890324', 'c': 1, 'd': 'durant'}, ..{many more with similar format}]
</code></pre>
<p>So I'm given diction_a as the dictionary but I need to extract the value of 'b' from 'teams' from multiple dictionaries within the list. I have this code below, but when I print list_of_b its an empty list.</p>
<pre><code>search = diction_a ['x']['teams']
list_of_b = [a.get('b') for a in search if 'b' in a]
</code></pre>
| -2 | 2016-08-23T11:12:56Z | 39,100,665 | <pre><code>print [val['b'] for x in diction_a.values() for val in x['teams'] ]
</code></pre>
<p>Input : </p>
<pre><code>diction_a = {'x': {'zebra':'white', 'raptors':'bosh','teams' : [{'a': 0, 'b': '123456', 'c': 1, 'd': 'xuix'}, {'a': 0, 'b': '234567', 'c': 1, 'd': 'lebron?', 'owner': 'heat'},{'a': 0, 'b': '7890324', 'c': 1, 'd': 'durant'}] } }
</code></pre>
<p>Output :</p>
<pre><code>['123456', '234567', '7890324']
</code></pre>
| 0 | 2016-08-23T12:03:53Z | [
"python",
"python-3.x",
"dictionary"
] |
Openerp Schdular execute at once | 39,099,616 | <p>I have created scheduled task and in local-host the scheduler with the function is working fine. In server I set Number of Calls=10, Interval Unit = Minutes and Interval Number = 1 </p>
<p>The issue is when the server start after the particular upgrades , after only one minute the Number of Calls shows as 0 instead of 9</p>
<p>Please help me with this</p>
<p>The Function</p>
<pre><code>def allocate_on_probations(self, cr, uid, ids,tl, context=None):
allo=0
state='active'
result = {}
emps=self.pool.get('hr.employee').search(cr, uid, [('current_status','=','active')], context=context)
if emps:
for r in emps:
hol_state=2
gt_dt=cr.execute("""SELECT appointed_date FROM hr_employee WHERE id= %d order by id"""%(r))
gt_dd=cr.fetchone()[0]
#getting today details
today = datetime.datetime.now()
tt=today.date()
td=tt.day
tm=tt.month
ty=tt.year
#getting appointment date details
app=datetime.datetime.strptime(gt_dd, "%Y-%m-%d").date()
#print app
ay=app.year
am=app.month
ad=app.day
if ay==ty:
#compairing today and appointed date
comp=(tt-app)
chat=int(comp.days)
chat_mod=chat%30
print chat_mod
print r
if chat_mod==29:
hol_obj=self.pool.get('hr.holidays')
print hol_obj
condition_1=[('employee_id','=',r),('type','=','add'),('holiday_status_id','=',hol_state)]
hol_emp=hol_obj.search(cr, uid,condition_1, context=context)
if hol_emp:
for n in hol_emp:
hol_dt=cr.execute("""SELECT number_of_days_temp FROM hr_holidays WHERE id= %d order by id"""%(n))
hol_dd=cr.fetchone()[0]
hol_inc=(hol_dd+0.5)
print hol_inc
cr.execute("""UPDATE hr_holidays SET number_of_days_temp= %d WHERE id= %d"""%(hol_inc,n))
cr.execute("""UPDATE hr_holidays SET number_of_days= %d WHERE id= %d"""%(hol_inc,n))
return True
</code></pre>
<p>XML Scheduler call</p>
<pre><code><record id="ir_cron_scheduler" model="ir.cron">
<field name="name">Casual Leave Allocation</field>
<field name="interval_number">1</field>
<field name="interval_type">minutes</field>
<field name="numbercall">10</field>
<field eval="False" name="doall"/>
<field eval="'hr.holidays'" name="hr.holidays"/>
<field eval="'allocate_on_probations'" name="allocate_on_probations"/>
<field eval="'()'" name="args"/>
</record>
</code></pre>
<p>UI
<a href="http://i.stack.imgur.com/8veWE.png" rel="nofollow"><img src="http://i.stack.imgur.com/8veWE.png" alt="enter image description here"></a></p>
<p><a href="http://i.stack.imgur.com/LCEuj.png" rel="nofollow"><img src="http://i.stack.imgur.com/LCEuj.png" alt="enter image description here"></a></p>
| 0 | 2016-08-23T11:13:26Z | 39,138,344 | <p>The problem you're having is with <code>Repeat missed</code></p>
<p>When you set it to True, it means that missed actions that were missed when the server was done should be executed when the server restarts, so if the server was down for at least 10 minutes, when you restart it all the actions that were missed during that period would be executed as soon as possible. so don't untick that option, it's actually <code>False</code> in your code</p>
<p>you can also set the Argument that triggers the function from the xml</p>
<p><code><field eval="'(True,)'" name="args"/></code></p>
| 1 | 2016-08-25T06:41:09Z | [
"python",
"openerp",
"openerp-7"
] |
Generate different name of text file at every hit | 39,099,766 | <p>I have an endpoint hosted in ec2 machine. This endpoint has a piece of code that has to generate a text file.<br>
I want that if multiple people are hitting this endpoint, then this snippet should generate different text file name for each of them.</p>
<p>I tried using md5 hash in Python. but unable to append this hash value in the name of text file.</p>
<pre><code>hash2 = random.getrandbits(128)
name = "test_data" + str(hash2)
sys.stdout = open(name.txt, "w")
</code></pre>
| -1 | 2016-08-23T11:21:23Z | 39,099,849 | <p>You try to open <code>name.txt</code>, where you should try to open <code>name</code>.</p>
<p>It is also not very often seen that you assign the <code>open()</code> value to sys.stdout. Better to use a variable of your own (<code>fp</code>, <code>stream</code>) instead.</p>
| 1 | 2016-08-23T11:24:59Z | [
"python",
"md5"
] |
Storing tweets in MongoDB using pymongo | 39,099,914 | <p>I am trying to save tweets directly from <code>Twitter</code> into <code>MongoDB</code> for retrieval later, but I keep getting error messages with regards to <code>json</code>. Someone please help! Here is the sample codes with error messages.</p>
<pre><code>searcher = keywordSearcher('','','') ## this is an object class
client = MongoClient('localhost', 27017)
db = client.test_dbase ## connect to database twitter
collection = db.rio_olympics ## create a collection object
result = searcher.getTwitterComment('Olympics 2016', '21 August 2016', 2) ## this is where I query Twitter Search API
py_dict = json.load(result)
post_id = collection.insert_many(py_dict)
</code></pre>
<p>error message: </p>
<pre><code>Traceback (most recent call last):
File "/home/edidiong/myWorkSpace/keywordSearchTest.py", line 12, in <module>
class keywordSearchTest:
File "/home/edidiong/myWorkSpace/keywordSearchTest.py", line 45, in keywordSearchTest
py_dict = json.load(result)
File "/usr/lib/python2.7/json/__init__.py", line 287, in load
return loads(fp.read(),
AttributeError: 'dict' object has no attribute 'read'
</code></pre>
| 0 | 2016-08-23T11:28:15Z | 39,100,778 | <p>Your <code>searcher.getTwitterComment</code> returns a dictionary and not json. </p>
<p>That is why you get this error, <code>json.load()</code> is already called probably. </p>
| 1 | 2016-08-23T12:09:26Z | [
"python",
"mongodb"
] |
Storing tweets in MongoDB using pymongo | 39,099,914 | <p>I am trying to save tweets directly from <code>Twitter</code> into <code>MongoDB</code> for retrieval later, but I keep getting error messages with regards to <code>json</code>. Someone please help! Here is the sample codes with error messages.</p>
<pre><code>searcher = keywordSearcher('','','') ## this is an object class
client = MongoClient('localhost', 27017)
db = client.test_dbase ## connect to database twitter
collection = db.rio_olympics ## create a collection object
result = searcher.getTwitterComment('Olympics 2016', '21 August 2016', 2) ## this is where I query Twitter Search API
py_dict = json.load(result)
post_id = collection.insert_many(py_dict)
</code></pre>
<p>error message: </p>
<pre><code>Traceback (most recent call last):
File "/home/edidiong/myWorkSpace/keywordSearchTest.py", line 12, in <module>
class keywordSearchTest:
File "/home/edidiong/myWorkSpace/keywordSearchTest.py", line 45, in keywordSearchTest
py_dict = json.load(result)
File "/usr/lib/python2.7/json/__init__.py", line 287, in load
return loads(fp.read(),
AttributeError: 'dict' object has no attribute 'read'
</code></pre>
| 0 | 2016-08-23T11:28:15Z | 39,100,789 | <p>The error message indicates you are trying to <code>load</code> a dictionary object. This means you already have a dictionary object. I'm not sure what the point of the <code>json.load</code> would be even if it did work. </p>
<p>So you can probably just do:</p>
<pre><code>py_dict = searcher.getTwitterComment("Olympics 2016", '21 August 2016', 2)
post_id = collection.insert_many(py_dict)
</code></pre>
| 1 | 2016-08-23T12:10:07Z | [
"python",
"mongodb"
] |
Updating global object from python threads/processes | 39,099,938 | <p>I'm trying to access a global dict from different threads. A complete example is below:</p>
<pre><code>results = {0: 'pass'}
def checkResult(thread_num, result_map):
while(True):
results[thread_num] = 'fail'
print('Thread results : '+str(results))
time.sleep(5)
multiprocessing.Process(target = checkResult, args=(1, results)).start()
multiprocessing.Process(target = checkResult, args=(2, results)).start()
while(True):
print('Main results: '+str(results))
time.sleep(3)
</code></pre>
<p>The "main results" only sees thread 0, and the "thread results" only modify the dict as per their own thread's results:</p>
<pre><code>Thread results : {0: 'pass', 1: 'fail'}
Main results: {0: 'pass'}
Thread results : {0: 'pass', 2: 'fail'}
Main results: {0: 'pass'}
Thread results : {0: 'pass', 1: 'fail'}
Thread results : {0: 'pass', 2: 'fail'}
Main results: {0: 'pass'}
^C
</code></pre>
<p>It seems that the "results" map is being passed-by-value instead of passed-by-reference. Is there any way to have the threads refer to the original global map instead of having each thread use it's own copy?</p>
<p>I know that I should be using locking to avoid issues where one thread overwrites the changes of another (and I plan to do so in the actual solution). For now though I'm just trying to have all the threads working with a common results dictionary.</p>
| 0 | 2016-08-23T11:29:12Z | 39,102,788 | <p>What you need is parallel access to a global object which can be done by using threads instead of processes. All threads share the same adressspace which means, they have access to the same refereces.
(also instead of using a dict with integer-keys, you could use a list)</p>
<p>If you're using unique "thread numbers" you actually don't need to worry about race-conditions because every thread writes to it`s own index.</p>
<p>Something like this should do the trick:</p>
<pre><code>import _thread, time
results = {0 : 'pass'}
def checkResult(thread_num):
while True:
results[thread_num] = 'fail'
print('Thread results: ' + str(results))
time.sleep(3)
_thread.start_new_thread(checkResult, (1,))
_thread.start_new_thread(checkResult, (2,))
while True:
print('Main results: ' + str(results))
time.sleep(3)
</code></pre>
<p>(<a href="https://stackoverflow.com/questions/3044580/multiprocessing-vs-threading-python">this</a> might help you)</p>
| 1 | 2016-08-23T13:36:21Z | [
"python",
"multithreading"
] |
Define custom function in selenium python | 39,099,961 | <p>How I can define custom function and then use it in test function, it works when I run single test case but don't work when I run multiple test cases.</p>
<pre><code>class AlphaTest(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Firefox()
self.driver.implicitly_wait(30)
self.driver.get("http://google.com/")
def asserTrueId(self, value):
self.assertTrue(self.driver.find_element_by_id(value))
time.sleep(1)
def test_flush_cache(self):
self.asserTrueId("block-menu-menu-menu-for-directories")
</code></pre>
| 0 | 2016-08-23T11:30:12Z | 39,102,045 | <p>You could use <code>unittest.setUpClass()</code> to instantiate a class level <code>driver</code> instance. Similarly you can use <code>tearDownClass()</code> to clean up class level variables if required. </p>
<p>Since <code>setUpClass()</code> and <code>tearDownClass()</code> will only be run once inside your Test class you can use this to guarantee there is only one driver. Otherwise using <code>setUp()</code> would be run for each test method - each creating a browser instance each time - which could be slow and possibly memory inefficient.</p>
<pre><code>class AlphaTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.driver = webdriver.Firefox()
cls.driver.implicitly_wait(30)
cls.driver.get("http://google.com/")
def asserTrueId(self, value):
self.assertTrue(self.driver.find_element_by_id(value))
time.sleep(1)
def test_flush_cache(self):
self.asserTrueId("block-menu-menu-menu-for-directories")
</code></pre>
| 0 | 2016-08-23T13:03:29Z | [
"python",
"selenium"
] |
How do I count number of tabs in screenshot using OpenCV houghlines? | 39,100,020 | <p>I am trying to count number of tabs in screenshot using OpenCV. I first cropped my image to limit to chrome tabs. Then I used edge detection, Canny algorithm to find edges in chrome. Then I am using Houghlines to find number of tabs, but I am not getting the required ouput through Houghlines. Below is my code and output. </p>
<pre><code>import cv2
import numpy as np
import math
from matplotlib import pyplot as plt
img = cv2.imread('1.png')
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
edges = cv2.Canny(gray,50,200,apertureSize = 3)
cv2.imwrite('result.png',edges)
lines = cv2.HoughLines(edges,1,np.pi/180,50)
for rho,theta in lines[0]:
slope = 180*theta*1.0/np.pi
if slope > 110 and slope <148: # for identifying chrome tab angle (right slope line of each tab)
a = np.cos(theta)
b = np.sin(theta)
x0 = a*rho
y0 = b*rho
x1 = int(x0 + 1000*(-b))
y1 = int(y0 + 1000*(a))
x2 = int(x0 - 1000*(-b))
y2 = int(y0 - 1000*(a))
cv2.line(img,(x1,y1),(x2,y2),(0,0,255),3)
cv2.imwrite('result2.png',img)
</code></pre>
<p><a href="http://i.stack.imgur.com/lFZgA.png" rel="nofollow"><img src="http://i.stack.imgur.com/lFZgA.png" alt="Original cropped image"></a>
<a href="http://i.stack.imgur.com/JR1bP.png" rel="nofollow"><img src="http://i.stack.imgur.com/JR1bP.png" alt="Final Image"></a></p>
<p><a href="http://i.stack.imgur.com/zYpkw.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/zYpkw.jpg" alt="Firefox image"></a></p>
<p><a href="http://i.stack.imgur.com/QZWP9.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/QZWP9.jpg" alt="enter image description here"></a></p>
| 0 | 2016-08-23T11:32:19Z | 39,104,369 | <p>Very interesting:D
A really simple solution would be to binarize your image and to define a line in the upper area of the image and get the gray values. Then you could count the intersections. Here is an example:
<a href="http://i.stack.imgur.com/40O9Z.png" rel="nofollow"><img src="http://i.stack.imgur.com/40O9Z.png" alt="Finding number of tabs from gray value profile"></a></p>
<p>The fancy algorithms arent always the best solution. Define what you want to do and try to find a solution as simple as possible. </p>
<p>Here is my solution in C++. Quick and dirty ;)</p>
<pre><code>#include "opencv2/imgproc.hpp"
#include "opencv2/highgui.hpp"
#include <vector>
#include <stdlib.h>
#include <stdio.h>
using namespace cv;
using namespace std;
Mat src, binary, morph, gray, morph_rgb;
/**
*Compute number of tabs
*/
int getNumberOfTabs(Mat& src, int start_col, int stop_col, int search_row, bool draw=false);
/**
* @function main
*/
int main(int argc, char** argv)
{
const int morph_size = 2;
const int start_col = 5;
const int stop_col = 1750;
const int row_index = 2;
/// Load an image
src = imread("C:\\Users\\phili\\Pictures\\Tab.png", 1);
//Convert for binarization
cvtColor(src, gray, CV_RGB2GRAY);
threshold(gray, binary, 164, 255, 1);
//Remove icons and text on tabs
Mat element = getStructuringElement(CV_SHAPE_RECT, Size(2 * morph_size + 1, 2 * morph_size + 1), Point(morph_size, morph_size));
morphologyEx(binary, morph, CV_MOP_OPEN, element);
int nmb_tabs = getNumberOfTabs(morph, start_col, stop_col, row_index, true);
imshow("Original", src);
imshow("Binary", binary);
imshow("Binary", morph);
/// Wait until user finishes program
while (true)
{
int c;
c = waitKey(20);
if ((char)c == 27)
{
break;
}
}
}
int getNumberOfTabs(Mat& src,int start_col,int stop_col, int row_index, bool draw)
{
int length = stop_col - start_col;
//Extract gray value profil
Mat profil = cv::Mat(0, length, CV_8U);
profil = src.colRange(start_col, stop_col).row(row_index);
Mat src_rgb;
if (draw)
{
cvtColor(src, src_rgb, CV_GRAY2RGB);
line(src_rgb, Point(start_col, row_index), Point(stop_col, row_index), Scalar(0, 0, 255), 2);
}
//Convolve profil with [1 -1] to detect edges
unsigned char* input = (unsigned char*)(profil.data);
vector<int> positions;
for (int i = 0; i < stop_col - start_col - 1; i++)
{
//Kernel
int first = input[i];
int second = input[i + 1];
int ans = first - second;
//Positiv or negativ slope ?
if (ans < 0)
{
positions.push_back(i + 1);
if(draw)
circle(src_rgb, Point(i + start_col, row_index), 2, Scalar(255,0, 0), -1);
}
else if (ans > 0)
{
positions.push_back(i);
if (draw)
circle(src_rgb, Point(i + start_col + 1, row_index), 2, Scalar(255,0, 0), -1);
}
}
if (draw)
imshow("Detected Edges", src_rgb);
//Number of tabs
return positions.size() / 2;
}
</code></pre>
<p>and the results with the search line in red and the detected edges in blue:
<a href="http://i.stack.imgur.com/sLk4w.png" rel="nofollow"><img src="http://i.stack.imgur.com/sLk4w.png" alt="enter image description here"></a></p>
| 4 | 2016-08-23T14:47:57Z | [
"python",
"opencv",
"image-processing",
"edge-detection",
"hough-transform"
] |
How to capture value of dropdown widget in bokeh python? | 39,100,095 | <p>The official documentation of bokeh 0.12.1 in the link give the below code for creating a dropdown. </p>
<p><a href="http://bokeh.pydata.org/en/latest/docs/user_guide/interaction/widgets.html#userguide-interaction-widgets" rel="nofollow">http://bokeh.pydata.org/en/latest/docs/user_guide/interaction/widgets.html#userguide-interaction-widgets</a></p>
<p>But its doesn't clearly mention how to capture the value of the dropdown widget when someone click and selects a value from the dropdown.</p>
<pre><code>from bokeh.io import output_file, show
from bokeh.layouts import widgetbox
from bokeh.models.widgets import Dropdown
output_file("dropdown.html")
menu = [("Item 1", "item_1"), ("Item 2", "item_2"), None, ("Item 3", "item_3")]
dropdown = Dropdown(label="Dropdown button", button_type="warning", menu=menu)
show(widgetbox(dropdown))
</code></pre>
<p><strong>Question</strong></p>
<p>Is see that there are 2 methods called on_click() & on_change() but from the documentation couldn't figure out how to capture the value.
How can we assign the selected value to a new variable?</p>
<p><strong>EDIT</strong></p>
<p>Based on input from @Ascurion i have updated my code as shown below. But when i select a value in dropdown nothing is printed in ipython console in Spyder.
Please advise.</p>
<pre><code> from bokeh.io import output_file, show
from bokeh.layouts import widgetbox
from bokeh.models.widgets import Dropdown
output_file("dropdown.html")
menu = [("Item 1", "item_1"), ("Item 2", "item_2"), None, ("Item 3", "item_3")]
dropdown = Dropdown(label="Dropdown button", button_type="warning", menu=menu)
def function_to_call(attr, old, new):
print dropdown.value
dropdown.on_change('value', function_to_call)
dropdown.on_click(function_to_call)
show(widgetbox(dropdown))
</code></pre>
| 0 | 2016-08-23T11:36:24Z | 39,100,521 | <p>If you set on_change e.g. as follows:</p>
<pre><code>dropdown.on_change('value', function_to_call)
</code></pre>
<p>one can access the value of the selected item in <code>function_to_call</code> as follows:</p>
<pre><code>def function_to_call(attr, old, new):
print dropdown.value
</code></pre>
<p>For this to work dropdown has to be defined before function_to_call.</p>
<p>The documentation on how to access values set in widgets with on_click and on_change (bokeh version 12.1) can be found here at the top of the page:</p>
<p><a href="http://bokeh.pydata.org/en/latest/docs/user_guide/interaction/widgets.html" rel="nofollow">http://bokeh.pydata.org/en/latest/docs/user_guide/interaction/widgets.html</a></p>
<p><strong>EDIT</strong></p>
<p>To get interactive feedback you have to run bokeh in server mode, so that the python code can be evaluated when you interact with a widget. I changed your example slightly to allow to be run with the </p>
<pre><code>bokeh serve --show file_name.py
</code></pre>
<p>command. The code below then prints out the selected item in the terminal.</p>
<pre><code>from bokeh.io import output_file, show
from bokeh.layouts import widgetbox
from bokeh.models.widgets import Dropdown
from bokeh.plotting import curdoc
menu = [("Quaterly", "time_windows"), ("Half Yearly", "time_windows"), None, ("Yearly", "time_windows")]
dropdown = Dropdown(label="Time Period", button_type="warning", menu=menu)
def function_to_call(attr, old, new):
print dropdown.value
dropdown.on_change('value', function_to_call)
curdoc().add_root(dropdown)
</code></pre>
<p>See here for more information: </p>
<p><a href="http://bokeh.pydata.org/en/latest/docs/user_guide/server.html" rel="nofollow">http://bokeh.pydata.org/en/latest/docs/user_guide/server.html</a></p>
| 2 | 2016-08-23T11:56:44Z | [
"python",
"plot",
"widget",
"data-visualization",
"bokeh"
] |
How to improve python import speed? | 39,100,391 | <p>This question has been asked many times on SO (for instance <a href="http://stackoverflow.com/q/16373510/2612235">here</a>), but there is no real answer yet.</p>
<p>I am writing a short command line tool that renders templates. It is frigged using a Makefile: </p>
<pre><code>i = $(wildcard *.in)
o = $(patsubst %.in, %.out, $(t))
all: $(o)
%.out: %.in
./script.py -o $@ $<
</code></pre>
<p>In this dummy example, the Makefile parses every <code>.in</code> file to generate an <code>.out</code> file. It is very convenient for me to use <code>make</code> because I have a lot of other actions to trig before and after this script. Moreover I would like to remain as <a href="https://en.wikipedia.org/wiki/KISS_principle" rel="nofollow">KISS</a> as possible.</p>
<blockquote>
<p>Thus, I want to keep my tool simple, stupid and process each file separately using the syntax <code>script -o out in</code></p>
</blockquote>
<p>My script uses the following: </p>
<pre><code>#!/usr/bin/env python
from jinja2 import Template, nodes
from jinja2.ext import Extension
import hiyapyco
import argparse
import re
...
</code></pre>
<p>The problem is that each execution costs me about 1.2s ( ~60ms for the processing and ~1140ms for the import directives):</p>
<pre><code>$ time ./script.py -o foo.out foo.in
real 0m1.625s
user 0m0.452s
sys 0m1.185s
</code></pre>
<p>The overall execution of my Makefile for 100 files is ridiculous: ~100 files x 1.2s = 120s.</p>
<p>This is not a solution, but this should be the solution. </p>
<p>What alternative can I use?</p>
<p><strong>EDIT</strong></p>
<p>I love Python because its syntax is readable and size of its community. In this particular case (command line tools), I have to admit Perl is still a decent alternative. The same script written in Perl (which is also an interpreted language) is about 12 times faster (using <code>Text::Xslate</code>). </p>
<p>I don't want to promote Perl in anyway I am just trying to solve my biggest issue with Python: it is not yet a suitable language for simple command line tools because of the poor import time. </p>
| 0 | 2016-08-23T11:50:33Z | 39,100,537 | <p>You could use <a href="https://docs.python.org/2/library/glob.html" rel="nofollow"><code>glob</code></a> to perform that actions with the files you need.</p>
<pre><code>import glob
in_files=glob.glob('*.in')
out_files=glob.glob('*.out')
</code></pre>
<p>Thus, you process all the files in the same script, instead of calling the script every time with every pair of files. At least that way you don't have to start python every time.</p>
| 0 | 2016-08-23T11:58:00Z | [
"python",
"performance",
"python-import"
] |
How to improve python import speed? | 39,100,391 | <p>This question has been asked many times on SO (for instance <a href="http://stackoverflow.com/q/16373510/2612235">here</a>), but there is no real answer yet.</p>
<p>I am writing a short command line tool that renders templates. It is frigged using a Makefile: </p>
<pre><code>i = $(wildcard *.in)
o = $(patsubst %.in, %.out, $(t))
all: $(o)
%.out: %.in
./script.py -o $@ $<
</code></pre>
<p>In this dummy example, the Makefile parses every <code>.in</code> file to generate an <code>.out</code> file. It is very convenient for me to use <code>make</code> because I have a lot of other actions to trig before and after this script. Moreover I would like to remain as <a href="https://en.wikipedia.org/wiki/KISS_principle" rel="nofollow">KISS</a> as possible.</p>
<blockquote>
<p>Thus, I want to keep my tool simple, stupid and process each file separately using the syntax <code>script -o out in</code></p>
</blockquote>
<p>My script uses the following: </p>
<pre><code>#!/usr/bin/env python
from jinja2 import Template, nodes
from jinja2.ext import Extension
import hiyapyco
import argparse
import re
...
</code></pre>
<p>The problem is that each execution costs me about 1.2s ( ~60ms for the processing and ~1140ms for the import directives):</p>
<pre><code>$ time ./script.py -o foo.out foo.in
real 0m1.625s
user 0m0.452s
sys 0m1.185s
</code></pre>
<p>The overall execution of my Makefile for 100 files is ridiculous: ~100 files x 1.2s = 120s.</p>
<p>This is not a solution, but this should be the solution. </p>
<p>What alternative can I use?</p>
<p><strong>EDIT</strong></p>
<p>I love Python because its syntax is readable and size of its community. In this particular case (command line tools), I have to admit Perl is still a decent alternative. The same script written in Perl (which is also an interpreted language) is about 12 times faster (using <code>Text::Xslate</code>). </p>
<p>I don't want to promote Perl in anyway I am just trying to solve my biggest issue with Python: it is not yet a suitable language for simple command line tools because of the poor import time. </p>
| 0 | 2016-08-23T11:50:33Z | 39,100,627 | <p>It seems quite clear where the problem is, right now you got:</p>
<p><code>cost(file) = 1.2s = 60ms + 1040ms</code>, which means:</p>
<p><code>cost(N*files) = N*1.2s</code></p>
<p>now, why don't you change it to become:</p>
<p><code>cost1(files) = 1040ms + N*60ms</code></p>
<p>that way, theorically processing 100 files would be 7,04s instead 120s</p>
<p><strong>EDIT:</strong></p>
<p>Because I'm receiving downvotes to this question, I'll post a little example, let's assume you got this python file:</p>
<pre><code># foo.py
import numpy
import cv2
print sys.argv[0]
</code></pre>
<p>The execution time is 1.3s on my box, now, if i do:</p>
<pre><code>for /l %x in (1, 1, 100) do python foo.py
</code></pre>
<p>I'll get 100*1.3s execution time, my proposal was turn foo.py into this:</p>
<pre><code>import numpy
import cv2
def whatever_rendering_you_want_to_do(file):
pass
for file in sys.argv:
whatever_rendering_you_want_to_do(file)
</code></pre>
<p>That way you're importing only <strong>once</strong> instead of 100 times</p>
| 0 | 2016-08-23T12:02:12Z | [
"python",
"performance",
"python-import"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.