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 listlengths 1 5 |
|---|---|---|---|---|---|---|---|---|---|
How is int() implemented in Python? | 38,542,263 | <p>How does it convert binary numbers to base 10 as quickly as it does? bin() returns a string, how does it convert them to integers to do the math on them?</p>
| 0 | 2016-07-23T13:22:10Z | 38,542,789 | <p>you can use int plus extra parameter to convert it </p>
<pre><code>int('1000', 2)
output:
8
</code></pre>
<p>int class:</p>
<pre><code>class int(x, base=10)
</code></pre>
<blockquote>
<p>Return an integer object constructed from a number or string x, or
return 0 if no arguments are given. If x is a number, it can be a
plain integer, a long integer, or a floating point number. If x is
floating point, the conversion truncates towards zero. If the argument
is outside the integer range, the function returns a long object
instead.</p>
<p>If x is not a number or if base is given, then x must be a string or
Unicode object representing an integer literal in radix base.
Optionally, the literal can be preceded by + or - (with no space in
between) and surrounded by whitespace. A base-n literal consists of
the digits 0 to n-1, with a to z (or A to Z) having values 10 to 35.
The default base is 10. The allowed values are 0 and 2-36. Base-2, -8,
and -16 literals can be optionally prefixed with 0b/0B, 0o/0O/0, or
0x/0X, as with integer literals in code. Base 0 means to interpret the
string exactly as an integer literal, so that the actual base is 2, 8,
10, or 16.</p>
</blockquote>
| 0 | 2016-07-23T14:21:02Z | [
"python",
"binary"
] |
Python3 webserver communicate between threads for IRC bot | 38,542,298 | <p>I've read a lot of documentation about Threading, Queuing, Pooling etc. but still couldn't figure out how to solve my problem.
Here's the situation :
I built a python3 Django application that's served by cherrypy. The application is basically another IRC client. When I use the GUI to run my code the first time, an IRC bot is launched through a deamon Thread and listens to events. My problem is the following : how do I send data to that thread (and my bot), for instance to tell him to join a second channel ? When I run my code a second time, obviously a new instance of my bot is created, along with a new server connection. I need a way to communicate with my bot through GUI interaction. Right now the only way I had to make my bot react the specific things is by reading the database. Some other GUI action would change that database. Which is a bad system.</p>
<p>Here is the relevant code that starts my bot.</p>
<pre><code>def DCC_deamonthread(c, server, nickname, upload):
try:
c.connect(server, 6667, nickname)
c.start()
except irc.client.ServerConnectionError as x:
log("error" + str(x)).write()
upload.status, upload.active = "Error during connection", False
upload.save()
def upload_file(filename, rec_nick, pw):
global upload
Upload_Ongoing.objects.all().delete()
upload = Upload_Ongoing(filename=filename,status="Connecting to server...", active=True)
upload.save()
irc.client.ServerConnection.buffer_class.encoding = 'latin-1'
c = DCCSend(filename, rec_nick, pw)
server = "irc.rizon.net"
nickname = ''.join(random.choice(string.ascii_lowercase) for i in range(10))
t = threading.Thread(target=DCC_deamonthread, args=(c, server, nickname, upload))
t.daemon=True
t.start()
</code></pre>
| 0 | 2016-07-23T13:26:22Z | 38,542,615 | <p>The problem is, as you noticed, that you spawn a new thread/bot each time there is an upload. A possible solution would be to rewrite your code to do something like this:</p>
<pre><code>event_queue = multiprocessing.Queue() # Events that will be sent to the IRC bot thread
def irc_bot_thread():
bot = connect_to_irc()
for event in event_queue:
bot.handle_event(event)
threading.Thread(target=irc_bot_thread).start()
def upload_file(filename, rec_nick, pw):
# Django stuff
event_queue.push(<necessary data for use by the bot>)
</code></pre>
| 1 | 2016-07-23T14:01:27Z | [
"python",
"django",
"multithreading",
"irc"
] |
Could pandas use column as index? | 38,542,419 | <p>I have a spreadsheet like this:</p>
<pre><code>Locality 2005 2006 2007 2008 2009
ABBOTSFORD 427000 448000 602500 600000 638500
ABERFELDIE 534000 600000 735000 710000 775000
AIREYS INLET459000 440000 430000 517500 512500
</code></pre>
<p>I don't want to manually swap the column with the row. Could it be possible to use pandas reading data to a list as this:</p>
<pre><code>data['ABBOTSFORD']=[427000,448000,602500,600000,638500]
data['ABERFELDIE']=[534000,600000,735000,710000,775000]
data['AIREYS INLET']=[459000,440000,430000,517500,512500]
</code></pre>
| 0 | 2016-07-23T13:39:10Z | 38,542,447 | <p>Yes, with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.set_index.html" rel="nofollow">set_index</a> you can make Locality your row index. <em>If you want to swap all row and column labels/indices, transpose is the way to go as <a href="http://stackoverflow.com/a/38542453/6525140">Psidom</a> correctly denoted in his answer</em>.</p>
<pre><code>data.set_index('Locality', inplace=True)
</code></pre>
<p>If <code>inplace=True</code> is not provided, <code>set_index</code> returns the modified dataframe as a result.</p>
<p>Example:</p>
<pre><code>> import pandas as pd
> df = pd.DataFrame([['ABBOTSFORD', 427000, 448000], ['ABERFELDIE', 534000, 600000]], columns=['Locality', 2005, 2006])
> df
Locality 2005 2006
0 ABBOTSFORD 427000 448000
1 ABERFELDIE 534000 600000
> df.set_index('Locality', inplace=True)
> df
2005 2006
Locality
ABBOTSFORD 427000 448000
ABERFELDIE 534000 600000
> df.loc['ABBOTSFORD']
2005 427000
2006 448000
Name: ABBOTSFORD, dtype: int64
> df.loc['ABBOTSFORD'][2005]
427000
</code></pre>
| 1 | 2016-07-23T13:42:12Z | [
"python",
"excel",
"pandas"
] |
Palindrome recursive function | 38,542,526 | <p>I tried to write a <strong>recursive</strong> function that says if a string is a palindrome, but all I get is an infinite loop and I don't know what the problem is</p>
<pre><code>def isPalindrome(S):
listush=list(S) #listush=['a', 'b', 'n', 'n', 'b', 'a']
length=len(listush) #length=6
if length==0 or length==1:
return S, "is a palindrome!"
elif listush[0]!=listush[-1]:
return S, "is not a palindrome!"
else:
del listush[0]
del listush[-1]
return isPalindrome(S)
print isPalindrome("abnnba")
</code></pre>
| -1 | 2016-07-23T13:52:06Z | 38,542,595 | <p>First of all, indent your code properly.</p>
<p>Secondly, you are calling the function again with the same argument. Call with 'listush' list from which you are deleting or delete from 'S' and recurse with S argument.</p>
| 1 | 2016-07-23T14:00:04Z | [
"python",
"list",
"function",
"recursion",
"palindrome"
] |
Palindrome recursive function | 38,542,526 | <p>I tried to write a <strong>recursive</strong> function that says if a string is a palindrome, but all I get is an infinite loop and I don't know what the problem is</p>
<pre><code>def isPalindrome(S):
listush=list(S) #listush=['a', 'b', 'n', 'n', 'b', 'a']
length=len(listush) #length=6
if length==0 or length==1:
return S, "is a palindrome!"
elif listush[0]!=listush[-1]:
return S, "is not a palindrome!"
else:
del listush[0]
del listush[-1]
return isPalindrome(S)
print isPalindrome("abnnba")
</code></pre>
| -1 | 2016-07-23T13:52:06Z | 38,542,598 | <p>If you do an <code>print(listush)</code> you can see, that your list never changes.
The following modification of your code works:</p>
<pre><code>def isPalindrome(testStr, orig=None):
if orig is None:
orig = testStr
length = len(testStr) #length=6
print(testStr)
if length == 0 or length == 1:
return orig, "is a palindrome!"
elif testStr[0] != testStr[-1]:
return orig, "is not a palindrome!"
else:
return isPalindrome(testStr[1:-1], orig)
print isPalindrome("abnnba")
</code></pre>
| 0 | 2016-07-23T14:00:43Z | [
"python",
"list",
"function",
"recursion",
"palindrome"
] |
Palindrome recursive function | 38,542,526 | <p>I tried to write a <strong>recursive</strong> function that says if a string is a palindrome, but all I get is an infinite loop and I don't know what the problem is</p>
<pre><code>def isPalindrome(S):
listush=list(S) #listush=['a', 'b', 'n', 'n', 'b', 'a']
length=len(listush) #length=6
if length==0 or length==1:
return S, "is a palindrome!"
elif listush[0]!=listush[-1]:
return S, "is not a palindrome!"
else:
del listush[0]
del listush[-1]
return isPalindrome(S)
print isPalindrome("abnnba")
</code></pre>
| -1 | 2016-07-23T13:52:06Z | 38,542,623 | <p>There's no need for creating a list. A python string is already an indexable sequence. </p>
<p>Even better, we can employ slicing and let the function return <code>True</code> and <code>False</code> instead of a tuple with text, With all of this, <code>isPalindrome()</code> becomes a one-liner:</p>
<pre><code>def isPalindrome(S):
return len(S) < 2 or (S[0] == S[-1] and isPalindrome(S[1:-2]))
print isPalindrome('A')
>>> True
print isPalindrome('AA')
>>> True
print isPalindrome('BAAB')
>>> True
print isPalindrome('ABAB')
>>> False
</code></pre>
| 1 | 2016-07-23T14:02:39Z | [
"python",
"list",
"function",
"recursion",
"palindrome"
] |
Palindrome recursive function | 38,542,526 | <p>I tried to write a <strong>recursive</strong> function that says if a string is a palindrome, but all I get is an infinite loop and I don't know what the problem is</p>
<pre><code>def isPalindrome(S):
listush=list(S) #listush=['a', 'b', 'n', 'n', 'b', 'a']
length=len(listush) #length=6
if length==0 or length==1:
return S, "is a palindrome!"
elif listush[0]!=listush[-1]:
return S, "is not a palindrome!"
else:
del listush[0]
del listush[-1]
return isPalindrome(S)
print isPalindrome("abnnba")
</code></pre>
| -1 | 2016-07-23T13:52:06Z | 38,542,637 | <p>There are some things I would like to say about your code</p>
<ul>
<li>You can send a slice of the list, saving you the trouble of deleting
elements.</li>
<li>You don't need to convert it to a list, all the operations you need
in finding palindrome are supported by strings.</li>
<li>You are returning S in the recursive function, which would be an
empty list(or string) because it is diminishing each recursion. In
recursive cases, I suggest you to just return <code>True</code> or <code>False</code></li>
</ul>
<p>Here is an example.</p>
<pre><code>def isPalindrome(S):
length=len(S)
if length < 2:
return True
elif S[0] != S[-1]:
return False
else:
return isPalindrome(S[1:length - 1])
</code></pre>
<p>Simple as that.</p>
| 0 | 2016-07-23T14:03:43Z | [
"python",
"list",
"function",
"recursion",
"palindrome"
] |
Functionality of Python `in` vs. `__contains__` | 38,542,543 | <p>I implemented the <code>__contains__</code> method on a class for the first time the other day, and the behavior wasn't what I expected. I suspect there's some subtlety to the <a href="https://docs.python.org/2/library/operator.html" rel="nofollow"><code>in</code></a> operator that I don't understand and I was hoping someone could enlighten me.</p>
<p>It appears to me that the <code>in</code> operator doesn't simply wrap an object's <code>__contains__</code> method, but it also attempts to coerce the output of <code>__contains__</code> to boolean. For example, consider the class</p>
<pre><code>class Dummy(object):
def __contains__(self, val):
# Don't perform comparison, just return a list as
# an example.
return [False, False]
</code></pre>
<p>The <code>in</code> operator and a direct call to the <code>__contains__</code> method return very different output:</p>
<pre><code>>>> dum = Dummy()
>>> 7 in dum
True
>>> dum.__contains__(7)
[False, False]
</code></pre>
<p>Again, it looks like <code>in</code> is calling <code>__contains__</code> but then coercing the result to <code>bool</code>. I can't find this behavior documented anywhere except for the fact that the <code>__contains__</code> <a href="https://docs.python.org/2/reference/datamodel.html#object.__contains__" rel="nofollow">documentation</a> says <code>__contains__</code> should only ever return <code>True</code> or <code>False</code>.</p>
<p>I'm happy following the convention, but can someone tell me the precise relationship between <code>in</code> and <code>__contains__</code>?</p>
<h1>Epilogue</h1>
<p>I decided to choose @eli-korvigo answer, but everyone should look at @ashwini-chaudhary <a href="http://stackoverflow.com/questions/38542543/functionality-of-python-in-vs-contains/38542777?noredirect=1#comment64477339_38542543">comment</a> about the <a href="https://bugs.python.org/issue16011" rel="nofollow">bug</a>, below.</p>
| 7 | 2016-07-23T13:54:30Z | 38,542,655 | <p>In <a href="https://docs.python.org/3/reference/datamodel.html#object.__contains__" rel="nofollow">Python reference for <code>__contains__</code></a> it's written that <code>__contains__</code> should return <code>True</code> or <code>False</code>.</p>
<p>If the return value is not boolean it's converted to boolean. Here is proof:</p>
<pre><code>class MyValue:
def __bool__(self):
print("__bool__ function runned")
return True
class Dummy:
def __contains__(self, val):
return MyValue()
</code></pre>
<p>Now write in shell:</p>
<pre><code>>>> dum = Dummy()
>>> 7 in dum
__bool__ function runned
True
</code></pre>
<p>And <code>bool()</code> of nonempty list returns <code>True</code>.</p>
<p><strong>Edit:</strong></p>
<p>It's only documentation for <code>__contains__</code>, if you really want to see precise relation you should consider looking into source code although I'm not sure where exactly, but it's already answered. In <a href="https://docs.python.org/3/reference/datamodel.html#object.__lt__" rel="nofollow">documentation for comparison</a> it's written:</p>
<blockquote>
<p>However, these methods can return any value, so if the comparison operator is used in a Boolean context (e.g., in the condition of an <code>if</code> statement), Python will call <a href="https://docs.python.org/3/library/functions.html#bool" rel="nofollow">bool()</a> on the value to determine if the result is true or false.</p>
</blockquote>
<p>So you can guess that it's similar with <code>__contains__</code>.</p>
| 3 | 2016-07-23T14:05:52Z | [
"python",
"contains"
] |
Functionality of Python `in` vs. `__contains__` | 38,542,543 | <p>I implemented the <code>__contains__</code> method on a class for the first time the other day, and the behavior wasn't what I expected. I suspect there's some subtlety to the <a href="https://docs.python.org/2/library/operator.html" rel="nofollow"><code>in</code></a> operator that I don't understand and I was hoping someone could enlighten me.</p>
<p>It appears to me that the <code>in</code> operator doesn't simply wrap an object's <code>__contains__</code> method, but it also attempts to coerce the output of <code>__contains__</code> to boolean. For example, consider the class</p>
<pre><code>class Dummy(object):
def __contains__(self, val):
# Don't perform comparison, just return a list as
# an example.
return [False, False]
</code></pre>
<p>The <code>in</code> operator and a direct call to the <code>__contains__</code> method return very different output:</p>
<pre><code>>>> dum = Dummy()
>>> 7 in dum
True
>>> dum.__contains__(7)
[False, False]
</code></pre>
<p>Again, it looks like <code>in</code> is calling <code>__contains__</code> but then coercing the result to <code>bool</code>. I can't find this behavior documented anywhere except for the fact that the <code>__contains__</code> <a href="https://docs.python.org/2/reference/datamodel.html#object.__contains__" rel="nofollow">documentation</a> says <code>__contains__</code> should only ever return <code>True</code> or <code>False</code>.</p>
<p>I'm happy following the convention, but can someone tell me the precise relationship between <code>in</code> and <code>__contains__</code>?</p>
<h1>Epilogue</h1>
<p>I decided to choose @eli-korvigo answer, but everyone should look at @ashwini-chaudhary <a href="http://stackoverflow.com/questions/38542543/functionality-of-python-in-vs-contains/38542777?noredirect=1#comment64477339_38542543">comment</a> about the <a href="https://bugs.python.org/issue16011" rel="nofollow">bug</a>, below.</p>
| 7 | 2016-07-23T13:54:30Z | 38,542,777 | <p>Use the source, Luke!</p>
<p>Let's trace down the <code>in</code> operator implementation</p>
<pre><code>>>> import dis
>>> class test(object):
... def __contains__(self, other):
... return True
>>> def in_():
... return 1 in test()
>>> dis.dis(in_)
2 0 LOAD_CONST 1 (1)
3 LOAD_GLOBAL 0 (test)
6 CALL_FUNCTION 0 (0 positional, 0 keyword pair)
9 COMPARE_OP 6 (in)
12 RETURN_VALUE
</code></pre>
<p>As you can see, the <code>in</code> operator becomes the <code>COMPARE_OP</code> virtual machine instruction. You can find that in <a href="http://hg.python.org/cpython/file/tip/Python/ceval.c">ceval.c</a></p>
<pre><code>TARGET(COMPARE_OP)
w = POP();
v = TOP();
x = cmp_outcome(oparg, v, w);
Py_DECREF(v);
Py_DECREF(w);
SET_TOP(x);
if (x == NULL) break;
PREDICT(POP_JUMP_IF_FALSE);
PREDICT(POP_JUMP_IF_TRUE);
DISPATCH();
</code></pre>
<p>Take a look at one of the switches in <code>cmp_outcome()</code></p>
<pre><code>case PyCmp_IN:
res = PySequence_Contains(w, v);
if (res < 0)
return NULL;
break;
</code></pre>
<p>Here we have the <code>PySequence_Contains</code> call</p>
<pre><code>int
PySequence_Contains(PyObject *seq, PyObject *ob)
{
Py_ssize_t result;
PySequenceMethods *sqm = seq->ob_type->tp_as_sequence;
if (sqm != NULL && sqm->sq_contains != NULL)
return (*sqm->sq_contains)(seq, ob);
result = _PySequence_IterSearch(seq, ob, PY_ITERSEARCH_CONTAINS);
return Py_SAFE_DOWNCAST(result, Py_ssize_t, int);
}
</code></pre>
<p>That always returns an <code>int</code> (a boolean). </p>
<p>P.S.</p>
<p>Thanks to Martijn Pieters for providing the <a href="http://stackoverflow.com/a/12244378/3846213">way</a> to find the implementation of the <code>in</code> operator.</p>
| 7 | 2016-07-23T14:19:30Z | [
"python",
"contains"
] |
Numpy mean of nonzero values | 38,542,548 | <p>I have a matrix of size N*M and I want to find the mean value for each row. The values are from 1 to 5 and entries that do not have any value are set to 0. However, when I want to find the mean using the following method, it gives me the wrong mean as it also counts the entries that have value of 0.</p>
<pre><code>matrix_row_mean= matrix.mean(axis=1)
</code></pre>
<p>How can I get the mean of only nonzero values?</p>
| 1 | 2016-07-23T13:54:49Z | 38,542,569 | <p>Get the count of non-zeros in each row and use that for averaging the summation along each row. Thus, the implementation would look something like this -</p>
<pre><code>np.true_divide(matrix.sum(1),(matrix!=0).sum(1))
</code></pre>
<p>If you are on an older version of NumPy, you can use float conversion of the count to replace <code>np.true_divide</code>, like so -</p>
<pre><code>matrix.sum(1)/(matrix!=0).sum(1).astype(float)
</code></pre>
<p>Sample run -</p>
<pre><code>In [160]: matrix
Out[160]:
array([[0, 0, 1, 0, 2],
[1, 0, 0, 2, 0],
[0, 1, 1, 0, 0],
[0, 2, 2, 2, 2]])
In [161]: np.true_divide(matrix.sum(1),(matrix!=0).sum(1))
Out[161]: array([ 1.5, 1.5, 1. , 2. ])
</code></pre>
<hr>
<p>Another way to solve the problem would be to replace zeros with <code>NaNs</code> and then use <code>np.nanmean</code>, which would ignore those <code>NaNs</code> and in effect those original <code>zeros</code>, like so -</p>
<pre><code>np.nanmean(np.where(matrix!=0,matrix,np.nan),1)
</code></pre>
<p>From performance point of view, I would recommend the first approach.</p>
| 2 | 2016-07-23T13:57:10Z | [
"python",
"numpy"
] |
print(sys.argv) doesn't take arguments | 38,542,581 | <p>that's probably a pretty dumb question, but I'm a beginner programmer and i can't get this.</p>
<p>basically, i think im using sys.argv wrong because it just doesn't take arguments as much as i can tell. the first code i've written with sys.argv looks like this:</p>
<pre><code>import sys
import pyperclip
dict = {'email': 'foo',
'blog': 'monty',
'briefcase': 666,
'stack overflow': 'pulp'}
if len(sys.argv) < 2:
print('no arguments')
sys.exit()
account = sys.argv[1]
if account in dict:
pyperclip.copy(dict[account])
else:
print('no value found under' + account)
</code></pre>
<p>saved it under the name pw.py and tried to use it via command prompt by typing in </p>
<pre><code>pw.py email
</code></pre>
<p>but no matters what i type it returns 'no arguments'. the second program i tried going simple and just giving it a simple print function:</p>
<pre><code>import sys
print(sys.argv)
</code></pre>
<p>this one just returns the path to the program. what am i doing wrong?</p>
<p>i get that this a noob question, and that this is a horrible way to save passwords, this is for a project I'm doing trying to learn python by myself.</p>
| 0 | 2016-07-23T13:58:44Z | 38,542,630 | <p>Use ' python pw.py email ' for the first script
and for the second 'python pw.py any_args'</p>
| 1 | 2016-07-23T14:03:18Z | [
"python",
"windows",
"sys"
] |
Getting openCV error: Assertion Failed | 38,542,599 | <p>I'm using opencv 3.1 in RaspberryPi 3. I,m trying to run the following Hough Circle detection algorithm </p>
<pre><code>#! /usr/bin/python
import numpy as np
import cv2
from cv2 import cv
VInstance = cv2.VideoCapture(0)
key = True
"""
params = dict(dp,
minDist,
circles,
param1,
param2,
minRadius,
maxRadius)
"""
def draw_circles(circles, output):
if circles is not None:
for i in circles[0,:]:
#draw the outer circle
cv2.circle(output,(i[0],i[1]),i[2],(0,255,0),2)
#draw the centre of the circle
cv2.circle(output,(i[0],i[1]),2,(0,0,255),3)
print("The number of circles if %d" %(circles[0].shape[0]))
elif circles is None:
print ("The number of circles is 0")
if __name__ == '__main__':
while key:
ret,img = VInstance.read()
## Smooth image to reduce the input noise
imgGray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
imgSmooth = cv2.GaussianBlur(imgGray,(5,5),3)
## Compute Hough Circles
circles = cv2.HoughCircles(imgSmooth,cv2.cv.CV_HOUGH_GRADIENT,1,100,
param1=80,
param2=50,
minRadius=50,
maxRadius=100)
draw_circles(circles,img)
## Display the circles
cv2.imshow('detected circles',imgGray)
cv2.imshow("result",img)
k = cv2.waitKey(1)
if k == 27:
cv2.destroyAllWindows()
break
</code></pre>
<p>But I'm getting Assertion Failed error, details are below.</p>
<blockquote>
<p>OpenCV Error: Assertion failed (scn == 3 || scn == 4) in cvtColor,
file /home/pi/opencv-3.1.0/modules/imgproc/src/color.cpp, line 8000
Traceback (most recent call last): File "HoughCircles.py", line 70,
in
imgGray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) cv2.error: /home/pi/opencv-3.1.0/modules/imgproc/src/color.cpp:8000: error:
(-215) scn == 3 || scn == 4 in function cvtColor</p>
</blockquote>
<p>Can anyone please check and help!</p>
| 1 | 2016-07-23T14:00:44Z | 38,543,384 | <p>Error code "Assertion failed (scn == 3 || scn == 4) in cvtColor" means that the input (source) image in your <code>cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)</code> method does not have 3 or 4 channels, which are necessary for this type of conversion. Probably your input image is already grayscale format. Try just not to use that method and your problem should be solved. If it does throw other unsolvable errors or does not solve the problem, post your issues in comments. </p>
| 0 | 2016-07-23T15:27:11Z | [
"python",
"opencv",
"raspberry-pi",
"assertions"
] |
Getting openCV error: Assertion Failed | 38,542,599 | <p>I'm using opencv 3.1 in RaspberryPi 3. I,m trying to run the following Hough Circle detection algorithm </p>
<pre><code>#! /usr/bin/python
import numpy as np
import cv2
from cv2 import cv
VInstance = cv2.VideoCapture(0)
key = True
"""
params = dict(dp,
minDist,
circles,
param1,
param2,
minRadius,
maxRadius)
"""
def draw_circles(circles, output):
if circles is not None:
for i in circles[0,:]:
#draw the outer circle
cv2.circle(output,(i[0],i[1]),i[2],(0,255,0),2)
#draw the centre of the circle
cv2.circle(output,(i[0],i[1]),2,(0,0,255),3)
print("The number of circles if %d" %(circles[0].shape[0]))
elif circles is None:
print ("The number of circles is 0")
if __name__ == '__main__':
while key:
ret,img = VInstance.read()
## Smooth image to reduce the input noise
imgGray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
imgSmooth = cv2.GaussianBlur(imgGray,(5,5),3)
## Compute Hough Circles
circles = cv2.HoughCircles(imgSmooth,cv2.cv.CV_HOUGH_GRADIENT,1,100,
param1=80,
param2=50,
minRadius=50,
maxRadius=100)
draw_circles(circles,img)
## Display the circles
cv2.imshow('detected circles',imgGray)
cv2.imshow("result",img)
k = cv2.waitKey(1)
if k == 27:
cv2.destroyAllWindows()
break
</code></pre>
<p>But I'm getting Assertion Failed error, details are below.</p>
<blockquote>
<p>OpenCV Error: Assertion failed (scn == 3 || scn == 4) in cvtColor,
file /home/pi/opencv-3.1.0/modules/imgproc/src/color.cpp, line 8000
Traceback (most recent call last): File "HoughCircles.py", line 70,
in
imgGray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) cv2.error: /home/pi/opencv-3.1.0/modules/imgproc/src/color.cpp:8000: error:
(-215) scn == 3 || scn == 4 in function cvtColor</p>
</blockquote>
<p>Can anyone please check and help!</p>
| 1 | 2016-07-23T14:00:44Z | 39,885,029 | <p>This means the input image is invalid, which is why you need to check the <code>ret</code> value in your loop!</p>
<p>The error and question title doesn't have anything to do with your Hough circles, so I'll condense my answer to address the assertion failure (add back in your stuff later!):</p>
<pre><code>#!/usr/bin/python
import numpy as np
import cv2
VInstance = cv2.VideoCapture(0)
if __name__ == '__main__':
while True:
ret,img = VInstance.read()
# Confirm we have a valid image returned
if not ret:
break
imgGray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
cv2.imshow("result",img)
k = cv2.waitKey(1)
if k == 27:
break
cv2.destroyAllWindows()
</code></pre>
| 0 | 2016-10-05T23:07:11Z | [
"python",
"opencv",
"raspberry-pi",
"assertions"
] |
Compare pandas dataframes for common rows in two dataframes | 38,542,645 | <p>I have two data frames df-1 and df-2 like this,</p>
<pre><code>import pandas as pd
raw_data = {'company': ['comp1', 'comp1', 'comp1', 'comp1', 'comp2', 'comp2', 'comp2', 'comp2', 'comp3', 'comp3', 'comp3', 'comp3'],
'region': ['1st', '1st', '2nd', '2nd', '1st', '1st', '2nd', '2nd','1st', '1st', '2nd', '2nd'],
'name': ['John', 'Jake', 'Alice', 'Mathew', 'Mark', 'Jacon', 'Ryan', 'Sone', 'Steve', 'Rooke', 'Rani', 'Alice'],
'preTestScore': [4, 24, 31, 2, 3, 4, 24, 31, 2, 3, 2, 3],
'postTestScore': [25, 94, 57, 62, 70, 25, 94, 57, 62, 70, 62, 70]}
df1 = pd.DataFrame(raw_data, columns = ['company', 'region', 'name', 'preTestScore'])
print df1
raw_data = {'company': [ 'comp1', 'comp1', 'comp2', 'comp2', 'comp2', 'comp2', 'comp3', 'comp3', 'comp3'],
'region': [ '2nd', '2nd', '1st', '1st', '2nd', '2nd','1st', '1st', '2nd'],
'name': [ 'Alice', 'Mathew', 'Mark', 'Jacon', 'Ryan', 'Sone', 'Steve', 'Rooke', 'Rani', ],
'status': [ 'great', 'average', 'average', 'average', 'good', 'great', 'average', 'average', 'average']}
df2 = pd.DataFrame(raw_data, columns = ['company', 'region', 'name', 'status'])
print df2
</code></pre>
<p>How to find the rows of company, region and name in df-1 which is same as df-2. In other words, how to find the inner join with combination of all three columns.</p>
| 3 | 2016-07-23T14:04:46Z | 38,542,786 | <p>It depends what you mean by </p>
<blockquote>
<p>rows in df-1 which is same as df-2.</p>
</blockquote>
<p>since the columns are not identical. </p>
<p>If you mean rows that have the same value for the intersection of columns, you can perform an <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.merge.html" rel="nofollow">inner join user <code>merge</code></a>:</p>
<pre><code>In [13]: pd.merge(df1, df2, how='inner')
Out[13]:
company region name preTestScore status
0 comp1 2nd Alice 31 great
1 comp1 2nd Mathew 2 average
2 comp2 1st Mark 3 average
3 comp2 1st Jacon 4 average
4 comp2 2nd Ryan 24 good
5 comp2 2nd Sone 31 great
6 comp3 1st Steve 2 average
7 comp3 1st Rooke 3 average
8 comp3 2nd Rani 2 average
</code></pre>
<p><strong>Edit</strong></p>
<p>If you'd like greater control for the join columns, you can use the <code>on</code>, or <code>left_on</code> and <code>right_on</code> parameters of the <code>merge</code> function. If you don't, pandas will assume you mean the intersection of columns of the two dataframes.</p>
| 2 | 2016-07-23T14:20:30Z | [
"python",
"pandas"
] |
Compare pandas dataframes for common rows in two dataframes | 38,542,645 | <p>I have two data frames df-1 and df-2 like this,</p>
<pre><code>import pandas as pd
raw_data = {'company': ['comp1', 'comp1', 'comp1', 'comp1', 'comp2', 'comp2', 'comp2', 'comp2', 'comp3', 'comp3', 'comp3', 'comp3'],
'region': ['1st', '1st', '2nd', '2nd', '1st', '1st', '2nd', '2nd','1st', '1st', '2nd', '2nd'],
'name': ['John', 'Jake', 'Alice', 'Mathew', 'Mark', 'Jacon', 'Ryan', 'Sone', 'Steve', 'Rooke', 'Rani', 'Alice'],
'preTestScore': [4, 24, 31, 2, 3, 4, 24, 31, 2, 3, 2, 3],
'postTestScore': [25, 94, 57, 62, 70, 25, 94, 57, 62, 70, 62, 70]}
df1 = pd.DataFrame(raw_data, columns = ['company', 'region', 'name', 'preTestScore'])
print df1
raw_data = {'company': [ 'comp1', 'comp1', 'comp2', 'comp2', 'comp2', 'comp2', 'comp3', 'comp3', 'comp3'],
'region': [ '2nd', '2nd', '1st', '1st', '2nd', '2nd','1st', '1st', '2nd'],
'name': [ 'Alice', 'Mathew', 'Mark', 'Jacon', 'Ryan', 'Sone', 'Steve', 'Rooke', 'Rani', ],
'status': [ 'great', 'average', 'average', 'average', 'good', 'great', 'average', 'average', 'average']}
df2 = pd.DataFrame(raw_data, columns = ['company', 'region', 'name', 'status'])
print df2
</code></pre>
<p>How to find the rows of company, region and name in df-1 which is same as df-2. In other words, how to find the inner join with combination of all three columns.</p>
| 3 | 2016-07-23T14:04:46Z | 38,542,932 | <p>result = pd.merge(df1,df2, on=['company','region','region'],how="left")</p>
| 0 | 2016-07-23T14:37:03Z | [
"python",
"pandas"
] |
GAE Python Blobstore doesn't save filename containing unicode literals in Firefox only | 38,542,758 | <p>I am developing an app which prompts the user to upload a file which is then available for download.
Here is the download handler:</p>
<pre><code>class ViewPrezentacje(blobstore_handlers.BlobstoreDownloadHandler, BaseHandler):
def get(self,blob_key):
blob_key = str(urllib.unquote(blob_key))
blob_info=blobstore.BlobInfo.get(blob_key)
self.send_blob(blob_info, save_as=urllib.quote(blob_info.filename.encode('utf-8')))
</code></pre>
<p>The file is downloaded with the correct file name (i.e. unicode literals are properly displayed) while using Chrome or IE, but in Firefox it is saved as a string of the form "%83%86%E3..."
Is there any way to make it work properly in Firefox?</p>
| 0 | 2016-07-23T14:17:20Z | 38,552,379 | <p>Sending filenames with non-ASCII characters in attachments is fraught with difficulty, as the original specification was broken and browser behaviours have varied.</p>
<p>You shouldn't be %-encoding (<code>urllib.quote</code>) the filename; Firefox is right to offer it as literal % sequences as a result. IE's behaviour of %-decoding sequences in the filename is incorrect, even though Chrome eventually went on to copy it.</p>
<p>Ultimately the right way to send non-ASCII filenames is to use the mechanism specified in <a href="https://tools.ietf.org/html/rfc6266" rel="nofollow">RFC6266</a>, which ends up with a header that looks like this:</p>
<pre><code>Content-Disposition: attachment; filename*=UTF-8''foo-%c3%a4-%e2%82%ac.html
</code></pre>
<p>However:</p>
<ul>
<li>older browsers such as IE8 don't support it so if you care you should pass <em>something</em> as an ASCII-only <code>filename=</code> as well;</li>
<li>BlobstoreDownloadHandler doesn't know about this mechanism.</li>
</ul>
<p>The bit of BlobstoreDownloadHandler that needs fixing is this inner function in <code>send_blob</code>:</p>
<pre><code>def send_attachment(filename):
if isinstance(filename, unicode):
filename = filename.encode('utf-8')
self.response.headers['Content-Disposition'] = (
_CONTENT_DISPOSITION_FORMAT % filename)
</code></pre>
<p>which really wants to do:</p>
<pre><code>rfc6266_filename = "UTF-8''" + urllib.quote(filename.encode('utf-8'))
fallback_filename = filename.encode('us-ascii', 'ignore')
self.response.headers['Content-Disposition'] = 'attachment; filename="%s"; filename*=%s' % (rfc6266_filename, fallback_filename)
</code></pre>
<p>but unfortunately being an inner function makes it annoying to try to fix in a subclass. You could:</p>
<ul>
<li>override the whole of <code>send_blob</code> to replace the <code>send_attachment</code> inner function</li>
<li>or maybe you can write <code>self.response.headers['Content-Disposition']</code> like this after calling <code>send_blob</code>? I'm not sure how GAE handles this</li>
<li>or, probably most practical of all, give up on having Unicode filenames for now until GAE fixes it</li>
</ul>
| 1 | 2016-07-24T13:07:48Z | [
"python",
"python-2.7",
"google-app-engine",
"firefox",
"unicode"
] |
Theano/Lasagne basic neural network with regression won't overfit dataset of size one | 38,542,760 | <p>I'm using a basic neural network in Theano/Lasagne to try to identify facial keypoints in images, and am currently trying to get it to learn a single image (I've just taken the first image from my training set). The images are 96x96 pixels, and there are 30 key points (outputs) that it needs to learn, but it fails to do so. This is my first attempt at using Theano/Lasagne, so I'm sure I've just missed something obvious, but I can't see what I've done wrong:</p>
<pre><code>import sys
import os
import time
import numpy as np
import theano
import theano.tensor as T
import lasagne
import pickle
import matplotlib.pyplot as plt
def load_data():
with open('FKD.pickle', 'rb') as f:
save = pickle.load(f)
trainDataset = save['trainDataset'] # (5000, 1, 96, 96) np.ndarray of pixel values [-1,1]
trainLabels = save['trainLabels'] # (5000, 30) np.ndarray of target values [-1,1]
del save # Hint to help garbage collection free up memory
# Overtrain on dataset of 1
trainDataset = trainDataset[:1]
trainLabels = trainLabels[:1]
return trainDataset, trainLabels
def build_mlp(input_var=None):
relu = lasagne.nonlinearities.rectify
softmax = lasagne.nonlinearities.softmax
network = lasagne.layers.InputLayer(shape=(None, 1, imageSize, imageSize), input_var=input_var)
network = lasagne.layers.DenseLayer(network, num_units=numLabels, nonlinearity=softmax)
return network
def main(num_epochs=500, minibatch_size=500):
# Load the dataset
print "Loading data..."
X_train, y_train = load_data()
# Prepare Theano variables for inputs and targets
input_var = T.tensor4('inputs')
target_var = T.matrix('targets')
# Create neural network model
network = build_mlp(input_var)
# Create a loss expression for training, the mean squared error (MSE)
prediction = lasagne.layers.get_output(network)
loss = lasagne.objectives.squared_error(prediction, target_var)
loss = loss.mean()
# Create update expressions for training
params = lasagne.layers.get_all_params(network, trainable=True)
updates = lasagne.updates.nesterov_momentum(loss, params, learning_rate=0.01, momentum=0.9)
# Compile a function performing a training step on a mini-batch
train_fn = theano.function([input_var, target_var], loss, updates=updates)
# Collect points for final plot
train_err_plot = []
# Finally, launch the training loop.
print "Starting training..."
# We iterate over epochs:
for epoch in range(num_epochs):
# In each epoch, we do a full pass over the training data:
start_time = time.time()
train_err = train_fn(X_train, y_train)
# Then we print the results for this epoch:
print "Epoch %s of %s took %.3fs" % (epoch+1, num_epochs, time.time()-start_time)
print " training loss:\t\t%s" % train_err
# Save accuracy to show later
train_err_plot.append(train_err)
# Show plot
plt.plot(train_err_plot)
plt.title('Graph')
plt.xlabel('Epochs')
plt.ylabel('Training loss')
plt.tight_layout()
plt.show()
imageSize = 96
numLabels = 30
if __name__ == '__main__':
main(minibatch_size=1)
</code></pre>
<p>This gives me a graph that looks like this:</p>
<p><a href="http://i.stack.imgur.com/GEyYB.png" rel="nofollow"><img src="http://i.stack.imgur.com/GEyYB.png" alt="enter image description here"></a></p>
<p>I'm pretty this network should be able to get the loss down to basically zero. I'd appreciate any help or thoughts on the matter :)</p>
<p>EDIT: Removed dropout and hidden layer to simplify the problem.</p>
| 0 | 2016-07-23T14:17:35Z | 38,551,407 | <p>It turns out that I'd forgotten to change the output node functions from:</p>
<pre><code>lasagne.nonlinearities.softmax
</code></pre>
<p>to:</p>
<pre><code>lasagne.nonlinearities.linear
</code></pre>
<p>The code I was using as a base was for a classification problem (e.g. working out which digit the picture showed), whereas I was using the network for a regression problem (e.g. trying to find where certain features in an image are located). There are several useful output functions for classification problems, of which softmax is one of them, but regression problems require a linear output function to work.</p>
<p>Hope this helps someone else in the future :)</p>
| 1 | 2016-07-24T11:12:25Z | [
"python",
"neural-network",
"theano",
"lasagne"
] |
Can't create user site-packages directory for usercustomize.py file | 38,542,834 | <p>I need to add the win_unicode_console module to my <code>usercustomize.py</code> file, as described by the documentation.</p>
<p>I've discovered my user site packages directory with:</p>
<pre><code>>>> import site
>>> site.getusersitepackages()
'C:\\Users\\my name\\AppData\\Roaming\\Python\\Python35\\site-packages'
</code></pre>
<p>I haven't been able to get to this directory using any method. I've tried using pushd instead of cd to emulate a network drive, and I've also tried getting there using run. No matter what I do in python, or in cmd terminal. I get the response <code>The network path was not found</code>. </p>
<p>Here is an example of one I've tried in cmd:</p>
<pre><code>C:\>pushd \\Users\\my name\\AppData\\Roaming\\Python\\Python35\\site-packages
The network path was not found.
</code></pre>
<p>What am I doing wrong, or what could be wrong with the path?</p>
| 0 | 2016-07-23T14:25:26Z | 38,606,990 | <p>DOS style backslashes don't need to be escaped within the Windows console (else they may have used forward slashes way back when!).</p>
<p>Follow these steps to manually create <code>usercustomize.py</code>:</p>
<ol>
<li>Start->Run:<code>cmd</code></li>
<li><p>Make sure you're on the C: drive</p>
<pre><code>c:
</code></pre></li>
<li><p>Create the directory. <code>mkdir</code> creates the missing parents. Obviously, change <em>"my name"</em> as appropriate.</p>
<pre><code>mkdir C:\Users\my name\AppData\Roaming\Python\Python35\site-packages
</code></pre></li>
<li><p>Create usercustomize.py: </p>
<pre><code>notepad C:\Users\my name\AppData\Roaming\Python\Python35\site-packages\usercustomize.py
</code></pre></li>
<li><p>Click "yes" to create your file.</p></li>
<li>Edit as appropriate</li>
</ol>
<p><strong>Or use the following script to have Python do it for you:</strong></p>
<pre><code>import site
import os
import os.path
import io
user_site_dir = site.getusersitepackages()
user_customize_filename = os.path.join(user_site_dir, 'usercustomize.py')
win_unicode_console_text = u"""
# win_unicode_console
import win_unicode_console
win_unicode_console.enable()
"""
if os.path.exists(user_site_dir):
print("User site dir already exists")
else:
print("Creating site dir")
os.makedirs(user_site_dir)
if not os.path.exists(user_customize_filename):
print("Creating {filename}".format(filename=user_customize_filename))
file_mode = 'w+t'
else:
print("{filename} already exists".format(filename=user_customize_filename))
file_mode = 'r+t'
with io.open(user_customize_filename, file_mode) as user_customize_file:
existing_text = user_customize_file.read()
if not win_unicode_console_text in existing_text:
# file pointer should already be at the end of the file after read()
user_customize_file.write(win_unicode_console_text)
print("win_unicode_console added to {filename}".format(filename=user_customize_filename))
else:
print("win_unicode_console already enabled")
</code></pre>
| 0 | 2016-07-27T07:52:34Z | [
"python",
"windows",
"unicode",
"module",
"python-unicode"
] |
Clicking "button" in Selenium | 38,542,882 | <p>[Using Python 2.7 and Selenium Web-driver]</p>
<p>So there's this HTML code, which is kind of a button. How do I click it in Selenium?</p>
<pre><code><div class="PermalinkProfile-dismiss">
<span class="Icon Icon--close Icon--large"></span>
</div>
</code></pre>
<p>I've tried:</p>
<pre><code>elem = driver.find_element_by_xpath('//*[@id="permalink-overlay-body"]/div/div[1]').click
</code></pre>
<p>and</p>
<pre><code>elem = driver.find_element_by_xpath('//*[@id="permalink-overlay-body"]/div/div[1]/span').click()
</code></pre>
<p>None of them worked.</p>
<p>Any suggestions?</p>
| -1 | 2016-07-23T14:30:17Z | 38,543,215 | <p><code>click()</code> is a function that doesn't return value, you can't assign it to variable. You can do</p>
<pre><code>driver.find_element_by_xpath('//*[@id="permalink-overlay-body"]/div/div[1]/span').click()
</code></pre>
<p>Or</p>
<pre><code>elem = driver.find_element_by_xpath('//*[@id="permalink-overlay-body"]/div/div[1]/span')
elem.click()
</code></pre>
| 0 | 2016-07-23T15:07:23Z | [
"python",
"selenium"
] |
Clicking "button" in Selenium | 38,542,882 | <p>[Using Python 2.7 and Selenium Web-driver]</p>
<p>So there's this HTML code, which is kind of a button. How do I click it in Selenium?</p>
<pre><code><div class="PermalinkProfile-dismiss">
<span class="Icon Icon--close Icon--large"></span>
</div>
</code></pre>
<p>I've tried:</p>
<pre><code>elem = driver.find_element_by_xpath('//*[@id="permalink-overlay-body"]/div/div[1]').click
</code></pre>
<p>and</p>
<pre><code>elem = driver.find_element_by_xpath('//*[@id="permalink-overlay-body"]/div/div[1]/span').click()
</code></pre>
<p>None of them worked.</p>
<p>Any suggestions?</p>
| -1 | 2016-07-23T14:30:17Z | 38,543,380 | <p>It's possible that your selector is wrong. You can try other selection methods, for example <code>find_element_by_css_selector()</code>. </p>
<p>First find the element and see if it returns anything. Modify which <code>find_*</code> method you use and experiment with your selector patterns untill it matches - returns the element that you want.
elem = driver.find_element_by_css_selector('.PermalinkProfile-dismiss span')</p>
<p>See <a href="http://selenium-python.readthedocs.io/locating-elements.html" rel="nofollow">Locating elements</a> guide for possible aproaches here. </p>
<p>If you have the element than click on it:</p>
<pre><code>elem.click()
</code></pre>
<p>As Guy stated <code>click()</code> doesn't return anything, so you need to do it in two steps.</p>
| 0 | 2016-07-23T15:26:39Z | [
"python",
"selenium"
] |
Restart a function in python | 38,542,917 | <p>My code is in a while True loop.
It basically tries something like captcha.</p>
<p>So what I want is something like this</p>
<pre><code>def loop():
toplam = 0
global sayilar
x = br.open(something)
html = x.read()
sayilar = map(str.strip,''.join(kod.findall(html)).split("\xc4\x84\xc5\x95\xc5\xa3\xc4\xb1"))
print sayilar
for i in sayilar:
if i in diction:
toplam += diction[i]
else
#break the function
if __name__ == "__main__":
giris()
while 1:
loop()
</code></pre>
<p>it can't find the number in dictionary it will break the function and restart the function again because function is in while loop.</p>
| -5 | 2016-07-23T14:34:57Z | 38,542,988 | <p>Ok found a good way to restart it.</p>
<pre><code>class CustomError(Exception):
def __init__(self, arg):
# Set some exception infomation
self.msg = arg
def loop():
toplam = 0
global sayilar
x = br.open(something)
html = x.read()
sayilar = map(str.strip,''.join(kod.findall(html)).split("\xc4\x84\xc5\x95\xc5\xa3\xc4\xb1"))
print sayilar
for i in sayilar:
if i in diction:
toplam += diction[i]
else
raise CustomError('Kelime Dictionaryde bulunamadi')
if __name__ == "__main__":
giris()
while 1:
try:
loop()
except CustomError, arg:
print "Can't find in dictionary"
</code></pre>
| 0 | 2016-07-23T14:43:23Z | [
"python",
"loops",
"if-statement",
"while-loop",
"break"
] |
Restart a function in python | 38,542,917 | <p>My code is in a while True loop.
It basically tries something like captcha.</p>
<p>So what I want is something like this</p>
<pre><code>def loop():
toplam = 0
global sayilar
x = br.open(something)
html = x.read()
sayilar = map(str.strip,''.join(kod.findall(html)).split("\xc4\x84\xc5\x95\xc5\xa3\xc4\xb1"))
print sayilar
for i in sayilar:
if i in diction:
toplam += diction[i]
else
#break the function
if __name__ == "__main__":
giris()
while 1:
loop()
</code></pre>
<p>it can't find the number in dictionary it will break the function and restart the function again because function is in while loop.</p>
| -5 | 2016-07-23T14:34:57Z | 38,543,064 | <p>You can literally use <code>break</code>. By using <code>break</code>, you can stop the loop immediately. You will see the use of the <code>return</code> later.</p>
<pre><code>for i in sayilar:
if i in diction:
toplam += diction[i]
else:
return None
break
return True # Anything but None will work in place of True
</code></pre>
<p>This goes the same for the <code>while</code> loop:</p>
<pre><code>while True: # Use True instead of 1
loop()
if loop() == None: # The function call is equal to what it returned
break
else:
continue # Optional else statement: continues loop if loop() != None
</code></pre>
| 0 | 2016-07-23T14:52:16Z | [
"python",
"loops",
"if-statement",
"while-loop",
"break"
] |
Stack two columns in a DataFrame, repeat others | 38,543,026 | <p>I have a pandas DataFrame with a structure like this:</p>
<pre><code>df = pd.DataFrame( [
[ 'foo1', 'a', 'z', 'bar1', 1, 4 ],
[ 'foo2', 'b', 'y', 'bar2', 2, 5 ],
[ 'foo3', 'c', 'x', 'bar3', 3, 6 ]
] )
df.columns = [ 'foo', 'let1', 'let2', 'bar', 'num1', 'num2' ]
print( df )
</code></pre>
<hr>
<pre><code> foo let1 let2 bar num1 num2
0 foo1 a z bar1 1 4
1 foo2 b y bar2 2 5
2 foo3 c x bar3 3 6
</code></pre>
<p>I want to stack the columns <code>let1</code> and <code>let2</code>, and add a label telling where they came from. The same for <code>num1</code> and <code>num2</code>. In the end, I would like to achieve this:</p>
<pre><code> foo let letval bar num numval
0 foo1 let1 a bar1 num1 1
1 foo2 let1 b bar2 num1 2
2 foo3 let1 c bar3 num1 3
3 foo1 let2 z bar1 num2 4
4 foo2 let2 y bar2 num2 5
5 foo3 let2 x bar3 num2 6
</code></pre>
<hr>
<p>So far, I've done this:</p>
<pre><code>let = pd.concat( [ df.let1, df.let2 ] )
num = pd.concat( [ df.num1, df.num2 ] )
df = df.drop( ['let1', 'let2', 'num1', 'num2' ], axis=1 )
df = pd.concat( [ df, df ] )
df[ 'letval' ] = let
df[ 'numval' ] = num
print( df )
foo bar letval numval
0 foo1 bar1 a 1
1 foo2 bar2 b 2
2 foo3 bar3 c 3
0 foo1 bar1 z 4
1 foo2 bar2 y 5
2 foo3 bar3 x 6
</code></pre>
<p>However, I am pretty sure that there is an easier way to achieve that, without copying to dummy variables and such workarounds.</p>
<p>Any ideas?</p>
| 3 | 2016-07-23T14:47:49Z | 38,543,214 | <p>Here is my attempt to combine <a href="http://stackoverflow.com/questions/38543026/stack-two-columns-in-a-dataframe-repeat-others/38543214#comment64478268_38543026">@ayhan</a>'s solution with the <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.melt.html" rel="nofollow">pd.melt()</a> method:</p>
<pre><code>In [191]: (pd.melt(df.drop(['num1','num2'], 1), id_vars=['foo','bar'],
.....: var_name='let', value_name='letval')
.....: .assign(numval=pd.lreshape(df.filter(like='num'),
.....: {'numval': ['num1', 'num2']})))
Out[191]:
foo bar let letval numval
0 foo1 bar1 let1 a 1
1 foo2 bar2 let1 b 2
2 foo3 bar3 let1 c 3
3 foo1 bar1 let2 z 4
4 foo2 bar2 let2 y 5
5 foo3 bar3 let2 x 6
</code></pre>
| 4 | 2016-07-23T15:07:20Z | [
"python",
"pandas",
"dataframe"
] |
Stack two columns in a DataFrame, repeat others | 38,543,026 | <p>I have a pandas DataFrame with a structure like this:</p>
<pre><code>df = pd.DataFrame( [
[ 'foo1', 'a', 'z', 'bar1', 1, 4 ],
[ 'foo2', 'b', 'y', 'bar2', 2, 5 ],
[ 'foo3', 'c', 'x', 'bar3', 3, 6 ]
] )
df.columns = [ 'foo', 'let1', 'let2', 'bar', 'num1', 'num2' ]
print( df )
</code></pre>
<hr>
<pre><code> foo let1 let2 bar num1 num2
0 foo1 a z bar1 1 4
1 foo2 b y bar2 2 5
2 foo3 c x bar3 3 6
</code></pre>
<p>I want to stack the columns <code>let1</code> and <code>let2</code>, and add a label telling where they came from. The same for <code>num1</code> and <code>num2</code>. In the end, I would like to achieve this:</p>
<pre><code> foo let letval bar num numval
0 foo1 let1 a bar1 num1 1
1 foo2 let1 b bar2 num1 2
2 foo3 let1 c bar3 num1 3
3 foo1 let2 z bar1 num2 4
4 foo2 let2 y bar2 num2 5
5 foo3 let2 x bar3 num2 6
</code></pre>
<hr>
<p>So far, I've done this:</p>
<pre><code>let = pd.concat( [ df.let1, df.let2 ] )
num = pd.concat( [ df.num1, df.num2 ] )
df = df.drop( ['let1', 'let2', 'num1', 'num2' ], axis=1 )
df = pd.concat( [ df, df ] )
df[ 'letval' ] = let
df[ 'numval' ] = num
print( df )
foo bar letval numval
0 foo1 bar1 a 1
1 foo2 bar2 b 2
2 foo3 bar3 c 3
0 foo1 bar1 z 4
1 foo2 bar2 y 5
2 foo3 bar3 x 6
</code></pre>
<p>However, I am pretty sure that there is an easier way to achieve that, without copying to dummy variables and such workarounds.</p>
<p>Any ideas?</p>
| 3 | 2016-07-23T14:47:49Z | 38,545,243 | <p>In the meantime, I came out with an answer as well. </p>
<p>Far more modest than <a href="http://stackoverflow.com/a/38543214/776515">@MaxU</a>'s, and based on <a href="http://stackoverflow.com/questions/38543026/stack-two-columns-in-a-dataframe-repeat-others/38543214#comment64478268_38543026">@ayhan</a>'s comment as well.</p>
<pre><code>let = [ 'let1', 'let2' ]
num = [ 'num1', 'num2' ]
n = df.shape[0]
df = pd.lreshape(df, { 'letval': let, 'numval': num } )
df[ 'let' ] = [ item for item in let for _ in range(n) ]
df[ 'num' ] = [ item for item in num for _ in range(n) ]
print( df )
bar foo letval numval let num
0 bar1 foo1 a 1 let1 num1
1 bar2 foo2 b 2 let1 num1
2 bar3 foo3 c 3 let1 num1
3 bar1 foo1 z 4 let2 num2
4 bar2 foo2 y 5 let2 num2
5 bar3 foo3 x 6 let2 num2
</code></pre>
| 2 | 2016-07-23T18:38:52Z | [
"python",
"pandas",
"dataframe"
] |
Stack two columns in a DataFrame, repeat others | 38,543,026 | <p>I have a pandas DataFrame with a structure like this:</p>
<pre><code>df = pd.DataFrame( [
[ 'foo1', 'a', 'z', 'bar1', 1, 4 ],
[ 'foo2', 'b', 'y', 'bar2', 2, 5 ],
[ 'foo3', 'c', 'x', 'bar3', 3, 6 ]
] )
df.columns = [ 'foo', 'let1', 'let2', 'bar', 'num1', 'num2' ]
print( df )
</code></pre>
<hr>
<pre><code> foo let1 let2 bar num1 num2
0 foo1 a z bar1 1 4
1 foo2 b y bar2 2 5
2 foo3 c x bar3 3 6
</code></pre>
<p>I want to stack the columns <code>let1</code> and <code>let2</code>, and add a label telling where they came from. The same for <code>num1</code> and <code>num2</code>. In the end, I would like to achieve this:</p>
<pre><code> foo let letval bar num numval
0 foo1 let1 a bar1 num1 1
1 foo2 let1 b bar2 num1 2
2 foo3 let1 c bar3 num1 3
3 foo1 let2 z bar1 num2 4
4 foo2 let2 y bar2 num2 5
5 foo3 let2 x bar3 num2 6
</code></pre>
<hr>
<p>So far, I've done this:</p>
<pre><code>let = pd.concat( [ df.let1, df.let2 ] )
num = pd.concat( [ df.num1, df.num2 ] )
df = df.drop( ['let1', 'let2', 'num1', 'num2' ], axis=1 )
df = pd.concat( [ df, df ] )
df[ 'letval' ] = let
df[ 'numval' ] = num
print( df )
foo bar letval numval
0 foo1 bar1 a 1
1 foo2 bar2 b 2
2 foo3 bar3 c 3
0 foo1 bar1 z 4
1 foo2 bar2 y 5
2 foo3 bar3 x 6
</code></pre>
<p>However, I am pretty sure that there is an easier way to achieve that, without copying to dummy variables and such workarounds.</p>
<p>Any ideas?</p>
| 3 | 2016-07-23T14:47:49Z | 38,545,269 | <p>Try this: </p>
<pre><code>dfm = pd.melt(df.drop(['num1','num2'], 1), id_vars=['foo','bar'], var_name=('let'), value_name=('letval'))
dfm[['num', 'numvals']] = pd.melt(df.drop(['let1','let2'], 1), id_vars=['foo','bar'], var_name=('num'), value_name=('numvals'))[['num', 'numvals']]
dfm:
foo bar let letval num numvals
0 foo1 bar1 let1 a num1 1
1 foo2 bar2 let1 b num1 2
2 foo3 bar3 let1 c num1 3
3 foo1 bar1 let2 z num2 4
4 foo2 bar2 let2 y num2 5
5 foo3 bar3 let2 x num2 6
</code></pre>
| 1 | 2016-07-23T18:41:58Z | [
"python",
"pandas",
"dataframe"
] |
i am trying to code a quiz with python but its not working | 38,543,125 | <p>i am coding a quiz in python. everything seems to work until i try to input the answer. i am very new to this. also can somebody explain what an indentation block is and an example of it.
this is the code:</p>
<pre><code>>>> print('physics quiz')
physics quiz
>>> print('round 1')
round 1
>>> print('what is the 1st stage of a stars life?')
what is the 1st stage of a stars life?
>>> print('a...protostar')
a...protostar
>>> print('b...nebula')
b...nebula
>>> print('c...red giant')
c...red giant
>>>answer=int(input('you have 5 seconds'))
you have 5 seconds
'a'
if answer=='a':
print('correct')
else:
print('incorrect, it was protostar')
</code></pre>
| -4 | 2016-07-23T14:58:18Z | 38,543,165 | <p>in this line </p>
<pre><code>answer=int(input('you have 5 seconds'))
</code></pre>
<p>you are converting input to int, therefore it will fail once int() can't convert input</p>
| 0 | 2016-07-23T15:02:32Z | [
"python"
] |
i am trying to code a quiz with python but its not working | 38,543,125 | <p>i am coding a quiz in python. everything seems to work until i try to input the answer. i am very new to this. also can somebody explain what an indentation block is and an example of it.
this is the code:</p>
<pre><code>>>> print('physics quiz')
physics quiz
>>> print('round 1')
round 1
>>> print('what is the 1st stage of a stars life?')
what is the 1st stage of a stars life?
>>> print('a...protostar')
a...protostar
>>> print('b...nebula')
b...nebula
>>> print('c...red giant')
c...red giant
>>>answer=int(input('you have 5 seconds'))
you have 5 seconds
'a'
if answer=='a':
print('correct')
else:
print('incorrect, it was protostar')
</code></pre>
| -4 | 2016-07-23T14:58:18Z | 38,545,624 | <p>You are trying to get input from the user and change it to an integer in this line:</p>
<p><code>answer=int(input('you have 5 seconds'))</code></p>
<p>However, an integer can only be a number without a period (if that wasn't clear yet), and Python doesn't know what to do. And it gives you an error. Change this line to:</p>
<p><code>answer=input('you have 5 seconds')</code></p>
<p>and it will all work.</p>
| 0 | 2016-07-23T19:20:49Z | [
"python"
] |
Detecting Dash button ARP requests | 38,543,131 | <p>I am having some trouble finding working code to find ARP requests sent out by an Amazon dash button. I tried <a href="https://medium.com/@edwardbenson/how-i-hacked-amazon-s-5-wifi-button-to-track-baby-data-794214b0bdd8#.utodl94ug" rel="nofollow">Ted Benson's code</a>, and also <a href="https://gist.github.com/ibrahima/5e43439eb71066bf891f" rel="nofollow">this code here</a>, but neither seem to be working. </p>
<p>Ted's code: </p>
<pre><code>from scapy.all import *
def arp_display(pkt):
if pkt[ARP].op == 1: #who-has (request)
if pkt[ARP].psrc == '0.0.0.0': # ARP Probe
print("ARP Probe from: " + pkt[ARP].hwsrc)
print(sniff(prn=arp_display, filter="arp", store=0, count=10))
</code></pre>
<p>The issue I am having is with the line <code>scapy.all import *</code>. I get a long list of explanation, but the last line of the error is
<code>import dnet ImportError: No module named dnet</code>.</p>
<p>The second code I tried is </p>
<pre><code>import socket
import struct
import binascii
# Written by Bob Steinbeiser (https://medium.com/@xtalker)
rawSocket = socket.socket(socket.AF_PACKET, socket.SOCK_RAW,
socket.htons(0x0003))
MAC = '74c24671971c'
while True:
packet = rawSocket.recvfrom(2048)
ethernet_header = packet[0][0:14]
ethernet_detailed = struct.unpack('!6s6s2s', ethernet_header)
arp_header = packet[0][14:42]
arp_detailed = struct.unpack('2s2s1s1s2s6s4s6s4s', arp_header)
# skip non-ARP packets
ethertype = ethernet_detailed[2]
if ethertype != '\x08\x06':
continue
source_mac = binascii.hexlify(arp_detailed[5])
dest_ip = socket.inet_ntoa(arp_detailed[8])
if source_mac == MAC:
print "Dash button pressed!, IP = " + dest_ip
</code></pre>
<p>This is the error I am getting: <code>'AttributeError: 'module' object has no attribute 'AF_PACKET''</code>.</p>
<p>I have tried both code in python 2.7 and 3.4 and it neither work. Please let me know if there is anything I can do, or any code I can re-appropriate.</p>
| 0 | 2016-07-23T14:59:04Z | 39,907,430 | <p>For the first example, you are probably missing the <code>libdnet</code> dependency, as discussed in <a href="http://stackoverflow.com/a/26247500/1772214">this SO answer</a>.</p>
<p>Also, note that a different approach is required to detect newer model Dash buttons (listening for DHCP requests rather than ARP requests). I describe the solution in <a href="http://stackoverflow.com/a/39906246/1772214">this answer</a>.</p>
| 0 | 2016-10-07T00:04:54Z | [
"python",
"arp"
] |
How to read MLComp dataset using python? | 38,543,156 | <p>MLComp dataset have special type of file format what I don't know about. I want to read using python but can't. </p>
| -1 | 2016-07-23T15:00:52Z | 38,552,967 | <p>First thing to note is that <code>sklearn</code> (v0.17.1, as of 24th July 2016), only supports the <code>DocumentClassification</code> domain of <code>mlcomp</code>.</p>
<p>Supposing you've downloaded the e.g. <a href="http://mlcomp.org/datasets/523" rel="nofollow">WebKB dataset</a>, which has <code>id=523</code>, to <code>/somewhere/on/your/computer</code>, you can use the following <code>sklearn</code> snippet to load the dataset and train a classifier:</p>
<pre><code>from sklearn.datasets import load_mlcomp
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.metrics import accuracy_score
from sklearn.naive_bayes import MultinomialNB
# Load mlcomp data using sklearn
train_data = load_mlcomp(name_or_id=523, set_='train', mlcomp_root='/somewhere/on/your/computer')
test_data = load_mlcomp(name_or_id=523, set_='test', mlcomp_root='/somewhere/on/your/computer')
# if you had the environment variable `MLCOMP_DATASETS_HOME` set, you wouldn't need to explicitly pass anything to `mlcomp_root`
# `data` is a standard `Bunch` object, so you can now straightforwardly go on and vectorize the dataset,...
vec = CountVectorizer(decode_error='replace')
X_train = vec.fit_transform(train_data.data)
X_test = vec.transform(test_data.data)
# ...train a classifier...
mnb = MultinomialNB()
mnb.fit(X_train, train_data.target)
# ...and evaluate it.
print('Accuracy: {}'.format(accuracy_score(test_data.target, mnb.predict(X_test))))
</code></pre>
| 0 | 2016-07-24T14:14:34Z | [
"python",
"machine-learning",
"dataset",
"scikit-learn"
] |
Python Agglomerative Clustering : finding the closest points in clusters | 38,543,185 | <p>The linkage matrix for clustering provides the cluster index, and distance
for each step of the clustering hierarchy.
When two clusters are merged, I would like to know which two points were the closest in the clusters. I am using the metric "single" i.e. closest distance</p>
<p>I know I can do this trivially by an exhaustive search and comparison. Is the information already there after linkage ? Is there a smarter way to get this information?</p>
| 0 | 2016-07-23T15:04:32Z | 38,547,221 | <p>To answer your questions:</p>
<ul>
<li><p>No, this information is not available after linkage, at least according to the official Python documentation.</p></li>
<li><p>The <strong>closest pair of points problem</strong> is a problem of computational geometry, and can be solved in logarithmic time by a recursive <em>divide and conquer</em> algorithm (note that exhaustive search is quadratic). See this Wikipedia <a href="https://en.wikipedia.org/wiki/Closest_pair_of_points_problem" rel="nofollow">article</a> for more information. Check also this <a href="http://euro.ecom.cmu.edu/people/faculty/mshamos/1975ClosestPoint.pdf" rel="nofollow">paper</a> by Shamos and Hoey. Note that the original formulation of the problem involves only one set of points. However, adaptation for two sets is straightforward; you might find this <a href="http://cs.stackexchange.com/questions/2415/shortest-distance-between-a-point-in-a-and-a-point-in-b">discussion</a> helpful. </p></li>
</ul>
| 0 | 2016-07-23T23:12:35Z | [
"python",
"hierarchical-clustering"
] |
How to make gif at pygame? | 38,543,187 | <p>I have 6 photos that I wanna make gif from them and show it on Pygame.
I get that I can't preview it so simply, so what I can do to show the animation like a gif?</p>
<p>Python 2.7</p>
| 0 | 2016-07-23T15:04:35Z | 38,558,336 | <p>You can create a class that switch between your images based on a time interval.</p>
<pre><code>class Animation(pygame.sprite.Sprite):
def __init__(self, images, time_interval):
super(Animation, self).__init__()
self.images = images
self.image = self.images[0]
self.time_interval = time_interval
self.index = 0
self.timer = 0
def update(self, seconds):
self.timer += seconds
if self.timer >= self.time_interval:
self.image = self.images[self.index]
self.index = (self.index + 1) % len(self.images)
self.timer = 0
</code></pre>
<p>I created a small sample program to try it out.</p>
<pre><code>import pygame
import sys
pygame.init()
class Animation(pygame.sprite.Sprite):
def __init__(self, images, time_interval):
super(Animation, self).__init__()
self.images = images
self.image = self.images[0]
self.time_interval = time_interval
self.index = 0
self.timer = 0
def update(self, seconds):
self.timer += seconds
if self.timer >= self.time_interval:
self.image = self.images[self.index]
self.index = (self.index + 1) % len(self.images)
self.timer = 0
def create_images():
images = []
for i in xrange(6):
image = pygame.Surface((256, 256))
image.fill((255 - i * 50, 255, i * 50))
images.append(image)
return images
def main():
images = create_images() # Or use a list of your own images.
a = Animation(images, 0.25)
# Main loop.
while True:
seconds = clock.tick(FPS) / 1000.0 # 'seconds' is the amount of seconds each loop takes.
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
a.update(seconds)
screen.fill((0, 0, 0))
screen.blit(a.image, (250, 100))
pygame.display.update()
if __name__ == '__main__':
screen = pygame.display.set_mode((720, 480))
clock = pygame.time.Clock()
FPS = 60
main()
</code></pre>
| 0 | 2016-07-25T00:54:05Z | [
"python",
"python-2.7",
"pygame"
] |
pandas, multiply all the numeric values in the data frame by a constant | 38,543,263 | <p>How to multiply all the numeric values in the data frame by a constant without having to specify column names explicitly? Example:</p>
<pre><code>In [13]: df = pd.DataFrame({'col1': ['A','B','C'], 'col2':[1,2,3], 'col3': [30, 10,20]})
In [14]: df
Out[14]:
col1 col2 col3
0 A 1 30
1 B 2 10
2 C 3 20
</code></pre>
<p>I tried <code>df.multiply</code> but it affects the string values as well by concatenating them several times.</p>
<pre><code>In [15]: df.multiply(3)
Out[15]:
col1 col2 col3
0 AAA 3 90
1 BBB 6 30
2 CCC 9 60
</code></pre>
<p>Is there a way to preserve the string values intact while multiplying only the numeric values by a constant? </p>
| 4 | 2016-07-23T15:13:01Z | 38,543,323 | <p>you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.select_dtypes.html" rel="nofollow">select_dtypes()</a> including <code>number</code> dtype or excluding all columns of <code>object</code> and <code>datetime64</code> dtypes:</p>
<p>Demo:</p>
<pre><code>In [162]: df
Out[162]:
col1 col2 col3 date
0 A 1 30 2016-01-01
1 B 2 10 2016-01-02
2 C 3 20 2016-01-03
In [163]: df.dtypes
Out[163]:
col1 object
col2 int64
col3 int64
date datetime64[ns]
dtype: object
In [164]: df.select_dtypes(exclude=['object', 'datetime']) * 3
Out[164]:
col2 col3
0 3 90
1 6 30
2 9 60
</code></pre>
<p>or a much better solution (c) <a href="http://stackoverflow.com/questions/38543263/pandas-multiply-all-the-numeric-values-in-the-data-frame-by-a-constant/38543323?noredirect=1#comment64478587_38543323">ayhan</a>:</p>
<pre><code>df[df.select_dtypes(include=['number']).columns] *= 3
</code></pre>
<p>From <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.melt.html" rel="nofollow">docs</a>:</p>
<blockquote>
<p>To select all numeric types use the numpy dtype numpy.number</p>
</blockquote>
| 3 | 2016-07-23T15:20:35Z | [
"python",
"pandas",
"dataframe"
] |
pandas, multiply all the numeric values in the data frame by a constant | 38,543,263 | <p>How to multiply all the numeric values in the data frame by a constant without having to specify column names explicitly? Example:</p>
<pre><code>In [13]: df = pd.DataFrame({'col1': ['A','B','C'], 'col2':[1,2,3], 'col3': [30, 10,20]})
In [14]: df
Out[14]:
col1 col2 col3
0 A 1 30
1 B 2 10
2 C 3 20
</code></pre>
<p>I tried <code>df.multiply</code> but it affects the string values as well by concatenating them several times.</p>
<pre><code>In [15]: df.multiply(3)
Out[15]:
col1 col2 col3
0 AAA 3 90
1 BBB 6 30
2 CCC 9 60
</code></pre>
<p>Is there a way to preserve the string values intact while multiplying only the numeric values by a constant? </p>
| 4 | 2016-07-23T15:13:01Z | 38,543,397 | <p>The other answer specifies how to multiply only numeric columns. Here's how to update it:</p>
<pre><code>df = pd.DataFrame({'col1': ['A','B','C'], 'col2':[1,2,3], 'col3': [30, 10,20]})
s = df.select_dtypes(include=[np.number])*3
df[s.columns] = s
print (df)
col1 col2 col3
0 A 3 90
1 B 6 30
2 C 9 60
</code></pre>
| 1 | 2016-07-23T15:28:54Z | [
"python",
"pandas",
"dataframe"
] |
pandas, multiply all the numeric values in the data frame by a constant | 38,543,263 | <p>How to multiply all the numeric values in the data frame by a constant without having to specify column names explicitly? Example:</p>
<pre><code>In [13]: df = pd.DataFrame({'col1': ['A','B','C'], 'col2':[1,2,3], 'col3': [30, 10,20]})
In [14]: df
Out[14]:
col1 col2 col3
0 A 1 30
1 B 2 10
2 C 3 20
</code></pre>
<p>I tried <code>df.multiply</code> but it affects the string values as well by concatenating them several times.</p>
<pre><code>In [15]: df.multiply(3)
Out[15]:
col1 col2 col3
0 AAA 3 90
1 BBB 6 30
2 CCC 9 60
</code></pre>
<p>Is there a way to preserve the string values intact while multiplying only the numeric values by a constant? </p>
| 4 | 2016-07-23T15:13:01Z | 38,543,403 | <p>One way would be to get the <code>dtypes</code>, match them against <code>object</code> and <code>datetime</code> dtypes and exclude them with a mask, like so -</p>
<pre><code>df.ix[:,~np.in1d(df.dtypes,['object','datetime'])] *= 3
</code></pre>
<p>Sample run -</p>
<pre><code>In [273]: df
Out[273]:
col1 col2 col3
0 A 1 30
1 B 2 10
2 C 3 20
In [274]: df.ix[:,~np.in1d(df.dtypes,['object','datetime'])] *= 3
In [275]: df
Out[275]:
col1 col2 col3
0 A 3 90
1 B 6 30
2 C 9 60
</code></pre>
| 4 | 2016-07-23T15:29:49Z | [
"python",
"pandas",
"dataframe"
] |
pandas, multiply all the numeric values in the data frame by a constant | 38,543,263 | <p>How to multiply all the numeric values in the data frame by a constant without having to specify column names explicitly? Example:</p>
<pre><code>In [13]: df = pd.DataFrame({'col1': ['A','B','C'], 'col2':[1,2,3], 'col3': [30, 10,20]})
In [14]: df
Out[14]:
col1 col2 col3
0 A 1 30
1 B 2 10
2 C 3 20
</code></pre>
<p>I tried <code>df.multiply</code> but it affects the string values as well by concatenating them several times.</p>
<pre><code>In [15]: df.multiply(3)
Out[15]:
col1 col2 col3
0 AAA 3 90
1 BBB 6 30
2 CCC 9 60
</code></pre>
<p>Is there a way to preserve the string values intact while multiplying only the numeric values by a constant? </p>
| 4 | 2016-07-23T15:13:01Z | 38,543,416 | <p>This should work even over mixed types within columns but is likely slow over large dataframes. </p>
<pre><code>def mul(x, y):
try:
return pd.to_numeric(x) * y
except:
return x
df.applymap(lambda x: mul(x, 3))
</code></pre>
| 2 | 2016-07-23T15:31:10Z | [
"python",
"pandas",
"dataframe"
] |
How to write server for chat program in php by using socket | 38,543,264 | <p>I use php as server on localhost.
I use python as client.</p>
<p>I want that:
Client will send message to server.
Server will send the same message to clients.
And all of clients will show the message which is sent.
But when I open 2 clients, the clients can't get answer from server when they send message.</p>
<p>How can I write a server with php which works correctly ?
Any idea ?</p>
<p>server.php:</p>
<pre><code> <?php
error_reporting(E_ALL);
set_time_limit(0);
header("Content-Type: text/plain; charset=UTF-8");
define("HOST", "127.0.0.1");
define("PORT", 28028);
a:
$socket = socket_create(AF_INET, SOCK_STREAM, 0) or die("Could not create socket\n");
$result = socket_bind($socket, HOST, PORT) or die("Could not bind to socket\n");
$result = socket_listen($socket, 50) or die("Could not set up socket listener\n");
$error = 0;
while (true){
$error = 0;
$spawn = socket_accept($socket) or die("Could not accept incoming connection\n");
$input = socket_read($spawn, 1024);
if (!$input) {
$error = 1;
}
if (socket_write($spawn, $input, strlen($input)) === false){
$error = 1;
}
if ($error){
goto a;
}
}
socket_close($spawn);
socket_close($socket);
</code></pre>
<p>client.py:</p>
<pre><code>from socket import *
from threading import Thread
import sys
HOST = 'localhost'
PORT = 28028
BUFSIZE = 1024
ADDR = (HOST, PORT)
tcpCliSock = socket(AF_INET, SOCK_STREAM)
tcpCliSock.connect(ADDR)
def recv():
while True:
data = tcpCliSock.recv(BUFSIZE)
if not data: sys.exit(0)
print data
Thread(target=recv).start()
while True:
data = raw_input('> ')
if not data: break
tcpCliSock.send(data)
tcpCliSock.close()
</code></pre>
| 0 | 2016-07-23T15:13:04Z | 38,782,141 | <p>The server has to wait simultaneously for connections and data from clients; this is easy with <code>socket_select()</code>. Replace your <code>while (true){â¦}</code> loop with</p>
<pre><code> $s = array($socket); // initially wait for connections
while ($r = $s and socket_select($r, $n=NULL, $n=NULL, NULL))
foreach ($r as $stream)
if ($stream == $socket) // new client
$s[] = socket_accept($socket); // add it to $s (index 1 on)
else // data from a client
if ($input = socket_read($stream, 1024))
foreach (array_slice($s, 1) as $client) // clients from index 1 on
socket_write($client, $input, strlen($input));
else
{
close($stream);
array_splice($s, array_search($stream, $s), 1); // remove client
}
</code></pre>
<p>Here the server socket and the client sockets are stored in the array <code>$s</code>.</p>
| 0 | 2016-08-05T06:01:54Z | [
"php",
"python",
"sockets"
] |
How to activate conda env with space in its name | 38,543,266 | <p><code>conda env list</code> or <code>conda info -e</code> shows</p>
<p><code>py35 python=3.5</code> as one of the environment.</p>
<p>How to activate conda env which has space in its name?</p>
| 1 | 2016-07-23T15:13:20Z | 38,897,486 | <p>tl;dr <strong>Surround the environment name with quotes.</strong></p>
<p>@centau you can most definitely create environments with spaces in the name.</p>
<p>Duplicating the problem:</p>
<pre><code>conda create -n "foo bar" python=3.5
</code></pre>
<p>Then inspecting the environments:</p>
<pre><code>conda info -e
</code></pre>
<p>produces:</p>
<pre><code># conda environments:
#
foo bar C:\Users\edill\AppData\Local\Continuum\Miniconda3\envs\foo bar
root * C:\Users\edill\AppData\Local\Continuum\Miniconda3
</code></pre>
<p>So you can see that there is an environment with the name "foo bar"</p>
<p>Then to activate it:</p>
<pre><code>activate "foo bar"
</code></pre>
<p>Which modifies the command line to show:</p>
<pre><code>(foo bar) C:\Users\edill>
</code></pre>
<p>So at this point I am reasonably confident that all is working properly with a space in the environment name, but let's just double check to make sure. Check the file that one of the built in modules is coming from:</p>
<pre><code>(foo bar) C:\Users\edill>python -c "import os; print(os.__file__)"
</code></pre>
<p>Shows that this built in <code>os</code> module is indeed coming from the <code>foo bar</code> environment</p>
<pre><code>C:\Users\edill\AppData\Local\Continuum\Miniconda3\envs\foo bar\lib\os.py
</code></pre>
| 0 | 2016-08-11T13:16:05Z | [
"python",
"anaconda",
"conda"
] |
Caffe always gives the same prediction in Python, but training accuracy is good | 38,543,440 | <p>I have a trained model with caffe (through the command line) where I get an <strong>accuracy of 63%</strong> (according to the log files). However, when I try to run a script in Python to test the accuracy, I get all the predictions in the same class, with very similar prediction values, but not quite identical. My goal is to compute the accuracy per class.</p>
<p>Here are some examples of predictions:</p>
<pre><code>[ 0.20748076 0.20283087 0.04773897 0.28503627 0.04591063 0.21100247] (label 0)
[ 0.21177764 0.20092578 0.04866471 0.28302929 0.04671735 0.20888527] (label 4)
[ 0.19711637 0.20476575 0.04688895 0.28988105 0.0465695 0.21477833] (label 3)
[ 0.21062914 0.20984225 0.04802448 0.26924771 0.05020727 0.21204917] (label 1)
</code></pre>
<p>Here is the prediction script (only the part which gives the predictions for a specific image):</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
import sys
import os
import caffe
caffe.set_device(0)
caffe.set_mode_gpu()
# Prepare Network
MODEL_FILE = 'finetune_deploy.prototxt'
PRETRAINED = 'finetune_lr3_iter_25800.caffemodel.h5'
MEAN_FILE = 'balanced_dataset_256/Training/labels_mean/trainingMean_original.binaryproto'
blob = caffe.proto.caffe_pb2.BlobProto()
dataBlob = open( MEAN_FILE , 'rb' ).read()
blob.ParseFromString(dataBlob)
dataMeanArray = np.array(caffe.io.blobproto_to_array(blob))
mu = dataMeanArray[0].mean(1).mean(1)
net = caffe.Classifier(MODEL_FILE, PRETRAINED,
mean=mu,
channel_swap=(2,1,0),
raw_scale=255,
image_dims=(256, 256))
PREFIX='balanced_dataset_256/PrivateTest/'
LABEL = '1'
imgName = '33408.jpg'
IMAGE_PATH = PREFIX + LABEL + '/' + imgName
input_image = caffe.io.load_image(IMAGE_PATH)
plt.imshow(input_image)
prediction = net.predict([input_image]) # predict takes any number of images, and formats them for the Caffe net automatically
print 'prediction shape:', prediction[0].shape
plt.plot(prediction[0])
print 'predicted class:', prediction[0].argmax()
print prediction[0]
</code></pre>
<p>The input data is <strong>grayscale</strong>, but I convert it to <strong>RGB</strong> by duplicating the channels.</p>
<p>Here's the architecture file finetune_deploy.prototxt:</p>
<pre><code>name: "FlickrStyleCaffeNetTest"
layer {
name: "data"
type: "Input"
top: "data"
# top: "label"
input_param { shape: { dim: 1 dim: 3 dim: 256 dim: 256 } }
}
layer {
name: "conv1"
type: "Convolution"
bottom: "data"
top: "conv1"
param {
lr_mult: 1
decay_mult: 1
}
param {
lr_mult: 2
decay_mult: 0
}
convolution_param {
num_output: 96
kernel_size: 11
stride: 4
weight_filler {
type: "gaussian"
std: 0.01
}
bias_filler {
type: "constant"
value: 0
}
}
}
layer {
name: "relu1"
type: "ReLU"
bottom: "conv1"
top: "conv1"
}
layer {
name: "pool1"
type: "Pooling"
bottom: "conv1"
top: "pool1"
pooling_param {
pool: MAX
kernel_size: 3
stride: 2
}
}
layer {
name: "norm1"
type: "LRN"
bottom: "pool1"
top: "norm1"
lrn_param {
local_size: 5
alpha: 0.0001
beta: 0.75
}
}
layer {
name: "conv2"
type: "Convolution"
bottom: "norm1"
top: "conv2"
param {
lr_mult: 1
decay_mult: 1
}
param {
lr_mult: 2
decay_mult: 0
}
convolution_param {
num_output: 256
pad: 2
kernel_size: 5
group: 2
weight_filler {
type: "gaussian"
std: 0.01
}
bias_filler {
type: "constant"
value: 1
}
}
}
layer {
name: "relu2"
type: "ReLU"
bottom: "conv2"
top: "conv2"
}
layer {
name: "pool2"
type: "Pooling"
bottom: "conv2"
top: "pool2"
pooling_param {
pool: MAX
kernel_size: 3
stride: 2
}
}
layer {
name: "norm2"
type: "LRN"
bottom: "pool2"
top: "norm2"
lrn_param {
local_size: 5
alpha: 0.0001
beta: 0.75
}
}
layer {
name: "conv3"
type: "Convolution"
bottom: "norm2"
top: "conv3"
param {
lr_mult: 1
decay_mult: 1
}
param {
lr_mult: 2
decay_mult: 0
}
convolution_param {
num_output: 384
pad: 1
kernel_size: 3
weight_filler {
type: "gaussian"
std: 0.01
}
bias_filler {
type: "constant"
value: 0
}
}
}
layer {
name: "relu3"
type: "ReLU"
bottom: "conv3"
top: "conv3"
}
layer {
name: "conv4"
type: "Convolution"
bottom: "conv3"
top: "conv4"
param {
lr_mult: 1
decay_mult: 1
}
param {
lr_mult: 2
decay_mult: 0
}
convolution_param {
num_output: 384
pad: 1
kernel_size: 3
group: 2
weight_filler {
type: "gaussian"
std: 0.01
}
bias_filler {
type: "constant"
value: 1
}
}
}
layer {
name: "relu4"
type: "ReLU"
bottom: "conv4"
top: "conv4"
}
layer {
name: "conv5"
type: "Convolution"
bottom: "conv4"
top: "conv5"
param {
lr_mult: 1
decay_mult: 1
}
param {
lr_mult: 2
decay_mult: 0
}
convolution_param {
num_output: 256
pad: 1
kernel_size: 3
group: 2
weight_filler {
type: "gaussian"
std: 0.01
}
bias_filler {
type: "constant"
value: 1
}
}
}
layer {
name: "relu5"
type: "ReLU"
bottom: "conv5"
top: "conv5"
}
layer {
name: "pool5"
type: "Pooling"
bottom: "conv5"
top: "pool5"
pooling_param {
pool: MAX
kernel_size: 3
stride: 2
}
}
layer {
name: "fc6"
type: "InnerProduct"
bottom: "pool5"
top: "fc6"
param {
lr_mult: 1
decay_mult: 1
}
param {
lr_mult: 2
decay_mult: 0
}
inner_product_param {
num_output: 4096
weight_filler {
type: "gaussian"
std: 0.005
}
bias_filler {
type: "constant"
value: 1
}
}
}
layer {
name: "relu6"
type: "ReLU"
bottom: "fc6"
top: "fc6"
}
layer {
name: "drop6"
type: "Dropout"
bottom: "fc6"
top: "fc6"
dropout_param {
dropout_ratio: 0.5
}
}
layer {
name: "fc7"
type: "InnerProduct"
bottom: "fc6"
top: "fc7"
# Note that lr_mult can be set to 0 to disable any fine-tuning of this, and any other, layer
param {
lr_mult: 1
decay_mult: 1
}
param {
lr_mult: 2
decay_mult: 0
}
inner_product_param {
num_output: 4096
weight_filler {
type: "gaussian"
std: 0.005
}
bias_filler {
type: "constant"
value: 1
}
}
}
layer {
name: "relu7"
type: "ReLU"
bottom: "fc7"
top: "fc7"
}
layer {
name: "drop7"
type: "Dropout"
bottom: "fc7"
top: "fc7"
dropout_param {
dropout_ratio: 0.5
}
}
layer {
name: "fc8_flickr"
type: "InnerProduct"
bottom: "fc7"
top: "fc8_flickr"
# lr_mult is set to higher than for other layers, because this layer is starting from random while the others are already trained
param {
lr_mult: 10
decay_mult: 1
}
param {
lr_mult: 20
decay_mult: 0
}
inner_product_param {
num_output: 6
weight_filler {
type: "gaussian"
std: 0.01
}
bias_filler {
type: "constant"
value: 0
}
}
}
layer {
name: "prob"
type: "Softmax"
bottom: "fc8_flickr"
top: "prob"
}
</code></pre>
| 0 | 2016-07-23T15:34:33Z | 39,570,767 | <p>I figured it out,
the deploy.prototxt had some input_param mismatch. </p>
<p>Strange behavior. </p>
| 0 | 2016-09-19T10:20:42Z | [
"python",
"caffe",
"pycaffe"
] |
How do I print a 2d array in python | 38,543,484 | <p>I'm having problems printing this 2d array for my Battleship game. </p>
<pre><code>class Battleship:
def __init__(self):
self.__init__()
def board(self, locate):
locate = []
for i in range(10):
locate.append([])
for j in range(10):
locate[i].append(0)
for i in range(10):
for j in range(10):
locate[i][j] = '%s,%s'%(i,j)
print(locate)
</code></pre>
<p>I found how to initialise the array here: <a href="http://stackoverflow.com/questions/24023115/how-to-initialise-a-2d-array-in-python">How to initialise a 2D array in Python?</a>
This is where I found the code sample to iterate over the 2d array, but it doesn't work for me:
<a href="http://stackoverflow.com/questions/16548668/iterating-over-a-2-dimensional-python-list">Iterating over a 2 dimensional python list</a></p>
<p>Can you give me some help please?</p>
| 1 | 2016-07-23T15:39:04Z | 38,543,548 | <pre><code>for i in range(10):
for j in range(10):
print(locate[i][j])`
</code></pre>
<p>This should make it work. </p>
| 0 | 2016-07-23T15:45:39Z | [
"python",
"arrays",
"multidimensional-array"
] |
How do I print a 2d array in python | 38,543,484 | <p>I'm having problems printing this 2d array for my Battleship game. </p>
<pre><code>class Battleship:
def __init__(self):
self.__init__()
def board(self, locate):
locate = []
for i in range(10):
locate.append([])
for j in range(10):
locate[i].append(0)
for i in range(10):
for j in range(10):
locate[i][j] = '%s,%s'%(i,j)
print(locate)
</code></pre>
<p>I found how to initialise the array here: <a href="http://stackoverflow.com/questions/24023115/how-to-initialise-a-2d-array-in-python">How to initialise a 2D array in Python?</a>
This is where I found the code sample to iterate over the 2d array, but it doesn't work for me:
<a href="http://stackoverflow.com/questions/16548668/iterating-over-a-2-dimensional-python-list">Iterating over a 2 dimensional python list</a></p>
<p>Can you give me some help please?</p>
| 1 | 2016-07-23T15:39:04Z | 38,543,590 | <p>how do you want to print it? Please be more informative regarding the output format.</p>
<p>Assuming you want <em>that</em> format, i.e. xOy coordinates (x,y):</p>
<p>In this for-loop:</p>
<pre><code>for i in range(10):
locate.append([])
for j in range(10):
locate[i].append(0)
</code></pre>
<p>your code might fail because of this line:</p>
<pre><code>locate[i].append(0)
</code></pre>
<p>The problem here is that your locate variable is a 2D array, so you might want to try something like:</p>
<pre><code>locate[i][j].append(0)
</code></pre>
<p>Otherwise, you will have to append a full List, if I'm not mistaken</p>
<p>Also, your last statement "print(locate)" should be outside the for-loop to print the matrix only once</p>
| 0 | 2016-07-23T15:49:29Z | [
"python",
"arrays",
"multidimensional-array"
] |
How do I print a 2d array in python | 38,543,484 | <p>I'm having problems printing this 2d array for my Battleship game. </p>
<pre><code>class Battleship:
def __init__(self):
self.__init__()
def board(self, locate):
locate = []
for i in range(10):
locate.append([])
for j in range(10):
locate[i].append(0)
for i in range(10):
for j in range(10):
locate[i][j] = '%s,%s'%(i,j)
print(locate)
</code></pre>
<p>I found how to initialise the array here: <a href="http://stackoverflow.com/questions/24023115/how-to-initialise-a-2d-array-in-python">How to initialise a 2D array in Python?</a>
This is where I found the code sample to iterate over the 2d array, but it doesn't work for me:
<a href="http://stackoverflow.com/questions/16548668/iterating-over-a-2-dimensional-python-list">Iterating over a 2 dimensional python list</a></p>
<p>Can you give me some help please?</p>
| 1 | 2016-07-23T15:39:04Z | 38,543,605 | <p>here is some code i wrote to generate the multiplication board, in order to demonstrate how to print a 2d array of unknowen size </p>
<pre><code>l = [] # empty list
a,b = 10,10 # size of board aXb
for i in range(1,a+1): # generate board
temp = []
for j in range(1,b+1):
temp.append(i*j)
l.append(temp)
for i in l: # print the board
print i
</code></pre>
<p>the output is</p>
<pre><code>[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
[3, 6, 9, 12, 15, 18, 21, 24, 27, 30]
[4, 8, 12, 16, 20, 24, 28, 32, 36, 40]
[5, 10, 15, 20, 25, 30, 35, 40, 45, 50]
[6, 12, 18, 24, 30, 36, 42, 48, 54, 60]
[7, 14, 21, 28, 35, 42, 49, 56, 63, 70]
[8, 16, 24, 32, 40, 48, 56, 64, 72, 80]
[9, 18, 27, 36, 45, 54, 63, 72, 81, 90]
[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
</code></pre>
<p>here is a different way to print</p>
<pre><code>for i in l: # print the board
for j in i:
print j,
print
</code></pre>
<p>the output</p>
<pre><code>1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30
4 8 12 16 20 24 28 32 36 40
5 10 15 20 25 30 35 40 45 50
6 12 18 24 30 36 42 48 54 60
7 14 21 28 35 42 49 56 63 70
8 16 24 32 40 48 56 64 72 80
9 18 27 36 45 54 63 72 81 90
10 20 30 40 50 60 70 80 90 100
</code></pre>
| 0 | 2016-07-23T15:50:38Z | [
"python",
"arrays",
"multidimensional-array"
] |
How do I print a 2d array in python | 38,543,484 | <p>I'm having problems printing this 2d array for my Battleship game. </p>
<pre><code>class Battleship:
def __init__(self):
self.__init__()
def board(self, locate):
locate = []
for i in range(10):
locate.append([])
for j in range(10):
locate[i].append(0)
for i in range(10):
for j in range(10):
locate[i][j] = '%s,%s'%(i,j)
print(locate)
</code></pre>
<p>I found how to initialise the array here: <a href="http://stackoverflow.com/questions/24023115/how-to-initialise-a-2d-array-in-python">How to initialise a 2D array in Python?</a>
This is where I found the code sample to iterate over the 2d array, but it doesn't work for me:
<a href="http://stackoverflow.com/questions/16548668/iterating-over-a-2-dimensional-python-list">Iterating over a 2 dimensional python list</a></p>
<p>Can you give me some help please?</p>
| 1 | 2016-07-23T15:39:04Z | 38,543,772 | <p>You have many forms of printing</p>
<p>Using numpy</p>
<pre><code>import numpy as np
print(np.matrix(matrix))
</code></pre>
<p>Using pprint</p>
<pre><code>import pprint
pprint.pprint(matrix)
</code></pre>
| 0 | 2016-07-23T16:08:30Z | [
"python",
"arrays",
"multidimensional-array"
] |
How do I print a 2d array in python | 38,543,484 | <p>I'm having problems printing this 2d array for my Battleship game. </p>
<pre><code>class Battleship:
def __init__(self):
self.__init__()
def board(self, locate):
locate = []
for i in range(10):
locate.append([])
for j in range(10):
locate[i].append(0)
for i in range(10):
for j in range(10):
locate[i][j] = '%s,%s'%(i,j)
print(locate)
</code></pre>
<p>I found how to initialise the array here: <a href="http://stackoverflow.com/questions/24023115/how-to-initialise-a-2d-array-in-python">How to initialise a 2D array in Python?</a>
This is where I found the code sample to iterate over the 2d array, but it doesn't work for me:
<a href="http://stackoverflow.com/questions/16548668/iterating-over-a-2-dimensional-python-list">Iterating over a 2 dimensional python list</a></p>
<p>Can you give me some help please?</p>
| 1 | 2016-07-23T15:39:04Z | 38,544,008 | <p>First, let's clean up the creation of the 2D-list :</p>
<pre><code>locate = [[str(i)+","+str(j) for j in range(10)] for i in range(10)]
</code></pre>
<p>Then, to iterate over the array and print the values stored in each case :</p>
<pre><code>for locate_i in locate:
for locate_i_j in locate_i:
print locate_i_j
</code></pre>
<p>Explanation : when you use a for X in list, X will have the value of each element in the list. So, our <code>locate_i</code> is each of the sub-list of a given i index. When we loop over this list, we get the content, "%s,%s"%(i,j)</p>
| 0 | 2016-07-23T16:33:16Z | [
"python",
"arrays",
"multidimensional-array"
] |
Change logging "print" function to "tqdm.write" so logging doesn't interfere with progress bars | 38,543,506 | <p>I have a simple question: How do I change the built-in Python logger's <code>print</code> function to <code>tqdm.write</code> such that logging messages do not interfere with tqdm's progress bars? Thanks!</p>
| 3 | 2016-07-23T15:40:48Z | 38,543,578 | <p>Not sure about what you are trying to do but if you use:</p>
<pre><code>import tqdm
</code></pre>
<p>instead of</p>
<pre><code>from tqdm import tqdm
</code></pre>
<p>when you (or some of your modules) put </p>
<pre><code>print
</code></pre>
<p>in your program it won't make reference to </p>
<pre><code>tqdm.print
</code></pre>
<p>but the original print.
You'll have the small inconvenient of having to type the later instruction when you want to see a progress bar.</p>
| -2 | 2016-07-23T15:48:22Z | [
"python",
"logging",
"tqdm"
] |
Change logging "print" function to "tqdm.write" so logging doesn't interfere with progress bars | 38,543,506 | <p>I have a simple question: How do I change the built-in Python logger's <code>print</code> function to <code>tqdm.write</code> such that logging messages do not interfere with tqdm's progress bars? Thanks!</p>
| 3 | 2016-07-23T15:40:48Z | 38,739,634 | <p>You need a custom logging handler:</p>
<pre><code>import logging
import tqdm
class TqdmLoggingHandler (logging.Handler):
def __init__ (self, level = logging.NOTSET):
super (self.__class__, self).__init__ (level)
def emit (self, record):
try:
msg = self.format (record)
tqdm.tqdm.write (msg)
self.flush ()
except (KeyboardInterrupt, SystemExit):
raise
except:
self.handleError(record)
</code></pre>
<p>and then add this to the logging chain:</p>
<pre><code>import time
log = logging.getLogger (__name__)
log.setLevel (logging.INFO)
log.addHandler (TqdmLoggingHandler ())
for i in tqdm.tqdm (range (100)):
if i == 50:
log.info ("Half-way there!")
time.sleep (0.1)
</code></pre>
| 3 | 2016-08-03T09:28:06Z | [
"python",
"logging",
"tqdm"
] |
Django 1.9 + Celery unregistered tasks | 38,543,513 | <blockquote>
<p>This configuration is <strong>correct</strong>. I was starting celery
the wrong way :(, without specifying the project name. (celery worker -A
hockey_manager -l info</p>
</blockquote>
<p>I did upgrade to Django 1.9 from 1.6.5 and I can't make the celery configuration work again.</p>
<p>After almost two days of searching for a solution I didn't find anything working.</p>
<p>Celery doesn't detect my tasks. I tried with:</p>
<ul>
<li>CELERY_IMPORTS</li>
<li>autodiscover_tasks</li>
<li>bind=True</li>
</ul>
<p><em>Dependencies</em></p>
<pre><code>amqp==2.0.3
celery==3.1.23
Django==1.9.8
django-celery==3.1.17
kombu==3.0.35
</code></pre>
<p><strong>PROJECT STRUCTURE</strong></p>
<p><a href="http://i.stack.imgur.com/CRV9T.png" rel="nofollow"><img src="http://i.stack.imgur.com/CRV9T.png" alt="enter image description here"></a></p>
<p><strong>hockey_manager/__init__.py</strong></p>
<pre><code>from __future__ import absolute_import
# This will make sure the app is always imported when
# Django starts so that shared_task will use this app.
from .celery import app as celery_app
</code></pre>
<p><strong>hockey_manager/celery.py</strong></p>
<pre><code>from __future__ import absolute_import
import os
from celery import Celery
# set the default Django settings module for the 'celery' program.
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'hockey_manager.settings.common')
app = Celery('hockey_manager')
# Using a string here means the worker will not have to
# pickle the object when using Windows.
app.config_from_object('django.conf:settings')
# load task modules from all registered Django app configs.
app.autodiscover_tasks(['hockey'])
# Using a string here means the worker will not have to
# pickle the object when using Windows.
# app.config_from_object('django.conf:settings')
# app.autodiscover_tasks(lambda: settings.INSTALLED_APPS)
# Celery backend configs
app.conf.update(
CELERY_RESULT_BACKEND='djcelery.backends.database:DatabaseBackend',
)
if __name__ == '__main__':
app.start()
@app.task(bind=True)
def debug_task(self):
print('Request: {0!r}'.format(self.request))
</code></pre>
<p><strong>hockey_manager/settings/common.py</strong></p>
<pre><code>INSTALLED_APPS = [
...
'hockey',
'djcelery',
'kombu.transport.django',
...
]
##
# Celery
##
# BROKER_POOL_LIMIT = 3
BROKER_URL = os.environ.get('CLOUDAMQP_URL')
#BROKER_URL = 'django://'
# List of modules to import when celery starts.
CELERY_IMPORTS = ('hockey.tasks', )
#: Only add pickle to this list if your broker is secured
#: from unwanted access (see userguide/security.html)
CELERY_ACCEPT_CONTENT = ['json']
CELERY_TASK_SERIALIZER = 'json'
CELERY_RESULT_SERIALIZER = 'json'
</code></pre>
<p><strong>hockey/tasks.py</strong></p>
<pre><code>from __future__ import absolute_import
from hockey_manager.celery import app
@app.task(name='hockey.tasks.league_schedule_results')
def league_schedule_results(schedule, statistics):
...
</code></pre>
<p><em>Error from Celery</em></p>
<blockquote>
<p>[2016-07-23 17:05:46,231: ERROR/MainProcess] Received unregistered
task of type 'hockey.tasks.league_schedule_results'.
The message has been ignored and discarded.</p>
</blockquote>
<p>I also receive a deprecation warning from <em>amqp</em> starting from version 2.0:</p>
<blockquote>
<p>AMQPDeprecationWarning: The .transport attribute on the connection was
accessed before
the connection was established. This is supported for now, but will
be deprecated in amqp 2.2.0.</p>
<pre><code>Since amqp 2.0 you have to explicitly call Connection.connect()
before using the connection.
W_FORCE_CONNECT.format(attr=attr)))
</code></pre>
</blockquote>
| 1 | 2016-07-23T15:41:33Z | 38,564,457 | <p>use <code>django-celery</code> module.</p>
<p>here is <a href="https://github.com/hirenalken/django-awesome-example/blob/master/django-celery-setup-steps.txt" rel="nofollow">link</a> to example how to use <code>django-celery</code> with django 1.9.1+</p>
| 2 | 2016-07-25T09:45:45Z | [
"python",
"django",
"celery",
"django-celery"
] |
Python if/elif syntax error... WHY | 38,543,524 | <p>I'm absolutely pulling my hair out over this. The if/elif statement in this function throws a syntax error on the elif line. To me there are no obvious syntax problems.</p>
<pre><code>"elif n == cs_index:"
^
SyntaxError: invalid syntax
</code></pre>
<p>I tried switching it to a bear "else:" just to see if that would stupidly word and it didn't. I'm sure there's something I don't see.</p>
<pre><code>def higherhighlight(cs_index):
text.tag_remove("the hello","1.0", END)
idex = "1.0"
for n in range(cs_index):
if n < cs_index:
idex = text.search("Hello", idex, nocase=1, stopindex=END)
lastidex = idex+"+"+str(len("hello"))+"c"
idex = lastidex
elif n == cs_index:
idex = text.search("Hello", idex, nocase=1, stopindex=END)
print idex
lastidex = idex+"+"+str(len("hello"))+"c"
print lastidex
text.tag_remove("hellos", idex, lastidex)
text.tag_add("the hello", idex, lastidex)
text.tag_config("the hello", background="dark green")
</code></pre>
| 0 | 2016-07-23T15:43:28Z | 38,543,579 | <p>After pasting my code into my Spyder IDE and running it, I exhibit no errors (apart from the parentheses missing in the <code>print</code> statements - you should really upgrade to Python 3.5.2!)</p>
<p>Try re-indenting that line by resetting the indentation and adding three tabs. I get similar errors when I copy and paste code that uses spaces for indentation.</p>
| 1 | 2016-07-23T15:48:23Z | [
"python",
"syntax-error"
] |
Python if/elif syntax error... WHY | 38,543,524 | <p>I'm absolutely pulling my hair out over this. The if/elif statement in this function throws a syntax error on the elif line. To me there are no obvious syntax problems.</p>
<pre><code>"elif n == cs_index:"
^
SyntaxError: invalid syntax
</code></pre>
<p>I tried switching it to a bear "else:" just to see if that would stupidly word and it didn't. I'm sure there's something I don't see.</p>
<pre><code>def higherhighlight(cs_index):
text.tag_remove("the hello","1.0", END)
idex = "1.0"
for n in range(cs_index):
if n < cs_index:
idex = text.search("Hello", idex, nocase=1, stopindex=END)
lastidex = idex+"+"+str(len("hello"))+"c"
idex = lastidex
elif n == cs_index:
idex = text.search("Hello", idex, nocase=1, stopindex=END)
print idex
lastidex = idex+"+"+str(len("hello"))+"c"
print lastidex
text.tag_remove("hellos", idex, lastidex)
text.tag_add("the hello", idex, lastidex)
text.tag_config("the hello", background="dark green")
</code></pre>
| 0 | 2016-07-23T15:43:28Z | 38,543,673 | <p>You are mixing tabs and spaces in your code; taking the source of your initial post and pasting it into Sublime Text, then selecting all lines I see this:</p>
<p><a href="http://i.stack.imgur.com/yYweS.png" rel="nofollow"><img src="http://i.stack.imgur.com/yYweS.png" alt="source code with spaces and tabs"></a></p>
<p>The grey lines are tabs, the dots are spaces. I have tabs set to expand to every 4th column, you probably have the same setting.</p>
<p>Python, which expands tabs to every <em>8th</em> column, sees this:</p>
<p><a href="http://i.stack.imgur.com/vb5IF.png" rel="nofollow"><img src="http://i.stack.imgur.com/vb5IF.png" alt="same source with tabs set to 8 spaces"></a></p>
<p>Note how the <code>elif</code> indentation <strong>matches the preceding lines</strong>, because the tab character following those 4 spaces is expanded to the <em>first</em> 8th column, not a second. This is the cause of the exception you see.</p>
<p>Don't mix tabs and spaces. Preferably, stick to spaces for indentation <em>only</em>; it is what the <a href="https://www.python.org/dev/peps/pep-0008/#tabs-or-spaces" rel="nofollow">Python styleguide recommends</a>:</p>
<blockquote>
<p>Spaces are the preferred indentation method.</p>
<p>Tabs should be used solely to remain consistent with code that is already indented with tabs.</p>
</blockquote>
<p>Configure your editor to use spaces <strong>only</strong>. You can still use the <kbd>TAB</kbd> key, but your editor will use spaces to indent lines when you do.</p>
| 1 | 2016-07-23T15:57:47Z | [
"python",
"syntax-error"
] |
slicing numpy array to get nth column | 38,543,660 | <p>Having the example array below, how do you slice by column to get the following (e.g. 3rd column) <code>[0, 0, ..., 1338, 1312, 1502, 0, ...]</code>
Looking for the most efficient way, thanks!</p>
<pre><code>>>> r
array([[[ 0, 0, 0],
[ 0, 0, 0],
[ 0, 0, 0],
[ 0, 0, 0],
[ 0, 0, 0],
[ 0, 0, 0]],
[[ 0, 0, 1338],
[ 0, 0, 1312],
[ 0, 0, 1502],
[ 0, 0, 0],
[ 0, 0, 0],
[ 0, 0, 0]],
[[ 0, 0, 1400],
[ 0, 0, 1277],
[ 0, 0, 1280],
[ 0, 0, 0],
[ 0, 0, 0],
[ 0, 0, 0]]], dtype=uint16)
</code></pre>
| 1 | 2016-07-23T15:55:36Z | 38,543,690 | <p>For a generic ndarray of any dimensions, one way would be -</p>
<pre><code>arr[...,n]
</code></pre>
<p>To get a flattened version, use <code>.ravel()</code> method -</p>
<pre><code>arr[...,n].ravel()
</code></pre>
<p>Sample run -</p>
<pre><code>In [317]: arr
Out[317]:
array([[[[2, 1, 2],
[0, 2, 3],
[1, 0, 1]],
[[0, 2, 0],
[3, 1, 2],
[3, 3, 1]]],
[[[2, 0, 0],
[0, 2, 3],
[3, 3, 1]],
[[2, 0, 1],
[2, 3, 0],
[3, 3, 2]]]])
In [318]: arr[...,2].ravel()
Out[318]: array([2, 3, 1, 0, 2, 1, 0, 3, 1, 1, 0, 2])
</code></pre>
| 7 | 2016-07-23T15:59:54Z | [
"python",
"numpy"
] |
slicing numpy array to get nth column | 38,543,660 | <p>Having the example array below, how do you slice by column to get the following (e.g. 3rd column) <code>[0, 0, ..., 1338, 1312, 1502, 0, ...]</code>
Looking for the most efficient way, thanks!</p>
<pre><code>>>> r
array([[[ 0, 0, 0],
[ 0, 0, 0],
[ 0, 0, 0],
[ 0, 0, 0],
[ 0, 0, 0],
[ 0, 0, 0]],
[[ 0, 0, 1338],
[ 0, 0, 1312],
[ 0, 0, 1502],
[ 0, 0, 0],
[ 0, 0, 0],
[ 0, 0, 0]],
[[ 0, 0, 1400],
[ 0, 0, 1277],
[ 0, 0, 1280],
[ 0, 0, 0],
[ 0, 0, 0],
[ 0, 0, 0]]], dtype=uint16)
</code></pre>
| 1 | 2016-07-23T15:55:36Z | 38,543,734 | <p>Numpy supports the "semicolon notation" like matlab.
In your case you should be able to take the third column by doing:<br>
<code>x = r[:,:,2]</code> <br> and then <br>
<code>a = numpy.concatenate([x[0],x[1],x[2]])</code></p>
| 3 | 2016-07-23T16:04:48Z | [
"python",
"numpy"
] |
List comprehension: Multiply each string to a single list | 38,543,703 | <p>I have a list of strings and want to get a new list consisting on each element a number of times.</p>
<pre><code>lst = ['abc', '123']
n = 3
</code></pre>
<p>I can do that with a for loop:</p>
<pre><code>res = []
for i in lst:
res = res + [i]*n
print( res )
['abc', 'abc', 'abc', '123', '123', '123']
</code></pre>
<p><strong>How do I do it with list comprehension?</strong></p>
<p>My best try so far:</p>
<pre><code>[ [i]*n for i in ['abc', '123'] ]
[['abc', 'abc', 'abc'], ['123', '123', '123']]
</code></pre>
| 0 | 2016-07-23T16:01:25Z | 38,543,715 | <p>Use a <a href="https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions">nested list comprehension</a></p>
<pre><code>>>> lst = ['abc', '123']
>>> n = 3
>>> [i for i in lst for j in range(n)]
['abc', 'abc', 'abc', '123', '123', '123']
</code></pre>
<p>The idea behind this is, you loop through the list twice and you print each of the element thrice. </p>
<p>See the <a class='doc-link' href="http://stackoverflow.com/documentation/python/196/comprehensions/2655/list-comprehensions-with-nested-loops#t=201607231604160889023">documentation</a> for more examples and details. Also see <a href="http://stackoverflow.com/q/34835951/4099593">What does "list comprehension" in Python mean? How does it work and how can I use it?</a></p>
| 6 | 2016-07-23T16:03:05Z | [
"python",
"list",
"python-3.x",
"list-comprehension"
] |
List comprehension: Multiply each string to a single list | 38,543,703 | <p>I have a list of strings and want to get a new list consisting on each element a number of times.</p>
<pre><code>lst = ['abc', '123']
n = 3
</code></pre>
<p>I can do that with a for loop:</p>
<pre><code>res = []
for i in lst:
res = res + [i]*n
print( res )
['abc', 'abc', 'abc', '123', '123', '123']
</code></pre>
<p><strong>How do I do it with list comprehension?</strong></p>
<p>My best try so far:</p>
<pre><code>[ [i]*n for i in ['abc', '123'] ]
[['abc', 'abc', 'abc'], ['123', '123', '123']]
</code></pre>
| 0 | 2016-07-23T16:01:25Z | 38,544,066 | <p>It can also be done as:</p>
<pre><code>>>> lst = ['abc', '123']
>>> n=3
>>> [j for i in lst for j in (i,)*n]
['abc', 'abc', 'abc', '123', '123', '123']
</code></pre>
| 1 | 2016-07-23T16:37:56Z | [
"python",
"list",
"python-3.x",
"list-comprehension"
] |
Count lines of code in directory using Python | 38,543,709 | <p>I have a project whose lines of code I want to count. Is it possible to count all the lines of code in the file directory containing the project by using Python?</p>
| 0 | 2016-07-23T16:02:40Z | 38,543,710 | <pre><code>from os import listdir
from os.path import isfile, join
def countLinesInPath(path,directory):
count=0
for line in open(join(directory,path), encoding="utf8"):
count+=1
return count
def countLines(paths,directory):
count=0
for path in paths:
count=count+countLinesInPath(path,directory)
return count
def getPaths(directory):
return [f for f in listdir(directory) if isfile(join(directory, f))]
def countIn(directory):
return countLines(getPaths(directory),directory)
</code></pre>
<p>To count all the lines of code in the files in a directory, call the "countIn" function, passing the directory as a parameter.</p>
| 1 | 2016-07-23T16:02:40Z | [
"python",
"lines-of-code"
] |
wxpython: closing application does not close the progress bar | 38,543,721 | <p>I have an app that retrieves data from a SQL server. I include a progress bar to show the progress. </p>
<p>However, the problem is that when I try to close the application by clicking the "x" at the top right corner of the application window, the application's main window will close, but the progress bar will continue to run, until all the work with the SQL server is finished. </p>
<p><strong>I wonder if there is a way to terminate everything when clicking "x".</strong> A sample code (minus the part that does the data retrieval from SQL server) is below:</p>
<pre><code>import wx, pyodbc
class App(wx.Frame):
def __init__(self, parent, title):
super(App, self).__init__(parent, title=title, size=(600, 400))
#-----------------------------------------------------------
self.Bind(wx.EVT_CLOSE, self.OnExit) # ADDED
#-----------------------------------------------------------
p = wx.Panel(self)
nb = wx.Notebook(p)
self.Panel1 = PanelMaker(nb, 'Foo')
nb.AddPage(self.Panel1, "Foo")
sizer = wx.BoxSizer()
sizer.Add(nb, 1, wx.EXPAND)
p.SetSizer(sizer)
self.Centre()
#-----------------------------------------------------------
def OnExit(self, evt): #ADDED
self.Destroy()
#self.Close() #I tried self.Close(), but I could not even
#close the application window when using it.
#-----------------------------------------------------------
class ProgressBar(wx.Frame):
def __init__(self, parent):
wx.Frame.__init__(self, parent, title="In progress...", size=(300, 90), style = wx.FRAME_FLOAT_ON_PARENT)
GridBagSizer = wx.GridBagSizer()
self.gauge = wx.Gauge(self, range = 100, size = (-1, 30), style = wx.GA_HORIZONTAL, name = 'In Progress')
self.gauge.SetValue(0)
txt = wx.StaticText(self, label = 'Hamsters are working very hard to move data', style = wx.ALIGN_CENTER)
GridBagSizer.Add(self.gauge, pos = (0, 0), span = (1, 1), flag = wx.EXPAND|wx.ALL, border = 15)
GridBagSizer.Add(txt, pos = (1, 0), span = (1, 1), flag = wx.ALL, border = 15)
self.SetSizer(GridBagSizer)
self.Layout()
def Update(self, step):
self.gauge.SetValue(step)
if step == 100:
self.Close()
class PanelMaker(wx.Panel):
def __init__(self, parent, tool):
wx.Panel.__init__(self, parent = parent)
Panel1Sizer = wx.GridBagSizer(0, 10)
ProceedButton = wx.Button(self, label = tool, size = (-1, -1))
ProceedButton.Bind(wx.EVT_BUTTON, self.OnProceedButton)
Panel1Sizer.Add(ProceedButton, pos = (7, 0), span = (1, 1), flag = wx.EXPAND|wx.LEFT, border = 12)
Panel1Sizer.Layout()
self.SetSizer(Panel1Sizer)
def OnProceedButton(self, evt):
Progbar = ProgressBar(self.GetParent())
Progbar.Show()
connection = pyodbc.connect(DRIVER = '{SQL Server}',
SERVER = ServerName,
DATABASE = DatabaseName,
Trusted_Connection = True)
cursor = connection.cursor()
for i in range(100):
#retrieve data from the SQL server.......
wx.Yield()
Progbar.Update(i+1)
#Closing SQL connection
cursor.close()
del cursor
connection.close()
</code></pre>
| 0 | 2016-07-23T16:03:31Z | 38,543,960 | <p>Yes, bind the close event.</p>
<pre><code>self.Bind(wx.EVT_CLOSE, self.OnExit)
</code></pre>
<p>Also, I don't see you closing the database connection or a <code>self.Destroy()</code></p>
| 0 | 2016-07-23T16:28:53Z | [
"python",
"wxpython",
"progress-bar"
] |
Django: duplicate key value violates unique constraint | 38,543,752 | <p>I have a Joke model:</p>
<pre><code>class Joke(models.Model):
...
date_created = models.DateTimeField(default=datetime.now, blank=True)
date_modified = models.DateTimeField(default=datetime.now, blank=True)
creator = models.OneToOneField(User, default=1)
</code></pre>
<p>Now, when I try to migrate the last line I get errors. Basically, I want to link a User to the Joke object, and since I already have a database, I want the default value to be 1, which is the admin user's id(I checked...). Makemigrations works just fine but when I try to migrate, I get this:</p>
<pre><code>Operations to perform:
Apply all migrations: jokes_app, sessions, contenttypes, auth, taggit, default, admin
Running migrations:
Rendering model states... DONE
Applying jokes_app.0008_auto_20160723_1559...Traceback (most recent call last):
File "/home/antoni4040/Documents/Jokes_Website/django-jokes/venv/lib/python3.4/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
psycopg2.IntegrityError: duplicate key value violates unique constraint "jokes_app_joke_creator_id_key"
DETAIL: Key (creator_id)=(1) already exists.
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "./manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/home/antoni4040/Documents/Jokes_Website/django-jokes/venv/lib/python3.4/site-packages/django/core/management/__init__.py", line 353, in execute_from_command_line
utility.execute()
File "/home/antoni4040/Documents/Jokes_Website/django-jokes/venv/lib/python3.4/site-packages/django/core/management/__init__.py", line 345, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/antoni4040/Documents/Jokes_Website/django-jokes/venv/lib/python3.4/site-packages/django/core/management/base.py", line 348, in run_from_argv
self.execute(*args, **cmd_options)
File "/home/antoni4040/Documents/Jokes_Website/django-jokes/venv/lib/python3.4/site-packages/django/core/management/base.py", line 399, in execute
output = self.handle(*args, **options)
File "/home/antoni4040/Documents/Jokes_Website/django-jokes/venv/lib/python3.4/site-packages/django/core/management/commands/migrate.py", line 200, in handle
executor.migrate(targets, plan, fake=fake, fake_initial=fake_initial)
File "/home/antoni4040/Documents/Jokes_Website/django-jokes/venv/lib/python3.4/site-packages/django/db/migrations/executor.py", line 92, in migrate
self._migrate_all_forwards(plan, full_plan, fake=fake, fake_initial=fake_initial)
File "/home/antoni4040/Documents/Jokes_Website/django-jokes/venv/lib/python3.4/site-packages/django/db/migrations/executor.py", line 121, in _migrate_all_forwards
state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)
File "/home/antoni4040/Documents/Jokes_Website/django-jokes/venv/lib/python3.4/site-packages/django/db/migrations/executor.py", line 198, in apply_migration
state = migration.apply(state, schema_editor)
File "/home/antoni4040/Documents/Jokes_Website/django-jokes/venv/lib/python3.4/site-packages/django/db/migrations/migration.py", line 123, in apply
operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
File "/home/antoni4040/Documents/Jokes_Website/django-jokes/venv/lib/python3.4/site-packages/django/db/migrations/operations/fields.py", line 201, in database_forwards
schema_editor.alter_field(from_model, from_field, to_field)
File "/home/antoni4040/Documents/Jokes_Website/django-jokes/venv/lib/python3.4/site-packages/django/db/backends/base/schema.py", line 482, in alter_field
old_db_params, new_db_params, strict)
File "/home/antoni4040/Documents/Jokes_Website/django-jokes/venv/lib/python3.4/site-packages/django/db/backends/postgresql/schema.py", line 110, in _alter_field
new_db_params, strict,
File "/home/antoni4040/Documents/Jokes_Website/django-jokes/venv/lib/python3.4/site-packages/django/db/backends/base/schema.py", line 644, in _alter_field
[new_default],
File "/home/antoni4040/Documents/Jokes_Website/django-jokes/venv/lib/python3.4/site-packages/django/db/backends/base/schema.py", line 110, in execute
cursor.execute(sql, params)
File "/home/antoni4040/Documents/Jokes_Website/django-jokes/venv/lib/python3.4/site-packages/django/db/backends/utils.py", line 79, in execute
return super(CursorDebugWrapper, self).execute(sql, params)
File "/home/antoni4040/Documents/Jokes_Website/django-jokes/venv/lib/python3.4/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "/home/antoni4040/Documents/Jokes_Website/django-jokes/venv/lib/python3.4/site-packages/django/db/utils.py", line 95, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/home/antoni4040/Documents/Jokes_Website/django-jokes/venv/lib/python3.4/site-packages/django/utils/six.py", line 685, in reraise
raise value.with_traceback(tb)
File "/home/antoni4040/Documents/Jokes_Website/django-jokes/venv/lib/python3.4/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
django.db.utils.IntegrityError: duplicate key value violates unique constraint "jokes_app_joke_creator_id_key"
DETAIL: Key (creator_id)=(1) already exists.
</code></pre>
<p>I really don't understand what's wrong. Any ideas?</p>
| 0 | 2016-07-23T16:06:58Z | 38,543,873 | <p>OneToOne field enforces, as it's name says, an one-to-one relationship, which in your case means that one user can be creator of one and only one joke - definitely not what you want. Use <a href="https://docs.djangoproject.com/en/1.9/ref/models/fields/#foreignkey" rel="nofollow">ForeignKey</a> instead:</p>
<pre><code> creator = models.ForeignKey(User, default=1, on_delete=models.SET_DEFAULT)
</code></pre>
| 2 | 2016-07-23T16:18:57Z | [
"python",
"django",
"postgresql",
"one-to-one"
] |
How to use PowerShell to set some primitive files? | 38,543,786 | <p>I've been doing "learn python the hard way" ex46 to make a skeleton of project, and I am confused about how to set the primitive files using Windows PowerShell. These are the instructions:</p>
<pre><code>new-item -type file NAME/_init_.py
</code></pre>
<p>I typed that into PowerShell but I get an error.</p>
| -1 | 2016-07-23T16:09:52Z | 38,543,950 | <p>You didn't follow the instructions. You need to create the directory <code>NAME</code> first before you can create a file inside it.</p>
<p>Quoting from the <a href="http://learnpythonthehardway.org/book/ex46.html" rel="nofollow">exercise in question</a> (emphasis mine):</p>
<blockquote>
<p>First, create the structure of your skeleton directory with these commands:</p>
<pre>$ mkdir projects
$ cd projects/
$ mkdir skeleton
$ cd skeleton
$ <b>mkdir bin NAME tests docs</b></pre>
</blockquote>
| 1 | 2016-07-23T16:27:33Z | [
"python",
"powershell"
] |
Pandas join dataframes by multiple key | 38,543,800 | <p>I have 3 different dataframes that I want to join, using label and window as keys.</p>
<p>DataFrame1</p>
<pre><code>Window Label FeatA
123 1 h
123 2 f
</code></pre>
<p>DataFrame2</p>
<pre><code>Window Label FeatB
123 1 d
123 2 s
</code></pre>
<p>DataFrame3</p>
<pre><code>Window Label FeatC
123 1 d
123 2 c
</code></pre>
<p>Result</p>
<pre><code>Window Label FeatA FeatB FeatC
123 1 h d d
123 2 f s c
</code></pre>
<p>I know how to join dataframes using <code>pandas.concat</code> but don't know how to specify keys. Any help would be greatly appreciated.</p>
| 3 | 2016-07-23T16:11:26Z | 38,544,019 | <p>You need to use the <code>merge</code> function for joining tables, for your case, since you have multiple data frames to join, you can put them into a list and then use the <code>reduce</code> from <code>functools</code> to merge them one by one: </p>
<pre><code>import pandas as pd
from functools import reduce
reduce(lambda x, y: pd.merge(x, y, on = ['Window', 'Label']), [df1, df2, df3])
# Window Label FeatA FeatB FeatC
# 0 123 1 h d d
# 1 123 2 f s c
</code></pre>
| 3 | 2016-07-23T16:33:47Z | [
"python",
"pandas"
] |
Pandas join dataframes by multiple key | 38,543,800 | <p>I have 3 different dataframes that I want to join, using label and window as keys.</p>
<p>DataFrame1</p>
<pre><code>Window Label FeatA
123 1 h
123 2 f
</code></pre>
<p>DataFrame2</p>
<pre><code>Window Label FeatB
123 1 d
123 2 s
</code></pre>
<p>DataFrame3</p>
<pre><code>Window Label FeatC
123 1 d
123 2 c
</code></pre>
<p>Result</p>
<pre><code>Window Label FeatA FeatB FeatC
123 1 h d d
123 2 f s c
</code></pre>
<p>I know how to join dataframes using <code>pandas.concat</code> but don't know how to specify keys. Any help would be greatly appreciated.</p>
| 3 | 2016-07-23T16:11:26Z | 38,548,114 | <p>you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.combine_first.html" rel="nofollow">combine_first</a>:</p>
<pre><code>In[44]:df.combine_first(df1).combine_first(df2)[['Window','Label','FeatA','FeatB','FeatC']]
Out[44]:
Window Label FeatA FeatB FeatC
0 123 1 h d d
1 123 2 f s c
</code></pre>
<p>or you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.merge.html" rel="nofollow">merge</a>:</p>
<pre><code>In[30]:df.merge(df1,on=['Window','Label']).merge(df2,on=['Window','Label'])
Out[30]:
Window Label FeatA FeatB FeatC
0 123 1 h d d
1 123 2 f s c
</code></pre>
| 1 | 2016-07-24T02:10:32Z | [
"python",
"pandas"
] |
Pandas join dataframes by multiple key | 38,543,800 | <p>I have 3 different dataframes that I want to join, using label and window as keys.</p>
<p>DataFrame1</p>
<pre><code>Window Label FeatA
123 1 h
123 2 f
</code></pre>
<p>DataFrame2</p>
<pre><code>Window Label FeatB
123 1 d
123 2 s
</code></pre>
<p>DataFrame3</p>
<pre><code>Window Label FeatC
123 1 d
123 2 c
</code></pre>
<p>Result</p>
<pre><code>Window Label FeatA FeatB FeatC
123 1 h d d
123 2 f s c
</code></pre>
<p>I know how to join dataframes using <code>pandas.concat</code> but don't know how to specify keys. Any help would be greatly appreciated.</p>
| 3 | 2016-07-23T16:11:26Z | 38,548,213 | <p>A pure pandas answer using <code>pd.concat</code></p>
<pre><code>pd.concat([df.set_index(['Window', 'Label']) for df in [df1_, df2_, df3_]],
axis=1).reset_index()
</code></pre>
<p><a href="http://i.stack.imgur.com/C0WOv.png" rel="nofollow"><img src="http://i.stack.imgur.com/C0WOv.png" alt="enter image description here"></a></p>
| 3 | 2016-07-24T02:31:20Z | [
"python",
"pandas"
] |
Efficiency of using subprocess in conjunction with threads, in Python | 38,543,836 | <p>I am using Python 2.7. I have a multi-threaded program where the threads launch commands using the <code>subprocess</code> module. The processes run on the system and report data occasionally to the threads. The majority of the work is done in the processes - the threads just take information from the processes and write them to a file, for example.</p>
<p>I understand that there are limitations on using multithreading with python. But in this case, I expect that all the heavy lifting will be done by the system (Linux), because the subprocesses launched are doing the CPU-intensive stuff. So the threads don't have to carry any load, and therefore should not be a bottleneck.</p>
<p>Is my understanding of using threads and subprocesses together in Python accurate? I think a foundational part of my understanding is that these different subprocesses can run on different cores, so even if the threads are bound to one core, the processes will run efficiently, and the threads can collect information from them as it becomes available.</p>
| 0 | 2016-07-23T16:14:44Z | 38,543,963 | <p>Why not have the subprocesses just handle the data processing themselves? Passing stuff back to the process requires extra <a href="https://en.wikipedia.org/wiki/Context_switch" rel="nofollow">context switches</a> and the overhead of serialisation and deserialisation, which can become significant if you have a lot of work to pass back to the main process. It might be easier to use threads in the subprocesses rather than pay this penalty.</p>
<p>There is something important to note, however. Although I/O-bound code (file writes, sending and receiving data on a socket, etc.) won't run into bottlenecks with the Global Interpreter Lock, CPU-bound tasks will. See <a href="http://jessenoller.com/blog/2009/02/01/python-threads-and-the-global-interpreter-lock" rel="nofollow">Jesse Noller's blog post on threads</a> and <a href="https://wiki.python.org/moin/GlobalInterpreterLock" rel="nofollow">the Python Wiki's article on the GIL</a> for more information about threading issues.</p>
| 0 | 2016-07-23T16:29:18Z | [
"python",
"multithreading",
"subprocess"
] |
Tensorflow: How to Display Custom Images in Tensorboard (e.g. Matplotlib Plots) | 38,543,850 | <p>The <a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/tensorboard/README.md#image-dashboard" rel="nofollow">Image Dashboard</a> section of the Tensorboard ReadMe says:</p>
<blockquote>
<p>Since the image dashboard supports arbitrary pngs, you can use this to embed custom visualizations (e.g. matplotlib scatterplots) into TensorBoard.</p>
</blockquote>
<p>I see how a pyplot image could be written to file, read back in as a tensor, and then used with tf.image_summary() to write it to TensorBoard, but this statement from the readme suggests there is a more direct way. Is there? If so, is there any further documentation and/or examples of how to do this efficiently? </p>
| 3 | 2016-07-23T16:15:43Z | 38,676,842 | <p>It is quite easy to do if you have the image in a memory buffer. Below, I show an example, where a pyplot is saved to a buffer and then converted to a TF image representation which is then sent to an image summary.</p>
<pre><code>import io
import matplotlib.pyplot as plt
import tensorflow as tf
def gen_plot():
"""Create a pyplot plot and save to buffer."""
plt.figure()
plt.plot([1, 2])
plt.title("test")
buf = io.BytesIO()
plt.savefig(buf, format='png')
buf.seek(0)
return buf
# Prepare the plot
plot_buf = gen_plot()
# Convert PNG buffer to TF image
image = tf.image.decode_png(plot_buf.getvalue(), channels=4)
# Add the batch dimension
image = tf.expand_dims(image, 0)
# Add image summary
summary_op = tf.image_summary("plot", image)
# Session
with tf.Session() as sess:
# Run
summary = sess.run(summary_op)
# Write summary
writer = tf.train.SummaryWriter('./logs')
writer.add_summary(summary)
writer.close()
</code></pre>
<p>This gives the following TensorBoard visualization:</p>
<p><a href="http://i.stack.imgur.com/ARU43.png" rel="nofollow"><img src="http://i.stack.imgur.com/ARU43.png" alt="enter image description here"></a></p>
| 3 | 2016-07-30T17:51:10Z | [
"python",
"matplotlib",
"tensorflow",
"tensorboard"
] |
how to generate different color images according to one image in java or python? | 38,543,898 | <p>I want to generate some images in different color according to one image.But I couldn't find some resources about this.Could you recommand some useful reference material about how to implement by using java or python.</p>
<p>for example,the images below is generated from one image.
<a href="http://i.stack.imgur.com/Wpc5u.png" rel="nofollow"><img src="http://i.stack.imgur.com/Wpc5u.png" alt="enter image description here"></a></p>
| 1 | 2016-07-23T16:20:54Z | 38,544,018 | <p>In Python, you can take the help of the Image module to do this stuff.</p>
<p>For example - </p>
<pre><code>import Image
picture = Image.open("/path/to/my/picture.jpg")
r,g,b = picture.getpixel( (0,0) )
print("Red: {0}, Green: {1}, Blue: {2}".format(r,g,b))
</code></pre>
<p>This above code will give you information about the pixel at (0,0)</p>
<pre><code>import Image
picture = Image.open("/path/to/my/picture.jpg")
# Get the size of the image
width, height = picture.size()
# Process every pixel
for x in width:
for y in height:
# get pixel color
current_color = picture.getpixel( (x,y) )
# your main logic here to choose new color
# put the new color on the pixel
picture.putpixel( (x,y), new_color)
</code></pre>
| 0 | 2016-07-23T16:33:44Z | [
"java",
"python",
"image",
"image-processing"
] |
how to create and append multiple rows using two loops in python | 38,543,952 | <p>i need to create a dataframe such that i have the output as follows</p>
<pre><code>day hour cal_hr
1 6 106
1 7 107
1 8 108
..
..
1 24 124
..
7 1 701
7 2 702
..
..
7 24 724
</code></pre>
<p>i want to loop through day and then hour and then do a concat of day and hour. With preceding 0 for 106(say)</p>
<p>something like</p>
<pre><code>for i in range(1,8):
for j in range(6,25):
df.append(i,j)
df=pd.dataFrame(df)
</code></pre>
<p>can df.append create two variables simaltaneously</p>
| 1 | 2016-07-23T16:27:42Z | 38,544,005 | <p>Append to a list then convert to a dataframe. It would be much more efficient.</p>
<pre><code>df = pd.DataFrame([(i, j, 100*i+j)
for i in range(1, 8)
for j in range(6, 25)],
columns=['day', 'hour', 'cal_hr'])
df.head()
Out[143]:
day hour cal_hr
0 1 6 106
1 1 7 107
2 1 8 108
3 1 9 109
4 1 10 110
df.tail()
Out[144]:
day hour cal_hr
128 7 20 720
129 7 21 721
130 7 22 722
131 7 23 723
132 7 24 724
</code></pre>
| 4 | 2016-07-23T16:33:09Z | [
"python",
"python-3.x",
"pandas"
] |
how to create and append multiple rows using two loops in python | 38,543,952 | <p>i need to create a dataframe such that i have the output as follows</p>
<pre><code>day hour cal_hr
1 6 106
1 7 107
1 8 108
..
..
1 24 124
..
7 1 701
7 2 702
..
..
7 24 724
</code></pre>
<p>i want to loop through day and then hour and then do a concat of day and hour. With preceding 0 for 106(say)</p>
<p>something like</p>
<pre><code>for i in range(1,8):
for j in range(6,25):
df.append(i,j)
df=pd.dataFrame(df)
</code></pre>
<p>can df.append create two variables simaltaneously</p>
| 1 | 2016-07-23T16:27:42Z | 38,548,159 | <p>This isn't as fast or as intuitive as @ayhan's answer, but I think it's an interesting way to think about it.</p>
<pre><code>day = pd.Series(np.arange(1, 8), name='day')
hour = pd.Series(np.arange(6, 25), name='hour')
df = pd.DataFrame(np.add.outer(day * 100, hour), day, hour)
df = df.stack().rename('cal_hr').reset_index()
</code></pre>
<hr>
<pre><code>df.head()
</code></pre>
<p><a href="http://i.stack.imgur.com/xwsC3.png" rel="nofollow"><img src="http://i.stack.imgur.com/xwsC3.png" alt="enter image description here"></a></p>
<pre><code>df.tail()
</code></pre>
<p><a href="http://i.stack.imgur.com/fA201.png" rel="nofollow"><img src="http://i.stack.imgur.com/fA201.png" alt="enter image description here"></a></p>
| 2 | 2016-07-24T02:19:13Z | [
"python",
"python-3.x",
"pandas"
] |
I have a list of strings (html codes) and I want to extract all the emails in each of the string of my list | 38,543,989 | <p>I have a list of strings:</p>
<pre><code>urls = ["url1","url2","url3"]
</code></pre>
<p>in order to generate another list of strings:</p>
<pre><code>for i in range (0,2):
htmlist = [urllib.urlopen(url[i]).read() for i in range(0,2) ]
</code></pre>
<p>When I try to extract the emails from the texts htmlist[i] with this code:</p>
<pre><code>for i in range (0,2) :
emails = re.findall(r'[\w\.-]+@[\w\.-]+', htmlist[i])
print emails
</code></pre>
<p>the code only print emails in <code>htmlist[2]</code></p>
<p>Could you help me?
Thanks</p>
| 0 | 2016-07-23T16:31:40Z | 38,544,039 | <p>That's because <code>emails</code> takes the value of the last iteration (at <code>htmlist[2]</code>). Move the print statement into the <code>for</code> loop to see <code>emails</code> at each iteration:</p>
<pre><code>for i in range (0, 3) :
emails = re.findall(r'[\w\.-]+@[\w\.-]+', htmlist[i])
print emails
</code></pre>
<hr>
<p>More so, the first iteration does not require <code>range</code> since you already have a list comprehension. You only need to change the stop index to <code>3</code>, so you have <code>htmmlist[0]</code>, <code>htmmlist[1]</code> and <code>htmmlist[2]</code>:</p>
<pre><code>htmlist = [urllib.urlopen(url[i]).read() for i in range(0,3)]
# ^
</code></pre>
<p>Using <code>range</code> only repeats the initial iteration for as long the for loop runs. <code>htmlist</code> will only the last value from the loop. So the list comprehension is sufficient.</p>
<hr>
<p>You can also use a list comprehension to keep all the emails from each url in a list:</p>
<pre><code>htmlist = [urllib.urlopen(url[i]).read() for i in range(0,3)]
emails = [re.findall(r'[\w\.-]+@[\w\.-]+', htmlist[i]) for i in range(0,3)]
print emails
</code></pre>
| 0 | 2016-07-23T16:35:03Z | [
"python",
"string",
"text"
] |
How to position a borderless window in Kivy | 38,544,254 | <p>I was making an app with Kivy in python, and to make things a tad more stylish, I thought I could remove the border on the window and create by own:</p>
<pre><code>from kivy.config import Config
from kivy.core.window import Window
Window.size = (900,550)
Window.borderless = True
Config.set('graphics','resizable',0)
</code></pre>
<p>However the border less window will pop up in the very bottom left corner of my screen. Is there anyway I can position the window so its in the middle of my screen?</p>
<p>If I can't do that, then is there a way to remove the rounded corners on a window?</p>
<p>(I am doing this on a Mac OSX Yosemite)</p>
| 0 | 2016-07-23T16:54:38Z | 38,669,304 | <p>Borderless:</p>
<pre><code>from kivy.config import Config
Config.set('graphics','borderless',1)
Config.set('graphics','resizable',0)
</code></pre>
<p><em>at the top</em> of your file before anything else. Just the core(Window) will remain.</p>
<p>Position:</p>
<pre><code>Config.set('graphics','position','custom')
Config.set('graphics','left',500)
Config.set('graphics','top',10)
</code></pre>
<p>the same condition applies for all <a href="https://kivy.org/docs/api-kivy.config.html#available-configuration-tokens" rel="nofollow"><code>Config.set()</code></a>.</p>
| 0 | 2016-07-30T00:45:28Z | [
"python",
"python-3.x",
"window",
"kivy",
"borderless"
] |
python remove elements of list from another list WITH MULTIPLE OCCURRENCES of items in both | 38,544,296 | <p>Related to: <a href="http://stackoverflow.com/questions/4211209/remove-all-the-elements-that-occur-in-one-list-from-another">Remove all the elements that occur in one list from another</a></p>
<p>I have listA <code>[1, 1, 3, 5, 5, 5, 7]</code> and listB <code>[1, 2, 5, 5, 7]</code> and I want to subtract <em>occurrences</em> of items from listA. The result should be a new list: <code>[1, 3, 5]</code>
Note:</p>
<ol>
<li><code>1</code> had 2 occurrences in listA and once in listB, now it appears 2-1=1 times</li>
<li><code>2</code> did not appear in listA, so nothing happens</li>
<li><code>3</code> stays with 1 occurrence, as its not in listB</li>
<li><code>5</code> occurred 3 times in listA and 2 in listB, so now it occurs 3-2=1 times</li>
<li><code>7</code> occurred once in listA and once in listB, so now it will appear 1-1=0 times</li>
</ol>
<p>Does this make sense? </p>
| 1 | 2016-07-23T16:58:17Z | 38,544,362 | <p>In cases like these a list comprehension should always be used:</p>
<pre><code>listA = [1, 1, 3, 5, 5, 5, 7]
listB = [1, 2, 5, 5, 7]
newList = [i for i in listA if i not in listB or listB.remove(i)]
print (newList)
</code></pre>
<p>Here are the results:</p>
<p><code>[1, 3, 5]</code></p>
| 1 | 2016-07-23T17:04:14Z | [
"python",
"list"
] |
python remove elements of list from another list WITH MULTIPLE OCCURRENCES of items in both | 38,544,296 | <p>Related to: <a href="http://stackoverflow.com/questions/4211209/remove-all-the-elements-that-occur-in-one-list-from-another">Remove all the elements that occur in one list from another</a></p>
<p>I have listA <code>[1, 1, 3, 5, 5, 5, 7]</code> and listB <code>[1, 2, 5, 5, 7]</code> and I want to subtract <em>occurrences</em> of items from listA. The result should be a new list: <code>[1, 3, 5]</code>
Note:</p>
<ol>
<li><code>1</code> had 2 occurrences in listA and once in listB, now it appears 2-1=1 times</li>
<li><code>2</code> did not appear in listA, so nothing happens</li>
<li><code>3</code> stays with 1 occurrence, as its not in listB</li>
<li><code>5</code> occurred 3 times in listA and 2 in listB, so now it occurs 3-2=1 times</li>
<li><code>7</code> occurred once in listA and once in listB, so now it will appear 1-1=0 times</li>
</ol>
<p>Does this make sense? </p>
| 1 | 2016-07-23T16:58:17Z | 38,544,430 | <p>Here is a non list comprehension version for those new to Python</p>
<pre><code>listA = [1, 1, 3, 5, 5, 5, 7]
listB = [1, 2, 5, 5, 7]
for i in listB:
if i in listA:
listA.remove(i)
print listA
</code></pre>
| 3 | 2016-07-23T17:09:55Z | [
"python",
"list"
] |
Filter data with groupby in pandas | 38,544,301 | <p>I have a DataFrame where I have the following data. Here each row represents a word appearing in each episode of a TV series. Now if a word appears 3 times in an episode, the padas dataframe ahs 3 rows. Now I need to filter a list of words such that I should only get only words which appear more than or equal tp 2 times. I can do this by <code>groupby</code>, but if a word appears 2 (or say 3,4 or 5)times, I need two (3, 4 or 5) rows for it.</p>
<p>By groupby, I will only get the unique entry and count, but I need the entry to rpereat as many times as it appears in the dialogue. Is there a one-liner to do this?</p>
<pre><code> dialogue episode
0 music 1
1 corrections 1
2 somnath 1
3 yadav 5
4 join 2
5 instagram 1
6 wind 2
7 music 1
8 whimpering 2
9 music 1
10 wind 3
</code></pre>
<p>SO here I should ideally get, </p>
<pre><code> dialogue episode
0 music 1
6 wind 2
7 music 1
9 music 1
10 wind 3
</code></pre>
<p>As, these are the only 2 words that appears more than or equal to 2 times. </p>
| 3 | 2016-07-23T16:59:13Z | 38,544,486 | <p><strong>Answer for the updated question:</strong></p>
<pre><code>In [208]: df.groupby('dialogue')['episode'].transform('size') >= 3
Out[208]:
0 True
1 False
2 False
3 False
4 False
5 False
6 False
7 True
8 False
9 True
10 False
dtype: bool
In [209]: df[df.groupby('dialogue')['episode'].transform('size') >= 3]
Out[209]:
dialogue episode
0 music 1
7 music 1
9 music 1
</code></pre>
<p><strong>Answer for the original question:</strong></p>
<p>you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.duplicated.html" rel="nofollow">duplicated()</a> method:</p>
<pre><code>In [202]: df[df.duplicated(subset=['dialogue'], keep=False)]
Out[202]:
dialogue episode
0 music 1
6 wind 2
7 music 1
9 music 1
10 wind 3
</code></pre>
<p>if you want to sort the result:</p>
<pre><code>In [203]: df[df.duplicated(subset=['dialogue'], keep=False)].sort_values('dialogue')
Out[203]:
dialogue episode
0 music 1
7 music 1
9 music 1
6 wind 2
10 wind 3
</code></pre>
| 4 | 2016-07-23T17:16:27Z | [
"python",
"pandas",
"dataframe"
] |
Filter data with groupby in pandas | 38,544,301 | <p>I have a DataFrame where I have the following data. Here each row represents a word appearing in each episode of a TV series. Now if a word appears 3 times in an episode, the padas dataframe ahs 3 rows. Now I need to filter a list of words such that I should only get only words which appear more than or equal tp 2 times. I can do this by <code>groupby</code>, but if a word appears 2 (or say 3,4 or 5)times, I need two (3, 4 or 5) rows for it.</p>
<p>By groupby, I will only get the unique entry and count, but I need the entry to rpereat as many times as it appears in the dialogue. Is there a one-liner to do this?</p>
<pre><code> dialogue episode
0 music 1
1 corrections 1
2 somnath 1
3 yadav 5
4 join 2
5 instagram 1
6 wind 2
7 music 1
8 whimpering 2
9 music 1
10 wind 3
</code></pre>
<p>SO here I should ideally get, </p>
<pre><code> dialogue episode
0 music 1
6 wind 2
7 music 1
9 music 1
10 wind 3
</code></pre>
<p>As, these are the only 2 words that appears more than or equal to 2 times. </p>
| 3 | 2016-07-23T16:59:13Z | 38,544,851 | <p>You can use groupby's <a href="http://pandas.pydata.org/pandas-docs/stable/groupby.html#filtration"><code>filter</code></a>:</p>
<pre><code>In [11]: df.groupby("dialogue").filter(lambda x: len(x) > 1)
Out[11]:
dialogue episode
0 music 1
6 wind 2
7 music 1
9 music 1
10 wind 3
</code></pre>
| 5 | 2016-07-23T17:52:52Z | [
"python",
"pandas",
"dataframe"
] |
Filter data with groupby in pandas | 38,544,301 | <p>I have a DataFrame where I have the following data. Here each row represents a word appearing in each episode of a TV series. Now if a word appears 3 times in an episode, the padas dataframe ahs 3 rows. Now I need to filter a list of words such that I should only get only words which appear more than or equal tp 2 times. I can do this by <code>groupby</code>, but if a word appears 2 (or say 3,4 or 5)times, I need two (3, 4 or 5) rows for it.</p>
<p>By groupby, I will only get the unique entry and count, but I need the entry to rpereat as many times as it appears in the dialogue. Is there a one-liner to do this?</p>
<pre><code> dialogue episode
0 music 1
1 corrections 1
2 somnath 1
3 yadav 5
4 join 2
5 instagram 1
6 wind 2
7 music 1
8 whimpering 2
9 music 1
10 wind 3
</code></pre>
<p>SO here I should ideally get, </p>
<pre><code> dialogue episode
0 music 1
6 wind 2
7 music 1
9 music 1
10 wind 3
</code></pre>
<p>As, these are the only 2 words that appears more than or equal to 2 times. </p>
| 3 | 2016-07-23T16:59:13Z | 38,547,975 | <p>I'd use <code>value_counts</code></p>
<pre><code>vc = df.dialogue.value_counts() >= 2
vc = vc[vc]
df[df.dialogue.isin(vc.index)]
</code></pre>
<p><a href="http://i.stack.imgur.com/0EwfW.png" rel="nofollow"><img src="http://i.stack.imgur.com/0EwfW.png" alt="enter image description here"></a></p>
<hr>
<h3>Timing</h3>
<p>keep in mind, this is completely over the top. however, i'm sharpening up my timing skills.</p>
<p><strong>code</strong></p>
<pre><code>from timeit import timeit
def pirsquared(df):
vc = df.dialogue.value_counts() > 1
vc = vc[vc]
return df[df.dialogue.isin(vc.index)]
def maxu(df):
return df[df.groupby('dialogue')['episode'].transform('size') > 1]
def andyhayden(df):
return df.groupby("dialogue").filter(lambda x: len(x) > 1)
rows = ['pirsquared', 'maxu', 'andyhayden']
cols = ['OP_Given', '10000_3_letters']
summary = pd.DataFrame([], rows, cols)
iterations = 10
df = pd.DataFrame({'dialogue': {0: 'music', 1: 'corrections', 2: 'somnath', 3: 'yadav', 4: 'join', 5: 'instagram', 6: 'wind', 7: 'music', 8: 'whimpering', 9: 'music', 10: 'wind'}, 'episode': {0: 1, 1: 1, 2: 1, 3: 5, 4: 2, 5: 1, 6: 2, 7: 1, 8: 2, 9: 1, 10: 3}})
summary.loc['pirsquared', 'OP_Given'] = timeit(lambda: pirsquared(df), number=iterations)
summary.loc['maxu', 'OP_Given'] = timeit(lambda: maxu(df), number=iterations)
summary.loc['andyhayden', 'OP_Given'] = timeit(lambda: andyhayden(df), number=iterations)
df = pd.DataFrame(
pd.DataFrame(np.random.choice(list(lowercase), (10000, 3))).sum(1),
columns=['dialogue'])
df['episode'] = 1
summary.loc['pirsquared', '10000_3_letters'] = timeit(lambda: pirsquared(df), number=iterations)
summary.loc['maxu', '10000_3_letters'] = timeit(lambda: maxu(df), number=iterations)
summary.loc['andyhayden', '10000_3_letters'] = timeit(lambda: andyhayden(df), number=iterations)
summary
</code></pre>
<p><a href="http://i.stack.imgur.com/GzdPY.png" rel="nofollow"><img src="http://i.stack.imgur.com/GzdPY.png" alt="enter image description here"></a></p>
| 2 | 2016-07-24T01:39:59Z | [
"python",
"pandas",
"dataframe"
] |
conditionally print out lines in python | 38,544,476 | <p>I have a list of strings. I hope to print out the strings in the list that meet a condition. The list is as below:</p>
<pre><code>In [5]: L = ["John and Mary", "Leslie", "Iva and Mark Li"]
</code></pre>
<p>I hope to print out each of the strings in L that has an <code>and</code> in it --</p>
<pre><code>'John and Mary', 'Iva and Mark Li'
</code></pre>
<p>I have the following code:</p>
<pre><code>In [6]: def grep(pattern, line):
if pattern in line:
print line
In [7]: [grep("and", I) for I in L]
</code></pre>
<p>This returns</p>
<pre><code>John and Mary
Iva and Mark Li
Out[7]: [None, None, None]
</code></pre>
<p>What's the right way to do it? Thank you!!</p>
| 0 | 2016-07-23T17:14:48Z | 38,544,508 | <p>Should be straight-forward:</p>
<pre><code>>>> L = ["John and Mary", "Leslie", "Iva and Mark Li"]
>>> for s in L:
if ' and ' in s: print(s)
John and Mary
Iva and Mark Li
</code></pre>
<p>If you want to capture the strings in a list, use a comprehension:</p>
<pre><code>>>> [s for s in L if ' and ' in s]
['John and Mary', 'Iva and Mark Li']
</code></pre>
| 5 | 2016-07-23T17:18:39Z | [
"python",
"string",
"generator"
] |
conditionally print out lines in python | 38,544,476 | <p>I have a list of strings. I hope to print out the strings in the list that meet a condition. The list is as below:</p>
<pre><code>In [5]: L = ["John and Mary", "Leslie", "Iva and Mark Li"]
</code></pre>
<p>I hope to print out each of the strings in L that has an <code>and</code> in it --</p>
<pre><code>'John and Mary', 'Iva and Mark Li'
</code></pre>
<p>I have the following code:</p>
<pre><code>In [6]: def grep(pattern, line):
if pattern in line:
print line
In [7]: [grep("and", I) for I in L]
</code></pre>
<p>This returns</p>
<pre><code>John and Mary
Iva and Mark Li
Out[7]: [None, None, None]
</code></pre>
<p>What's the right way to do it? Thank you!!</p>
| 0 | 2016-07-23T17:14:48Z | 38,544,538 | <p>Because your function does not have a return statement, it always returns <code>None</code>. You need to replace <code>print</code> with <code>return</code>.</p>
| 5 | 2016-07-23T17:21:11Z | [
"python",
"string",
"generator"
] |
Python socket programming - exception handling | 38,544,493 | <p>I'm working on a basic socket client program in python and I'm not totally sure how to handle exceptions. This is what I did up to now:</p>
<pre><code>TCP_IP = '..............'
TCP_PORT = 4950
MESSAGE = "o3"
BUFFER_SIZE = 2048
data = ""
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(5.0)
try:
s.connect((TCP_IP, TCP_PORT))
except socket.error:
#write error code to file
s.close()
try:
s.sendall(MESSAGE)
except socket.error:
#write to file or whatever
s.close()
try:
data = s.recv(BUFFER_SIZE)
except socket.error:
#write to file or whatever
s.close()
finally:
s.close()
</code></pre>
<p>The code is working as I want, but I'm not sure if I should nest try/catch blocks or not? Should I put <code>socket.socket</code> into try/catch block too?</p>
<p>Second question, what will <code>s.settimeout()</code> do in my case? As far as I understood the documentation, it will throw an exception after 5 seconds, but for what? Just <code>connect</code> or will it do the same for <code>sendall</code> and <code>recv</code>? </p>
| 0 | 2016-07-23T17:17:04Z | 38,545,213 | <p>Since you're doing exactly the same actions in all the exception blocks and catching the same <code>socket.error</code> exception, you could put <code>s.connect</code>, <code>s.sendall</code> and <code>s.recv</code> in the same <code>try:</code> block. Like so:</p>
<pre><code>try:
s.connect((TCP_IP, TCP_PORT))
s.sendall(MESSAGE)
data = s.recv(BUFFER_SIZE)
except socket.error:
#write error code to file
finally:
s.close()
</code></pre>
<p>Note that since <code>s.close</code> is also in the <code>finally</code> section in your example, it will always get called, even after an exception has occurred. So you'd end up with another exception occurring when you try to close an already closed socket. By not putting it in the <code>except</code> block and only in <code>finally</code>, you can avoid that situation.</p>
<p>If you do intend to handle each error in a different way, then you can leave them separate as you already have. <em>But make sure to <code>break</code>/<code>return</code> at the end of the exception block so that you don't try the next.</em> It's done that way in the <a href="https://docs.python.org/2/library/socket.html#example" rel="nofollow">socket examples</a>, by using a <code>continue</code> in the loop.</p>
<p>Nesting them would help if you wanted to do something different in the exception block. But if not you'd be repeating the <code>except</code> block every time. And if you wanted to do something different, when you exit the nested-<code>try</code>s, you wouldn't be certain of which level it has completed or raised an exception - would need to use flag values etc. to merely track that. So for your example of the same error handling code, at the very least, do something like this in your <code>except</code> block:</p>
<pre><code>except socket.error as e:
socket_error_handler(e, s)
def socket_error_handler(exception, socket):
#write error code to file
etc.
</code></pre>
<blockquote>
<p>Should I put <code>socket.socket</code> into try/catch block too?</p>
</blockquote>
<p>They do that in the examples, linked above.</p>
<p>Apart from logging, you shouldn't really be doing the same exception handling at each stage. Probably need to handle those separately.</p>
<p>Part 2:</p>
<p><code>s.settimeout(5.0)</code> sets the timeout for each socket operation, not just the first connect. Also implies that it's in <a href="https://docs.python.org/2/library/socket.html" rel="nofollow">blocking mode</a>.</p>
| 1 | 2016-07-23T18:34:12Z | [
"python",
"sockets",
"tcp",
"client"
] |
Python data persistent object for communication between threads | 38,544,559 | <p>As shown <a href="http://stackoverflow.com/questions/38542298/python3-webserver-communicate-between-threads-for-irc-bot/38542615#38542615">here</a>, I set up a python Django application served by cherrypy wsgi server. The app is basically another IRC client. Here's the deal : it is very likely that I have to create several separate instances of my bot for every new server connection I need to establish. I need to be able to communicate with each bot. One suggested answer was to use <code>multiprocessing.Queue</code>. This object is data persistent and does allow me to communicate with a bot. However, I need all my bots to listen to the same signal simultaneously, to stop for instance. Every bot has to control whether the stop signal was for him or not. Therefore, I need an object, or some other method, that allows for each bot, running in a separate daemonic thread, to listen to a bunch of signals. The Bus system used by cherrypy for server wide messages is great but seems like an overkill here and I would have no idea how to implement it. Any suggestions ?</p>
| 1 | 2016-07-23T17:23:00Z | 38,615,661 | <p>So, turns out I just mixed up variables and objects. Variables cannot be defined in one module and imported to another one (a = foo, then modify a from another module and import a from third module). This is possible with lists, dicts and stuff.
Solution : at each bot launch (and attempt to connect to a given server), a queue is created and assigned to this server in a dict with a key : the nickname (that has to be unique on IRC). Each bot has a deamonic listener that reads the queue. Other modules import the dict, the specific queue, put a signal there, that is used by the listener.
The system works perfectly. Thumbs up. I'm having difficulties with one aspect though : each bot can have multiples DCC connections and it's hard to assign data to each connection and not mix them up.</p>
| 0 | 2016-07-27T14:20:43Z | [
"python",
"django",
"multithreading",
"data-structures",
"queue"
] |
Removing period from number in python | 38,544,578 | <p>Given a real number between 0 and 1 (for example 0.2836) I want to return only the number without the dot (for example in this case from 0.2836 -> 2836 or 02836). I was trying to use python to do this but I just started and I need some help.</p>
| -2 | 2016-07-23T17:24:58Z | 38,544,608 | <p>As long as you have a number, the following should do:</p>
<pre><code>>>> number = 0.2836
>>> int(str(number).replace('.', ''))
2836
</code></pre>
<p>If a <code>.</code> is not found in the string, <a href="https://docs.python.org/2/library/stdtypes.html#str.replace" rel="nofollow"><code>str.replace</code></a> just returns the original string.</p>
<p>With more numbers:</p>
<pre><code>>>> int(str(1).replace('.', ''))
1
>>> int(str(1.2).replace('.', ''))
12
</code></pre>
| 4 | 2016-07-23T17:27:35Z | [
"python"
] |
Removing period from number in python | 38,544,578 | <p>Given a real number between 0 and 1 (for example 0.2836) I want to return only the number without the dot (for example in this case from 0.2836 -> 2836 or 02836). I was trying to use python to do this but I just started and I need some help.</p>
| -2 | 2016-07-23T17:24:58Z | 38,544,653 | <p>The simplest way to remove an unwanted character from a strip is to call its <code>.replace</code> method with an empty string as the second argument:</p>
<pre><code>x = str(123.45)
x = x.replace('.','')
print(x) # Prints 12345
</code></pre>
<p>Note, this would leave any leading zeros (i.e. <code>0.123</code> using this method would result in <code>0123</code>)</p>
<p>If you know there are always, say, 4 numbers after the decimal (and in the case that there are less, you want trailing zeros), you could multiply the number by an appropriate factor first:</p>
<pre><code>x = 123.4567
x *= 10000
x = str(int(x)) # Convert float to integer first, then to string
print(x) # Prints 1234567
</code></pre>
<p>There are other options, but this may point you in the right direction.</p>
| 0 | 2016-07-23T17:31:01Z | [
"python"
] |
%USERPROFILE% env variable for python | 38,544,618 | <p>I am writing a script in Python 2.7.</p>
<p>It needs to be able to go whoever the current users profile in Windows. </p>
<p>This is the variable and function I currently have: </p>
<pre><code>import os
desired_paths = os.path.expanduser('HOME'\"My Documents")
</code></pre>
<p>I do have doubts that this <code>expanduser</code> will work though. I tried looking for Windows Env Variables to in Python to hopefully find a list and know what to convert it to. Either such tool doesn't exist or I am just not using the right search terms since I am still pretty new and learning.</p>
| 0 | 2016-07-23T17:28:14Z | 38,544,703 | <p>Going by <a href="https://docs.python.org/2/library/os.path.html#os.path.expanduser" rel="nofollow"><code>os.path.expanduser</code></a> , using a <code>~</code> would seem more reliable than using <code>'HOME'</code>.</p>
| 0 | 2016-07-23T17:36:57Z | [
"python",
"python-2.7",
"windows-7-x64",
"environment",
"os.path"
] |
%USERPROFILE% env variable for python | 38,544,618 | <p>I am writing a script in Python 2.7.</p>
<p>It needs to be able to go whoever the current users profile in Windows. </p>
<p>This is the variable and function I currently have: </p>
<pre><code>import os
desired_paths = os.path.expanduser('HOME'\"My Documents")
</code></pre>
<p>I do have doubts that this <code>expanduser</code> will work though. I tried looking for Windows Env Variables to in Python to hopefully find a list and know what to convert it to. Either such tool doesn't exist or I am just not using the right search terms since I am still pretty new and learning.</p>
| 0 | 2016-07-23T17:28:14Z | 38,544,715 | <p>You can access environment variables via the <a href="https://docs.python.org/2/library/os.html#os.environ" rel="nofollow"><code>os.environ</code> mapping</a>:</p>
<pre><code>import os;
print(os.environ['USERPROFILE'])
</code></pre>
<p>This will work in Windows. For another OS, you'd need the appropriate environment variable.</p>
<p>Also, the way to concatenate strings in Python is with <code>+</code> signs, so this:</p>
<pre><code>os.path.expanduser('HOME'\"My Documents")
^^^^^^^^^^^^^^^^^^^^^
</code></pre>
<p>should probably be something else. But to concatenate <em>paths</em> you should be more careful, and probably want to use something like:</p>
<pre><code>os.sep.join(<your path parts>)
# or
os.path.join(<your path parts>)
</code></pre>
<p>(There is a slight distinction between the two)</p>
<p>If you want the My Documents directory of the current user, you might try something like:</p>
<pre><code>docs = os.path.join(os.environ['USERPROFILE'], "My Documents")
</code></pre>
<p>Alternatively, using expanduser:</p>
<pre><code>docs = os.path.expanduser(os.sep.join(["~","My Documents"]))
</code></pre>
<p>Lastly, to see what environment variables are set, you can do something like:</p>
<pre><code>print(os.environ.keys())
</code></pre>
<p>(In reference to finding a list of what environment vars are set)</p>
| 0 | 2016-07-23T17:37:56Z | [
"python",
"python-2.7",
"windows-7-x64",
"environment",
"os.path"
] |
Can a class handle AttributeError by itself using some meta magic? | 38,544,643 | <p>So I have this example code, where Foo is very dynamic data structure. </p>
<pre><code>def fetch():
# simulate api request
return {'param1':1, 'param2':{'description':'param2', 'value':2}}
class Foo(object):
def __init__(self):
self._rawdata = fetch()
#set attributes accordingly to the downloaded data
for key, val in self._rawdata.items():
setattr(self, key, val)
def __str__(self):
# just an example
out = ''
for key, val in self._rawdata.items():
out += key + ': ' + str(val) + '\n'
return out
</code></pre>
<p>A user might want to try do this:</p>
<pre><code>f = Foo()
print(f.param3)
</code></pre>
<p>The user doesn't know whether the 'param3' exists or not (API might not have any data avaliable, in which case it won't provide the key at all)
Naturally, this will result in AttributeError being raised.</p>
<pre><code> print(f.param3)
AttributeError: 'Foo' object has no attribute 'param3'
</code></pre>
<p>My question is this: Is there some metaprogramming magic way to wrap the Foo() class into something that will make 'f.nonexistent_attribute' return 'None' instead of traceback? I would really like to avoid hardcoding expected properties (what if API changes?).</p>
| 0 | 2016-07-23T17:30:09Z | 38,544,660 | <p>Implement the <a href="https://docs.python.org/2/reference/datamodel.html#object.__getattr__" rel="nofollow"><code>__getattr__</code> method</a>; it'll be called for all <em>nonexistent</em> attributes:</p>
<pre><code>def __getattr__(self, name):
# all non-existing attributes produce None
return None
</code></pre>
<p>From the documentation:</p>
<blockquote>
<p>Called when an attribute lookup has not found the attribute in the usual places (i.e. it is not an instance attribute nor is it found in the class tree for <code>self</code>). <code>name</code> is the attribute name. This method should return the (computed) attribute value or raise an <code>AttributeError</code> exception.</p>
</blockquote>
<p>Demo:</p>
<pre><code>>>> def fetch():
... # simulate api request
... return {'param1':1, 'param2':{'description':'param2', 'value':2}}
...
>>> class Foo(object):
... def __init__(self):
... self._rawdata = fetch()
... #set attributes accordingly to the downloaded data
... for key, val in self._rawdata.items():
... setattr(self, key, val)
... def __getattr__(self, name):
... # all non-existing attributes produce None
... return None
...
>>> print(f.param1)
1
>>> f = Foo()
>>> print(f.param3)
None
</code></pre>
| 3 | 2016-07-23T17:31:19Z | [
"python"
] |
Django: DRY principle and UserPassesTestMixin | 38,544,692 | <p>I have a model named <code>Post</code> and have a field there called <code>owner</code> (foreign key to <code>User</code>). Of course, only owners can <code>update</code> or <code>delete</code> their own posts.</p>
<p>That being said, I use <code>login_required</code> decorator in the views to make sure the user is logged in but then, I also need to make sure the user trying to <code>update</code>/<code>delete</code> the question is the <code>owner</code>. </p>
<p>As I'm using <a href="https://docs.djangoproject.com/en/1.9/ref/class-based-views/generic-editing/" rel="nofollow">Django: Generic Editing Views</a> the documentation says I need to use <a href="https://docs.djangoproject.com/en/1.9/topics/auth/default/#django.contrib.auth.mixins.UserPassesTestMixin" rel="nofollow">Django: UserPassesTestMixin</a>. </p>
<p>This validation will be done for the <code>update</code> and <code>delete</code> views. DRY, what is the way to go about this? should I create a class named <code>TestUserOwnerOfPost</code> and create a <code>test_func()</code> and then make the <code>update</code> and <code>delete</code> views inherit from it? </p>
<p>Cause that's what I have tried and didn't work, code below: </p>
<pre><code>from django.views.generic.edit import UpdateView
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import UserPassesTestMixin
class TestUserOwnerOfPost(UserPassesTestMixin):
def test_func(self):
return self.request.user == self.post.owner
class EditPost(UpdateView, TestUserOwnerOfPost):
model = Post
@method_decorator(login_required)
def dispatch(self, *args, **kwargs):
return super(EditPost, self).dispatch(*args, **kwargs)
</code></pre>
<p>With the code above, every logged-in user in the system can <code>edit</code>/<code>delete</code> any post. What am I doing wrong? am I missing something? thanks.</p>
| 0 | 2016-07-23T17:35:21Z | 38,545,039 | <p>The order of the classes you inherit from matters. For your access control to work, it must be enforced before UpdateView is executed:</p>
<pre><code>class EditPost(TestUserOwnerOfPost, UpdateView):
</code></pre>
| 2 | 2016-07-23T18:13:21Z | [
"python",
"django",
"generics"
] |
Django: DRY principle and UserPassesTestMixin | 38,544,692 | <p>I have a model named <code>Post</code> and have a field there called <code>owner</code> (foreign key to <code>User</code>). Of course, only owners can <code>update</code> or <code>delete</code> their own posts.</p>
<p>That being said, I use <code>login_required</code> decorator in the views to make sure the user is logged in but then, I also need to make sure the user trying to <code>update</code>/<code>delete</code> the question is the <code>owner</code>. </p>
<p>As I'm using <a href="https://docs.djangoproject.com/en/1.9/ref/class-based-views/generic-editing/" rel="nofollow">Django: Generic Editing Views</a> the documentation says I need to use <a href="https://docs.djangoproject.com/en/1.9/topics/auth/default/#django.contrib.auth.mixins.UserPassesTestMixin" rel="nofollow">Django: UserPassesTestMixin</a>. </p>
<p>This validation will be done for the <code>update</code> and <code>delete</code> views. DRY, what is the way to go about this? should I create a class named <code>TestUserOwnerOfPost</code> and create a <code>test_func()</code> and then make the <code>update</code> and <code>delete</code> views inherit from it? </p>
<p>Cause that's what I have tried and didn't work, code below: </p>
<pre><code>from django.views.generic.edit import UpdateView
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import UserPassesTestMixin
class TestUserOwnerOfPost(UserPassesTestMixin):
def test_func(self):
return self.request.user == self.post.owner
class EditPost(UpdateView, TestUserOwnerOfPost):
model = Post
@method_decorator(login_required)
def dispatch(self, *args, **kwargs):
return super(EditPost, self).dispatch(*args, **kwargs)
</code></pre>
<p>With the code above, every logged-in user in the system can <code>edit</code>/<code>delete</code> any post. What am I doing wrong? am I missing something? thanks.</p>
| 0 | 2016-07-23T17:35:21Z | 38,545,128 | <p>The first problem is that the order of the classes you inherit is incorrect, as @rafalmp says.</p>
<p>However, fixing that doesn't solve the problem, because the <code>UserPassesTest</code> mixin performs the test <em>before</em> running the view. This means that it's not really suitable to check the owner of <code>self.object</code>, because <code>self.object</code> has not been set yet. Note I'm using <code>self.object</code> instead of <code>self.post</code> -- I'm don't think that the view ever sets <code>self.post</code> but I might be wrong about that.</p>
<p>One option is to call <code>self.get_object()</code> inside the test function. This is a bit inefficient because your view will fetch the object twice, but in practice it probably doesn't matter. </p>
<pre><code>def test_func(self):
self.object = self.get_object()
return self.request.user == self.object.owner
</code></pre>
<p>Another approach is to override <code>get_queryset</code>, to restrict it to objects owned by the user. This means the user will get a 404 error if they do not own the object. This behaviour is not exactly the same as the <code>UserPassesTestMixin</code>, which will redirect to a login page, but it might be ok for you.</p>
<pre><code>class OwnerQuerysetMixin(object):
def get_queryset(self):
queryset = super(OwnerQuerysetMixin, self).get_queryset()
# perhaps handle the case where user is not authenticated
queryset = queryset.filter(owner=self.request.user)
return queryset
</code></pre>
| 2 | 2016-07-23T18:24:21Z | [
"python",
"django",
"generics"
] |
How to resolve the django import from view function? | 38,545,126 | <p>developers.I am learning the django following this <a href="http://gsl.mit.edu/media/programs/south-africa-summer-2015/materials/djangobook.pdf" rel="nofollow">book</a> and making changes for django 1.8</p>
<p>The error showing is </p>
<pre><code>name 'addPublisher' is not defined
Request Method: GET
Request URL: http://127.0.0.1:8000/add
Django Version: 1.8.7
Exception Type: NameError
Exception Value:
*name 'addPublisher' is not defined*
Exception Location: /home/abhi/Desktop/Trade/Trade/urls.py in <module>, line 26
Python Executable: /usr/bin/python
Python Version: 2.7.11
Python Path:
['/home/abhi/Desktop/Trade',
'/usr/lib/python2.7',
'/usr/lib/python2.7/plat-x86_64-linux-gnu',
'/usr/lib/python2.7/lib-tk',
'/usr/lib/python2.7/lib-old',
'/usr/lib/python2.7/lib-dynload',
'/usr/local/lib/python2.7/dist-packages',
'/usr/lib/python2.7/dist-packages']
</code></pre>
<p>Server time: Sat, 23 Jul 2016 18:07:53 +0000</p>
<p>My views.py is -</p>
<pre><code>from django.shortcuts import render
from django.db.models import Q
from django.shortcuts import render_to_response
from django.template import Template, Context
from books.models import Book
from books.forms import ContactForm,PublisherForm
from django.core.mail import send_mail
# Create your views here.
def search(request):
query = request.GET.get('q', '')
if query:
qset = (
Q(title__icontains=query) |
Q(authors__first_name__icontains=query) |
Q(authors__last_name__icontains=query)
)
results = Book.objects.filter(qset).distinct()
else:
results = []
return render_to_response("search.html", {
"results": results,
"query": query
})
def contact(request):
if request.method == 'POST':
form = ContactForm(request.POST)
if form.is_valid():
topic = form.clean_data['topic']
message = form.clean_data['message']
sender = form.clean_data.get('sender', 'noreply@example.com')
send_mail(
'Feedback from your site, topic: %s' % topic,
message, sender,
['administrator@example.com']
)
return HttpResponseRedirect('/contact/thanks/')
else:
form = ContactForm()
return render_to_response('contact.html', {'form': form})
def addPublisher(request):
if request == 'POST':
form = PublisherForm(request.POST)
if form.is_valid:
form.save()
return HttpResponseRedirect('add_publisher/thanks/')
else:
form = PublisherForm()
return render_to_response('book/addPublisher.html',{'form':form})
</code></pre>
<p>My urls.py has following code-</p>
<pre><code>from django.conf.urls import include, url
from django.contrib import admin
from views import *
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^$',home),
url(r'^search/$',search),
url(r'^contact/$',contact),
url(r'^add/$',addPublisher)
]
</code></pre>
| 0 | 2016-07-23T18:24:02Z | 38,547,290 | <p>Your urls.py file is probably not in the same app (folder) than your views.py.
You are getting this error saying that addPublisher <strong>is not defined</strong> because it's literally not <em>there</em>, by <em>there</em> I mean the app where urls.py is located.</p>
<p>If that particular views.py above is located in another app, please import it with something like <br /> <br />
<strong>from [name of app].views import *</strong><br /><br />
Anyway, showing us the layout of your project will help us give you a more direct and specific answer! Thank you.</p>
| 1 | 2016-07-23T23:25:31Z | [
"python",
"django",
"django-1.8"
] |
Remove additional quotes from python list | 38,545,143 | <p>I have a list with below pattern and i want to get rid of <code>"</code> which is present at the beginning and end of each sub list. I tried replace, strip but they are not the attribute of list and therefore gives <code>AttributeError</code>.</p>
<pre><code>lst = [["'123', 'Name1', 'Status1'"], ["'234', 'Name2', 'Status2'"]]
</code></pre>
<p>I am looking for below as my final result:</p>
<pre><code>lst = [['123', 'Name1', 'Status1'], ['234', 'Name2', 'Status2']]
</code></pre>
<p>Please suggest how to remove double quotes from each sub list.</p>
| 0 | 2016-07-23T18:25:40Z | 38,545,153 | <p>This should do the trick:</p>
<pre><code>result = [[element.strip("'") for element in sub_list[0].split(', ')] for sub_list in lst]
</code></pre>
<p>I'm assuming that the format for the string is "strings wrapped in single quotes separated by commas and spaces." Note that my code will probably not do the expected thing with input like <code>[["'A comma here, changes the parsing', 'no comma here'"], ...]</code>. (This would look to my code like three elements in a list, while I imagine you want to consider it two.)</p>
<p><strong>EDIT</strong></p>
<p>This is perhaps easier to understand as compared to the longer list comprehension:</p>
<pre><code>result = []
for sub_list in lst:
s = sub_list[0]
result.append([element.strip("'") for element in s.split(', ')])
</code></pre>
| 1 | 2016-07-23T18:26:34Z | [
"python"
] |
Remove additional quotes from python list | 38,545,143 | <p>I have a list with below pattern and i want to get rid of <code>"</code> which is present at the beginning and end of each sub list. I tried replace, strip but they are not the attribute of list and therefore gives <code>AttributeError</code>.</p>
<pre><code>lst = [["'123', 'Name1', 'Status1'"], ["'234', 'Name2', 'Status2'"]]
</code></pre>
<p>I am looking for below as my final result:</p>
<pre><code>lst = [['123', 'Name1', 'Status1'], ['234', 'Name2', 'Status2']]
</code></pre>
<p>Please suggest how to remove double quotes from each sub list.</p>
| 0 | 2016-07-23T18:25:40Z | 38,545,181 | <p>You can use <a href="https://docs.python.org/2/library/shlex.html#shlex.split" rel="nofollow"><code>shlex.split</code></a> after <em>removing</em> commas with <code>replace</code>:</p>
<pre><code>import shlex
lst = [["'123', 'Name1', 'Status1'"], ["'234', 'Name2', 'Status2'"]]
r = [shlex.split(x[0].replace(',', '')) for x in lst]
# [['123', 'Name1', 'Status1'], ['234', 'Name2', 'Status2']]
</code></pre>
| 3 | 2016-07-23T18:29:47Z | [
"python"
] |
access jupyter notebook running on vm | 38,545,198 | <p>I want to run jupyter notebook running on my ubuntu vm which i fired using vagrant. </p>
<pre>
$ jupyter notebook --no-browser --port 8004
[I 18:26:10.152 NotebookApp] Serving notebooks from local directory: /home/vagrant/path/to/jupyter/notebook/directory
[I 18:26:10.153 NotebookApp] 0 active kernels
[I 18:26:10.154 NotebookApp] The Jupyter Notebook is running at: http://localhost:8004/
[I 18:26:10.154 NotebookApp] Use Control-C to stop this server and shut down all kernels (twice to skip confirmation).
</pre>
<p>Jupyter notebook starts in localhost. But to access the notebook from my host machine I need to start the notebook in 0.0.0.0. How to bind the ip 0.0.0.0 so that it routes to 127.0.0.1 in the vm?</p>
<p>My host machine is windows and vm is ubuntu 14.04.4</p>
| 0 | 2016-07-23T18:32:02Z | 38,545,410 | <p>how to run jupyter notebook as a server gives the answer</p>
<p>first generaTE jupyter_notebook_config.py file</p>
<pre><code>$ jupyter notebook --generate-config
</code></pre>
<p>jupyter_notebook_config.py would have everything commented. Find <code>c.NotebookApp.ip = 'localhost'</code> and edit it to <code>c.NotebookApp.ip = '0.0.0.0'</code></p>
| 0 | 2016-07-23T18:57:38Z | [
"python",
"vagrant",
"jupyter-notebook"
] |
Run-length encoding program | 38,545,225 | <p>i have a string say "AAABBCCCDAAT" so output for the following should be A3B2C3D1A2T1.</p>
<pre><code>data = input("enter data ")
count =1
for steps in range(0,len(data)-1):
if (str(data[steps])==str(data[steps+1])):
count = count+1
else:
str(data[steps])=str(data[steps+1])
count=1
print ((str(count)+str(data[steps]))
</code></pre>
<p>i have a string say "AAABBCCCDAAT" so output for the following should be A3B2C3D1A2T1.
Thanks</p>
| -4 | 2016-07-23T18:35:44Z | 38,547,108 | <p>Here's one way, using <a href="https://docs.python.org/3.1/library/itertools.html#itertools.groupby" rel="nofollow"><code>itertools.groupby</code></a>:</p>
<pre><code>In [62]: from itertools import groupby
In [63]: data
Out[63]: 'AAABBCCCDAAT'
In [64]: ''.join(char + str(len(list(grp))) for char, grp in groupby(data))
Out[64]: 'A3B2C3D1A2T1'
</code></pre>
| 2 | 2016-07-23T22:55:42Z | [
"python",
"python-3.x"
] |
Run-length encoding program | 38,545,225 | <p>i have a string say "AAABBCCCDAAT" so output for the following should be A3B2C3D1A2T1.</p>
<pre><code>data = input("enter data ")
count =1
for steps in range(0,len(data)-1):
if (str(data[steps])==str(data[steps+1])):
count = count+1
else:
str(data[steps])=str(data[steps+1])
count=1
print ((str(count)+str(data[steps]))
</code></pre>
<p>i have a string say "AAABBCCCDAAT" so output for the following should be A3B2C3D1A2T1.
Thanks</p>
| -4 | 2016-07-23T18:35:44Z | 38,547,146 | <p>I have a few approaches to share, but I think @Warren Weckesser's answer is better. :-)</p>
<pre><code># Regular expression approach:
import re
def run_length_encode(text):
# When the match is for AAA:
# match.group(1) == 'A'
# match.group(0) == 'AAA'
# len(match.group(0)) == 3
def encode_single_run(match):
return '{}{}'.format(match.group(1), len(match.group(0)))
# Replace each occurrence of a letter followed by any number of identical letters with the
# output of encode_single_run on that match
return re.sub(r'(.)\1*', encode_single_run, text)
assert run_length_encode('AAABBCCCDAAT') == 'A3B2C3D1A2T1'
# While loop approach:
def run_length_encode(text):
result = []
position = 0
# Until we pass the end of the string
while position < len(text):
# Grab the current letter
letter = text[position]
# Advance our current position
position += 1
# Start at a count of 1 (how many times the letter occurred)
count = 1
# While we haven't fallen off the array and the letter keeps repeating
while position < len(text) and text[position] == letter:
# Move forward
count += 1
position += 1
# Append the letter and count to the result
result.append((letter, count))
# At this point, result looks like [('A', 3), ('B', 2), ...]
# This next line combines the letters and counts and then puts everything into a single string
return ''.join('{}{}'.format(letter, count) for letter, count in result)
assert run_length_encode('AAABBCCCDAAT') == 'A3B2C3D1A2T1'
# State machine approach:
def run_length_encode(text):
result = []
# Keeps track of the letter we're in the midst of a run of
current_letter = None
# Keeps track of how many times we've seen that letter
count = 0
# Iterate over each letter in the string
for letter in text:
# If it's the same letter we're already tracking
if letter == current_letter:
count += 1
else:
# Unless it's the very start of the process
if count > 0:
result.append((current_letter, count))
# Start tracking the new letter
current_letter = letter
count = 1
# Without this, we'd fail to return the last letter
result.append((current_letter, count))
# At this point, result looks like [('A', 3), ('B', 2), ...]
# This next line combines the letters and counts and then puts everything into a single string
return ''.join('{}{}'.format(letter, count) for letter, count in result)
assert run_length_encode('AAABBCCCDAAT') == 'A3B2C3D1A2T1'
</code></pre>
| 0 | 2016-07-23T23:01:40Z | [
"python",
"python-3.x"
] |
How to read out *new* OS environment variables in Python? | 38,545,262 | <p>Reading out OS environment variables in Python is a piece of cake. Try out the following three code lines to read out the <code>'PATH'</code> variable in Windows:</p>
<pre><code> #################
# PYTHON 3.5 #
#################
>> import os
>> pathVar = os.getenv('Path')
>> print(pathVar)
C:\Anaconda3\Library\bin;C:\Anaconda3\Library\bin;
C:\WINDOWS\system32;C:\Anaconda3\Scripts;C:\Apps\SysGCC\arm-eabi\bin;
...
</code></pre>
<p>Now make a small change in the <code>'PATH'</code> variable. You can find them in:</p>
<blockquote>
<p>Control Panel >> System and Security >> System >> Advanced system settings >>
Environment variables</p>
</blockquote>
<p>If you run the same code in Python, the change is not visible! You've got to close down the terminal in which you started the Python session. When you restart it, and run the code again, the change will be visible.</p>
<p>Is there a way to see the change immediately - without the need to close python? This is important for the application that I'm building.</p>
<p>Thank you so much :-)</p>
<hr>
<p><strong>EDIT :</strong></p>
<p>Martijn Pieters showed me the following link:
<a href="http://stackoverflow.com/questions/171588/is-there-a-command-to-refresh-environment-variables-from-the-command-prompt-in-w">Is there a command to refresh environment variables from the command prompt in Windows?</a></p>
<p>There are many options mentioned in that link. I chose the following one (because it is just a batch file, no extra dependencies):</p>
<pre><code> REM --------------------------------------------
REM | refreshEnv.bat |
REM --------------------------------------------
@ECHO OFF
REM Source found on https://github.com/DieterDePaepe/windows-scripts
REM Please share any improvements made!
REM Code inspired by http://stackoverflow.com/questions/171588/is-there-a-command-to-refresh-environment-variables-from-the-command-prompt-in-w
IF [%1]==[/?] GOTO :help
IF [%1]==[/help] GOTO :help
IF [%1]==[--help] GOTO :help
IF [%1]==[] GOTO :main
ECHO Unknown command: %1
EXIT /b 1
:help
ECHO Refresh the environment variables in the console.
ECHO.
ECHO refreshEnv Refresh all environment variables.
ECHO refreshEnv /? Display this help.
GOTO :EOF
:main
REM Because the environment variables may refer to other variables, we need a 2-step approach.
REM One option is to use delayed variable evaluation, but this forces use of SETLOCAL and
REM may pose problems for files with an '!' in the name.
REM The option used here is to create a temporary batch file that will define all the variables.
REM Check to make sure we dont overwrite an actual file.
IF EXIST %TEMP%\__refreshEnvironment.bat (
ECHO Environment refresh failed!
ECHO.
ECHO This script uses a temporary file "%TEMP%\__refreshEnvironment.bat", which already exists. The script was aborted in order to prevent accidental data loss. Delete this file to enable this script.
EXIT /b 1
)
REM Read the system environment variables from the registry.
FOR /F "usebackq tokens=1,2,* skip=2" %%I IN (`REG QUERY "HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment"`) DO (
REM /I -> ignore casing, since PATH may also be called Path
IF /I NOT [%%I]==[PATH] (
ECHO SET %%I=%%K>>%TEMP%\__refreshEnvironment.bat
)
)
REM Read the user environment variables from the registry.
FOR /F "usebackq tokens=1,2,* skip=2" %%I IN (`REG QUERY HKCU\Environment`) DO (
REM /I -> ignore casing, since PATH may also be called Path
IF /I NOT [%%I]==[PATH] (
ECHO SET %%I=%%K>>%TEMP%\__refreshEnvironment.bat
)
)
REM PATH is a special variable: it is automatically merged based on the values in the
REM system and user variables.
REM Read the PATH variable from the system and user environment variables.
FOR /F "usebackq tokens=1,2,* skip=2" %%I IN (`REG QUERY "HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /v PATH`) DO (
ECHO SET PATH=%%K>>%TEMP%\__refreshEnvironment.bat
)
FOR /F "usebackq tokens=1,2,* skip=2" %%I IN (`REG QUERY HKCU\Environment /v PATH`) DO (
ECHO SET PATH=%%PATH%%;%%K>>%TEMP%\__refreshEnvironment.bat
)
REM Load the variable definitions from our temporary file.
CALL %TEMP%\__refreshEnvironment.bat
REM Clean up after ourselves.
DEL /Q %TEMP%\__refreshEnvironment.bat
ECHO Environment successfully refreshed.
</code></pre>
<p>This solution works on my computer (64-bit Windows 10). The environment variables get updated. However, I get the following error:</p>
<pre><code> ERROR: The system was unable to find the specified registry key or value.
</code></pre>
<p>Strange.. I get an error, but the variables do get updated.</p>
<hr>
<p><strong>EDIT :</strong></p>
<p>The environment variables get updated when I call the batch file <code>'refreshEnv'</code> directly in the terminal window. But it doesn't work when I call it from my Python program:</p>
<pre><code> #################################
# PYTHON 3.5 #
# ------------------------- #
# Refresh Environment variables #
#################################
def refresh(self):
p = Popen(self.homeCntr.myState.getProjectFolder() + "\\refreshEnv.bat", cwd=r"{0}".format(str(self.homeCntr.myState.getProjectFolder())))
###
</code></pre>
<p>Why? Is it because Popen runs the batch file in another cmd terminal, such that it doesn't affect the current Python process?</p>
| 1 | 2016-07-23T18:41:15Z | 38,546,615 | <p>On Windows, the initial environment variables are stored in the registry: <code>HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment</code> for system variables and <code>HKEY_CURRENT_USER\Environment</code> for user variables.</p>
<p>Using the <code>winreg</code> module in Python, you can query these environment variables easily without resorting to external scripts:</p>
<pre><code>import winreg
def get_sys_env(name):
key = winreg.CreateKey(winreg.HKEY_LOCAL_MACHINE, r"System\CurrentControlSet\Control\Session Manager\Environment")
return winreg.QueryValueEx(key, name)[0]
def get_user_env(name):
key = winreg.CreateKey(winreg.HKEY_CURRENT_USER, r"Environment")
return winreg.QueryValueEx(key, name)[0]
</code></pre>
<p>(On Python 2.x, use <code>import _winreg as winreg</code> on the first line instead).</p>
<p>With this, you can just use <code>get_sys_env("PATH")</code> instead of <code>os.environ["PATH"]</code> any time you want an up-to-date PATH variable. This is safer, faster and less complicated than shelling out to an external script.</p>
| 3 | 2016-07-23T21:32:34Z | [
"python",
"python-3.x",
"environment-variables"
] |
Time.sleep() function placement | 38,545,275 | <p>The problem I've encountered is while I am attempting to keep the first functions(StartUpScr) widgets on screen for 3 seconds using time.sleep(3) before deleting all it's widgets placed on screen and then continuing to place the next functions(MenuScr) widgets. I've managed to successfully use destroy() to delete the first widgets and replace them with the second widgets, but for some reason when inputting time.sleep(3) anywhere in the functions and the main program, rather than the first widgets staying for 3 seconds and then being replaced it delays the start of the program producing a blank screen before quickly flashing past the first screen onto the second.</p>
<pre><code>from tkinter import *
import tkinter
import time
window = tkinter.Tk()
window.title("BINARY-SUMS!!!")
window.geometry("1000x800")
window.wm_iconbitmap('flower3.ico')
window.configure(background='lavender')
def StartUpScr():
StartUpScr = tkinter.Label(window, text="FIRST-SCREEN!!!",fg = "Aqua",bg = "Lavender",font = ("Adobe Gothic Std B", 90, "bold" )).pack()
StartUpLabel = tkinter.Label(window, text="Developed by Robert Bibb 2016",bg = "Lavender",font = ("Calibri Light (Headings)", 10, "italic" ))
StartUpLabel.pack()
StartUpLabel.place(x = 400, y = 775)
def MenuScr():
StartUpScr = tkinter.Label(window, text="SECOND-SCREEN!!!",fg = "green",bg = "Lavender",font = ("Adobe Gothic Std B", 85, "bold" ))
StartUpScr.pack()
if __name__ == "__main__":
StartUpScr()
time.sleep(3)
for widget in window.winfo_children():
widget.destroy()
MenuScr()
</code></pre>
| 2 | 2016-07-23T18:42:40Z | 38,545,456 | <p>time.sleep() won't work here as it stops the execution of the program, you'll have to use after...and its also a bad practice to use sleep in GUI programming.</p>
<pre><code>root.after(time_delay, function_to_run, args_of_fun_to_run)
</code></pre>
<p>So in your case it'll like</p>
<pre><code>def destroy():
#destroy here
for widget in window.winfo_children():
widget.destroy()
</code></pre>
<p>and after the if statement - </p>
<pre><code>if __name__ == "__main__":
StartUpScr()
window.after(3000, destroy)
MenuScr()
</code></pre>
| 2 | 2016-07-23T19:02:23Z | [
"python",
"time",
"tkinter"
] |
Time.sleep() function placement | 38,545,275 | <p>The problem I've encountered is while I am attempting to keep the first functions(StartUpScr) widgets on screen for 3 seconds using time.sleep(3) before deleting all it's widgets placed on screen and then continuing to place the next functions(MenuScr) widgets. I've managed to successfully use destroy() to delete the first widgets and replace them with the second widgets, but for some reason when inputting time.sleep(3) anywhere in the functions and the main program, rather than the first widgets staying for 3 seconds and then being replaced it delays the start of the program producing a blank screen before quickly flashing past the first screen onto the second.</p>
<pre><code>from tkinter import *
import tkinter
import time
window = tkinter.Tk()
window.title("BINARY-SUMS!!!")
window.geometry("1000x800")
window.wm_iconbitmap('flower3.ico')
window.configure(background='lavender')
def StartUpScr():
StartUpScr = tkinter.Label(window, text="FIRST-SCREEN!!!",fg = "Aqua",bg = "Lavender",font = ("Adobe Gothic Std B", 90, "bold" )).pack()
StartUpLabel = tkinter.Label(window, text="Developed by Robert Bibb 2016",bg = "Lavender",font = ("Calibri Light (Headings)", 10, "italic" ))
StartUpLabel.pack()
StartUpLabel.place(x = 400, y = 775)
def MenuScr():
StartUpScr = tkinter.Label(window, text="SECOND-SCREEN!!!",fg = "green",bg = "Lavender",font = ("Adobe Gothic Std B", 85, "bold" ))
StartUpScr.pack()
if __name__ == "__main__":
StartUpScr()
time.sleep(3)
for widget in window.winfo_children():
widget.destroy()
MenuScr()
</code></pre>
| 2 | 2016-07-23T18:42:40Z | 38,547,052 | <p>So we are defining three functions: <code>firstScreen</code>, <code>secondScreen</code>, and <code>changeScreen</code>. The idea is running <code>firstScreen</code> and after 3 seconds, running <code>changeScreen</code> which will destroy the current parent window (<code>master</code>) and create the next brand new parent window (<code>master2</code>) that will call <code>secondScreen</code> which has completely new world. This is how it's going to happen:</p>
<pre><code>from tkinter import *
root = Tk()
import time
class App:
def __init__(self, master):
self.master = master
self.master.geometry("500x500-500+50")
def firstScreen(self):
self.master.title("FIRST SCREEN")
self.label1 = Label(self.master, width=50, height=20,
text="This is my FIRST screen", bg='red')
self.label1.pack()
self.master.after(3000, self.changeScreen)
def secondScreen(self):
self.label2 = Label(self.master, width=50, height=20,
text="This is my SECOND screen", bg='yellow')
self.label2.pack()
def changeScreen(self):
self.master.destroy()
self.master2 = Tk()
self.master2.title('SECOND SCREEN')
myapp = App(self.master2)
myapp.secondScreen()
myapp = App(root)
myapp.firstScreen()
</code></pre>
<p>I hope it helps!</p>
| 1 | 2016-07-23T22:45:38Z | [
"python",
"time",
"tkinter"
] |
Volume Yahoo Finance | 38,545,299 | <p>What is the meaning of Volume in Yahoo Finance (web.DataReader(stock, 'yahoo', start, end))? Is it average daily trading volume or average dollar volume? Is it a number of shares or number of dollars?</p>
| 0 | 2016-07-23T18:45:13Z | 38,547,342 | <p>According to:</p>
<p><a href="https://biz.yahoo.com/charts/guide20.html" rel="nofollow">https://biz.yahoo.com/charts/guide20.html</a></p>
<p>Volume on Yahoo Finance's charts are the physical number of shares traded of that stock (not dollar amount) for your given period of time. This is typically what volume is reported as, so it would be safe to assume their endpoint follows the same protocol. </p>
| 0 | 2016-07-23T23:35:13Z | [
"python",
"volume",
"datareader",
"yahoo-finance"
] |
Visual Studio code and virtualenv | 38,545,326 | <p>I am trying to use Visual Studio Code with virtual environment. In the Launch JSON I specify the nosetests launch like this:</p>
<pre><code>{
"name": "nosetests",
"type": "python",
"request": "launch",
"stopOnEntry": true,
"program": "${workspaceRoot}/env/dev/bin/nosetests",
"args": [
"--nocapture",
"tests"
],
"externalConsole": false,
"debugOptions": [
"WaitOnAbnormalExit",
"WaitOnNormalExit"
]
},
</code></pre>
<p>However when I launch the environment variables do not get picked up. I've tried setting up the python path in workspace settings:</p>
<pre><code>"python.pythonPath": "${workspaceRoot}/env/dev/bin/python"
</code></pre>
<p>but it doesn't seem to set the right environment. There needs to be something that' the equivalent of source activate. Has anyone figured it out?</p>
| 1 | 2016-07-23T18:48:21Z | 38,607,114 | <p>@mikebz you need to configure the path to the python executable as follows:<br>
<code>
"pythonPath":"${workspaceRoot}/env/dev/bin/python"
</code></p>
<p>The path may not be 100% accurate (please double check it), but that's how you need to configure it in launch.json.<br>
With the next version of VS Code you will no longer have to do this, i.e. you won't have to configure this same setting in two files.</p>
<p>More details on configuring the path for debugging can be found here:
<a href="https://github.com/DonJayamanne/pythonVSCode/wiki/Python-Path-and-Version#python-version-used-for-debugging" rel="nofollow">https://github.com/DonJayamanne/pythonVSCode/wiki/Python-Path-and-Version#python-version-used-for-debugging</a></p>
| 2 | 2016-07-27T07:58:47Z | [
"python",
"vscode",
"nose"
] |
How to free memory of python deleted object? | 38,545,463 | <p>It seems python3.5 does not completely free memory of any deleted object, this may because of python internally maintaining some kind of memroy pool for reusing purpose, however, I don't want to reuse them, and I want to free them to make memory available for other programs running on linux. </p>
<pre><code>>>> psutil.Process().memory_info().rss / 2**20
11.47265625
>>> d = {x:x for x in range(10**7)}
>>> psutil.Process().memory_info().rss / 2**20
897.1796875
>>> del d
>>> gc.collect()
0
>>> psutil.Process().memory_info().rss / 2**20
15.5859375
</code></pre>
<p>This is just a toy example, the real problem is on a running server, taking 20GB of unfreeable memory.</p>
<p>here is another example: (wd1 is a dict of dict with string keys)</p>
<pre><code>>>> psutil.Process().memory_info().rss / 2**20
28.1796875
>>> wd1 = {x:{i:i for i in d} for x in k}
>>> psutil.Process().memory_info().rss / 2**20
682.78125
>>> del wd1
>>> psutil.Process().memory_info().rss / 2**20
186.21484375
</code></pre>
| 10 | 2016-07-23T19:02:45Z | 38,545,526 | <p>Once you delete an object it is available to garbage collected rather than deleted immediately - so just give it some time and it will free up or trigger a <code>gc.collect()</code> to speed things up.</p>
<pre><code>python.exe
Python 3.5.1 (v3.5.1:37a07cee5969, Dec 6 2015, 01:38:48) [MSC v.1900 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import psutil
>>> import gc
>>> psutil.Process().memory_info().rss / 2**20
13.2890625
>>> d = {x:x for x in range(10**7)}
>>> psutil.Process().memory_info().rss / 2**20
359.13671875
>>> del d
>>> psutil.Process().memory_info().rss / 2**20
13.5234375
>>> gc.collect()
0
>>> psutil.Process().memory_info().rss / 2**20
13.4375
>>>
</code></pre>
<p>Just for reference the Python 3 shell is actually more like ipython 2 in that there is a certain amount of storage taken up with history, etc., just for reference:</p>
<pre><code>Python 3.5.1 (v3.5.1:37a07cee5969, Dec 6 2015, 01:38:48) [MSC v.1900 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import psutil
>>> psutil.Process().memory_info().rss / 2**20
13.1875
>>> psutil.Process().memory_info().rss / 2**20
13.20703125
>>> psutil.Process().memory_info().rss / 2**20
13.20703125
>>> psutil.Process().memory_info().rss / 2**20
13.20703125
>>> psutil.Process().memory_info().rss / 2**20
13.20703125
>>> 22*3
66
>>> psutil.Process().memory_info().rss / 2**20
13.25390625
>>> import gc
>>> psutil.Process().memory_info().rss / 2**20
13.25390625
>>> gc.collect()
0
>>> psutil.Process().memory_info().rss / 2**20
13.171875
>>>
</code></pre>
<p>Next Morning to check if doing dict update in a function is different:</p>
<pre><code>>>> psutil.Process().memory_info().rss / 2**20
13.1484375
>>> D = {}
>>> psutil.Process().memory_info().rss / 2**20
13.1484375
>>> def UpdateD(d, v):
... """ Add the text and value for v to dict d """
... d[v] = str(v)
...
>>> psutil.Process().memory_info().rss / 2**20
13.16015625
>>> for x in range(10**7):
... UpdateD(D, x)
...
>>> psutil.Process().memory_info().rss / 2**20
666.6328125
>>> del D
>>> psutil.Process().memory_info().rss / 2**20
10.765625
>>> gc.collect()
0
>>> psutil.Process().memory_info().rss / 2**20
12.8984375
>>>
</code></pre>
<p>So it looks like your production code might be hanging onto a reference that you still have to track down.</p>
| 5 | 2016-07-23T19:10:39Z | [
"python",
"python-3.x",
"memory",
"memory-management",
"memory-leaks"
] |
Merge DataFrames on two columns | 38,545,544 | <p>This is a follow-up from <a href="http://stackoverflow.com/questions/38543026/stack-two-columns-in-a-dataframe-repeat-others/38543214">this question</a></p>
<p>I have two pandas DataFrames, as follows:</p>
<pre><code>print( a )
foo bar let letval
9 foo1 bar1 let1 a
8 foo2 bar2 let1 b
7 foo3 bar3 let1 c
6 foo1 bar1 let2 z
5 foo2 bar2 let2 y
4 foo3 bar3 let2 x
print( b )
foo bar num numval
0 foo1 bar1 num1 1
1 foo2 bar2 num1 2
2 foo3 bar3 num1 3
3 foo1 bar1 num2 4
4 foo2 bar2 num2 5
5 foo3 bar3 num2 6
</code></pre>
<p>I want to <code>merge</code> the two of them on the columns <code>[ 'foo', 'bar' ]</code>. </p>
<p>If I simply do <code>c = pd.merge( a, b, on=['foo', 'bar'] )</code>, I get:</p>
<pre><code>prnint( c )
foo bar let letval num numval
0 foo1 bar1 let1 a num1 1
1 foo1 bar1 let1 a num2 4
2 foo1 bar1 let2 z num1 1
3 foo1 bar1 let2 z num2 4
4 foo2 bar2 let1 b num1 2
5 foo2 bar2 let1 b num2 5
6 foo2 bar2 let2 y num1 2
7 foo2 bar2 let2 y num2 5
8 foo3 bar3 let1 c num1 3
9 foo3 bar3 let1 c num2 6
10 foo3 bar3 let2 x num1 3
11 foo3 bar3 let2 x num2 6
</code></pre>
<p>I would like:</p>
<pre><code>print( c )
foo bar let letval num numval
0 foo1 bar1 let1 a num1 1
1 foo2 bar2 let1 b num1 2
2 foo3 bar3 let1 c num1 3
3 foo1 bar1 let2 z num2 4
4 foo2 bar2 let2 y num2 5
5 foo3 bar3 let2 x num2 6
</code></pre>
<p>The closest I've got is: </p>
<pre><code>c = pd.merge( a, b, left_index=['foo', 'bar'], right_index=['foo', 'bar'] )
</code></pre>
<p>What am I missing?</p>
<p>And why do I get <code>c.shape = (12,6)</code> in the first example?</p>
<hr>
<p><strong>Edit</strong></p>
<p>Thanks to <a href="http://stackoverflow.com/a/38547935/776515">@piRSquared's answer</a> I realized that the underlying problem is that there is not a single combination of columns to do that. Thus the merge problem, as posed before cannot be univocally solved. That said, the question is converted into a simpler one:</p>
<p><strong>How to make a univocal relationship between the tables?</strong></p>
<p>I solved that with a dictionary that maps the <em>desired</em> outputs that need to be aligned:</p>
<pre><code>map_ab = { 'num1':'let1', 'num2':'let2' }
b['let'] = b.apply( lambda x: map_ab[x['num']], axis=1 )
c = pd.merge( a, b, on=['foo', 'bar', 'let'] )
print( c )
</code></pre>
| 3 | 2016-07-23T19:12:29Z | 38,545,661 | <p>you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.combine_first.html" rel="nofollow">combine_first</a>:</p>
<pre><code>In[21]:a.combine_first(b)
Out[21]:
bar foo let letval num numval
0 bar1 foo1 let1 a num1 1
1 bar2 foo2 let1 b num1 2
2 bar3 foo3 let1 c num1 3
3 bar1 foo1 let2 z num2 4
4 bar2 foo2 let2 y num2 5
5 bar3 foo3 let2 x num2 6
</code></pre>
<p>In the first example you are doing <code>inner join</code> which returns all rows if <code>bar</code> & <code>foo</code> are equal in <code>a,b</code>.</p>
| 1 | 2016-07-23T19:24:48Z | [
"python",
"pandas",
"merge"
] |
Merge DataFrames on two columns | 38,545,544 | <p>This is a follow-up from <a href="http://stackoverflow.com/questions/38543026/stack-two-columns-in-a-dataframe-repeat-others/38543214">this question</a></p>
<p>I have two pandas DataFrames, as follows:</p>
<pre><code>print( a )
foo bar let letval
9 foo1 bar1 let1 a
8 foo2 bar2 let1 b
7 foo3 bar3 let1 c
6 foo1 bar1 let2 z
5 foo2 bar2 let2 y
4 foo3 bar3 let2 x
print( b )
foo bar num numval
0 foo1 bar1 num1 1
1 foo2 bar2 num1 2
2 foo3 bar3 num1 3
3 foo1 bar1 num2 4
4 foo2 bar2 num2 5
5 foo3 bar3 num2 6
</code></pre>
<p>I want to <code>merge</code> the two of them on the columns <code>[ 'foo', 'bar' ]</code>. </p>
<p>If I simply do <code>c = pd.merge( a, b, on=['foo', 'bar'] )</code>, I get:</p>
<pre><code>prnint( c )
foo bar let letval num numval
0 foo1 bar1 let1 a num1 1
1 foo1 bar1 let1 a num2 4
2 foo1 bar1 let2 z num1 1
3 foo1 bar1 let2 z num2 4
4 foo2 bar2 let1 b num1 2
5 foo2 bar2 let1 b num2 5
6 foo2 bar2 let2 y num1 2
7 foo2 bar2 let2 y num2 5
8 foo3 bar3 let1 c num1 3
9 foo3 bar3 let1 c num2 6
10 foo3 bar3 let2 x num1 3
11 foo3 bar3 let2 x num2 6
</code></pre>
<p>I would like:</p>
<pre><code>print( c )
foo bar let letval num numval
0 foo1 bar1 let1 a num1 1
1 foo2 bar2 let1 b num1 2
2 foo3 bar3 let1 c num1 3
3 foo1 bar1 let2 z num2 4
4 foo2 bar2 let2 y num2 5
5 foo3 bar3 let2 x num2 6
</code></pre>
<p>The closest I've got is: </p>
<pre><code>c = pd.merge( a, b, left_index=['foo', 'bar'], right_index=['foo', 'bar'] )
</code></pre>
<p>What am I missing?</p>
<p>And why do I get <code>c.shape = (12,6)</code> in the first example?</p>
<hr>
<p><strong>Edit</strong></p>
<p>Thanks to <a href="http://stackoverflow.com/a/38547935/776515">@piRSquared's answer</a> I realized that the underlying problem is that there is not a single combination of columns to do that. Thus the merge problem, as posed before cannot be univocally solved. That said, the question is converted into a simpler one:</p>
<p><strong>How to make a univocal relationship between the tables?</strong></p>
<p>I solved that with a dictionary that maps the <em>desired</em> outputs that need to be aligned:</p>
<pre><code>map_ab = { 'num1':'let1', 'num2':'let2' }
b['let'] = b.apply( lambda x: map_ab[x['num']], axis=1 )
c = pd.merge( a, b, on=['foo', 'bar', 'let'] )
print( c )
</code></pre>
| 3 | 2016-07-23T19:12:29Z | 38,547,935 | <p>The reason you are getting that is because the columns you are merging on do not constitute unique combinations. For example, The first (index 0) row of <code>a</code> has <code>foo1</code> and <code>bar1</code>, but so does the fourth row (index 3). Ok, that's fine, but <code>b</code> has the same issue. So, when you match up <code>b</code>'s <code>foo1</code> & <code>bar1</code> for row indexed with <code>0</code> it matches twice. Same is true when you match <code>foo1</code> & <code>bar1</code> in row indexed with <code>3</code>, it matches twice. So you end up with four matches for those 2 rows.</p>
<p>So you get </p>
<ul>
<li><code>a</code> row 0 matches with <code>b</code> row 0</li>
<li><code>a</code> row 0 matches with <code>b</code> row 3</li>
<li><code>a</code> row 3 matches with <code>b</code> row 0</li>
<li><code>a</code> row 3 matches with <code>b</code> row 3</li>
</ul>
<p>And THEN, your example does this 2 more times. <code>3 * 4 == 12</code></p>
<p>The only way to do this and be unambiguous is to decide on a rule on which match to take if there are more than one matches. I decided to groupby one of your other columns then take the first one. It still doesn't match your expected output but I'm proposing that you gave a bad example.</p>
<pre><code>pd.merge( a, b, on=['foo', 'bar']).groupby(['foo', 'bar', 'let'], as_index=False).first()
</code></pre>
<p><a href="http://i.stack.imgur.com/b9jAo.png" rel="nofollow"><img src="http://i.stack.imgur.com/b9jAo.png" alt="enter image description here"></a></p>
| 3 | 2016-07-24T01:31:01Z | [
"python",
"pandas",
"merge"
] |
python urlopen error [Errno 10060] | 38,545,603 | <p>I am trying to run the following code, </p>
<pre><code>for parname in parss:
data = {'action': 'listp', 'parish': parname}
data = urllib.urlencode(data)
req = urllib2.Request('http://www.irishancestors.ie/search/townlands/ded_index.php', data)
response = urllib2.urlopen(req)
</code></pre>
<p>but i get the error below few minutes after the code gets executed</p>
<pre><code>urllib2.URLError: <urlopen error [Errno 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond>
</code></pre>
<p>This is my proxy settings. </p>
<p><a href="http://i.stack.imgur.com/j0Zpb.png" rel="nofollow"><img src="http://i.stack.imgur.com/j0Zpb.png" alt="enter image description here"></a></p>
<p>Any help is highly appreciated</p>
| 0 | 2016-07-23T19:18:30Z | 38,552,666 | <p>As discussed in the comments, executing large numbers of requests in very short time can lead to the server, especially web-servers, to block your connection attempts.</p>
<p>This is a common counter measure to automated attacks on the web.
Depending on the server, waiting very short amounts of time between requests should solve your problem.</p>
<p>You could also use a more dynamic approach. First, execute as much requests as possible with no waits in between. If a request takes significantly longer than usual it is most likely a timeout and you have to wait. At this point, you cancel your request, wait and try again. If the subsequent try also results in a timeout you double the waiting time. With this procedure, called <em>adaptive backoff</em>, you should be (hopefully) able to access the data you want with minimal overhead.</p>
| 1 | 2016-07-24T13:42:54Z | [
"python",
"urlopen"
] |
What is the most efficient way to collect HoG descriptors (ndarrays) together for processing by Kmeans | 38,545,611 | <p>In scikit image there is a feature descriptor called <a href="http://scikit-image.org/docs/0.12.x/api/skimage.feature.html#hog" rel="nofollow">HoG</a></p>
<p>The code below will calculate the descriptor for a single frame "greyVideoFrame"</p>
<pre><code>HoGDescriptor = hog(greyVideoFrame, orientations=8, pixels_per_cell=(8, 8),cells_per_block=(2, 2), visualise=False)
</code></pre>
<p>Which returns a flattened (using ravel) nd array, below are some properties of the individual arrays</p>
<pre><code>('NDarray Shape', (251328,))
('NDarray Number of Dimensions', 1)
('NDarray length of 1 array element in Bytes', 8)
('NDarray Total bytes consumed by elements', 2010624)
('NDarray DataType', dtype('float64'))
</code></pre>
<p>My question is how would i collate* the results from multiple frames together which would be able to handle efficiently <strong>10,000 results</strong> of <code>shape (251328, )</code> .</p>
<p>*I'm not sure of the correct term to use here and whether I need to append or concatenate result 1, result 2,...result 10k and would welcome the communities guidance</p>
| -1 | 2016-07-23T19:19:35Z | 39,087,705 | <p>Decided to go with h5py to store the data in a format that wasn't limited to the size of RAM available</p>
| 0 | 2016-08-22T19:57:00Z | [
"python",
"computer-vision",
"scikit-image"
] |
How to convert an IP address to something 32 bit you can use as a dict key | 38,545,718 | <p>If I have an IP address I can use it as a key in a dict as follows:</p>
<pre><code>dict = {}
IP = "172.23.1.99"
dict[IP] = "pear"
</code></pre>
<p>However, if I have a lot of them this is very memory inefficient. </p>
<blockquote>
<p>How can I convert the IP to a 32 bit representation which I can still
use a key in a dict?</p>
</blockquote>
<p>I could just convert the IP to an int. But python ints seem to consume 24 bytes each which is 192 bits so this <strong>does not</strong> solve my problem.</p>
<pre><code>In [2]: sys.getsizeof(2**32-1)
Out[2]: 24
</code></pre>
<p>As I have 100s of millions of these IPs I would really like to represent them as 32 bits each.</p>
<p>From the comments it seems this may be hard in pure Python. I would be happy with a practical non-pure solution too (including using numpy or any other easily available package).</p>
| 4 | 2016-07-23T19:32:27Z | 38,545,780 | <p>Yes you can use the <a href="https://docs.python.org/3/library/ipaddress.html#module-ipaddress" rel="nofollow"><code>ipaddress</code></a> module:</p>
<pre><code>from ipaddress import ip_address
int(ip_address('172.23.1.99'))
</code></pre>
<p>output:</p>
<pre><code>2887188835
</code></pre>
<p>and back:</p>
<pre><code>from ipaddress import ip_address
str(ip_address(2887188835))
</code></pre>
<p>output:</p>
<pre><code>'172.23.1.99'
</code></pre>
| 0 | 2016-07-23T19:40:23Z | [
"python"
] |
How to convert an IP address to something 32 bit you can use as a dict key | 38,545,718 | <p>If I have an IP address I can use it as a key in a dict as follows:</p>
<pre><code>dict = {}
IP = "172.23.1.99"
dict[IP] = "pear"
</code></pre>
<p>However, if I have a lot of them this is very memory inefficient. </p>
<blockquote>
<p>How can I convert the IP to a 32 bit representation which I can still
use a key in a dict?</p>
</blockquote>
<p>I could just convert the IP to an int. But python ints seem to consume 24 bytes each which is 192 bits so this <strong>does not</strong> solve my problem.</p>
<pre><code>In [2]: sys.getsizeof(2**32-1)
Out[2]: 24
</code></pre>
<p>As I have 100s of millions of these IPs I would really like to represent them as 32 bits each.</p>
<p>From the comments it seems this may be hard in pure Python. I would be happy with a practical non-pure solution too (including using numpy or any other easily available package).</p>
| 4 | 2016-07-23T19:32:27Z | 38,546,641 | <p>Given the number of entries you intend to store, I suggest you use SQLite. It's both easy and probably efficient enough. In fact, it has the nice property that for every record it uses only as much space as necessary. For an IP address that is between 1 and 5 bytes depending on the IP address (so on average, 3 bytes).</p>
<p>Here's an example:</p>
<pre><code>from ipaddress import ip_address
import sqlite3
# Create an in-memory database.*
db_connection = sqlite3.connect(':memory:')
cursor = db_connection.cursor()
cursor.execute('''
CREATE TABLE ip_address_associations (
ip_address INTEGER PRIMARY KEY,
value TEXT
)
''')
# Store the value for an IP address
cursor.execute(
'INSERT OR REPLACE INTO ip_address_associations VALUES (?, ?)',
(int(ip_address('172.23.1.99')), 'pear')
)
# Retrieve the value for an IP address
row = cursor.execute(
'SELECT value FROM ip_address_associations WHERE ip_address = ?',
(int(ip_address('172.23.1.99')),)
).fetchone()
if row:
value = row[0]
print(value)
else:
print('No results found.')
</code></pre>
<p>*Although I don't know exactly what your application is about, I highly suspect that there's no need to keep the whole database in memory all the time. You can save greatly on memory usage while not losing too much in access time by using a (temporary) file and relying on file caching. Replace <code>':memory:'</code> by <code>''</code> for a temporary file, or by a filename for a persistent one. </p>
| 2 | 2016-07-23T21:36:42Z | [
"python"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.