title stringlengths 10 172 | question_id int64 469 40.1M | question_body stringlengths 22 48.2k | question_score int64 -44 5.52k | question_date stringlengths 20 20 | answer_id int64 497 40.1M | answer_body stringlengths 18 33.9k | answer_score int64 -38 8.38k | answer_date stringlengths 20 20 | tags list |
|---|---|---|---|---|---|---|---|---|---|
Problems with pandas and numpy where condition/multiple values? | 38,781,540 | <p>I have the follwoing pandas dataframe:</p>
<pre><code>A B
1 3
0 3
1 2
0 1
0 0
1 4
....
0 0
</code></pre>
<p>I would like to add a new column at the right side, following the following condition:</p>
<p>If the value in <code>B</code> has <code>3</code> or <code>2</code> add <code>1</code> in the <code>new_... | 2 | 2016-08-05T05:11:26Z | 38,781,646 | <pre><code>df=pd.DataFrame({'A':[1,0,1,0,0,1],'B':[3,3,2,1,0,4]})
print df
df['C']=[1 if vals==2 or vals==3 else 0 for vals in df['B'] ]
print df
A B
0 1 3
1 0 3
2 1 2
3 0 1
4 0 0
5 1 4
A B C
0 1 3 1
1 0 3 1
2 1 2 1
3 0 1 0
4 0 0 0
5 1 4 0
</code></pre>
| 1 | 2016-08-05T05:23:50Z | [
"python",
"python-3.x",
"pandas",
"numpy",
"scipy"
] |
Problems with pandas and numpy where condition/multiple values? | 38,781,540 | <p>I have the follwoing pandas dataframe:</p>
<pre><code>A B
1 3
0 3
1 2
0 1
0 0
1 4
....
0 0
</code></pre>
<p>I would like to add a new column at the right side, following the following condition:</p>
<p>If the value in <code>B</code> has <code>3</code> or <code>2</code> add <code>1</code> in the <code>new_... | 2 | 2016-08-05T05:11:26Z | 38,781,707 | <p>You can use Pandas <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.isin.html" rel="nofollow">isin</a> which will return a boolean showing whether the elements you're looking for are contained in column <code>'B'</code>.</p>
<pre><code>df['new_col'] = df['B'].isin([3, 2])
A B new_... | 3 | 2016-08-05T05:28:43Z | [
"python",
"python-3.x",
"pandas",
"numpy",
"scipy"
] |
Problems with pandas and numpy where condition/multiple values? | 38,781,540 | <p>I have the follwoing pandas dataframe:</p>
<pre><code>A B
1 3
0 3
1 2
0 1
0 0
1 4
....
0 0
</code></pre>
<p>I would like to add a new column at the right side, following the following condition:</p>
<p>If the value in <code>B</code> has <code>3</code> or <code>2</code> add <code>1</code> in the <code>new_... | 2 | 2016-08-05T05:11:26Z | 38,781,726 | <pre><code>df['new_col'] = [1 if x in [2, 3] else 0 for x in df.B]
</code></pre>
<p>The operators <code>* + ^</code> work on booleans as expected, and mixing with integers give the expected result. So you can also do:</p>
<pre><code>df['new_col'] = [(x in [2, 3]) * 1 for x in df.B]
</code></pre>
| 2 | 2016-08-05T05:30:15Z | [
"python",
"python-3.x",
"pandas",
"numpy",
"scipy"
] |
Problems with pandas and numpy where condition/multiple values? | 38,781,540 | <p>I have the follwoing pandas dataframe:</p>
<pre><code>A B
1 3
0 3
1 2
0 1
0 0
1 4
....
0 0
</code></pre>
<p>I would like to add a new column at the right side, following the following condition:</p>
<p>If the value in <code>B</code> has <code>3</code> or <code>2</code> add <code>1</code> in the <code>new_... | 2 | 2016-08-05T05:11:26Z | 38,781,753 | <p>Using <code>numpy</code>:</p>
<pre><code>>>> df['new_col'] = np.where(np.logical_or(df['B'] == 3, df['B'] == 2), '1','0')
>>> df
A B new_col
0 1 3 1
1 0 3 1
2 1 2 1
3 0 1 0
4 0 0 0
5 1 4 0
</code></pre>
| 1 | 2016-08-05T05:32:43Z | [
"python",
"python-3.x",
"pandas",
"numpy",
"scipy"
] |
Problems with pandas and numpy where condition/multiple values? | 38,781,540 | <p>I have the follwoing pandas dataframe:</p>
<pre><code>A B
1 3
0 3
1 2
0 1
0 0
1 4
....
0 0
</code></pre>
<p>I would like to add a new column at the right side, following the following condition:</p>
<p>If the value in <code>B</code> has <code>3</code> or <code>2</code> add <code>1</code> in the <code>new_... | 2 | 2016-08-05T05:11:26Z | 38,781,803 | <p>using numpy</p>
<pre><code>df['new'] = (df.B.values[:, None] == np.array([2, 3])).any(1) * 1
</code></pre>
<hr>
<h3>Timing</h3>
<p><strong><em>over given data set</em></strong></p>
<p><a href="http://i.stack.imgur.com/YCFDd.png" rel="nofollow"><img src="http://i.stack.imgur.com/YCFDd.png" alt="enter image descr... | 1 | 2016-08-05T05:36:19Z | [
"python",
"python-3.x",
"pandas",
"numpy",
"scipy"
] |
Using itertools.groupby in pyspark but fail | 38,781,579 | <p>I wrote a map function to aggregate data by using itertools.groupby, and what I do is like below.</p>
<p><strong>Driver code</strong></p>
<pre><code>pair_count = df.mapPartitions(lambda iterable: pair_func_cnt(iterable))
pair_count.collection()
</code></pre>
<p><strong>Map function</strong></p>
<pre><code>def pa... | 0 | 2016-08-05T05:17:05Z | 38,787,353 | <p>Python <code>pickle</code> cannot serialize anonymous functions. Lets illustrate that on a simplified example:</p>
<pre><code>import pickle
xs = [[1, 2, 3], [1, 2, 5], [1, 3, 5], [2, 4, 6]]
pickle.dumps([x for x in groupby(xs, lambda x: x[0])])
## PicklingError
## ...
## PicklingError: Can't pickle ...
</code></... | 0 | 2016-08-05T10:46:27Z | [
"python",
"apache-spark",
"pyspark"
] |
Lambda in Python class referring to self | 38,781,686 | <p>I'm trying to define a function in a Python class using lambda and I want to refer to the instance of the class from which it's being called and can't figure out how.</p>
<pre><code>properties.append(pf.moleculeProperties())
properties[-1].name = "Monatomic Hydrogen"
properties[-1].formula = "H"
properties[-1].mass... | 0 | 2016-08-05T05:27:28Z | 38,781,831 | <p>You need to evaluate <code>properties</code> in the argument list rather than the body of the lambda so that it binds early. So, define <code>q</code> as:</p>
<pre><code>properties[-1].q = lambda T,V,self=properties[-1] : pf.q_trans(self,T,V) * pf.q_elec(self,T,V)
</code></pre>
<p>When you do the above, the assig... | 2 | 2016-08-05T05:38:32Z | [
"python",
"oop",
"lambda"
] |
Error While Running Kivy Application on Pydev | 38,781,744 | <p>On python34 and Mingw compiler, While running <code>kivy</code> application, I am facing this error. Can someone help me?</p>
<pre><code>[INFO ] [Logger ] Record log in C:\Users\Naver-Say\.kivy\logs\kivy_16-08-05_8.txt
[INFO ] [Kivy ] v1.9.1
[INFO ] [Python ]... | 1 | 2016-08-05T05:31:48Z | 38,984,374 | <p>The error I believe is due to the dependencies not being installed. Here is the link to install it for windows <a href="https://kivy.org/docs/installation/installation-windows.html" rel="nofollow">https://kivy.org/docs/installation/installation-windows.html</a> and you only need to install the top one.</p>
| 0 | 2016-08-16T20:59:02Z | [
"python",
"kivy"
] |
Computation on a Tensor as numpy array in graph? | 38,781,746 | <p>Is there any way to do some computation on a tensor in graph.</p>
<p>Example my graph:</p>
<pre><code>slim = tf.contrib.slim
def slim_graph(images, train=False):
with slim.arg_scope([slim.conv2d, slim.fully_connected],
activation_fn=tf.nn.relu,
weights_initializer=tf.trunca... | 1 | 2016-08-05T05:32:13Z | 39,281,170 | <p>You can use <a href="https://www.tensorflow.org/versions/r0.7/api_docs/python/script_ops.html#py_func" rel="nofollow">tf.py_func</a> wrapper for python functions.</p>
| 0 | 2016-09-01T21:31:32Z | [
"python",
"numpy",
"tensorflow",
"deep-learning"
] |
Thrift / Fedora 24 no Python library | 38,781,789 | <p><strong>./configure</strong> </p>
<pre><code>thrift 1.0.0-dev
Building C++ Library ......... : yes
Building C (GLib) Library .... : yes
Building Java Library ........ : yes
Building C# Library .......... : no
Building Python Library ...... : **no**
Building Ruby Library ........ : no
Building Haxe Library ........... | 0 | 2016-08-05T05:35:43Z | 38,782,035 | <p>From: <a href="https://github.com/apache/thrift/blob/master/configure.ac#L279-L289" rel="nofollow">https://github.com/apache/thrift/blob/master/configure.ac#L279-L289</a></p>
<pre><code>if test "$with_python" = "yes"; then
AC_PATH_PROG([PIP], [pip])
AC_PATH_PROG([TRIAL], [trial])
if test -n "$TRIAL" &&am... | 1 | 2016-08-05T05:54:03Z | [
"python",
"python-3.x",
"thrift"
] |
When didving by 0, I want it to print given text | 38,781,820 | <pre><code>import math
def roots4(outfile,a,b,c):
"""Prints the solutions of 'x' for equation ax² + bx + c = 0 """
d = b * b - 4 * a * c
if a == 0 and b == 0 and c == 0:
print "X = All complex/real numbers."
if c != 0:
print "X = No real solutions."
e = (-c / (b))
if a == 0 a... | 0 | 2016-08-05T05:37:36Z | 38,782,884 | <p>I don't know the Python. But know the concept.</p>
<p>So please rectify the Python code error.</p>
<p><strong>Prints the solutions of ax² + bx + c = 0</strong></p>
<pre><code>def roots4(outfile,a,b,c):
d = (b * b) - (4 * a * c)
if a == 0 and b == 0 and c==0:
print "This is not quadratic equations"
if a ... | 0 | 2016-08-05T06:49:25Z | [
"python",
"if-statement",
"math",
"printing",
"error-handling"
] |
Why is Python Printing out multiple values here? | 38,781,868 | <p>I am writing this function to test the primality of numbers, I know that it is not the best code but I would wish it prints out <strong>Not prime</strong> when a number is not prime and <strong>Is prime</strong> when a number is prime. The problem is that it prints out <strong>Not prime</strong> then <strong>Is prim... | 0 | 2016-08-05T05:40:42Z | 38,781,905 | <p><code>break</code> doesn't exist out of a function -- it just exits a loop. So as soon as you print "Not prime", you exit the loop and move on to the next print statement.</p>
<p>replace the <code>break</code> with the keyword <code>return</code> instead. <code>return</code> will immediately exit the function, retu... | 1 | 2016-08-05T05:44:15Z | [
"python"
] |
Why is Python Printing out multiple values here? | 38,781,868 | <p>I am writing this function to test the primality of numbers, I know that it is not the best code but I would wish it prints out <strong>Not prime</strong> when a number is not prime and <strong>Is prime</strong> when a number is prime. The problem is that it prints out <strong>Not prime</strong> then <strong>Is prim... | 0 | 2016-08-05T05:40:42Z | 38,781,927 | <p>Here is a fix (python 3)</p>
<pre><code>
def isPrime(n):
prime = True
for i in range(2, n):
if n%i==0:
print("Not Prime!")
prime = False
break
if prime:
print("Is Prime")
isPrime(5)
isPrime(18)
isPrime(11)
</code></pre>
<p>The problem in the code you posted is that the las... | 1 | 2016-08-05T05:46:18Z | [
"python"
] |
raspberry pi unable to install lxml pip package | 38,782,004 | <p>I am trying to install <code>lxml</code> package after i installed <code>BeautifulSoup4</code> package.</p>
<p>In the terminal i type:</p>
<pre><code>sudo pip install lxml
</code></pre>
<p>This is what i get</p>
<pre><code>sudo pip install lxml
Downloading/unpacking lxml
Running setup.py egg_info for package l... | 0 | 2016-08-05T05:52:06Z | 38,782,069 | <p>well you could open python and try importing it. But if its python 3 try this</p>
<pre><code>sudo apt-get install python3-lxml
</code></pre>
<p>else its </p>
<pre><code>sudo apt-get install python-lxml
</code></pre>
| 1 | 2016-08-05T05:56:12Z | [
"python",
"beautifulsoup",
"raspberry-pi",
"pip",
"lxml"
] |
Cross validation incompatible shapes | 38,782,072 | <p>My csv data is follows:</p>
<pre><code>0.03095566878715169,False
0.9700097239723956,False
0.9756176662740987,False
0.9516273399151274,False
0.21111951544035354,False
0.10371038060888567,False
0.018505911665029413,True
0.3595877911788813,True
0.010223522470333259,True
0.0812290660300292,True
0.19798744613629704,True... | 1 | 2016-08-05T05:56:33Z | 38,806,645 | <p>For sklearn estimators <code>X</code> must be a 2-dimensional array. Try the following:</p>
<pre><code>npX = np.array(X).reshape([-1, 1])
</code></pre>
| 0 | 2016-08-06T16:54:41Z | [
"python",
"scikit-learn",
"cross-validation"
] |
django a href tag not routing properly | 38,782,075 | <p>how can properly route pages using a href tag in templates in django ?
my urls.py</p>
<pre><code>urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$', views.home_page, name='home_page'),
url(r'^post/', include('blog.urls')),
url(r'^post/(?P<slug>[-\w]+)/$', views.single_post, name='post'),
url(r'^about... | 0 | 2016-08-05T05:56:47Z | 38,782,114 | <p>Replace your code with the line below.</p>
<pre><code><li><a href="{% url 'about_page' %}">About</a></li>
</code></pre>
<p>You have defined named url's in your urls.py, so make good use of it.
For more information read this article this will help you making the best use of named urls. <a hr... | 2 | 2016-08-05T06:00:04Z | [
"python",
"html",
"django",
"web",
"url-routing"
] |
Import issue with Theano: AttributeError: 'module' object has no attribute 'poll' | 38,782,089 | <p>I've switched to a new machine and tried to use my code (that working on the previous one).
I'm using python/django/Theano/Keras with the following versions (aligned with the previous machine of course...):</p>
<ul>
<li>Django==1.9.6</li>
<li>django-cors-headers==1.1.0 </li>
<li>django-user-agents==0.3.0 </li>
<l... | 0 | 2016-08-05T05:57:58Z | 38,788,562 | <p>Solved!
The issue was gunicorn version.
gunicorn wasn't listed using pip freeze - therefore I didn't if the versions are aligned.
Anyway - this line solves the issue:</p>
<pre><code>sudo pip install gunicorn==19.4.5
</code></pre>
<p>Note that you'll might have some problems with permissions for .theano folder.
In ... | 0 | 2016-08-05T11:51:06Z | [
"python",
"django",
"import",
"theano",
"keras"
] |
What's wrong with this webcam face detection? | 38,782,191 | <p>Dlib has a really handy, fast and efficient object detection routine, and I wanted to make a cool face tracking example similar to the example <a href="https://realpython.com/blog/python/face-detection-in-python-using-a-webcam/" rel="nofollow">here</a>.</p>
<p>OpenCV, which is widely supported, has VideoCapture mod... | 3 | 2016-08-05T06:05:07Z | 38,782,739 | <p>If you want to show a frame read in OpenCV, you can do it with the help of <code>cv2.imshow()</code> function without any need of changing the colors order. On the other hand, if you still want to show the picture in matplotlib, then you can't avoid using the methods like this:</p>
<pre><code>b,g,r = cv2.split(img)... | 0 | 2016-08-05T06:40:48Z | [
"python",
"opencv",
"webcam",
"dlib"
] |
What's wrong with this webcam face detection? | 38,782,191 | <p>Dlib has a really handy, fast and efficient object detection routine, and I wanted to make a cool face tracking example similar to the example <a href="https://realpython.com/blog/python/face-detection-in-python-using-a-webcam/" rel="nofollow">here</a>.</p>
<p>OpenCV, which is widely supported, has VideoCapture mod... | 3 | 2016-08-05T06:05:07Z | 38,822,675 | <p>I tried multithreading, and it was just as slow, then I multithreaded with just the <code>.read()</code> in the thread, no processing, no thread locking, and it worked quite fast - maybe 1 second or so of delay, not 3 or 5. See <a href="http://www.pyimagesearch.com/2015/12/21/increasing-webcam-fps-with-python-and-op... | 0 | 2016-08-08T06:38:04Z | [
"python",
"opencv",
"webcam",
"dlib"
] |
Inconsistent skewness results between basic skewness formula, Python and R | 38,782,203 | <p>The data I'm using is pasted below. When I apply <a href="http://study.com/academy/lesson/skewness-in-statistics-definition-formula-example.html" rel="nofollow">the basic formula</a> for skewness to my data in R:</p>
<pre><code>3*(mean(data) - median(data))/sd(data)
</code></pre>
<p>The result is -0.07949198. I g... | 1 | 2016-08-05T06:05:55Z | 38,782,731 | <p>The skewness is generally defined as the third central moment (at least when it is being used by statisticians.) The Wikipedia skewness page explains why the definition you found is unreliable. (I had never seen that definition.) The code in <code>descdist</code> is easy to review:</p>
<pre><code>moment <- funct... | 2 | 2016-08-05T06:40:29Z | [
"python",
"scipy",
"distribution"
] |
Inconsistent skewness results between basic skewness formula, Python and R | 38,782,203 | <p>The data I'm using is pasted below. When I apply <a href="http://study.com/academy/lesson/skewness-in-statistics-definition-formula-example.html" rel="nofollow">the basic formula</a> for skewness to my data in R:</p>
<pre><code>3*(mean(data) - median(data))/sd(data)
</code></pre>
<p>The result is -0.07949198. I g... | 1 | 2016-08-05T06:05:55Z | 38,782,831 | <p>I don't have access to the packages you mention right now so I can't check which formula they apply, however, you seem to be using Pearson's second skewness coefficient (see <a href="https://en.wikipedia.org/wiki/Skewness" rel="nofollow">wikipedia</a>). The estimator for the sample skewness is given on the same page... | 3 | 2016-08-05T06:46:31Z | [
"python",
"scipy",
"distribution"
] |
Freeswitch mod_python No module named freeswitch | 38,782,263 | <p>I installed Freeswitch 1.6 in Debian 8, using <a href="https://freeswitch.org/confluence/display/FREESWITCH/Debian+8+Jessie" rel="nofollow">this</a> link. Installing latest release branch section.</p>
<p>Module python is enabled using fs_cli:</p>
<pre><code>>module_exists mod_python ... | 1 | 2016-08-05T06:09:42Z | 38,782,276 | <p>I copied <code>freeswitch.py</code> to <code>/usr/share/freeswitch/scripts/</code>
and that solved the problem.</p>
| 2 | 2016-08-05T06:11:09Z | [
"python",
"freeswitch"
] |
Python Script to convert Excel Date Format from mmm-yy to yyyy-mm-dd? | 38,782,344 | <p>Hi can someone please assist.</p>
<p>I wish to modify Column A, on Sheet 3 of an Excel Work book to change the Date Format from:</p>
<p>Sep-15 to 2016-09-15.</p>
<p>In Excel this the format is mmm-yy I wish to change it to yyyy-mm-dd.</p>
<p>Trying to get my head around it, I know you could use a module like pan... | 0 | 2016-08-05T06:15:56Z | 38,782,525 | <p>See this example.</p>
<pre><code>import xlsxwriter
workbook = xlsxwriter.Workbook('date_examples.xlsx')
worksheet = workbook.add_worksheet()
# Widen column A for extra visibility.
worksheet.set_column('A:A', 30)
# A number to convert to a date.
number = 41333.5
# Write it as a number without formatting.
workshe... | 1 | 2016-08-05T06:27:31Z | [
"python",
"excel"
] |
wxPython: ListBox not selectable/clickable when used with ComboCtrl | 38,782,346 | <p>I am trying to couple <code>wx.ListBox</code> with <code>wx.combo.Comboctrl</code>. A sample code is below. For some reason, the items in the ListBox are not clickable/selectable. I wonder how I can make it work. Thanks!</p>
<h2>EDIT: Missing code added</h2>
<pre><code>import wx, wx.combo
class MainFrame(wx.Frame... | 0 | 2016-08-05T06:16:00Z | 38,834,478 | <p>You are missing a few things in your <code>ListBoxComboPopup</code> class needed to make it work well with the <code>ComboCtrl</code>. At a minimum you are missing some event binding and handler to catch selection events from the <code>ListBox</code>, and an implementation of the <code>GetStringValue</code> method w... | 0 | 2016-08-08T16:41:25Z | [
"python",
"listbox",
"wxpython"
] |
Reading nastran geometry file with python | 38,782,398 | <h2>What I want to do</h2>
<p>I am trying to parse the geometry information of a nastran file using python. My current attempts use NumPy as well as regular expressions. It is important to read the data fast and that the result is a NumPy array.</p>
<h2>Nastran file format</h2>
<p>A nastran file can look like the fo... | 2 | 2016-08-05T06:18:58Z | 38,782,611 | <p>Would something like this work fine? Match the <code>.-</code> and replace with <code>.e-</code>.</p>
<p>Regex: <code>(\.-)(?!(.{7})?$)</code></p>
<p><a href="https://regex101.com/r/uB8dO7/1" rel="nofollow">DEMO</a></p>
| 0 | 2016-08-05T06:33:50Z | [
"python",
"regex",
"numpy",
"nastran"
] |
Python subprocess Popen returns with non zero error code but no error | 38,782,423 | <p>I am trying to execute an executable binary that produces an error. My code for the execution of binary using Popen:</p>
<pre><code>p = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True)
output, error = p.communicate()
return_code = p.returncode
if error:
raise SomeLocallyDefinedError
</code></pre>
<p>This is sup... | 0 | 2016-08-05T06:20:36Z | 38,782,689 | <p>The output is generated by the shell, while catching an <code>SIGFPE</code> signal. You have to catch this signal in your program by yourself and handle it as you wish.</p>
| 0 | 2016-08-05T06:37:53Z | [
"python",
"subprocess",
"popen"
] |
Python subprocess Popen returns with non zero error code but no error | 38,782,423 | <p>I am trying to execute an executable binary that produces an error. My code for the execution of binary using Popen:</p>
<pre><code>p = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True)
output, error = p.communicate()
return_code = p.returncode
if error:
raise SomeLocallyDefinedError
</code></pre>
<p>This is sup... | 0 | 2016-08-05T06:20:36Z | 38,782,714 | <p>This is not just an ordinary runtime error, it is a process crash raised by kernel (via a signal). </p>
<p>If you are running on UNIX//Linux/OS X you should get a core dump (<code>ulimit -c unlimited</code> in the shell). Kernel does not write to a process's stderr - it can't because the process has crashed. </p>
... | 0 | 2016-08-05T06:39:21Z | [
"python",
"subprocess",
"popen"
] |
ImportError: No module named package | 38,782,478 | <p>I found importing modules in Python complicated, so I'm doing experiments to clear it up. Here is my file structure:</p>
<pre><code>PythonTest/
package/
__init__.py
test.py
</code></pre>
<p>Content of <code>__init__.py</code>:</p>
<pre><code>package = 'Variable package in __init__.py'
from package impor... | 0 | 2016-08-05T06:24:38Z | 38,810,996 | <p>First Let's see how Python search for packages and modules. <a href="https://docs.python.org/3/library/sys.html#sys.path" rel="nofollow"><code>sys.path</code></a> </p>
<blockquote>
<p>A list of strings that specifies the search path for modules. Initialized from the environment variable <code>PYTHONPATH</code>, p... | 1 | 2016-08-07T04:55:31Z | [
"python",
"python-2.7",
"import",
"module",
"python-import"
] |
Python mocking a parameter | 38,782,666 | <p>I have some code which invokes a HTTP request and I would like to unit test a negative case where it should raise a specific exception for a 404 response. However I am trying to figure out how to mock the parameter so it can raise the <code>HTTPError</code> as a side-effect in the calling function, the mock object s... | 0 | 2016-08-05T06:36:40Z | 38,782,964 | <p>Mock the <code>urlopen()</code> to raise an exception; you can do this by setting the <a href="https://docs.python.org/3/library/unittest.mock.html#unittest.mock.Mock.side_effect" rel="nofollow"><code>side_effect</code> attribute</a> of the mock:</p>
<pre><code>with mock.patch('urlopen') as urlopen_mock:
urlope... | 1 | 2016-08-05T06:53:24Z | [
"python",
"unit-testing",
"mocking",
"magicmock"
] |
read certificate(.crt) and key(.key) file in python | 38,782,787 | <p>So i'm using the JIRA-Python module to connect to my company's instance on JIRA and it requires me to pass the certificate and key for this.
However using the OpenSSL module,i'm unable to read my local certificate and key to pass it along the request.</p>
<p>the code for reading is below</p>
<pre><code>import Open... | 1 | 2016-08-05T06:44:06Z | 39,230,784 | <p>Which format in your <code>.crt</code> file.
Are there:</p>
<ol>
<li>text starting with <code>-----BEGIN CERTIFICATE-----</code></li>
<li>base64 text started with <code>MI</code> chars</li>
<li>binary data starting with <code>\x30</code> byte?</li>
</ol>
<p>In first two case there are PEM format, but in second one... | 0 | 2016-08-30T14:51:43Z | [
"python",
"pyopenssl",
"python-jira"
] |
Creating an adjacency list graph from a matrix in python | 38,782,820 | <p>So I'm trying to make a graph of letters (to represent a boggle board) from a matrix of letters. So say I have something like:</p>
<pre><code>[ [ A, B, C, D],
[E, F, G, H],
[I, J, K, L],
[M, N, O, P] ].
</code></pre>
<p>I want each node to be a letter, but I'm having trouble figuring out how to get the ne... | 1 | 2016-08-05T06:45:42Z | 38,782,931 | <p>You have to use dictionary to store the nodes connected to a node
:</p>
<pre><code>g = { "A" : ["D", "F"],
"B" : ["C"],
"C" : ["B", "C", "D", "E"],
"D" : ["A", "C"],
"E" : ["C"],
"F" : ["D"]
}
</code></pre>
<p>depending on the structure of your graph.</p>
<p>To get the neighbors ... | 0 | 2016-08-05T06:51:54Z | [
"python",
"matrix",
"graph",
"adjacency-list",
"adjacency-matrix"
] |
Creating an adjacency list graph from a matrix in python | 38,782,820 | <p>So I'm trying to make a graph of letters (to represent a boggle board) from a matrix of letters. So say I have something like:</p>
<pre><code>[ [ A, B, C, D],
[E, F, G, H],
[I, J, K, L],
[M, N, O, P] ].
</code></pre>
<p>I want each node to be a letter, but I'm having trouble figuring out how to get the ne... | 1 | 2016-08-05T06:45:42Z | 38,783,642 | <p>Assuming your matrix is an n x m matrix, and each element is a <strong>unique</strong> string like the following:
<pre><code>
# The matrix</p>
<pre><code>matrix = [
['A', 'B', 'C', 'D'],
['E', 'F', 'G', 'H'],
['I', 'J', 'K', 'L'],
['M', 'N', 'O', 'P']
]
</code></pre>
<p></pre></code></p>
<p>Yo... | 2 | 2016-08-05T07:33:54Z | [
"python",
"matrix",
"graph",
"adjacency-list",
"adjacency-matrix"
] |
Creating an adjacency list graph from a matrix in python | 38,782,820 | <p>So I'm trying to make a graph of letters (to represent a boggle board) from a matrix of letters. So say I have something like:</p>
<pre><code>[ [ A, B, C, D],
[E, F, G, H],
[I, J, K, L],
[M, N, O, P] ].
</code></pre>
<p>I want each node to be a letter, but I'm having trouble figuring out how to get the ne... | 1 | 2016-08-05T06:45:42Z | 38,784,574 | <p>You could loop through every node in your matrix and then add every neighboring node at right & below to the result:</p>
<pre><code>matrix = [
['A', 'B', 'C', 'D'],
['E', 'F', 'G', 'H'],
['I', 'J', 'K', 'L'],
['M', 'N', 'O', 'P']
]
def add(adj_list, a, b):
adj_list.setdefault(a, []).append(... | 1 | 2016-08-05T08:24:33Z | [
"python",
"matrix",
"graph",
"adjacency-list",
"adjacency-matrix"
] |
How to disable input history in Django forms? | 38,782,869 | <p>I'm capturing sensitive information on the main page of my Django project.
Is there a way to prevent the previous login info from showing when a user clicks or starts typing in the box?</p>
| 2 | 2016-08-05T06:48:21Z | 38,783,031 | <p>You can disable autocomplete on such fields by setting the HTML5 <code>autocomplete</code> attribute to <code>off</code>. To achieve this in Django's forms you need to pass additional information to the widget for each input, e.g.:</p>
<pre><code>class MyForm(forms.Form):
secret = forms.CharField(widget=forms.... | 2 | 2016-08-05T06:58:36Z | [
"python",
"django",
"django-forms"
] |
Why is this code printing None? | 38,782,905 | <p>Tried to execute the below program along with values its printing <code>None</code>. Can anyone help me why its printing <code>None</code>?</p>
<pre><code>class Myself(object):
def __init__(self):
self.record={}
def __iter__(self):
self._roles = list(self.record.keys())
#print ("in i... | 1 | 2016-08-05T06:50:30Z | 38,783,041 | <p>You should raise <code>StopIteration</code>:</p>
<pre><code>def __next__(self):
if self._roles:
return self._roles.pop()
else:
raise StopIteration
</code></pre>
| 1 | 2016-08-05T06:58:57Z | [
"python"
] |
Why is this code printing None? | 38,782,905 | <p>Tried to execute the below program along with values its printing <code>None</code>. Can anyone help me why its printing <code>None</code>?</p>
<pre><code>class Myself(object):
def __init__(self):
self.record={}
def __iter__(self):
self._roles = list(self.record.keys())
#print ("in i... | 1 | 2016-08-05T06:50:30Z | 38,783,147 | <p>You need to <em>raise</em> the <code>StopIteration</code> execption:</p>
<pre><code>def __next__(self):
if self._roles:
return self._roles.pop()
else:
raise StopIteration
</code></pre>
<p>Because you don't <code>raise</code> it, you are merely referencing the name, which does nothing. Then ... | 1 | 2016-08-05T07:05:04Z | [
"python"
] |
Python replace string (upper or lower case) with another string | 38,782,913 | <p>I want to replace the word ?Month in a text with the word August.</p>
<pre><code>text=text.replace('?Month','August')
</code></pre>
<p>The issue is that I don't want upper or lower case to matter in ?Month. Regardless if ?Month is upper or lower case (or a mixture) it shall be overwritten with August. See the exam... | 0 | 2016-08-05T06:50:49Z | 38,783,023 | <p>Use a regular expression (via the <a href="https://docs.python.org/2/library/re.html" rel="nofollow"><code>re</code> module</a>):</p>
<pre><code>import re
text = re.sub(r'\?month', 'August', text, flags=re.IGNORECASE)
</code></pre>
<p>The <a href="https://docs.python.org/2/library/re.html#re.I" rel="nofollow"><co... | 2 | 2016-08-05T06:57:52Z | [
"python",
"python-2.7"
] |
Python replace string (upper or lower case) with another string | 38,782,913 | <p>I want to replace the word ?Month in a text with the word August.</p>
<pre><code>text=text.replace('?Month','August')
</code></pre>
<p>The issue is that I don't want upper or lower case to matter in ?Month. Regardless if ?Month is upper or lower case (or a mixture) it shall be overwritten with August. See the exam... | 0 | 2016-08-05T06:50:49Z | 38,786,435 | <p>For the sport of it, without importing anything:</p>
<pre><code>text = text.split(' ')
for i, s in enumerate(text): text[i] = 'August' if s.lower() == 'month' else text[i]
print((' ').join(text))
</code></pre>
<p>This will replace every occurence of <code>s</code> by <code>August</code> if <code>s.lower()</code... | 0 | 2016-08-05T09:57:48Z | [
"python",
"python-2.7"
] |
building a package from source whose binary is already installed | 38,782,969 | <p>I need to build a python module from source. It is just my second build and I'm a bit confused regarding the interaction between built packages and binaries installed through package manager.</p>
<p>Do I need to uninstall the binary first?</p>
<p>If I don't need to Will it overwrite the installed version or will b... | 1 | 2016-08-05T06:53:42Z | 38,783,475 | <p>I strongly recommend to use <code>virtualenv</code> and build your package inside. Is it really necessary to install via <code>setup.py</code>? If not, you can consider using <code>pip</code> to install your package inside <code>virtualenv</code>.</p>
| 1 | 2016-08-05T07:23:37Z | [
"python",
"linux",
"matplotlib",
"build",
"fedora"
] |
how to add a new column to a dataframe in python and insert d/f values in it for d/f rows? | 38,783,110 | <p>I have the following dataframe(df1) in python :</p>
<pre><code> ID Date Time XYZ
0 GP3 2016-01-08 16:00:00 64
1 GP2 2016-01-08 16:00:00 557
2 GP4 2016-01-08 16:00:00 747
3 GP1 2016-01-08 16:00:00 406
4 EP3 2016-01-08 16:0... | 3 | 2016-08-05T07:02:56Z | 38,783,171 | <p>Use the <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.map.html" rel="nofollow"><code>.map</code></a> method:</p>
<pre><code>df1['ABC'] = df1['ID'].map(dict1)
df1
Out[7]:
ID Date Time XYZ ABC
0 GP3 2016-01-08 16:00:00 64 23
1 GP2 2016-01-08 16:00:00 557 45... | 1 | 2016-08-05T07:06:15Z | [
"python",
"pandas",
"dataframe"
] |
error message "(#12) fql is deprecated for versions v2.1 and higher" | 38,783,494 | <p>I tried to fetching facebook messages using python script which is mentioned in the code below :</p>
<pre><code>#!/usr/bin/python
import sys
from facepy import GraphAPI
from facepy import exceptions
#Acces token with expire time = 60days
LONG_LIVE_ACCESS_TOKEN = 'EAAZA7IlqBfvkBAKOjc7esSqY1VRJdsMkZC6QXM2mVlAwZAW... | -2 | 2016-08-05T07:25:18Z | 38,783,582 | <p>FQL is deprecated and will be completely unsupported by Facebook by August 8, 2016. <a href="https://developers.facebook.com/docs/reference/fql/" rel="nofollow">Facebook Query Language (FQL) Reference</a>:</p>
<blockquote>
<p>As of August 8, 2016, <code>FQL</code> will no longer be available and cannot be
queri... | 0 | 2016-08-05T07:30:50Z | [
"python",
"facebook"
] |
Pyspider Installation for Python 3.5/win 64 "Failed building wheel for lxml | 38,783,619 | <p>I'm trying to install pyspider and always got </p>
<p>"Failed building wheel for lxml...", It looks like the lxml is not installed properly and I've tried to download lxml-3.6.1-cp35-cp35m-win_amd64.whl from <a href="http://www.lfd.uci.edu/~gohlke/pythonlibs/#psutil" rel="nofollow">http://www.lfd.uci.edu/~gohlke/py... | 0 | 2016-08-05T07:32:33Z | 38,823,031 | <p>I changed another computer and download successfully. Maybe it's just a connecting issue.</p>
<p>Pyspider installation step:</p>
<p>1.python get-pip.py</p>
<p>2.download lxml-3.6.1-cp35-cp35m-win_amd64.whl from <a href="http://www.lfd.uci.edu/~gohlke/pythonlibs/#lxml" rel="nofollow">http://www.lfd.uci.edu/~gohlke... | 0 | 2016-08-08T07:02:16Z | [
"python",
"lxml",
"wheel",
"pyspider"
] |
How to get a name of a css property using selenium-python? | 38,783,813 | <p>am trying to get the following text</p>
<pre><code>5 â's all the way! There is no better place to be!
</code></pre>
<p>using the following</p>
<pre><code>reviews_title = browser.find_elements_by_xpath('//span[@class="review-title"]/following-sibling::')
</code></pre>
<p>from the snippet below</p>
<pre><code>&... | -1 | 2016-08-05T07:43:50Z | 38,784,513 | <p>Text is inside <code>body</code> tag, you can directly identify it using:-</p>
<pre><code>reviews_title = browser.find_elements_by_xpath('//body/text()')
</code></pre>
| 0 | 2016-08-05T08:20:23Z | [
"python",
"selenium-webdriver"
] |
How to get a name of a css property using selenium-python? | 38,783,813 | <p>am trying to get the following text</p>
<pre><code>5 â's all the way! There is no better place to be!
</code></pre>
<p>using the following</p>
<pre><code>reviews_title = browser.find_elements_by_xpath('//span[@class="review-title"]/following-sibling::')
</code></pre>
<p>from the snippet below</p>
<pre><code>&... | -1 | 2016-08-05T07:43:50Z | 38,784,600 | <p>Assuming you have HTML like this:</p>
<pre><code><div class="review">
<span class="review-title">Love!</span>
5 â's all the way! There is no better place to be!
</div>
<div class="review">
<span class="review-title">Foo!</span>
Lorem ipsum dolor sit amet... | 1 | 2016-08-05T08:25:55Z | [
"python",
"selenium-webdriver"
] |
One to One LSTM | 38,783,981 | <p>I have a sequence of numbers of length 1000, which I chop up into 100 length sequences. So I end up with 901 sequences of length 100. Let the first 900 be <code>trainX</code>. <code>trainY</code> is the 2nd to the 901th of these sequences.</p>
<p>In keras I wish to build the following pictured model: <a href="http:... | 1 | 2016-08-05T07:52:25Z | 38,828,047 | <p>You don't need multiple outputs. Train your model to predict the next number in the sequence. Then, use the predicted number and feed it to the trained model and predict the next one and repeat this task. In other words:</p>
<p>Prepare data for training:</p>
<pre><code>X_train = np.zeros((901, 100))
y_train = np.z... | 1 | 2016-08-08T11:27:32Z | [
"python",
"deep-learning",
"keras",
"lstm"
] |
Can I add links manually to LinkExtractor? | 38,784,183 | <p>It looks like that LinkExtractor can't extract links from data that was loaded/generated by an ajax request inside a function (<a href="http://stackoverflow.com/q/38777236/587990">see here</a>)!</p>
<p>So, is there a way to add extract links in the function and then add them manually to LinkExtractor, or force Link... | 0 | 2016-08-05T08:03:15Z | 38,784,478 | <p>I'm not sure if I understand you correctly here but it seems you are confusing <code>LinkExtractor</code> with <code>CrawlSpider.rules</code>. LinkExtractor is just an object which extracts links from response, where rules attribute describes crawling rules for <code>CrawlSpider</code>.</p>
<p>If you want to use Cr... | 1 | 2016-08-05T08:18:49Z | [
"python",
"scrapy"
] |
Surprised about good recursion performance in python | 38,784,246 | <p>I wrote this rather poor Python function for prime factorization:</p>
<pre><code>import math
def factor(n):
for i in range(2, int(math.sqrt(n)+1)):
if not n % i:
return [i] + factor(n//i)
return [n]
</code></pre>
<p>and it worked as expected, now I was interested in whether the perform... | 4 | 2016-08-05T08:06:05Z | 38,784,376 | <p>Itâs because youâre recomputing <code>sqrt</code> each time. This modification runs as fast as your recursive version:</p>
<pre><code>def factor_it2(n):
r = []
i = 2
lim = int(math.sqrt(n)+1)
while i < lim:
while not n % i:
r.append(i)
n //= i
lim = int... | 5 | 2016-08-05T08:13:10Z | [
"python",
"performance",
"python-3.x",
"recursion"
] |
Conditional fill dataframe pandas | 38,784,260 | <p>I am fairly new to pandas so bear with me. I have a dataframe with interaction-data (begin time of the interaction, end time of the interaction, userA and userB that had interaction):</p>
<blockquote>
<p>begin, end, userA, userB.</p>
</blockquote>
<p>Now I would like to transform this data into the following for... | 1 | 2016-08-05T08:06:46Z | 38,786,081 | <p>assuming you have the following source DF:</p>
<pre><code>In [134]: df
Out[134]:
begin end userA userB
0 130 134 1 2
1 201 203 5 1
2 333 334 2 5
</code></pre>
<p>we can do the following:</p>
<pre><code>time_range = np.arange(0, 1001)
dfs = []
for u in df[['userA','... | 1 | 2016-08-05T09:39:23Z | [
"python",
"pandas",
"dataframe",
"conditional",
"data-science"
] |
Python pandas: create new column based on category values from another dataframe | 38,784,330 | <p>I have two dataframes: </p>
<ul>
<li><code>dfA</code>, which contains thousands of lines of temperature data. Each temperature value is linked to a <code>timeID</code> value (1, 2, 3, ..., n) measured from different objects, so that there are repeated time IDs</li>
<li><code>dfB</code> contains labels identifying e... | 1 | 2016-08-05T08:10:45Z | 38,784,582 | <p>Try this: </p>
<pre><code>dfNew = dfA.join(dfB, on='timeID')
</code></pre>
| 0 | 2016-08-05T08:25:07Z | [
"python",
"pandas",
"dataframe",
"category"
] |
Python pandas: create new column based on category values from another dataframe | 38,784,330 | <p>I have two dataframes: </p>
<ul>
<li><code>dfA</code>, which contains thousands of lines of temperature data. Each temperature value is linked to a <code>timeID</code> value (1, 2, 3, ..., n) measured from different objects, so that there are repeated time IDs</li>
<li><code>dfB</code> contains labels identifying e... | 1 | 2016-08-05T08:10:45Z | 38,784,850 | <p>First of all you will need to make sure that the <code>timeID</code> column is of the same dtype in both DFs and then you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.map.html" rel="nofollow">map()</a> method:</p>
<pre><code>In [78]: dfA['date'] = dfA['timeID'].astype(dfB.ind... | 1 | 2016-08-05T08:38:48Z | [
"python",
"pandas",
"dataframe",
"category"
] |
separation of the string in .ini file (configparser) | 38,784,427 | <p>My ConfigParser.ini file looks like:</p>
<pre><code>[Filenames]
Table1={"logs.table2",92}
Table2=("logs.table2",91)
Table3=("audit.table3",34)
Table4=("audit.table4",85)
</code></pre>
<p>and now for example for Table1, I would like to get "logs.table2" value as saperate variable and 92 as saperate variable.</p>
<... | 0 | 2016-08-05T08:16:08Z | 38,784,730 | <p>Parsing .ini files is getting strings.</p>
<blockquote>
<p>[Filenames] </p>
<p>Table1=logs.table2,92 </p>
<p>Table2=logs.table2,91 </p>
<p>Table3=audit.table3,34 </p>
<p>Table4=audit.table4,85</p>
</blockquote>
<p><code>table</code> is a string, so you can split its contents into a list of ... | 1 | 2016-08-05T08:33:21Z | [
"python",
"configparser"
] |
separation of the string in .ini file (configparser) | 38,784,427 | <p>My ConfigParser.ini file looks like:</p>
<pre><code>[Filenames]
Table1={"logs.table2",92}
Table2=("logs.table2",91)
Table3=("audit.table3",34)
Table4=("audit.table4",85)
</code></pre>
<p>and now for example for Table1, I would like to get "logs.table2" value as saperate variable and 92 as saperate variable.</p>
<... | 0 | 2016-08-05T08:16:08Z | 38,784,843 | <p>Yet another way:</p>
<p>ConfigParser.ini</p>
<pre><code>[Filenames]
Table1.filename=logs.table2
Table1.filenumber=92
Table2.filename=logs.table2
Table2.filenumber=91
Table3.filename=audit.table3
Table3.filenumber=34
Table4.filename=audit.table4
Table4.filenumber=85
</code></pre>
<p>Code:</p>
<pre><code>from conf... | 1 | 2016-08-05T08:38:30Z | [
"python",
"configparser"
] |
Dynamically printing value of entry in another entry | 38,784,575 | <p>My code:</p>
<pre><code>import tkinter as tk
disp = tk.Tk()
hlabel=tk.Label(text="host")
hlabel.grid(column=0,row=0)
host_entry = tk.Entry(disp)
host_entry.grid(row=0,column=1)
plabel=tk.Label(text="port")
plabel.grid(column=0,row=1)
port_entry = tk.Entry(disp)
port_entry.grid(row=1,column=1)
ulabel=tk.Label(te... | -1 | 2016-08-05T08:24:34Z | 38,789,098 | <p>The simplest solution is to use a <code>textvariable</code> for each entry, put a trace on each variable, and then update the third entry whenever the trace fires.</p>
<p>First, define a function to update the third entry. It will be called by the trace functions, which automatically appends some arguments which we... | 0 | 2016-08-05T12:19:31Z | [
"python",
"tkinter"
] |
NodeJS TCP connection timeout | 38,784,682 | <p>I'm trying to get my javascript file connected with my Application server(on another computer A, within the same network) with <a href="https://gist.github.com/tedmiston/5935757" rel="nofollow">NodeJS TCP</a>
but failed to do so.</p>
<p><strong>Client Script</strong></p>
<pre><code>var net = require('net');
var cl... | 1 | 2016-08-05T08:30:24Z | 38,810,481 | <p>Are you sure you are connecting to the correct port number? It happened to me one time and it was a terrible careless mistake</p>
| 0 | 2016-08-07T03:00:02Z | [
"javascript",
"python",
"node.js",
"sockets",
"tcp"
] |
Creating a single instance of an object for composition vs SomeClass().someMethod() performance | 38,784,747 | <p>I am not sure if the title is descriptive of my question really but I don't know how to better phrase it. I am working with an API that has a Util class for gui testing. Inside the Util class there are a lot of functions such as click, type, and other gui interactions. I am wondering what the benefits and downsides ... | 0 | 2016-08-05T08:33:54Z | 38,784,980 | <p>As you mentioned, performance-wise it may e irrelevant. So irrelevant, in fact that it may be difficult to even say which method would be faster. However, if you know that constructing <code>Util()</code> is expensive and you expect to call <code>typeSomething(...)</code> often, then the instance of util becomes a r... | 0 | 2016-08-05T08:45:16Z | [
"python",
"performance",
"oop"
] |
Check if two strings contain the same pattern in python | 38,784,759 | <p>I have the following list:</p>
<pre><code>names = ['s06_215','s06_235b','s06_235','s08_014','18:s08_014','s08_056','s08_169']
</code></pre>
<p><code>s06_235b</code> and <code>s06_235</code>, <code>s08_014</code> and <code>18:s08_014</code> are duplicated. However, as shown in the example, there is no specific patt... | -1 | 2016-08-05T08:34:34Z | 38,784,894 | <p>You can use an 'in' operator to see if on variable contains another</p>
<pre><code>if "example" in "this is an example":
</code></pre>
<p>Try this:</p>
<pre><code>for i in range(0, len(names)-1):
for index, value in enumerate(names):
if names[i] in names[index] and len(names[i]) > 4:
print... | 1 | 2016-08-05T08:40:41Z | [
"python",
"regex",
"string",
"pattern-matching"
] |
Check if two strings contain the same pattern in python | 38,784,759 | <p>I have the following list:</p>
<pre><code>names = ['s06_215','s06_235b','s06_235','s08_014','18:s08_014','s08_056','s08_169']
</code></pre>
<p><code>s06_235b</code> and <code>s06_235</code>, <code>s08_014</code> and <code>18:s08_014</code> are duplicated. However, as shown in the example, there is no specific patt... | -1 | 2016-08-05T08:34:34Z | 38,785,053 | <p>You could iterate all the <a href="https://docs.python.org/3/library/itertools.html#itertools.combinations" rel="nofollow"><code>combinations</code></a>, <code>join</code> them with some special character that can not be part of those strings, and use a <a href="https://docs.python.org/3/library/re.html" rel="nofoll... | 2 | 2016-08-05T08:49:06Z | [
"python",
"regex",
"string",
"pattern-matching"
] |
Type annotation in Python | 38,784,965 | <p>how to write the <strong>:type</strong> annotation in Python in case the argument can have different types?</p>
<pre><code> """
:type param_name: type1|type2
"""
</code></pre>
<p>or</p>
<pre><code> """
:type param_name: type1 / type2
"""
</code></pre>
<p>PyCharm accepts the 2nd variant</p>
| -1 | 2016-08-05T08:44:33Z | 38,785,188 | <p>You are using the <em>Sphinx project notation</em>, which incidentally was rejected for inclusion in the <a href="https://www.python.org/dev/peps/pep-0484/#other-backwards-compatible-conventions" rel="nofollow">PEP 484 -- <em>Type Hints</em> proposal</a>. </p>
<p><code>:type</code> is an <a href="http://www.sphinx-... | 0 | 2016-08-05T08:55:56Z | [
"python",
"annotations",
"type-hinting"
] |
Read txt file into dictionary in python | 38,784,970 | <p>I am having problems trying to read this <em>txt</em> file into dictionary in python. How can do it?</p>
<p><code>
NAMES MARKS
Lux 95
Veron 70
Lesley 88
Sticks 80
Tipsy 40
Joe 62
Goms 18
Wistly 35
Villa 11
Dentist 72
Onty 50
</code></p>
| -5 | 2016-08-05T08:44:37Z | 38,785,209 | <p>You can open a file using the line:</p>
<pre><code>with open('<filename>') as f:
</code></pre>
<p>This will set the variable called f to the file.
you could try using the split function</p>
<pre><code>with open('<filename>') as f:
dict = {}
for line in f:
part_one, part_two = line.spli... | 0 | 2016-08-05T08:57:08Z | [
"python"
] |
Can't execute casperjs through python on mac | 38,784,975 | <p>I'm pretty new to Mac, sorry if this is something very simple.</p>
<p>I can run my javascript file through terminal using command:</p>
<pre><code>casperjs myfile.js
</code></pre>
<p>However, I want to execute this command through python script.</p>
<p>this is what i've got:</p>
<pre><code>pathBefore = os.getcwd... | 0 | 2016-08-05T08:45:04Z | 38,851,694 | <p>Solved my issue by typing these three lines in terminal:
<code>
sudo ln -s /path/to/bin/phantomjs /usr/local/share/phantomjs
sudo ln -s /path/to/bin/phantomjs /usr/local/bin/phantomjs
sudo ln -s /path/to/bin/phantomjs /usr/bin/phantomjs</code></p>
<p>and using python code:</p>
<pre><code>commands = '''
pwd
cd ..
p... | 0 | 2016-08-09T13:08:51Z | [
"python",
"osx",
"casperjs"
] |
write a part of a file to another file | 38,785,021 | <p>I want to read a input file (input.txt) line by line in a main directory. This input file consists of the name of some subfolders (subfolder1, subfolder2,...). Each subfolder contains a file (for instance the subfolder1 contains subfolder1.pdb) with the same name. The code will read each subfolder's name from the in... | 0 | 2016-08-05T08:47:13Z | 38,785,273 | <p>Considering you'll be reading from a different file than the one you'll be writing to, you're going to have to have multiple files open. If these are always the same files, you only need to do two <code>open</code>s. For example, the following just copies every line to the other file:</p>
<pre><code>with open("inpu... | 1 | 2016-08-05T08:59:52Z | [
"python"
] |
Machine Learning Naive Bayes Classifier in Python | 38,785,032 | <p>I've been experimenting with machine learning and need to develop a model which will make a prediction based on a number of variables. The easiest way I can explain this is through the "play golf" example below:</p>
<p>train.csv</p>
<pre><code>Outlook,Temperature,Humidity,Windy,Play
overcast,hot,high,FALSE,yes
ove... | 1 | 2016-08-05T08:47:52Z | 38,788,614 | <p>It depends. If you don't want to code, Try <a href="https://rapidminer.com/" rel="nofollow">Rapidminier</a>. It is very simple to learn and experiment. It's <a href="http://docs.rapidminer.com/studio/getting-started/" rel="nofollow">documentation</a> is very good and clear.You can see <a href="http://docs.rapidminer... | 1 | 2016-08-05T11:53:50Z | [
"python",
"machine-learning",
"naivebayes"
] |
404 while connecting to /hello/1 but 200 while connecting to any other number such as /hello/12 in flask | 38,785,169 | <p>Trying to learn flask but stuck with some error or maybe an issue.</p>
<pre><code>def check_int(no):
return "number is %d" %no
app.add_url_rule('/hello/<int:no>', 'nothign_specific', check_int)
</code></pre>
<p>So when I do a curl call to <code>http://127.0.0.1:5000/hello/1</code> it fails wherein the sa... | 0 | 2016-08-05T08:54:49Z | 38,785,655 | <p>In flask, if your route (or rule) definition has <em>no trailing slash</em> is explicit. If you would add a trailing <code>/</code> to your url rule, i.e.</p>
<pre><code>'/hello/<int:no>/'
</code></pre>
<p>then you would be able to use both (request with or without <code>/</code>).</p>
<p>According to flask... | 1 | 2016-08-05T09:18:26Z | [
"python",
"flask"
] |
Count elements in a nested list in an elegant way | 38,785,229 | <p>I have nested tuples in a list like</p>
<pre><code>l = [(1, 'a', 'b'), (2, 'b', 'c'), (3, 'e', 'a')]
</code></pre>
<p>I want to know how many 'a' and 'b' in the list in total. So I currently use the following code to get the result.</p>
<pre><code>amount_a_and_b = len([None for _, elem2, elem3 in l if elem2 == 'a... | 1 | 2016-08-05T08:58:10Z | 38,785,265 | <p>I'd flatten the list with <a href="https://docs.python.org/3/library/itertools.html#itertools.chain.from_iterable" rel="nofollow"><code>itertools.chain.from_iterable()</code></a> and pass it to a <a href="https://docs.python.org/3/library/collections.html#collections.Counter" rel="nofollow"><code>collections.Counter... | 6 | 2016-08-05T08:59:37Z | [
"python",
"python-3.x"
] |
Count elements in a nested list in an elegant way | 38,785,229 | <p>I have nested tuples in a list like</p>
<pre><code>l = [(1, 'a', 'b'), (2, 'b', 'c'), (3, 'e', 'a')]
</code></pre>
<p>I want to know how many 'a' and 'b' in the list in total. So I currently use the following code to get the result.</p>
<pre><code>amount_a_and_b = len([None for _, elem2, elem3 in l if elem2 == 'a... | 1 | 2016-08-05T08:58:10Z | 38,785,367 | <p>Just for fun, functional method using reduce:</p>
<pre><code>>>> l = [(1, 'a', 'b'), (2, 'b', 'c'), (3, 'e', 'a')]
>>> from functools import reduce
>>> reduce(lambda x, y: (1 if 'a' in y else 0) + (1 if 'b' in y else 0) + x, l, 0)
4
</code></pre>
| 0 | 2016-08-05T09:04:08Z | [
"python",
"python-3.x"
] |
Count elements in a nested list in an elegant way | 38,785,229 | <p>I have nested tuples in a list like</p>
<pre><code>l = [(1, 'a', 'b'), (2, 'b', 'c'), (3, 'e', 'a')]
</code></pre>
<p>I want to know how many 'a' and 'b' in the list in total. So I currently use the following code to get the result.</p>
<pre><code>amount_a_and_b = len([None for _, elem2, elem3 in l if elem2 == 'a... | 1 | 2016-08-05T08:58:10Z | 38,785,560 | <p>You want to avoid putting data in a datastructure. The <code>[...]</code> syntax constructs a new list and fills it with the content you put in <code>...</code> , after which the length of the array is taken and the array is never used. If the list if very large, this uses a lot of memory, and it is inelegant in gen... | 1 | 2016-08-05T09:13:57Z | [
"python",
"python-3.x"
] |
Count elements in a nested list in an elegant way | 38,785,229 | <p>I have nested tuples in a list like</p>
<pre><code>l = [(1, 'a', 'b'), (2, 'b', 'c'), (3, 'e', 'a')]
</code></pre>
<p>I want to know how many 'a' and 'b' in the list in total. So I currently use the following code to get the result.</p>
<pre><code>amount_a_and_b = len([None for _, elem2, elem3 in l if elem2 == 'a... | 1 | 2016-08-05T08:58:10Z | 38,786,711 | <p>You can iterate over both the list and the sub-lists in one list comprehension:</p>
<pre><code>len([i for sub_list in l for i in sub_list if i in ("a", "b")])
</code></pre>
<p>I think that's fairly concise.</p>
<p>To avoid creating a temporary list, you could use a generator expression to create a sequence of 1s ... | 0 | 2016-08-05T10:12:59Z | [
"python",
"python-3.x"
] |
Count elements in a nested list in an elegant way | 38,785,229 | <p>I have nested tuples in a list like</p>
<pre><code>l = [(1, 'a', 'b'), (2, 'b', 'c'), (3, 'e', 'a')]
</code></pre>
<p>I want to know how many 'a' and 'b' in the list in total. So I currently use the following code to get the result.</p>
<pre><code>amount_a_and_b = len([None for _, elem2, elem3 in l if elem2 == 'a... | 1 | 2016-08-05T08:58:10Z | 38,786,721 | <p>Although this question already has an accepted answer, just wondering why all of them as so complex. I would think that this would suffice.</p>
<pre><code>>>> l = [(1, 'a', 'b'), (2, 'b', 'c'), (3, 'e', 'a')]
>>> total = sum(tup.count('a') + tup.count('b') for tup in l)
>>> total
4
</code... | 0 | 2016-08-05T10:13:35Z | [
"python",
"python-3.x"
] |
Pandas time series add column showing 1 hour intervals | 38,785,382 | <p>I can create an hour of day column in Pandas using <code>data['hod'] = [r.hour for r in data.index]</code> which is really useful for groupby related analysis. However, I would like to be able to create a similar column for 1 hour intervals starting at 09:30 instead of 09:00. So the column values would be 09:30-10:... | 0 | 2016-08-05T09:04:55Z | 38,796,034 | <p>I assumed that when you start from half point of each hour then you divide a day into 25 sections instead of 24. Here is how I labelled those sections: Section -1: [0:00, 0:29], Section 0: [0:30, 1:29], Section 1: [1:30, 2:29] ... Section 22: [22:30, 23:29] and Section 23: [23:30, 23:50], where first and last sectio... | 0 | 2016-08-05T18:53:01Z | [
"python",
"pandas"
] |
Pandas: Create dataframe column based on other dataframe | 38,785,392 | <p>If I have 2 dataframes like these two:</p>
<pre><code>import pandas as pd
df1 = pd.DataFrame({'Type':list('AABAC')})
df2 = pd.DataFrame({'Type':list('ABCDEF'), 'Value':[1,2,3,4,5,6]})
Type
0 A
1 A
2 B
3 A
4 C
Type Value
0 A 1
1 B 2
2 C 3
3 D 4
4 E 5
5 ... | 1 | 2016-08-05T09:05:16Z | 38,785,620 | <p>You could create <code>dict</code> from your <code>df2</code> with <code>to_dict</code> method and then <code>map</code> result to <code>Type</code> column for <code>df1</code>:</p>
<pre><code>replace_dict = dict(df2.to_dict('split')['data'])
In [50]: replace_dict
Out[50]: {'A': 1, 'B': 2, 'C': 3, 'D': 4, 'E': 5, ... | 1 | 2016-08-05T09:17:08Z | [
"python",
"pandas",
"dataframe"
] |
Calculate stock returns in pandas DataFrame | 38,785,505 | <p>I would like to calculate the annual performance (as change in market value) of these two firms whose data is stored in the dataframe below.</p>
<pre><code>df = pd.DataFrame({'tic' : ['AAPL', 'AAPL', 'AAPL', 'GOOGL','GOOGL','GOOGL'],
'mktvalue' : [20,25,30,50,55,60],
'fyea... | 1 | 2016-08-05T09:10:53Z | 38,787,035 | <p>is that what you want?</p>
<pre><code>In [129]: df['performance'] = df.groupby('tic').mktvalue.pct_change().fillna(0)
In [130]: df
Out[130]:
fyear mktvalue tic performance
0 2014 20 AAPL 0.000000
1 2015 25 AAPL 0.250000
2 2016 30 AAPL 0.200000
3 2014 50... | 0 | 2016-08-05T10:30:11Z | [
"python",
"pandas",
"dataframe"
] |
Python print format umlaut align right | 38,785,511 | <p>I am trying to print text aligned right containing a german umlaut. This is, what the python interpreter produces:</p>
<pre><code>>>> print "----\n{:>4}\n{:>4}".format("Ho", "Hö")
----
Ho
Hö
</code></pre>
<p>so, what am i doing wrong ?</p>
| 1 | 2016-08-05T09:11:20Z | 38,785,768 | <p>Just let python know that you're leading with UTF-8 strings by adding a <code>u</code> in front of the string literal.
</p>
<pre><code>print u"----\n{:>4}\n{:>4}".format("Ho", u"Hö")
</code></pre>
| 1 | 2016-08-05T09:24:20Z | [
"python",
"printing",
"formatting"
] |
Django models, @property decorator for method | 38,785,514 | <p>Let's say I have model like this:</p>
<pre><code>class Article(models.Model):
...
def get_route(self):
...
return data
</code></pre>
<p>When I want to display value returned by <code>get_route()</code> in admin panel I have to create custom method like this:</p>
<pre><code>def list_displa... | 0 | 2016-08-05T09:11:49Z | 38,785,572 | <p>Using <code>get_route</code> in <code>list_display</code> should work even if you don't make it a property.</p>
<pre><code>class Article(models.Model):
def get_route(self):
...
return data
class ArticleAdmin(admin.ModelAdmin):
list_display = ('get_route', ...)
</code></pre>
<p>See the <a ... | 2 | 2016-08-05T09:14:45Z | [
"python",
"django",
"django-models"
] |
How to structure the output in timedelta computation? | 38,785,515 | <p>I have 2 lists of dicts: </p>
<pre><code>hah = [{1:[datetime(2014, 6, 26, 13, 7, 27), datetime(2014, 7, 26, 13, 7,27)]},
{2:datetime(2014, 5, 26,13,7,27)}]
dateofstart = [{1:datetime(2013, 6, 26, 13, 7, 27)}, {2:datetime(2013, 6,
26,13,7,27)}]` (just examples).
</code></pre>
<p... | 0 | 2016-08-05T09:11:51Z | 39,120,518 | <p>I am assuming that the example that you provided is having typo issues, because:</p>
<ul>
<li><p><code>hah</code> is a <code>list</code> of <code>dict</code> with just one <code>key</code> in each dictionary. Instead it is supposed to be single dictionary. Isn't? Also, for key <code>2</code>, value is single <code>... | 0 | 2016-08-24T10:17:35Z | [
"python",
"datetime"
] |
Multiplying 3D matrix with 2D matrix | 38,785,566 | <p>I have two matrices to multiply. One is weight matrix - W whose size is <strong>900x2x2</strong>.
Another is input matrix-I whose size is <strong>2x2</strong>.
Now I want to perform summation over <code>c = WI</code> which will be <strong>900x1</strong> matrix,
but when I perform the operation it multiplies and give... | 1 | 2016-08-05T09:14:24Z | 38,785,734 | <p>It seems you are trying to lose the last two axes of the first array against the only two axes of the second weight array with that matrix-multiplication. We could translate that idea into NumPy code with <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.tensordot.html" rel="nofollow"><code>np.tenso... | 1 | 2016-08-05T09:22:42Z | [
"python",
"numpy",
"matrix",
"matrix-multiplication"
] |
plotting both x and y axis in log scale in pandas using matplotlib | 38,785,579 | <p>My trace file can be downloaded from <a href="https://gist.github.com/ecenm/25df526d4398af2c3e41ae6df6c51155" rel="nofollow">here</a>.</p>
<p>When I plot only y axis in log scale. everything is fine</p>
<pre><code>import pandas as pd
import numpy
import matplotlib.pyplot as plt
iplevel = pd.read_csv('iplevel.csv'... | 0 | 2016-08-05T09:15:04Z | 38,785,701 | <p>It looks like you have some zeros in your X values. log(0) isn't defined, log(veryclosetozero) is 10^{-verymuch}.</p>
<p>Edit: In addition, float representation of numbers isn't always completely exact, so 0.0 might end up being stored as 0.00000000000000000001 or similar. The log function would not throw an error ... | 1 | 2016-08-05T09:20:58Z | [
"python",
"pandas",
"matplotlib",
"plot"
] |
What are MEAN and STD in Tensorflow Tflearn? | 38,785,625 | <p>When I launch TFLearn examples, I get this</p>
<p>Preprocessing... Calculating mean over all dataset (this may take long)...
Mean: 0.916834
Preprocessing... Calculating std over all dataset (this may take long)...
STD: 0.227089</p>
<p>I don't understand what they are. I googled it , I looked on SO, I read <a href... | 0 | 2016-08-05T09:17:21Z | 38,791,614 | <p>I presume you are running <a href="https://github.com/tflearn/tflearn/blob/master/tflearn/data_preprocessing.py" rel="nofollow">this</a> file.</p>
<p>The mean it is computing is the global mean as can be seen in the following snippet:</p>
<pre><code>print("Preprocessing... Calculating mean over all dataset "
... | 0 | 2016-08-05T14:24:46Z | [
"python",
"machine-learning",
"tensorflow"
] |
Python: What is an efficient way to sort a nested array by repeated values? | 38,785,669 | <ul>
<li><p><code>data</code> is a list, where each entry is a list of floats</p></li>
<li><p><code>L</code> is a range to check whether the first entry of <code>_</code> in <code>data</code> is equal to and if so store it at that index in <code>c</code></p></li>
</ul>
<hr>
<pre><code>c = []
d = []
for i in range(L):... | -2 | 2016-08-05T09:19:12Z | 38,786,556 | <h2>Optimization attempt</h2>
<p>Assuming you want to sort your sublists into <em>buckets</em> according to the first value of each sublist.</p>
<p>For simplicity, I use the following to generate random numbers for testing:</p>
<pre><code>L = 10
data = [[round(random.random() * 10.0, 2) for _ in range(3)] for _ in r... | 0 | 2016-08-05T10:04:05Z | [
"python",
"performance",
"list",
"nested",
"repeat"
] |
Python: What is an efficient way to sort a nested array by repeated values? | 38,785,669 | <ul>
<li><p><code>data</code> is a list, where each entry is a list of floats</p></li>
<li><p><code>L</code> is a range to check whether the first entry of <code>_</code> in <code>data</code> is equal to and if so store it at that index in <code>c</code></p></li>
</ul>
<hr>
<pre><code>c = []
d = []
for i in range(L):... | -2 | 2016-08-05T09:19:12Z | 38,787,679 | <p>Running in Python 3 I get 2 order of magnitude better performance than jbndlr with this algorithm:</p>
<pre><code>rl = range(L) # Generate the range list
buck = [[] for _ in rl] # Create all the buckets
for seq in data: # Loop over entire data
try:
idx = rl.index(int(seq[0])) # Find the bucket ... | 0 | 2016-08-05T11:04:01Z | [
"python",
"performance",
"list",
"nested",
"repeat"
] |
Check if a string contains another | 38,785,779 | <p>Checking if a string contains another, why does the first case turn False?</p>
<pre><code>'s161_1189a' in 's161_1189b'
</code></pre>
<p>False</p>
<pre><code>'s160_1156' in '159:s160_1156'
</code></pre>
<p>True</p>
| 0 | 2016-08-05T09:24:45Z | 38,785,984 | <p><code>in</code> operator is used to test if a sequence (list, tuple, string etc.) contains a value. It returns True if the value is present, else it returns False. For example</p>
<pre><code>>>> x = 'subset'
>>>'sub' in x
True
>>>'subsets' in x
False
>>> a = [1, 2, 3, 4, 5]
>... | 1 | 2016-08-05T09:33:55Z | [
"python",
"pattern-matching"
] |
Python: Access a list in a class with properties or custom methods | 38,785,836 | <p>I have the following class:</p>
<pre><code>def Interface:
def __init__(self, vlan, zone, address):
self.vlan = vlan
self.zone = zone
self.__address = []
for i in address:
self.__address.append(ipaddress.IPv4Interface(i))
</code></pre>
<p>An Interface instance could n... | 0 | 2016-08-05T09:27:19Z | 38,786,612 | <p>You change the interface to allow for a variable address count to be passed to the constructor.</p>
<pre class="lang-py prettyprint-override"><code>class Interface:
def __init__(self, vlan, zone, *addresses):
# ...
i = Interface(myVlan, myZone, myAddress1, myAddress2)
</code></pre>
<p><code>addresses<... | 0 | 2016-08-05T10:07:14Z | [
"python",
"list",
"class",
"properties",
"getter-setter"
] |
Executing Python scripts | 38,785,879 | <p>When reading <a href="http://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-i-hello-world" rel="nofollow">a Flask tutorial</a>, the author asked me to <code>chmod a+x run.py</code> and then <code>./run.py</code>, rather than simply <code>python run.py</code> as I usually do. When I ignored the author's in... | 2 | 2016-08-05T09:29:18Z | 38,786,224 | <p>I believe your suspicion is correct. Notice how he creates a virtualenv called <code>flask</code>:</p>
<pre><code>virtualenv flask
</code></pre>
<p><code>run.py</code> contains the following:</p>
<pre><code>#!flask/bin/python
from app import app
app.run(debug=True)
</code></pre>
<p>The first line is called a <a ... | 3 | 2016-08-05T09:46:50Z | [
"python",
"bash",
"command-line-interface",
"virtualenv",
"execution"
] |
Executing Python scripts | 38,785,879 | <p>When reading <a href="http://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-i-hello-world" rel="nofollow">a Flask tutorial</a>, the author asked me to <code>chmod a+x run.py</code> and then <code>./run.py</code>, rather than simply <code>python run.py</code> as I usually do. When I ignored the author's in... | 2 | 2016-08-05T09:29:18Z | 38,786,236 | <p>Take a look at the first line of the file:</p>
<pre><code>#!flask/bin/python
</code></pre>
<p>It means that running:</p>
<pre><code>$ ./run.py
</code></pre>
<p>is equivalent to:</p>
<pre><code>$ flask/bin/python run.py
</code></pre>
<p>and since flask/bin/python is in a virtual environment, it has different mo... | 1 | 2016-08-05T09:47:26Z | [
"python",
"bash",
"command-line-interface",
"virtualenv",
"execution"
] |
Imports with absolute paths in a small-medium data science project | 38,785,894 | <p>I know that there are tons of similar questions here but I couldn't figure out which best suits my project. This is a small data research project organized in the following way:</p>
<pre><code>project-name/
docs/
src/
__init__.py
config.yml
Makefile
data/
data_management/
... | 0 | 2016-08-05T09:29:58Z | 38,786,096 | <p>Several points:</p>
<ol>
<li>If this is Python 2.7 you must have <code>__init__.py</code> in each directory to make it importable. Not needed for Python 3.</li>
<li>Since the makefile is run from within <code>src</code> then that is base of your imports. Each script will need <code>sys.path.insert(0, '.')</code> an... | 0 | 2016-08-05T09:40:00Z | [
"python",
"makefile"
] |
Imports with absolute paths in a small-medium data science project | 38,785,894 | <p>I know that there are tons of similar questions here but I couldn't figure out which best suits my project. This is a small data research project organized in the following way:</p>
<pre><code>project-name/
docs/
src/
__init__.py
config.yml
Makefile
data/
data_management/
... | 0 | 2016-08-05T09:29:58Z | 38,786,173 | <p>I've noticed that, when you wrote about the config file, you've wrote 'config.py'. However in your code it seems to be a .yml file. </p>
<p>If you would choose to use a .py file, you could access it this way:</p>
<pre><code>from src import config
</code></pre>
| 0 | 2016-08-05T09:44:20Z | [
"python",
"makefile"
] |
Imports with absolute paths in a small-medium data science project | 38,785,894 | <p>I know that there are tons of similar questions here but I couldn't figure out which best suits my project. This is a small data research project organized in the following way:</p>
<pre><code>project-name/
docs/
src/
__init__.py
config.yml
Makefile
data/
data_management/
... | 0 | 2016-08-05T09:29:58Z | 38,786,180 | <p>You could make a Package out of your project by creating a <code>setup.py</code> file in <code>project-name</code>. Afterwards you can do</p>
<pre><code>pip install -e project-name/
</code></pre>
<p>and from everywhere in your Python environment you can then do</p>
<pre><code>import project_name
import project_na... | 3 | 2016-08-05T09:44:38Z | [
"python",
"makefile"
] |
Convert the delimited data in a string to values in a single column | 38,785,934 | <p>I have a dataframe like this:</p>
<pre><code>Var_1
201601_abc
201603_tbc;201608_sdf;201508_dsf
201601_abc;201508_dsf
...
</code></pre>
<p>I want a single column that contains the distinct values in Var1(values delimited by ";" are considered different</p>
<p>So Final dataframe will be like:</p>
<pre><code>Var_2
... | 1 | 2016-08-05T09:31:39Z | 38,786,023 | <p>IIUC the following should work:</p>
<pre><code>In [160]:
df2 = pd.DataFrame(df['Var_1'].str.split(';',expand=True).stack().unique(), columns=['Var_2'])
df2
Out[160]:
Var_2
0 201601_abc
1 201603_tbc
2 201608_sdf
3 201508_dsf
</code></pre>
<p>This splits the values on the delimiter, then <a href="http:/... | 2 | 2016-08-05T09:35:48Z | [
"python",
"pandas",
"data-manipulation"
] |
twistd and nohup &: what is the difference? | 38,785,979 | <p>What are the advantages of using twistd over nohup?</p>
<p>Why doing </p>
<pre><code>twistd -y service.tac
</code></pre>
<p>when I can do:</p>
<pre><code>nohup sudo python my_app.py &
</code></pre>
<p>?</p>
<p>I am asking this because I faced a difficulty to use twistd, see <a href="http://stackoverflow.co... | 1 | 2016-08-05T09:33:49Z | 38,786,295 | <p><code>nohup</code> vs. daemonization is explained beautifully in <a href="http://stackoverflow.com/questions/958249/whats-the-difference-between-nohup-and-a-daemon">this answer</a>, which basically can be tl;dr'd to <code>nohup command &</code> being the <em>"poor man;s way to daemonize a process</em>, as it doe... | 1 | 2016-08-05T09:50:37Z | [
"python",
"twisted",
"nohup",
"twisted.internet",
"twistd"
] |
ImportError: cannot import name patterns | 38,786,036 | <p><strong>Python Versionï¼2.7.5
django Versionï¼1.10</strong>
when i type <em>nohup python manage.py runserver 0.0.0.0:9001</em>
show me <a href="http://i.stack.imgur.com/8GcRc.png" rel="nofollow"><img src="http://i.stack.imgur.com/8GcRc.png" alt="enter image description here"></a></p>
<p>i have googled someone t... | 3 | 2016-08-05T09:36:24Z | 38,786,440 | <p>Use of patterns is deprecated since django 1.8. See <a href="https://docs.djangoproject.com/en/1.9/ref/urls/#patterns">docs</a>. You can use plain lists now.</p>
| 6 | 2016-08-05T09:57:59Z | [
"python",
"django",
"django-models"
] |
ImportError: cannot import name patterns | 38,786,036 | <p><strong>Python Versionï¼2.7.5
django Versionï¼1.10</strong>
when i type <em>nohup python manage.py runserver 0.0.0.0:9001</em>
show me <a href="http://i.stack.imgur.com/8GcRc.png" rel="nofollow"><img src="http://i.stack.imgur.com/8GcRc.png" alt="enter image description here"></a></p>
<p>i have googled someone t... | 3 | 2016-08-05T09:36:24Z | 39,415,862 | <p>I ran into this error when trying to install Django-Guardian. Instead of downgrading Django, you can install the latest version of Django-Guardian.
Try,</p>
<pre><code>pip install 'django-guardian>=1.4.6'
</code></pre>
<p>This resolved the issue for me.</p>
| 0 | 2016-09-09T16:21:31Z | [
"python",
"django",
"django-models"
] |
ImportError: cannot import name patterns | 38,786,036 | <p><strong>Python Versionï¼2.7.5
django Versionï¼1.10</strong>
when i type <em>nohup python manage.py runserver 0.0.0.0:9001</em>
show me <a href="http://i.stack.imgur.com/8GcRc.png" rel="nofollow"><img src="http://i.stack.imgur.com/8GcRc.png" alt="enter image description here"></a></p>
<p>i have googled someone t... | 3 | 2016-08-05T09:36:24Z | 39,792,874 | <p>The use of patterns is deprecated in Django1.10. Therefore do not import 'patterns' and your url pattern should be as follows:</p>
<pre><code>urlpatterns=[
url(r'^admin/', include(admin.site.urls)),
url(........),
]
</code></pre>
| 0 | 2016-09-30T13:36:43Z | [
"python",
"django",
"django-models"
] |
Want to get the mouse coordinate in a while loop | 38,786,057 | <p>I would like to get the mouse click coordinate for several images. This is my code:</p>
<pre><code>import matplotlib.pyplot as plt
j = 0
while j < nb_images:
plt.ion()
fig = plt.figure()
coords = []
#Affichage
plt.imshow(img[j], cmap="gray")
plt.draw()
while len(coords) <1:
... | -1 | 2016-08-05T09:37:42Z | 38,832,161 | <p>I'm trying to answer, although I cannot test, being unable to get hold of mathplotlib on windows, so I'm sure it does not work as is but at least it corrects the way to create things & callbacks.</p>
<p>The posted code had many flaws:</p>
<ul>
<li>it relied on an interactive way of doing things. Mathplotlib de... | 0 | 2016-08-08T14:42:16Z | [
"python",
"matplotlib",
"click",
"mouse",
"coordinate"
] |
Numpy's FFT with Intel MKL | 38,786,227 | <p>Running <code>numpy.fft.fft(np.eye(9),norm="ortho)</code> leads to <code>TypeError: fft() got an unexpected keyword argument 'norm'</code>. I am running Numpy with Intel MKL. Could it be that there is something wrong with the linkings inside the libraries?</p>
| 1 | 2016-08-05T09:46:57Z | 38,788,507 | <p>You can find the solution in the comments.</p>
| -1 | 2016-08-05T11:47:25Z | [
"python",
"numpy",
"fft",
"intel-mkl"
] |
Python multiprocessing/threading takes longer than single processing on a virtual machine | 38,786,312 | <p>I'm at work on a virtual machine which sits in my company's mainframe.</p>
<p>I have 4 cores assigned to work with so I'm trying to get into parallel processing of my Python code. I'm not familiar with it yet and I'm running into really unexpected behaviour, namely that multiprocessing/threading takes longer than s... | 3 | 2016-08-05T09:51:37Z | 38,786,832 | <p>So, firstly, you're not doing anything wrong, and when I run your example on my Macbook Pro, with cPython 2.7.12, I get:</p>
<pre><code>$ python test.py
Linear Processing:
0.733351945877
Threading:
1.20692706108
Multiprocessing:
0.256340026855
</code></pre>
<p>However, the difference becomes more apparent when I c... | 4 | 2016-08-05T10:19:26Z | [
"python",
"multithreading",
"multiprocessing",
"python-multithreading",
"python-multiprocessing"
] |
Django Admin: Creating users in the browser | 38,786,387 | <p>I have setup my Django (1.8) admin to allow superusers to create new users interactively. My User model is customized using <code>AbstractUser</code> which means my admin file looks like this: </p>
<p><em>admin.py</em></p>
<pre><code>from django.contrib import admin
from app.models import CPRUser
class UserAdmin(... | 0 | 2016-08-05T09:54:42Z | 38,791,659 | <p>According to the <a href="https://docs.djangoproject.com/en/1.9/topics/auth/customizing/#custom-users-and-django-contrib-admin" rel="nofollow">documentation</a>, </p>
<blockquote>
<p>If your custom User model extends django.contrib.auth.models.AbstractUser, you can use Djangoâs existing django.contrib.auth.admi... | 2 | 2016-08-05T14:27:01Z | [
"python",
"django",
"django-admin"
] |
django-axes installed, but axes.middleware module not available | 38,786,393 | <p>I recently refactored a lot of code and wanted a clean environment, so I deleted and recreated the database schema, created a new venv, and installed dependencies from <code>pip3</code> one-by-one so I didn't have any superfluous packages left over from the old environment. I quickly installed half a dozen packages,... | 0 | 2016-08-05T09:55:02Z | 38,803,410 | <p>As of 2.0.0, django-axes has <code>default_app_config</code> so you can just use axes in INSTALLED_APPS without installing middleware. Hence, delete the relevant <code>MIDDLEWARE_CLASSES</code> line in settings.py</p>
| 2 | 2016-08-06T10:47:09Z | [
"python",
"django"
] |
python selenium excpected conditions send_keys | 38,786,418 | <p>i'm having a problem with the following code: </p>
<pre><code>iFrame = EC.frame_to_be_available_and_switch_to_it(("MAIN_IFRAME"))
uscita = EC.presence_of_element_located((By.XPATH, "//input[contains(.,'password')]"))
uscita.send_keys('passwd')
</code></pre>
<p>and i'm getting the following error:</p>
<pre><code>A... | 1 | 2016-08-05T09:56:39Z | 38,786,595 | <p>You need to use <code>until</code> function from <code>WebDriverWait</code> with the <code>expected_conditions</code>. It also doesn't looks like the field is in <code>iframe</code>. Try this</p>
<pre><code>wait = WebDriverWait(driver, 10);
uscita = wait.until(EC.presence_of_element_located((By.ID, "password")))
us... | 1 | 2016-08-05T10:05:59Z | [
"python",
"selenium"
] |
Python regular expression for | 38,786,432 | <p>What would be the regular expression for such data</p>
<pre><code>/home//Desktop/3A5F.py
path/sth/R67G.py
a/b/c/d/t/6UY7.py
</code></pre>
<p>i would like to get these</p>
<pre><code>3A5F.py
R67G.py
6UY7.py
</code></pre>
| -2 | 2016-08-05T09:57:24Z | 38,786,464 | <p>use : <code>[^\/]*\.py$</code></p>
<p>But this is a bad question. You need to show what you have try. Whe are not here to do your work for you.</p>
| 0 | 2016-08-05T09:59:04Z | [
"python",
"regex"
] |
Python regular expression for | 38,786,432 | <p>What would be the regular expression for such data</p>
<pre><code>/home//Desktop/3A5F.py
path/sth/R67G.py
a/b/c/d/t/6UY7.py
</code></pre>
<p>i would like to get these</p>
<pre><code>3A5F.py
R67G.py
6UY7.py
</code></pre>
| -2 | 2016-08-05T09:57:24Z | 38,786,484 | <pre><code>output = re.search(r'(?is)(.*/)(.*$)',str(s)).group(2)
print(output)
</code></pre>
| 0 | 2016-08-05T09:59:52Z | [
"python",
"regex"
] |
Python regular expression for | 38,786,432 | <p>What would be the regular expression for such data</p>
<pre><code>/home//Desktop/3A5F.py
path/sth/R67G.py
a/b/c/d/t/6UY7.py
</code></pre>
<p>i would like to get these</p>
<pre><code>3A5F.py
R67G.py
6UY7.py
</code></pre>
| -2 | 2016-08-05T09:57:24Z | 38,786,509 | <p>As an alternative, you can get same result <strong>without regexps</strong>:</p>
<pre><code>lines = ['/home//Desktop/3A5F.py', 'path/sth/R67G.py', 'a/b/c/d/t/6UY7.py']
result = [l.split('/')[-1] for l in lines]
print result
# ['3A5F.py', 'R67G.py', '6UY7.py']
</code></pre>
| 1 | 2016-08-05T10:01:31Z | [
"python",
"regex"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.