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 |
|---|---|---|---|---|---|---|---|---|---|
parsing a dictionary from file in python using argparse? | 39,151,817 | <p>I have been using a file containing variables as input for a program, which is then imported into the main program at runtime. I am moving this system to using argparse reading the input values from a file. One of the current input variables is a list of dictionaries, with each dictionary providing settings for a g... | 0 | 2016-08-25T17:53:33Z | 39,152,312 | <p>As Dmitry Suggested, passing json as an argument to function is not a recommended way. </p>
<p>So, I would suggest you to pass json file path in argument instead whole json file.</p>
<pre><code># test_prog.py
import argparse
import json
parser = argparse.ArgumentParser()
parser.add_argument("-f","--filepath", hel... | 0 | 2016-08-25T18:23:53Z | [
"python",
"argparse"
] |
parsing a dictionary from file in python using argparse? | 39,151,817 | <p>I have been using a file containing variables as input for a program, which is then imported into the main program at runtime. I am moving this system to using argparse reading the input values from a file. One of the current input variables is a list of dictionaries, with each dictionary providing settings for a g... | 0 | 2016-08-25T17:53:33Z | 39,152,572 | <p>First option would be to pass in the arguments directly, and call the script once for each set of values. It's unclear if that meets your use case.</p>
<pre><code>./your_script.py startx=0, starty=0, endx=10, endy=10
</code></pre>
<p>Alternatively, you could use an easily parseable file format such as JSON or CFG... | 0 | 2016-08-25T18:39:49Z | [
"python",
"argparse"
] |
Python Print Variables with parameters | 39,151,868 | <p>I know you can do this for a string:</p>
<pre><code>print("You have inputted {0} postive numbers and {1} negative numbers".format('3','2'))
</code></pre>
<p>And this would produce:</p>
<pre><code>You have inputted 3 postive numbers and 2 negative numbers
</code></pre>
<p>But I want to insert a letter in a variab... | 0 | 2016-08-25T17:56:31Z | 39,151,914 | <pre><code>print(eval('nu{}ber'.format("m")))
</code></pre>
<p>Eval evaluates the expression from string, and has access to program variables by default.</p>
<p>Or:</p>
<pre><code>print(globals()['nu{}ber'.format("m")])
</code></pre>
<p>Globals is the dictionary {'variable_name': value}.</p>
<hr>
<p>Unless you do... | 2 | 2016-08-25T17:59:02Z | [
"python",
"output"
] |
Python Print Variables with parameters | 39,151,868 | <p>I know you can do this for a string:</p>
<pre><code>print("You have inputted {0} postive numbers and {1} negative numbers".format('3','2'))
</code></pre>
<p>And this would produce:</p>
<pre><code>You have inputted 3 postive numbers and 2 negative numbers
</code></pre>
<p>But I want to insert a letter in a variab... | 0 | 2016-08-25T17:56:31Z | 39,151,956 | <p>Though it's not recommended, you can access your variable dynamically through <code>globals</code>:</p>
<pre><code>>>> number = 4
>>> globals()['num' + 'ber']
4
</code></pre>
<p><code>eval</code> works too:</p>
<pre><code>>>> eval('num' + 'ber')
4
</code></pre>
| 0 | 2016-08-25T18:00:57Z | [
"python",
"output"
] |
Menu_Opciones() missing 2 required positional arguments: 'Pregunta' and 'Opciones' | 39,151,875 | <p>I have a problem which evolve a script: "script.py" and a view in "views.py" in a django project.
The goal is to show in a page a question: "Pregunta" and a list of options: "Opciones"
In a part of the script I need to call a view's function "Menu_Opciones" in this way:</p>
<pre><code>ESI_App.views.Menu_Opciones(r... | 0 | 2016-08-25T17:56:58Z | 39,190,432 | <p>I fixed it! First I tried to pass the parameters as keyword but got the same error, so I tried simply to define in views "Pregunta" and "Opciones" as global variables:</p>
<pre><code>Preg = ''
Opcs = []
</code></pre>
<p>I imported them in "script.py" and asigned their proper value:</p>
<pre><code>ESI_App.views.Pr... | 0 | 2016-08-28T10:41:05Z | [
"python",
"django",
"parameters",
"arguments",
"views"
] |
Pandas: Use index value in apply function over a column | 39,151,978 | <p>I was wondering if there's a way to use index value while using apply over a column of the dataframe. Suppose I have df like:</p>
<pre><code> col1 col2
0 a [0,1,2]
1 b [0,2]
2 c [0,1,2]
</code></pre>
<p>I want to write an apply function on df.col2 such that it removes the index values from the ... | 2 | 2016-08-25T18:01:54Z | 39,152,043 | <pre><code>def name_drop(x):
x_ = x.drop('col2')
_x = pd.Series(x.col2)
_x = _x[_x != x.name].tolist()
x = x_.append(pd.Series({'col2': _x}))
return x
df.apply(name_drop, axis=1)
</code></pre>
<p><a href="http://i.stack.imgur.com/Xw04j.png" rel="nofollow"><img src="http://i.stack.imgur.com/Xw04j.p... | 1 | 2016-08-25T18:07:15Z | [
"python",
"pandas",
"dataframe",
"apply"
] |
Pandas: Use index value in apply function over a column | 39,151,978 | <p>I was wondering if there's a way to use index value while using apply over a column of the dataframe. Suppose I have df like:</p>
<pre><code> col1 col2
0 a [0,1,2]
1 b [0,2]
2 c [0,1,2]
</code></pre>
<p>I want to write an apply function on df.col2 such that it removes the index values from the ... | 2 | 2016-08-25T18:01:54Z | 39,153,953 | <p>If I understand your question correctly, this should do the job:</p>
<pre><code>df.apply(lambda x: x.name in x.col2 and x.col2.remove(x.name), axis=1)
</code></pre>
<p>With the example from the original post:</p>
<pre><code>In [226]: df
Out[226]:
col1 col2
0 a [0, 1, 2]
1 b [0, 2]
2 c [0, ... | 2 | 2016-08-25T20:10:16Z | [
"python",
"pandas",
"dataframe",
"apply"
] |
Pandas: Use index value in apply function over a column | 39,151,978 | <p>I was wondering if there's a way to use index value while using apply over a column of the dataframe. Suppose I have df like:</p>
<pre><code> col1 col2
0 a [0,1,2]
1 b [0,2]
2 c [0,1,2]
</code></pre>
<p>I want to write an apply function on df.col2 such that it removes the index values from the ... | 2 | 2016-08-25T18:01:54Z | 39,187,431 | <p>maybe you can try this, this will not delete the index values from the list but will replace it with 'nan'</p>
<pre><code>df = pd.DataFrame({'a':list('mno'),'b':[[1,2,3],[1,3,4],[5,6,2]]})
df1 = df.b.apply(pd.Series)
df['b'] = np.array(df1[df1.apply(lambda x: x!=df.index.values)]).tolist()
</code></pre>
<blockquot... | 0 | 2016-08-28T02:10:09Z | [
"python",
"pandas",
"dataframe",
"apply"
] |
Assign permissions to user in Django | 39,152,165 | <p>I'm using Django User model in my Django project. my user view is:</p>
<pre><code>from django.contrib.auth.models import User
from django.dispatch import receiver
from django.db.models.signals import post_save
from rest_framework import generics
from rest_framework import permissions
from rest_framework import sta... | 0 | 2016-08-25T18:14:27Z | 39,157,722 | <blockquote>
<p>I can see the list of all the users. But when I try to access it with a non-superuser, I get an empty list.</p>
</blockquote>
<p>From your code you should be able to access UserList even if you are not superuser.</p>
<blockquote>
<p>I like every user to be able to view the user list but only its o... | 0 | 2016-08-26T03:06:47Z | [
"python",
"django",
"permissions",
"user",
"signals"
] |
Behaviour Driven Development - Undefined steps in Behave using Python with Flask | 39,152,217 | <p>I'm following a Flask tutorial and currently looking at Behaviour Driven Development using Behave.</p>
<p>My task is to build a very basic blog application that allows a single user to log in, log out and create blog posts, using BDD.</p>
<p>I've written the feature file, the steps file and the environment file. I... | 0 | 2016-08-25T18:17:38Z | 39,171,893 | <p>Moving the encode solved the problem. I now have</p>
<pre><code>@then(u'we should see the alert "{message}"')
def message(context, message):
assert message.encode("utf-8") in context.page.data
</code></pre>
| 0 | 2016-08-26T17:38:48Z | [
"python",
"flask",
"bdd",
"python-behave"
] |
Django Form validation errors handling using AJAX | 39,152,255 | <p>Having the following form being generated in a Modal:</p>
<p><strong>Template:</strong></p>
<p>...</p>
<pre><code><div id="form-modal-body" class="modal-body">
<form id="register_new_customer" method="post" action="{% url "customer:new_customer" %}">
{% csrf_token %}
... | 1 | 2016-08-25T18:19:56Z | 39,152,735 | <p>I think you want something along these lines from your view:</p>
<pre><code>from django.http import JsonResponse
def phone_number_eval(request):
if phone_number is valid:
response = {'status': 1, 'message': "Ok"}
else:
response = {'status': 2, 'message': "Please enter a valid phone number.... | 1 | 2016-08-25T18:50:59Z | [
"python",
"ajax",
"django"
] |
Computing the average of non-negative numbers from a text file | 39,152,256 | <p>I am trying to read in a text file of integers, make it a list, compute the average of all integers, compute the average of all non-negative integers, print max and min. I was able to compute the average of all integers but am having difficulty getting the average of all non-negative integers and the max and min. </... | 1 | 2016-08-25T18:19:58Z | 39,152,374 | <p>If the numbers are separated by spaces<br>
(or, as I understand from your code, by new lines)<br>
this is a very short and <em>"Pythonic"</em> task!</p>
<p>First, let's read the entire file into numbers<br>
and also have the file close automatically:</p>
<pre><code>with open('numberlist.txt') as f:
nums = [int... | 0 | 2016-08-25T18:27:12Z | [
"python",
"python-3.x",
"if-statement",
"for-loop",
"accumulator"
] |
Computing the average of non-negative numbers from a text file | 39,152,256 | <p>I am trying to read in a text file of integers, make it a list, compute the average of all integers, compute the average of all non-negative integers, print max and min. I was able to compute the average of all integers but am having difficulty getting the average of all non-negative integers and the max and min. </... | 1 | 2016-08-25T18:19:58Z | 39,152,407 | <p>This keeps most of your code and adds the non-negative part to it (perhaps should be called positive instead? :)</p>
<pre><code>file = open("numberlist.txt", "r")
sum = 0
nonNegativeTotal = 0
nonNegativeCount = 0
list = []
for num in file:
list.append(num)
for number in list:
x = int(number)
if x >... | 0 | 2016-08-25T18:29:33Z | [
"python",
"python-3.x",
"if-statement",
"for-loop",
"accumulator"
] |
undefined variable while playing with dates and functions | 39,152,276 | <p>You could call me an extreme newbie, I have a course at school for which I need to be able, sort of, to solve problems using python. All so far have worked, but the last one (just a small part really) wont give in.</p>
<p>The first 4 functions work fine (2 arguments each, a birthday (bday) and a random date (today)... | 0 | 2016-08-25T18:21:11Z | 39,152,322 | <p>You cannot read from a variable before it's been created:</p>
<pre><code>def birthdays(bday, start=bday, end=date.today(), birthday=birthday):
^---1 ^---2
</code></pre>
<p>Function arguments as above are just variable name definitions. "The chunk of data inserted into the function call at this... | 2 | 2016-08-25T18:24:34Z | [
"python",
"function",
"date"
] |
undefined variable while playing with dates and functions | 39,152,276 | <p>You could call me an extreme newbie, I have a course at school for which I need to be able, sort of, to solve problems using python. All so far have worked, but the last one (just a small part really) wont give in.</p>
<p>The first 4 functions work fine (2 arguments each, a birthday (bday) and a random date (today)... | 0 | 2016-08-25T18:21:11Z | 39,152,347 | <p>One solution would be to default start=None, and then in the function body have:</p>
<pre><code>if start is None:
start = bday
</code></pre>
<p>which should give you the behaviour you want.</p>
| 2 | 2016-08-25T18:25:49Z | [
"python",
"function",
"date"
] |
Multilayer feedforward net fails to train in TensorFlow | 39,152,282 | <p>I started with the TensorFlow tutorial to classify the images in the mnist data set using a single layer feedforward neural net. That works OK, i get 80+ percent on the test set. Then I tried to modify it to a multilayer network by adding a new layer in between. After this modification all my attempts to train the n... | 1 | 2016-08-25T18:21:40Z | 39,155,484 | <p>Few suggestions:</p>
<p>1- Add standard deviation to both weight variable initialization, instead of initializing with <code>zeros</code>:</p>
<pre><code>weight_1 = tf.Variable(tf.truncated_normal([784,10], stddev=0.1))
</code></pre>
<p>2- Lower the learning rate until the accuracy value show a varying behavior.<... | 1 | 2016-08-25T22:08:00Z | [
"python",
"numpy",
"neural-network",
"tensorflow",
"feed-forward"
] |
Why does python3-config list -ldl before the last lined library? | 39,152,358 | <p>Running <code>python2.7-config --libs</code>, <code>python3.5-config --libs</code>, etc. results in the following output:</p>
<pre><code>-lpython<version> -lpthread -ldl -lutil -lm
</code></pre>
<p>Why isn't libdl the last linked library? I believe the order only matters when the preceding libraries referenc... | 0 | 2016-08-25T18:26:08Z | 39,228,654 | <p>Neither of the later libraries appear to reference libdl, so linking to libdl first is unnecessary. In fact, linking to libdl <em>first</em> appears to have no effect, nor does skipping it entirely.</p>
<pre><code>#include "Python.h"
int main(int argc, const char **argv) {}
</code></pre>
<p>...</p>
<pre><code>gcc... | 0 | 2016-08-30T13:19:10Z | [
"python"
] |
Python 2.7 Improve algorithm that checks if a dictionary key is not in a list and if so deletes that key | 39,152,395 | <p>I was playing around with a few solutions but am looking for an optimal and clean way to do this in Python. Basically I have a dictionary called 'd', and a list 'l'. If the dictionary contains a value not in the list delete that value in the dictionary. So given: </p>
<pre><code>d = {1 : "bob", 2 : "mary", 3 : "joe... | 0 | 2016-08-25T18:28:48Z | 39,152,561 | <p>A list comprehension will work starting from Python 2.7:</p>
<pre><code>d = {k: v for k, v in d.iteritems() if k in l}
</code></pre>
<p>Use <code>items()</code> instead of <code>iteritems()</code> in Python 3:</p>
<pre><code>d = {k: v for k, v in d.items() if k in l}
</code></pre>
| 4 | 2016-08-25T18:39:05Z | [
"python",
"python-2.7",
"dictionary"
] |
Python 2.7 Improve algorithm that checks if a dictionary key is not in a list and if so deletes that key | 39,152,395 | <p>I was playing around with a few solutions but am looking for an optimal and clean way to do this in Python. Basically I have a dictionary called 'd', and a list 'l'. If the dictionary contains a value not in the list delete that value in the dictionary. So given: </p>
<pre><code>d = {1 : "bob", 2 : "mary", 3 : "joe... | 0 | 2016-08-25T18:28:48Z | 39,152,779 | <p>You can also use sets for achieving the same:</p>
<pre><code>z={i:d[i] for i in set(d.keys()).intersection(l)}
</code></pre>
<p>or use the below</p>
<pre><code>p={i:d[i] for i in d.keys() if i in l}
</code></pre>
<p>or do this</p>
<pre><code>q={i:d[i] for i in set(d.keys()) & set(l)}
</code></pre>
<p>Alter... | 0 | 2016-08-25T18:53:40Z | [
"python",
"python-2.7",
"dictionary"
] |
ValueError: Invalid chart type given scatter | 39,152,398 | <p>I am new to Python and I am trying to plot a simple scatter plot for 2 stocks (Adj Close). For some reason I am unable to generate a scatter plot (when I remove the <code>kind='scatter'</code> argument, the chart runs as expected, but is a line chart). Here is my code:</p>
<pre><code>from pandas.io.data import Data... | 0 | 2016-08-25T18:28:56Z | 39,154,004 | <p>"Create" <code>scatter</code> plot from <code>line</code> chart if <code>line</code> works:</p>
<pre><code>dlyRtns.plot(x=xPlt, y=yPlt, marker='o', linewidth=0)
</code></pre>
| 1 | 2016-08-25T20:13:42Z | [
"python",
"python-2.7",
"pandas",
"matplotlib",
"plot"
] |
Python - BaseHTTPServer - Overriding "handle_timeout" method | 39,152,411 | <p>I'm currently working with Python's <code>BaseHTTPServer</code> and I need to override the <code>handle_timeout()</code> method of the server.</p>
<p>According to Python's documentation (<a href="https://docs.python.org/2/library/basehttpserver.html" rel="nofollow">https://docs.python.org/2/library/basehttpserver.h... | 0 | 2016-08-25T18:29:41Z | 39,228,920 | <p>For anyone interested, after trying a few things out I finally came to a conclusion:</p>
<p>According to this file (<a href="https://svn.python.org/projects/python/trunk/Lib/BaseHTTPServer.py" rel="nofollow">https://svn.python.org/projects/python/trunk/Lib/BaseHTTPServer.py</a>), I directly copied the code from <co... | 0 | 2016-08-30T13:31:01Z | [
"python",
"timeout",
"basehttpserver"
] |
Function that returns an equation | 39,152,420 | <p>I am writing a script to calculate the definite integral of an equation. I'm writing a helper function that would take in coefficients as parameters and return a function of x.</p>
<pre><code>def eqn(x, k, c, a):
return ((k*x + c**(1-a))
</code></pre>
<p>Next, I define a function that calculates the definite i... | 2 | 2016-08-25T18:30:12Z | 39,184,239 | <p>The mistake here is that the function 'eqn' does not return a function, it returns the <em>value</em> of a function at some point x, given parameters k,c,a.</p>
<p>quad should be passed a function (in your case, eqn) where the first argument (in your case, x) is assumed to be the variable over which the function is... | 0 | 2016-08-27T18:07:51Z | [
"python",
"python-2.7",
"scipy"
] |
Function that returns an equation | 39,152,420 | <p>I am writing a script to calculate the definite integral of an equation. I'm writing a helper function that would take in coefficients as parameters and return a function of x.</p>
<pre><code>def eqn(x, k, c, a):
return ((k*x + c**(1-a))
</code></pre>
<p>Next, I define a function that calculates the definite i... | 2 | 2016-08-25T18:30:12Z | 39,195,020 | <p>This is not what you asked. However, as someone else has mentioned, sympy would probably make your life much easier. For instance, suppose you need to be able to evaluate integrals of functions of <strong>x</strong> such as f in the code below, where <strong>a</strong> and <strong>b</strong> are arbitrary constants.... | 0 | 2016-08-28T19:31:12Z | [
"python",
"python-2.7",
"scipy"
] |
python: how to explain the following codes | 39,152,577 | <p>Tested on my local machine:</p>
<pre><code>Python 2.7.3 (default, Jun 22 2015, 19:33:41)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> q=[2,3]
>>> p=[1,q,4]
>>> p[1].append('test')
>>> q
[2, 3, 'test']
>>> hex(id(q))
'0... | 0 | 2016-08-25T18:40:22Z | 39,152,683 | <p>Well, I can explain. Your <code>p</code> keeps reference to <code>q</code> and you cannot change that. That's all. So if you will edit <code>p[1]</code>, then basically it modifies <code>q</code>, because going there through reference.</p>
<p><strong>Any document can help understand the above behaviour?</strong>
<a... | 1 | 2016-08-25T18:47:55Z | [
"python"
] |
python: how to explain the following codes | 39,152,577 | <p>Tested on my local machine:</p>
<pre><code>Python 2.7.3 (default, Jun 22 2015, 19:33:41)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> q=[2,3]
>>> p=[1,q,4]
>>> p[1].append('test')
>>> q
[2, 3, 'test']
>>> hex(id(q))
'0... | 0 | 2016-08-25T18:40:22Z | 39,152,694 | <p>When you append <code>q</code> to <code>p</code>, you are not creating a copy of <code>q</code>, you are actually appending a reference to the object that the name <code>q</code> currently points to. Therefore, when you append to <code>q</code> (or in this case <code>p[1]</code>, which points to the same object), i... | 3 | 2016-08-25T18:48:45Z | [
"python"
] |
python: how to explain the following codes | 39,152,577 | <p>Tested on my local machine:</p>
<pre><code>Python 2.7.3 (default, Jun 22 2015, 19:33:41)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> q=[2,3]
>>> p=[1,q,4]
>>> p[1].append('test')
>>> q
[2, 3, 'test']
>>> hex(id(q))
'0... | 0 | 2016-08-25T18:40:22Z | 39,153,121 | <p>If you are new to Python you may run into issues like this.</p>
<p>In Python if you say </p>
<pre><code> a = [10]
</code></pre>
<p>And then say </p>
<pre><code> b = a
</code></pre>
<p>What happens? b gets the value of a, but also any change in a will make the similar change in b, because instead of just c... | 1 | 2016-08-25T19:15:51Z | [
"python"
] |
Pandas Merge - put all join-column data under one output column instead of two? | 39,152,595 | <p>I have two CSV files, with the following schemas:</p>
<p>CSV1 columns:</p>
<pre><code>"Id","First","Last","Email","Company"
</code></pre>
<p>CSV2 columns:</p>
<pre><code>"PersonId","FirstName","LastName","Em","FavoriteFood"
</code></pre>
<p>If I load them each into a Pandas DataFrame and do <code>newdf = df1.me... | 0 | 2016-08-25T18:41:42Z | 39,152,701 | <p>One way to do it would be to just merge the same way but drop columns that you'd like to remove.</p>
<pre><code>newdf.drop(['LastName','FirstName'], 1, inplace=True)
</code></pre>
| 0 | 2016-08-25T18:49:14Z | [
"python",
"join",
"merge",
"rename"
] |
Selenium with Python: First instance of the element is identified but the next occurance is ElementNotVisibleException | 39,152,629 | <p>I have the following Selenium Test for Python/Django application:</p>
<pre><code>class EmailRecordsTest(StaticLiveServerTestCase):
def test_can_store_email_and_retrieve_it_later(self):
self.browser.get(self.live_server_url)
emailbox = self.browser.find_element_by_xpath("//form[@class='pma-subsc... | 1 | 2016-08-25T18:44:32Z | 39,152,842 | <p>Actually <code>find_element</code> returns element which would be present on the <code>DOM</code> no matter it's visible or not and you can get attribute of this element as well but <code>send_keys</code> does an action on element and selenium does action only visible element, So you need to be sure before doing act... | 1 | 2016-08-25T18:57:41Z | [
"python",
"django",
"selenium"
] |
Selenium with Python: First instance of the element is identified but the next occurance is ElementNotVisibleException | 39,152,629 | <p>I have the following Selenium Test for Python/Django application:</p>
<pre><code>class EmailRecordsTest(StaticLiveServerTestCase):
def test_can_store_email_and_retrieve_it_later(self):
self.browser.get(self.live_server_url)
emailbox = self.browser.find_element_by_xpath("//form[@class='pma-subsc... | 1 | 2016-08-25T18:44:32Z | 39,252,938 | <p>Another option which worked in this case is that you scroll to the specific element (which was at the bottom of the page)and then use send_keys it works.</p>
<pre><code>emailbox = self.browser.find_element_by_xpath("//form[@class='mu-subscribe-form']/input[1]")
self.browser.execute_script("window.scrollTo(0, docume... | 0 | 2016-08-31T14:54:47Z | [
"python",
"django",
"selenium"
] |
Building a django queryset over foreign key and onetoone | 39,152,669 | <p>I have some two models (in different apps/models.py files) related with User:</p>
<pre><code>class Profile(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL, null=False)
...
class CourseStudent(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL)
semester = models.Fo... | 0 | 2016-08-25T18:47:09Z | 39,157,339 | <p>Not tested. Maybe you should try</p>
<pre><code>class Profile(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL, null=False)
...
class CourseStudent(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="course_student")
semester = models.ForeignKey(Semes... | 0 | 2016-08-26T02:07:47Z | [
"python",
"django",
"postgresql",
"foreign-keys",
"django-queryset"
] |
Python XOR Encryption program sometimes doesn't work | 39,152,671 | <p>I am trying to make a simple xor encryption program in python and what I have now is working almost fine, only sometimes it doesn't and I just can't figure out why. For example, if I input 'hello' and the key '1234' it will encrypt it to YW_X^ and if I then decrypt this with the same key it will print 'hello'. But i... | 2 | 2016-08-25T18:47:18Z | 39,152,838 | <p>It's probably working fine, but you are getting characters which you may not be able to re-input into your terminal directly as they don't correspond to the ordinarily inputtable ASCII characters. In particular, with the key <code>qwer</code>, the values of <code>ord</code> become <code>[25, 18, 9, 30, 30]</code>, w... | 0 | 2016-08-25T18:57:25Z | [
"python",
"python-2.7",
"encryption",
"cryptography",
"xor"
] |
Python XOR Encryption program sometimes doesn't work | 39,152,671 | <p>I am trying to make a simple xor encryption program in python and what I have now is working almost fine, only sometimes it doesn't and I just can't figure out why. For example, if I input 'hello' and the key '1234' it will encrypt it to YW_X^ and if I then decrypt this with the same key it will print 'hello'. But i... | 2 | 2016-08-25T18:47:18Z | 39,152,847 | <p>Your script is printing non-printing characters, which sometimes can't be copy/pasted. You could encode the ciphertext into a format that uses only the characters <code>abcdef0123456789</code>, which lets you display it without issue:</p>
<pre><code>print encrypted_message.encode('hex')
</code></pre>
<p>You can th... | 0 | 2016-08-25T18:57:54Z | [
"python",
"python-2.7",
"encryption",
"cryptography",
"xor"
] |
Queue doesn't process all elements when there are many threads | 39,152,680 | <p>I have noticed that when I have many threads pulling elements from a queue, there are less elements processed than the number that I put into the queue. This is sporadic but seems to happen somewhere around half the time when I run the following code.</p>
<pre><code>#!/bin/env python
from threading import Thread
i... | 3 | 2016-08-25T18:47:44Z | 39,152,814 | <p>Tim Peters hit the nail on the head in the comments. The issue is that the tracking of results is threaded and isn't protected by any sort of mutex. That allows something like this to happen:</p>
<pre><code>thread A gets result: "all good"
thread A checks results[result]
thread A sees no such key
thread A suspends ... | 1 | 2016-08-25T18:55:34Z | [
"python",
"multithreading",
"python-2.7"
] |
How to have multiple groups in Python statsmodels linear mixed effects model? | 39,152,729 | <p>I am trying to use the Python statsmodels linear mixed effects model to fit a model that has two random intercepts, e.g. two groups. I cannot figure out how to initialize the model so that I can do this. </p>
<p>Here's the example. I have data that looks like the following (taken from <a href="http://www.bodowinte... | 0 | 2016-08-25T18:50:35Z | 39,156,640 | <p>You are trying to fit a model with <em>crossed random effects</em>, i.e., you want to allow for consistent variation among subjects across scenarios as well as consistent variation among scenarios across subjects. You <em>can</em> use multiple random-effects terms in statsmodels, but they must be nested. Fitting cro... | 1 | 2016-08-26T00:23:01Z | [
"python",
"statsmodels",
"lme4",
"mixed-models"
] |
How to have multiple groups in Python statsmodels linear mixed effects model? | 39,152,729 | <p>I am trying to use the Python statsmodels linear mixed effects model to fit a model that has two random intercepts, e.g. two groups. I cannot figure out how to initialize the model so that I can do this. </p>
<p>Here's the example. I have data that looks like the following (taken from <a href="http://www.bodowinte... | 0 | 2016-08-25T18:50:35Z | 39,170,955 | <p>Multiple or crossed random intercepts crossed effects can be fit using variance components, which are implemented in a different way from the one-group mixed effects.</p>
<p>I don't find an example, and the documentation seems to be only partially updated.</p>
<p>The unit tests contain an example using the MixedLM... | 1 | 2016-08-26T16:37:00Z | [
"python",
"statsmodels",
"lme4",
"mixed-models"
] |
How can I organize case-insensitive text and the material following it? | 39,152,790 | <p>I'm very new to Python so it'd be very appreciated if this could be explained as in-depth as possible.</p>
<p>If I have some text like this on a text file:</p>
<pre><code>matthew : 60 kg
MaTtHew : 5 feet
mAttheW : 20 years old
maTThEw : student
MaTTHEW : dog owner
</code></pre>
<p>How can I make a piece of code ... | 0 | 2016-08-25T18:54:10Z | 39,153,529 | <pre><code>def test_data():
# This is obviously the source data as a multi-line string constant.
source = \
"""
matthew : 60 kg
MaTtHew : 5 feet
mAttheW : 20 years old
maTThEw : student
MaTTHEW : dog owner
bob : 70 kg
BoB : 6 ft
"""
# Split on newline. This will return a list of lines like ["matthe... | 0 | 2016-08-25T19:42:36Z | [
"python"
] |
How can I organize case-insensitive text and the material following it? | 39,152,790 | <p>I'm very new to Python so it'd be very appreciated if this could be explained as in-depth as possible.</p>
<p>If I have some text like this on a text file:</p>
<pre><code>matthew : 60 kg
MaTtHew : 5 feet
mAttheW : 20 years old
maTThEw : student
MaTTHEW : dog owner
</code></pre>
<p>How can I make a piece of code ... | 0 | 2016-08-25T18:54:10Z | 39,153,988 | <pre><code>import sys
# There's a number of assumptions I have to make based on your description.
# I'll try to point those out.
# Should be self-explanatory. something like: "C:\Users\yourname\yourfile"
path_to_file = "put_your_path_here"
# open a file for reading. The 'r' indicates read-only
infile = open(path... | 0 | 2016-08-25T20:12:49Z | [
"python"
] |
Python - Problems creating a list of URLs using BeautifulSoup | 39,152,827 | <p>I am trying to make a Python Crawler using BeautifulSoup, but I receive an error that I am trying to write a non-String or other character buffer type to a file. From examining the program output, I found that my list contains many items that are None. In addition to having None, I also have a lot of images and th... | 1 | 2016-08-25T18:56:41Z | 39,154,825 | <p>First off, use <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/" rel="nofollow">bs4</a> not the no longer maintained <em>BeautifulSoup3</em>, your error is because not all anchors have hrefs so you are trying to write <em>None</em> which causes your error, use <em>find_all</em> and set <em>href=True</... | 1 | 2016-08-25T21:13:38Z | [
"python",
"list",
"beautifulsoup"
] |
Print all characters in a string | 39,152,848 | <p>Is there a way to print all characters in python, even ones which usually aren't printed?</p>
<p>For example</p>
<pre><code>>>>print_all("skip
line")
skip\nline
</code></pre>
| 3 | 2016-08-25T18:57:57Z | 39,153,030 | <p>Looks like you want <a href="https://docs.python.org/3/library/functions.html#repr" rel="nofollow"><code>repr()</code></a></p>
<pre><code>>>> """skip
... line"""
'skip\nline'
>>>
>>> print(repr("""skip
... line"""))
'skip\nline'
>>> print(repr("skip line"))
'skip\tline
</code>... | 5 | 2016-08-25T19:09:55Z | [
"python",
"string"
] |
Print all characters in a string | 39,152,848 | <p>Is there a way to print all characters in python, even ones which usually aren't printed?</p>
<p>For example</p>
<pre><code>>>>print_all("skip
line")
skip\nline
</code></pre>
| 3 | 2016-08-25T18:57:57Z | 39,153,380 | <p>Even easier, cast it to a <em>raw string</em> by using <code>"%r"</code>, raw strings treat backslashes as literal characters:</p>
<pre><code>print("%r" % """skip
line""")
skip\nline
</code></pre>
<p>Additionally, use <code>!r</code> in a <code>format</code> call:</p>
<pre><code>print("{0!r}".format("""skip
line"... | 0 | 2016-08-25T19:32:25Z | [
"python",
"string"
] |
Merge events temporally close to one another in numpy (pandas) | 39,152,864 | <p>I would like to simplify a list of start and stop times. When the time between the stop of one and the start of another, I'd like to combine (rows). The following is a simplification of my data and what I would like as output:</p>
<pre><code>import numpy as np
import pandas as pd
start_time = [ 1, 7, 20, 22, 27... | 2 | 2016-08-25T18:58:40Z | 39,153,539 | <p>This solution uses <a href="http://pandas.pydata.org/pandas-docs/version/0.18.0/generated/pandas.DataFrame.iterrows.html" rel="nofollow">DataFrame.iterrows()</a> function.<br>
I made this assumption:</p>
<ul>
<li>start_time <= stop_time for all events</li>
</ul>
<pre class="lang-python prettyprint-override"><co... | 0 | 2016-08-25T19:42:54Z | [
"python",
"pandas",
"numpy",
"svg"
] |
Merge events temporally close to one another in numpy (pandas) | 39,152,864 | <p>I would like to simplify a list of start and stop times. When the time between the stop of one and the start of another, I'd like to combine (rows). The following is a simplification of my data and what I would like as output:</p>
<pre><code>import numpy as np
import pandas as pd
start_time = [ 1, 7, 20, 22, 27... | 2 | 2016-08-25T18:58:40Z | 39,155,712 | <p>A bit more efficient way to do that:</p>
<pre><code>In [106]: (events.groupby((events.start_time - events.stop_time.shift() > allowable_gap).cumsum())
.....: .agg({'start_time':'min', 'stop_time':'max'})[['start_time','stop_time']])
Out[106]:
start_time stop_time
0 1 9
1 ... | 1 | 2016-08-25T22:28:52Z | [
"python",
"pandas",
"numpy",
"svg"
] |
What's the best way to serialize more than one model to json in Django 1.6? | 39,152,899 | <p>I have 3 models show as below.</p>
<pre><code> class DocumentClass(models.Model):
text = models.CharField(max_length=100)
class DocumentGroup(models.Model):
text = models.CharField(max_length=100)
documentclass = models.ForeignKey(DocumentClass)
class DocumentType(models.Model... | 1 | 2016-08-25T19:01:20Z | 39,153,307 | <h2>If The Models Are Related</h2>
<p>This will require some more customized serialization, for which you will have to use <a href="http://www.django-rest-framework.org/api-guide/relations/#nested-relationships" rel="nofollow">Django Rest Framework's serializers</a>.</p>
<p>Try subclassing <code>ModelSerializer</code... | 1 | 2016-08-25T19:28:18Z | [
"python",
"json",
"serialization",
"django-views"
] |
What's the best way to serialize more than one model to json in Django 1.6? | 39,152,899 | <p>I have 3 models show as below.</p>
<pre><code> class DocumentClass(models.Model):
text = models.CharField(max_length=100)
class DocumentGroup(models.Model):
text = models.CharField(max_length=100)
documentclass = models.ForeignKey(DocumentClass)
class DocumentType(models.Model... | 1 | 2016-08-25T19:01:20Z | 39,164,684 | <p>As I follow by @nofinator's answer in "If The Models Are Related" section everything looks fine until <code>json = JSONRenderer().render(serializer.data)</code>I got above errors. How can I eliminate them?</p>
<pre><code>AttributeError: Got AttributeError when attempting to get a value for field `documenttypes` on ... | 0 | 2016-08-26T10:57:35Z | [
"python",
"json",
"serialization",
"django-views"
] |
What's the best way to serialize more than one model to json in Django 1.6? | 39,152,899 | <p>I have 3 models show as below.</p>
<pre><code> class DocumentClass(models.Model):
text = models.CharField(max_length=100)
class DocumentGroup(models.Model):
text = models.CharField(max_length=100)
documentclass = models.ForeignKey(DocumentClass)
class DocumentType(models.Model... | 1 | 2016-08-25T19:01:20Z | 39,169,543 | <p>Hi @nofinator and other django rookie like me!
Thanks @nofinator for the great answer! And for django rookies like me. If you want to use django-rest-framework to serialize queryset <strong>DO NOT FORGET</strong> to use the ** <strong>related_name</strong> **(without ** ) attribute in the model like this:</p>
<pre>... | 0 | 2016-08-26T15:14:36Z | [
"python",
"json",
"serialization",
"django-views"
] |
django: instantiating AdminSite changes not reflected | 39,152,958 | <p>I am trying to change the templates of admin site, and tried overriding by creating a local template for admin, but failed without knowing why: <a href="http://stackoverflow.com/questions/39132187/django-how-do-i-actually-override-admin-site-template?noredirect=1#comment65613565_39132187">template way</a>. So now I ... | 1 | 2016-08-25T19:05:54Z | 39,153,065 | <p>To change the text in the admin, all you need to add to the <code>admin.py</code> is as follows:</p>
<pre><code>admin.site.site_header = "Equipment Calibration Database"
admin.site.site_title = "Equipment Calibration Database"
admin.site.index_title = "Equipment Calibration Database"
</code></pre>
| 1 | 2016-08-25T19:12:01Z | [
"python",
"django",
"django-admin"
] |
1+ GET request returning error 403 to heroku python | 39,152,976 | <p>I'm using an api in my script. When I run the script via my own terminal, I'm successfully able to make 3 calls to the endpoint. But when I run the same script on heroku bash, only the first call is success, other two return Error 403. Here's my code</p>
<pre><code>results = []
for level in levels:
... | 1 | 2016-08-25T19:06:59Z | 39,153,243 | <p>It's a permissions error. My guess is that when you run this from your browser, the first page sets various cookies, which the second and third requests require.</p>
<p>A quick possible fix, <em>IF</em> that's the issue, is to use requests' Session() objects. This stores cookies and sends them back on subsequent re... | 0 | 2016-08-25T19:23:28Z | [
"python",
"heroku"
] |
How to sort numpy array by absolute value of a column? | 39,153,007 | <p>What I have now:</p>
<pre><code>import numpy as np
# 1) Read CSV with headers
data = np.genfromtxt("big.csv", delimiter=',', names=True)
# 2) Get absolute values for column in a new ndarray
new_ndarray = np.absolute(data["target_column_name"])
# 3) Append column in new_ndarray to data
# I'm having trouble here. Can... | 1 | 2016-08-25T19:08:56Z | 39,153,235 | <p>Here is a way to do it.<br>
First, let's create a sample array:</p>
<pre><code>In [39]: a = (np.arange(12).reshape(4, 3) - 6)
In [40]: a
Out[40]:
array([[-6, -5, -4],
[-3, -2, -1],
[ 0, 1, 2],
[ 3, 4, 5]])
</code></pre>
<p>Ok, lets say </p>
<pre><code>In [41]: col = 1
</code></pre>
<p>... | 1 | 2016-08-25T19:22:47Z | [
"python",
"python-3.x",
"csv",
"numpy"
] |
How to sort numpy array by absolute value of a column? | 39,153,007 | <p>What I have now:</p>
<pre><code>import numpy as np
# 1) Read CSV with headers
data = np.genfromtxt("big.csv", delimiter=',', names=True)
# 2) Get absolute values for column in a new ndarray
new_ndarray = np.absolute(data["target_column_name"])
# 3) Append column in new_ndarray to data
# I'm having trouble here. Can... | 1 | 2016-08-25T19:08:56Z | 39,153,314 | <p>Here's a solution using <a href="http://pandas.pydata.org/" rel="nofollow">pandas</a>:</p>
<pre><code>In [117]: import pandas as pd
In [118]: df = pd.read_csv('test.csv')
In [119]: df
Out[119]:
a b
0 1 -3
1 2 2
2 3 -1
3 4 4
In [120]: df['c'] = abs(df['b'])
In [121]: df
Out[121]:
a b c
0 1 -3 ... | 1 | 2016-08-25T19:28:32Z | [
"python",
"python-3.x",
"csv",
"numpy"
] |
Python recursive function or cycle to convert string to json logical object | 39,153,037 | <p>I have this function:</p>
<pre><code>def req_splitter(req_string):
req = {}
if " AND " in req_string:
cond = "AND"
req_splitted = req_string.split(" AND ")
elif " OR " in req_string:
cond = "OR"
req_splitted = req_string.split(" OR ")
else:
cond = "AND"
... | 1 | 2016-08-25T19:10:12Z | 39,153,634 | <p>You'll need to write a simple top-down parser. The inimitable effbot wrote a <a href="http://effbot.org/zone/simple-top-down-parsing.htm" rel="nofollow">great tutorial</a> about just that kind of thing.</p>
<p>Tokenizing is just splitting on the <code>r'\s+(OR|AND)\s+'</code> regex, then recognising <code>OR</code>... | 5 | 2016-08-25T19:49:53Z | [
"python",
"json",
"recursion",
"logic",
"polish-notation"
] |
Is there a way to print in Python that will not output the current contents of stdin? | 39,153,058 | <p>I'm using select to wait for stdin or data from the server/client, but if I receive a message while typing, my current text is printed as well the received message. I may be using select incorrectly, but I need to find a way to maintain what's currently being typed without it being output with the message.</p>
| -3 | 2016-08-25T19:11:23Z | 39,153,259 | <p>I haven't tried it (so I might be a bit out of my expertise) but <a href="http://rpyc.readthedocs.io/en/latest/index.html" rel="nofollow">RPyC</a> might be able to do what you are asking. In its <a href="http://rpyc.readthedocs.io/en/latest/docs/howto.html" rel="nofollow">How To</a> page they show a couple of snippe... | 1 | 2016-08-25T19:24:13Z | [
"python"
] |
Python Eve patch_internal set etag | 39,153,106 | <p>I am trying to make an <code>on_insert</code> event hook for a document from schema A, call eve's <code>patch_internal</code> to a document from schema B. </p>
<p>Since the request triggering the event hook is a <code>POST</code> for A, there's no <code>If-Match</code> header with the necessary B <code>etag</code> ... | 1 | 2016-08-25T19:14:54Z | 39,153,577 | <p>Can't say this is the best way, but it works.</p>
<p>Creating a new request context to call <code>patch_internal</code>, and setting the <code>etag</code> on the <code>environ</code> used to create it, works. Below an example:</p>
<pre><code>from flask import request, current_app
from eve.methods.patch import patc... | 0 | 2016-08-25T19:45:28Z | [
"python",
"flask",
"eve"
] |
Python Eve patch_internal set etag | 39,153,106 | <p>I am trying to make an <code>on_insert</code> event hook for a document from schema A, call eve's <code>patch_internal</code> to a document from schema B. </p>
<p>Since the request triggering the event hook is a <code>POST</code> for A, there's no <code>If-Match</code> header with the necessary B <code>etag</code> ... | 1 | 2016-08-25T19:14:54Z | 39,943,898 | <p>You can set <code>concurrency_check=False</code> in your call to <code>patch_internal</code></p>
<pre><code>from eve.methods.patch import patch_internal
with app.request_context():
payload = {"value_key": "new value"}
lookup = {"_id": "12ababa12..."}
patch_internal("res_name", payload, **lookup, concurren... | 1 | 2016-10-09T12:58:59Z | [
"python",
"flask",
"eve"
] |
How to apply bitwise operator to compare a list of objects | 39,153,200 | <p>Suppose I have a long list of objects (say, a list of numpy matrices of bool elements) <code>foo = [a, b, c]</code>, that I want to compare with some bitwise operator, to get something like <code>a | b | c</code>.</p>
<p>If I could use this bitwise operation as a function, say a <code>bitwiseor</code> function, I c... | 2 | 2016-08-25T19:21:03Z | 39,153,234 | <p>Using the functional method in <a href="https://docs.python.org/2/library/operator.html#operator.or_" rel="nofollow"><code>operator</code></a> in combination with <a href="https://docs.python.org/2/library/functions.html#reduce" rel="nofollow"><code>reduce</code></a>:</p>
<pre><code>>>> import operator, fu... | 8 | 2016-08-25T19:22:45Z | [
"python",
"bitwise-operators"
] |
How to apply bitwise operator to compare a list of objects | 39,153,200 | <p>Suppose I have a long list of objects (say, a list of numpy matrices of bool elements) <code>foo = [a, b, c]</code>, that I want to compare with some bitwise operator, to get something like <code>a | b | c</code>.</p>
<p>If I could use this bitwise operation as a function, say a <code>bitwiseor</code> function, I c... | 2 | 2016-08-25T19:21:03Z | 39,154,848 | <p><code>numpy</code> has a number of functions that support reducing along an axis. See <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.bitwise_or.html#numpy.bitwise_or" rel="nofollow"><code>numpy.bitwise_or</code></a> and <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.ufunc.red... | 1 | 2016-08-25T21:15:37Z | [
"python",
"bitwise-operators"
] |
Python Pandas Create Records from Complex Dictionary | 39,153,266 | <p>I have processed some very complex nested json objects to get the following general dictionary format:</p>
<pre><code>{'key1':'value1',
'key2':'value2',
'key3':'value3',
'key4':'value4',
'key5':[['value5', 'value6', 'value7'], ['value8', 'value9', 'value10']],
'key6':[['value5', 'value6', 'value7'], ['value8',... | 2 | 2016-08-25T19:25:19Z | 39,153,883 | <p>One option is to read the dictionary as it is and reshape the data frame:</p>
<pre><code>df = pd.DataFrame({'key1':'value1',
'key2':'value2',
'key3':'value3',
'key4':'value4',
'key5':[['value5', 'value6', 'value7'], ['value8', 'value9', 'value10']],
'key6':[['value5', 'value6', 'value7'], ['value8', 'value9', ... | 2 | 2016-08-25T20:06:08Z | [
"python",
"json",
"pandas",
"dictionary"
] |
Python Pandas Create Records from Complex Dictionary | 39,153,266 | <p>I have processed some very complex nested json objects to get the following general dictionary format:</p>
<pre><code>{'key1':'value1',
'key2':'value2',
'key3':'value3',
'key4':'value4',
'key5':[['value5', 'value6', 'value7'], ['value8', 'value9', 'value10']],
'key6':[['value5', 'value6', 'value7'], ['value8',... | 2 | 2016-08-25T19:25:19Z | 39,174,123 | <p>Try this:</p>
<pre><code>pd.DataFrame({k : pd.Series(v) for k, v in d.iteritems()}).ffill()
</code></pre>
| 1 | 2016-08-26T20:20:21Z | [
"python",
"json",
"pandas",
"dictionary"
] |
How to add a Group Knob in nuke using python api | 39,153,282 | <p>Using tcl script in nuke, adding a group knob to a node looks like this</p>
<pre><code>addUserKnob {20 start_group l "My Group" n 1}
... add other knobs
addUserKnob {20 end_group l endGroup n -1}
</code></pre>
<p>It appears that the Group knob uses the same knob type as the Tab knob, except that it uses the <code>... | 2 | 2016-08-25T19:25:57Z | 39,215,569 | <p>Here is how you add Group knobs using python in nuke.</p>
<pre><code>node = nuke.toNode('MyNode')
# A Group node is created by passing a 3rd argument to the Tab Knob
# This will create a Group knob that is open by default
begin = nuke.Tab_Knob('begin', 'My Group :', 1)
# Alternatively, if you want to create a Gr... | 0 | 2016-08-29T21:33:40Z | [
"python",
"nuke"
] |
Memory error in python with numpy.pad function | 39,153,343 | <p>I read a csv file in python and create an 4664605 x 4 array. I want a matrix. So, I use the numpy.pad (wit constant value = 0) function in order to create 4664605 x 4664605 matrix. But I have the following error messaage:</p>
<blockquote>
<p>Traceback (most recent call last): File
"C:\Users\Angelika\Eclipse... | 1 | 2016-08-25T19:30:06Z | 39,154,019 | <p>This is more of a question than an answer. But it's too long for comment lines.</p>
<p>The distinction between a <code>4664605 x 4 array</code> and <code>4664605 x 4664605 matrix</code> doesn't make much sense. Squareness does not define a <code>matrix</code>, at least not in most contexts.</p>
<p>What's the pur... | 1 | 2016-08-25T20:14:38Z | [
"python",
"arrays",
"numpy",
"out-of-memory",
"anaconda"
] |
Using Python's regex .match() method to get the string before and after an underscore | 39,153,351 | <p><strong><em>I have the following code...</em></strong></p>
<pre><code>tablesInDataset = ["henry_jones_12345678", "henry_jones", "henry_jones_123"]
for table in tablesInDataset:
tableregex = re.compile("\d{8}")
tablespec = re.match(tableregex, table)
everythingbeforedigits = tablespec.group(0)
digi... | 4 | 2016-08-25T19:30:37Z | 39,153,393 | <p>I think this pattern should match what you need: <code>(.*?_)(\d{8})</code>.</p>
<p>First group includes everything up to the 8 digits, including the underscore. Second group is the 8 digits.</p>
<p>If you don't want the underscore included, use this instead: <code>(.*?)_(\d{8})</code></p>
| 2 | 2016-08-25T19:33:22Z | [
"python",
"regex",
"string",
"iterator"
] |
Using Python's regex .match() method to get the string before and after an underscore | 39,153,351 | <p><strong><em>I have the following code...</em></strong></p>
<pre><code>tablesInDataset = ["henry_jones_12345678", "henry_jones", "henry_jones_123"]
for table in tablesInDataset:
tableregex = re.compile("\d{8}")
tablespec = re.match(tableregex, table)
everythingbeforedigits = tablespec.group(0)
digi... | 4 | 2016-08-25T19:30:37Z | 39,153,397 | <pre><code>tableregex = re.compile("(.*)_(\d{8})")
</code></pre>
| 4 | 2016-08-25T19:33:40Z | [
"python",
"regex",
"string",
"iterator"
] |
Using Python's regex .match() method to get the string before and after an underscore | 39,153,351 | <p><strong><em>I have the following code...</em></strong></p>
<pre><code>tablesInDataset = ["henry_jones_12345678", "henry_jones", "henry_jones_123"]
for table in tablesInDataset:
tableregex = re.compile("\d{8}")
tablespec = re.match(tableregex, table)
everythingbeforedigits = tablespec.group(0)
digi... | 4 | 2016-08-25T19:30:37Z | 39,153,400 | <p>Use capture groups:</p>
<pre><code>>>> import re
>>> pat = re.compile(r'(?P<name>.*)_(?P<number>\d{8})')
>>> pat.findall(s)
[('henry_jones', '12345678')]
</code></pre>
<p>You get the nice feature of named groups, if you want it:</p>
<pre><code>>>> match = pat.match(... | 5 | 2016-08-25T19:33:52Z | [
"python",
"regex",
"string",
"iterator"
] |
Using Python's regex .match() method to get the string before and after an underscore | 39,153,351 | <p><strong><em>I have the following code...</em></strong></p>
<pre><code>tablesInDataset = ["henry_jones_12345678", "henry_jones", "henry_jones_123"]
for table in tablesInDataset:
tableregex = re.compile("\d{8}")
tablespec = re.match(tableregex, table)
everythingbeforedigits = tablespec.group(0)
digi... | 4 | 2016-08-25T19:30:37Z | 39,153,647 | <p>Here you go:</p>
<pre><code>import re
tablesInDataset = ["henry_jones_12345678", "henry_jones", "henry_jones_123"]
rx = re.compile(r'^(\D+)_(\d{8})$')
matches = [(match.groups()) \
for item in tablesInDataset \
for match in [rx.search(item)] \
if match]
print(matches)
</code></... | 1 | 2016-08-25T19:50:38Z | [
"python",
"regex",
"string",
"iterator"
] |
How to sort stopped EC2s by time using "state_transition_reason" variable? Python Boto3 | 39,153,410 | <p>I am seeing a steep increase on my AWS account costs. The largest cost items are: <strong>EC2: 67% RDS: 12%</strong></p>
<p>I have more than 50 stopped EC2s. One of them has been sitting there in a stopped state from September of the year 2015.</p>
<p>I found the way to get the stopped time of EC2s using variable ... | 1 | 2016-08-25T19:34:22Z | 39,153,501 | <p>As long as the User initiated part never varies, we can simply sort the instances by state_transition_reason:</p>
<pre><code>sortedInstances = sorted(instances, key=lambda k: k.state_transition_reason)
</code></pre>
| 0 | 2016-08-25T19:40:35Z | [
"python",
"amazon-web-services",
"amazon-ec2",
"aws-lambda",
"boto3"
] |
How to efficiently preform loop statements for data analysis? | 39,153,448 | <p>I wrote this code recently to comb over data points and it works beautifully for small data sets. However whenever the data sets get too big all I get is junk output and a message in the pycharm console that reads <code>! Too much output to process</code>. Then the maximum line output seems to be around 55,000 lines... | 1 | 2016-08-25T19:36:57Z | 39,155,156 | <p>As dblclik mentions in his comment on the post, there are certainly ways to make you code more efficient, avoiding the full computation of the nested for-loop. However I do not think that this will help you solve the error-message, that you are getting:</p>
<p>I do not think that PyCharm has an issue processing n ... | 2 | 2016-08-25T21:42:10Z | [
"python",
"numpy",
"coordinates",
"pycharm",
"data-analysis"
] |
What is this kind of chain assignment and comparison in python? | 39,153,474 | <p>(Python 2.7 question)</p>
<p>I found a pattern similar to the following in a python codebase:</p>
<pre><code>>>> a = b == 7
>>> a
True
>>> b
7
>>> a = b == -7
>>> a
False
>>> b
7
</code></pre>
<p>I'm looking for the terminology for this - I found some other an... | 0 | 2016-08-25T19:39:07Z | 39,153,550 | <p><code>b == 7</code> is comparison for equality. The result of a comparison is a boolean value that is assigned to <code>a</code>.</p>
| 1 | 2016-08-25T19:43:46Z | [
"python",
"python-2.7"
] |
What is this kind of chain assignment and comparison in python? | 39,153,474 | <p>(Python 2.7 question)</p>
<p>I found a pattern similar to the following in a python codebase:</p>
<pre><code>>>> a = b == 7
>>> a
True
>>> b
7
>>> a = b == -7
>>> a
False
>>> b
7
</code></pre>
<p>I'm looking for the terminology for this - I found some other an... | 0 | 2016-08-25T19:39:07Z | 39,153,570 | <p>This is just a normal assignment statement. If you are ever curious about how a line of python is parsed, try the <code>ast</code> module:</p>
<pre><code>>>> import ast
>>> ast.dump(ast.parse('a = b == 7'), annotate_fields=False)
"Module([Assign([Name('a', Store())], Compare(Name('b', Load()), [E... | 1 | 2016-08-25T19:44:57Z | [
"python",
"python-2.7"
] |
What is this kind of chain assignment and comparison in python? | 39,153,474 | <p>(Python 2.7 question)</p>
<p>I found a pattern similar to the following in a python codebase:</p>
<pre><code>>>> a = b == 7
>>> a
True
>>> b
7
>>> a = b == -7
>>> a
False
>>> b
7
</code></pre>
<p>I'm looking for the terminology for this - I found some other an... | 0 | 2016-08-25T19:39:07Z | 39,153,584 | <p>This is just an assignment of boolean expression to a variable:</p>
<pre><code> a = (b == 7)
# ^ comparation expression that evaluate to True or False
# ^ assign the expression to a
</code></pre>
| 1 | 2016-08-25T19:45:45Z | [
"python",
"python-2.7"
] |
Converting binary numbers to hexadecimal in Python not working for more than 5 digits (Homework) | 39,153,583 | <p>I have an assignment from my computer science teacher to make a program that converts a binary number to hexadecimal using Python. I have made it so that the binary properly converts to base ten/decimal and the decimal properly converts to hex, but it only works if the binary number is less than 5 digits (i.e. 0110... | 2 | 2016-08-25T19:45:38Z | 39,153,839 | <p>You may convert the <code>binary</code> string to <code>hex</code> string (without using <code>hex()</code> function) as:</p>
<pre><code>>>> binary_string = '0000010010001101'
>>> '%0*X' % ((len(binary_string) + 3) // 4, int(binary_string, 2))
'048D'
</code></pre>
<p>There is simpler way to conve... | 0 | 2016-08-25T20:02:58Z | [
"python",
"computer-science"
] |
Converting binary numbers to hexadecimal in Python not working for more than 5 digits (Homework) | 39,153,583 | <p>I have an assignment from my computer science teacher to make a program that converts a binary number to hexadecimal using Python. I have made it so that the binary properly converts to base ten/decimal and the decimal properly converts to hex, but it only works if the binary number is less than 5 digits (i.e. 0110... | 2 | 2016-08-25T19:45:38Z | 39,153,970 | <p>I'm going to focus on helping you debug what's going wrong in your code as opposed to suggesting an alternative way to do it. It is homework after all :)</p>
<p>As others have noticed, the logic for base 10 conversion is off. A binary string of <code>01101</code> is equivalent to <code>13</code> in base ten, and <c... | 2 | 2016-08-25T20:11:45Z | [
"python",
"computer-science"
] |
Converting binary numbers to hexadecimal in Python not working for more than 5 digits (Homework) | 39,153,583 | <p>I have an assignment from my computer science teacher to make a program that converts a binary number to hexadecimal using Python. I have made it so that the binary properly converts to base ten/decimal and the decimal properly converts to hex, but it only works if the binary number is less than 5 digits (i.e. 0110... | 2 | 2016-08-25T19:45:38Z | 39,154,213 | <p>The following program can convert binary numbers into hexadecimal numbers, but it can also convert from and to other bases as well depending on the settings that you provide in your code:</p>
<pre><code>import string
TABLE = string.digits + string.ascii_uppercase
def main():
initial_variable = input('Please... | 0 | 2016-08-25T20:27:18Z | [
"python",
"computer-science"
] |
Whitespace at the end of line is not ignored by python regex | 39,153,613 | <p>The leading spaces are ignored but the trailing ones are not in the below regular expression code. It's just a <code>"Name = Value"</code> string but with spaces. I thought the <code>\s*</code> after the capture would ignore spaces.</p>
<pre><code>import re
line = " Name = Peppa Pig "
match = re.search(r"\s*(Nam... | 2 | 2016-08-25T19:48:23Z | 39,153,658 | <p>You're getting trailing spaces because of greedy nature of <code>.+</code>.</p>
<p>You can use this regex to correctly capture your value:</p>
<pre><code>>>> re.search(r"\s*(Name)\s*=\s*(.+?)\s*$", line).groups()
('Name', 'Peppa Pig')
</code></pre>
<p><code>\s*$</code> ensures we are capturing value befo... | 8 | 2016-08-25T19:51:11Z | [
"python",
"regex"
] |
Whitespace at the end of line is not ignored by python regex | 39,153,613 | <p>The leading spaces are ignored but the trailing ones are not in the below regular expression code. It's just a <code>"Name = Value"</code> string but with spaces. I thought the <code>\s*</code> after the capture would ignore spaces.</p>
<pre><code>import re
line = " Name = Peppa Pig "
match = re.search(r"\s*(Nam... | 2 | 2016-08-25T19:48:23Z | 39,154,641 | <p>Instead of using <code>(.+)\s*</code> <em>(where the <code>\s*</code> is useless since "zero or more white-spaces" isn't a constraint after the greedy quantifier <code>.+</code>, it's like to write nothing)</em>, you can use <code>(.*\S)</code> that will trim automatically the string after the last non-whitespace ch... | 2 | 2016-08-25T20:59:21Z | [
"python",
"regex"
] |
Whitespace at the end of line is not ignored by python regex | 39,153,613 | <p>The leading spaces are ignored but the trailing ones are not in the below regular expression code. It's just a <code>"Name = Value"</code> string but with spaces. I thought the <code>\s*</code> after the capture would ignore spaces.</p>
<pre><code>import re
line = " Name = Peppa Pig "
match = re.search(r"\s*(Nam... | 2 | 2016-08-25T19:48:23Z | 39,154,879 | <p>The last <code>.+</code> grabs the whole rest of the line (as <code>.</code> matches any char but a newline), and then starts backtracking, checking if the subsequent subpatterns should match. Since the subsequent subpattern is <code>\s*</code> that can match an empty string (it matches 0+ whitespaces), this pattern... | 1 | 2016-08-25T21:18:33Z | [
"python",
"regex"
] |
Why can't python's datetime.max survive a round trip through timestamp / fromtimestamp? | 39,153,700 | <p>In most cases I can round-trip datetimes to and from a timestamp as follows:</p>
<pre><code>from datetime import datetime
dt = datetime(2016, 1, 1, 12, 34, 56, 789)
print(dt)
print(datetime.fromtimestamp(dt.timestamp()))
</code></pre>
<blockquote>
<p>2016-01-01 12:34:56.000789</p>
<p>2016-01-01 12:34:56.00... | 1 | 2016-08-25T19:53:41Z | 39,153,819 | <p>Simply because the maximum of a datetime object is not the same as the maximum of a valid timestamp.</p>
<p>There's also a good reason to limit the range of timestamps: they are but a simple python <code>float</code>, which, on "normal" machines are double precision floating points. But: you lose more than a couple... | 1 | 2016-08-25T20:01:36Z | [
"python",
"python-3.x",
"datetime"
] |
Why can't python's datetime.max survive a round trip through timestamp / fromtimestamp? | 39,153,700 | <p>In most cases I can round-trip datetimes to and from a timestamp as follows:</p>
<pre><code>from datetime import datetime
dt = datetime(2016, 1, 1, 12, 34, 56, 789)
print(dt)
print(datetime.fromtimestamp(dt.timestamp()))
</code></pre>
<blockquote>
<p>2016-01-01 12:34:56.000789</p>
<p>2016-01-01 12:34:56.00... | 1 | 2016-08-25T19:53:41Z | 39,153,870 | <pre><code>dt = datetime.max
</code></pre>
<p>is checking against the maximum of the datetime class. It is a static value.</p>
<pre><code>datetime.fromtimestamp(dt.timestamp()))
</code></pre>
<p>This, however, is working against a timestamp. Different classes, different methods. <a href="https://docs.python.org/3.5/... | 0 | 2016-08-25T20:05:00Z | [
"python",
"python-3.x",
"datetime"
] |
Numpy array of numpy arrays with certain format | 39,153,756 | <p>I want to declare a numpy array (<code>arr</code>) with elements having a certain format, like this:</p>
<pre><code>dt1 = np.dtype([('sec', '<i8'), ('nsec', '<i8')])
dt2 = np.dtype([('name', 'S10'), ('value', '<i4')])
arr = np.array([('x', dtype=dt1), ('y', dtype=dt2)])
</code></pre>
<p>The structure is ... | 2 | 2016-08-25T19:57:08Z | 39,154,267 | <p>A doubly compound dtype might work:</p>
<pre><code>In [834]: dt1 = np.dtype([('sec', '<i8'), ('nsec', '<i8')])
...: dt2 = np.dtype([('name', 'S10'), ('value', '<i4')])
...:
In [835]: dt = np.dtype([('x', dt1),('y', dt2)])
In [837]: z=np.ones((3,), dtype=dt)
In [838]: z
Out[838]:
array([((1, 1)... | 3 | 2016-08-25T20:31:29Z | [
"python",
"arrays",
"numpy",
"syntax"
] |
Determining the Order Files Are Run in a Website Built By Someone Else | 39,153,790 | <p>Ok, this question is going to sound pretty dumb, but I'm an absolute novice when it comes to web development and have been tasked with fixing a website for my job (that has absolutely nothing in the way of documentation).</p>
<p>Basically, I'm wondering if there is any tool or method for tracking the order a websit... | 0 | 2016-08-25T19:59:31Z | 39,154,045 | <p>Try opening in the page in Chrome and hitting F12 - there's a tonne of developer tools and web page debuggers in there.</p>
<p>For your particular question about loading order, check the Network tab, then hit refresh on your page - it'll show you every file that the browser loads, starting with the HTML in your bro... | 0 | 2016-08-25T20:16:01Z | [
"javascript",
"python",
"django"
] |
why have duplications in mu code using python | 39,153,860 | <p>I read from a xlsx file.
I'm trying to group by router column and add all mb coulmn. However, I have some duplications and I don`t know why?</p>
<p>Here is the code, can help me? </p>
<pre><code>def totalroutermb():
arrayItems = items
arrayItems2 = items
arrayRouterAndMb = []
num_mb = float(0.0)
... | 2 | 2016-08-25T20:04:12Z | 39,186,920 | <p>I solved it!! Sorry but I'm only few days with python, i'm learning</p>
<pre><code>def totalroutermb():
arrayRouterAndMb = []
for item in items:
aux = [item.router.strip(), float(item.download_in_mb)]
arrayRouterAndMb.append(aux)
# order array
arrayRouterAndMb.sort()
# add all mb from e... | 0 | 2016-08-28T00:16:05Z | [
"python",
"python-3.x"
] |
How to define and use percentage in Pint | 39,153,885 | <p>I'm currently using <a href="https://pint.readthedocs.io/en/0.7.2/" rel="nofollow">Pint</a> to handle units and unit conversions. This seems to work well for the units that are already defined in Pint, for example</p>
<pre><code>>>> import pint
>>> ureg = pint.UnitRegistry()
>>> Q = ureg.... | 3 | 2016-08-25T20:06:15Z | 39,154,101 | <p>It seems that GitHub issue <a href="https://github.com/hgrecco/pint/issues/185" rel="nofollow">hgrecco/pint#185</a> covers the case you're describing.</p>
<p>Using the work-around discussed in that issue works for me using <code>Pint-0.7.2</code>:</p>
<pre><code>from pint.unit import ScaleConverter
from pint.unit ... | 3 | 2016-08-25T20:20:10Z | [
"python",
"units-of-measurement",
"pint"
] |
Update a list every time a function within a class is executexecuted with the function arguments and values | 39,154,006 | <p>In the last 6 months, I have created many classes and function for different calculations. Now I would like to join them into a class so it could be used by other users. Like many of the methods can be performed in sequence and the sequence may require to be run multiple times for different sets of data. I would lik... | 0 | 2016-08-25T20:13:45Z | 39,154,730 | <p>Here's how to use a decorator, per Moinuddin Quadri's suggestion:</p>
<pre><code>def remember(func):
def inner(*args, **kwargs):
args[0].procedure.append({'method': func,
'args': args,
'kwargs': kwargs})
return func(*args, **kwa... | 1 | 2016-08-25T21:06:30Z | [
"python"
] |
How to get matrix rows by indexes? | 39,154,021 | <p>Assuming that we have a matrix X and a target column y as following:</p>
<pre><code>import numpy as np
X = np.ones([10,2])
for i in range(0,X.shape[0]):
X[i][0] = i
y = [0,1,2,1,0,0,1,2,3,3]
</code></pre>
<p>I want to get rows of X depending on the value of y. From the small example above:</p>
<p>For y == 0, ... | 1 | 2016-08-25T20:14:44Z | 39,154,166 | <p>You were close, you just need <code>y</code> to be a numpy array instead of a list:</p>
<pre><code>>>> y = np.array(y)
>>> X[y==0]
array([[0, 1],
[4, 1],
[5, 1]])
>>> X[y==3]
array([[8, 1],
[9, 1]])
</code></pre>
| 0 | 2016-08-25T20:23:42Z | [
"python",
"matrix",
"indexing"
] |
Pyspark: spark data frame column width configuration in Jupyter Notebook | 39,154,093 | <p>I have the following code in Jupyter Notebook:</p>
<pre><code>import pandas as pd
pd.set_option('display.max_colwidth', 80)
my_df.select('field_1','field_2').show()
</code></pre>
<p>I want to increase the column width so I could see the full value of <code>field_1</code> and <code>field_2</code>. I know we can use... | 0 | 2016-08-25T20:19:09Z | 39,154,175 | <p>I don't think you can set a specific width, but this will show ensure your data is not cutoff no matter the size</p>
<pre><code>my_df.select('field_1','field_2').show(10, truncate = False)
</code></pre>
| 1 | 2016-08-25T20:24:15Z | [
"python",
"apache-spark",
"pyspark",
"spark-dataframe",
"jupyter-notebook"
] |
Pyspark: spark data frame column width configuration in Jupyter Notebook | 39,154,093 | <p>I have the following code in Jupyter Notebook:</p>
<pre><code>import pandas as pd
pd.set_option('display.max_colwidth', 80)
my_df.select('field_1','field_2').show()
</code></pre>
<p>I want to increase the column width so I could see the full value of <code>field_1</code> and <code>field_2</code>. I know we can use... | 0 | 2016-08-25T20:19:09Z | 39,164,559 | <p>This should give you what you want</p>
<pre><code>import pandas as pd
pd.set_option('display.max_colwidth', 80)
my_df.select('field_1','field_2').limit(100).toPandas()
</code></pre>
| 0 | 2016-08-26T10:52:10Z | [
"python",
"apache-spark",
"pyspark",
"spark-dataframe",
"jupyter-notebook"
] |
Why does referencing a concatenated pandas dataframe return multiple entries? | 39,154,230 | <p>When I create a dataframe using concat like this:</p>
<pre><code>import pandas as pd
dfa = pd.DataFrame({'a':[1],'b':[2]})
dfb = pd.DataFrame({'a':[3],'b':[4]})
dfc = pd.concat([dfa,dfb])
</code></pre>
<p>And I try to reference like I would for any other DataFrame I get the following result:</p>
<pre><code>>&g... | 3 | 2016-08-25T20:28:43Z | 39,154,289 | <p>You've mistaken what normal behavior is. <code>dfc['a'][0]</code> is a label lookup and matches anything with an index value of <code>0</code> in which there are two because you concatenated two dataframes with index values including <code>0</code>.</p>
<p>in order to specify position of <code>0</code></p>
<pre><... | 1 | 2016-08-25T20:33:03Z | [
"python",
"pandas",
"concat"
] |
Why does referencing a concatenated pandas dataframe return multiple entries? | 39,154,230 | <p>When I create a dataframe using concat like this:</p>
<pre><code>import pandas as pd
dfa = pd.DataFrame({'a':[1],'b':[2]})
dfb = pd.DataFrame({'a':[3],'b':[4]})
dfc = pd.concat([dfa,dfb])
</code></pre>
<p>And I try to reference like I would for any other DataFrame I get the following result:</p>
<pre><code>>&g... | 3 | 2016-08-25T20:28:43Z | 39,154,326 | <p><strong>EDITED</strong> (thx <a href="http://stackoverflow.com/users/2336654/pirsquared">piRSquared</a>'s comment)</p>
<p>Use <code>append()</code> instead <code>pd.concat()</code>:</p>
<pre><code>dfc = dfa.append(dfb, ignore_index=True)
dfc['a'][0]
1
</code></pre>
| 1 | 2016-08-25T20:35:39Z | [
"python",
"pandas",
"concat"
] |
Connection reset by peer [Errno 104] in Python | 39,154,241 | <p>I have witten a distributed program. Every node (Virtual machine) in the network sends data (through outgoing connection) to and receives data (through incomming connection) from every other node. Before sending data, all nodes has opend a socket to every other node (including the single source node). After a delay ... | 0 | 2016-08-25T20:29:34Z | 39,164,848 | <pre><code> for s, ip in connectionInfoList:
s.shutdown(1)# 0:Further receives are disallowed -- 1: Further sends are disallow / sends -- 2: Further sends and receives are disallowed.
s.close()
pool.close()
pool.join()
</code></pre>
<p>You <code>shutd... | 0 | 2016-08-26T11:06:35Z | [
"python",
"sockets",
"parallel-processing",
"distributed-computing",
"python-multithreading"
] |
Python: LINQ capable class supporting simultaneously laziness and fluent design | 39,154,269 | <p>How to create an Python class which would be a iterable wrapper with LINQ-like methods (select, where, orderby, etc.) without using extension methods or monkey patching.
?</p>
<p>That is this LinqCapable class would be capable to return its own type when it is relevant (i.e. fluent design) and support lazy evaluati... | 0 | 2016-08-25T20:31:37Z | 39,156,138 | <p>You should return a "Linq capable class" to achieve chaining and furthermore your implementation is not lazy: look at asq where method: it is based on the I filter and it appears correct...
Anyway, here it is a very basic implementation based on my understanding of your question and comments</p>
<pre><code>class L... | 2 | 2016-08-25T23:17:22Z | [
"python",
"linq",
"iterator",
"generator"
] |
Python: LINQ capable class supporting simultaneously laziness and fluent design | 39,154,269 | <p>How to create an Python class which would be a iterable wrapper with LINQ-like methods (select, where, orderby, etc.) without using extension methods or monkey patching.
?</p>
<p>That is this LinqCapable class would be capable to return its own type when it is relevant (i.e. fluent design) and support lazy evaluati... | 0 | 2016-08-25T20:31:37Z | 39,158,593 | <p>It's not enough to just return a generator for the implemented linq methods, you need to have it return an instance of the wrapper to be able to chain additional calls.</p>
<p>You can create a metaclass which can rewrap the linq implementations. So with this, you can just implement the methods you want to support ... | 1 | 2016-08-26T05:03:29Z | [
"python",
"linq",
"iterator",
"generator"
] |
Using Pandas str.contains to compare row-by-row | 39,154,306 | <p>I have set up the following very simple database to illustrate what I'm trying to do:</p>
<pre><code>teams = pd.DataFrame({"spreads":['New England Patriots -7.0','Atlanta Falcons 2.5','New Orleans Saints -4.5']})
teams['home'] = ['New England Patriots','Carolina Panthers','New Orleans Saints']
teams['away'] = ['Mia... | 0 | 2016-08-25T20:34:04Z | 39,154,468 | <p>Use <code>.str.extract</code></p>
<pre><code>teams.spreads.str.extract(r'(-?\d+\.?\d*)', expand=False)
0 -7.0
1 2.5
2 -4.5
Name: spreads, dtype: object
</code></pre>
<p>Fancier</p>
<pre><code>teams.spreads.str.extract(r'(?P<spread_val>-?\d+\.?\d*)', expand=True)
</code></pre>
<p><a href="http://... | 2 | 2016-08-25T20:46:19Z | [
"python",
"pandas"
] |
Using Pandas str.contains to compare row-by-row | 39,154,306 | <p>I have set up the following very simple database to illustrate what I'm trying to do:</p>
<pre><code>teams = pd.DataFrame({"spreads":['New England Patriots -7.0','Atlanta Falcons 2.5','New Orleans Saints -4.5']})
teams['home'] = ['New England Patriots','Carolina Panthers','New Orleans Saints']
teams['away'] = ['Mia... | 0 | 2016-08-25T20:34:04Z | 39,156,900 | <p>Try this <a href="http://pandas.pydata.org/pandas-docs/stable/text.html#splitting-and-replacing-strings" rel="nofollow">Splitting Strings</a>:</p>
<pre><code>teams['spreads_val'] = teams['spreads'].str.rsplit(" ").str.get(-1)
0 -7.0
1 2.5
2 -4.5
Name: spreads_vals, dtype: object
</code></pre>
| 1 | 2016-08-26T01:00:46Z | [
"python",
"pandas"
] |
Pyspark: show histogram of a data frame column | 39,154,325 | <p>In pandas data frame, I am using the following code to plot histogram of a column:</p>
<pre><code>my_df.hist(column = 'field_1')
</code></pre>
<p>Is there something that can achieve the same goal in pyspark data frame? (I am in Jupyter Notebook) Thanks!</p>
| 3 | 2016-08-25T20:35:24Z | 39,891,776 | <p>Unfortunately I don't think that there's a clean <code>plot()</code> or <code>hist()</code> function in the PySpark Dataframes API, but I'm hoping that things will eventually go in that direction.</p>
<p>For the time being, you could compute the histogram in Spark, and plot the computed histogram as a bar chart. Ex... | 0 | 2016-10-06T08:58:39Z | [
"python",
"pyspark",
"spark-dataframe",
"jupyter-notebook"
] |
Two Sum. I use a nested loop but it seems not work | 39,154,367 | <pre><code>class Solution(object)
def twoSum(self,num,target):
#nested for loop, but the result shows only the inner loop works
for i in range(0,len(num)-1,1):
for j in range(i+1,len(num),1):
target=target-num[i]-num[j]
if target!=0:
target=target+num[i]+num[j... | 0 | 2016-08-25T20:39:01Z | 39,173,428 | <p>Since you're not telling your goal, I guess that you're looking for sort of solution like this?<br /></p>
<pre><code>class Solution(object):
def twoSum(self, num, target):
ans = []
for i in range(len(num) - 1):
for j in range(i + 1, len(num)):
s = num[i] + num[j]
... | 1 | 2016-08-26T19:24:39Z | [
"python",
null,
"output"
] |
Scraping all text using Scrapy without knowing webpages' structure | 39,154,393 | <p>I am conducting a research which relates to distributing the indexing of the internet.</p>
<p>While several such projects exist (IRLbot, Distributed-indexing, Cluster-Scrapy, Common-Crawl etc.), mine is more focused on incentivising such behavior. I am looking for a simple way to crawl real webpages without knowin... | 2 | 2016-08-25T20:41:02Z | 39,162,546 | <p>What you are looking for here is scrapy <a href="http://doc.scrapy.org/en/latest/topics/spiders.html#scrapy.spiders.CrawlSpider" rel="nofollow">CrawlSpider</a></p>
<p>CrawlSpider lets you define crawling rules that are followed for every page. It's smart enough to avoid crawling images, documents and other files th... | 3 | 2016-08-26T09:08:40Z | [
"python",
"web-scraping",
"scrapy"
] |
Python cant handle exceptions from zipfile.BadZipFile | 39,154,470 | <p>Need to handle if a zip file is corrupt, so it just pass this file and can go on to the next.</p>
<p>In the code example underneath Im trying to catch the exception, so I can pass it. But my script is failing when the zipfile is corrupt*, and give me the "normal" traceback errors* istead of printing "my error", but... | -1 | 2016-08-25T20:46:36Z | 39,154,621 | <p>You need to put your context manager <em>inside</em> the <code>try-except</code> block:</p>
<pre><code>try:
with ZipFile(path) as zf:
print "zipfile is OK"
except BadZipfile:
print "Does not work "
</code></pre>
<p>The error is <em>raised by</em> <code>ZipFile</code> so placing it outside means no ... | 1 | 2016-08-25T20:57:59Z | [
"python",
"python-2.7",
"exception-handling",
"zipfile"
] |
How can i use e and power operation in python 2.7 | 39,154,611 | <p>How can i write <code>x.append(1-e^(-value1^2/2*value2^2))</code> in python 2.7?</p>
<p>I don't know how to use power operator and e.</p>
| 0 | 2016-08-25T20:57:19Z | 39,154,642 | <p>Power is <code>**</code> and <code>e^</code> is <code>math.exp</code>:</p>
<pre><code>x.append(1 - math.exp(-0.5 * (value1*value2)**2))
</code></pre>
| 3 | 2016-08-25T20:59:25Z | [
"python",
"math",
"equation",
"exp"
] |
How can i use e and power operation in python 2.7 | 39,154,611 | <p>How can i write <code>x.append(1-e^(-value1^2/2*value2^2))</code> in python 2.7?</p>
<p>I don't know how to use power operator and e.</p>
| 0 | 2016-08-25T20:57:19Z | 39,154,643 | <p>Python's power operator is <code>**</code> and Euler's number is <code>math.e</code>, so:</p>
<pre><code> from math import e
x.append(1-e**(-value1**2/2*value2**2))
</code></pre>
| 0 | 2016-08-25T20:59:31Z | [
"python",
"math",
"equation",
"exp"
] |
How can i use e and power operation in python 2.7 | 39,154,611 | <p>How can i write <code>x.append(1-e^(-value1^2/2*value2^2))</code> in python 2.7?</p>
<p>I don't know how to use power operator and e.</p>
| 0 | 2016-08-25T20:57:19Z | 39,154,677 | <p>Refer <a href="https://docs.python.org/2/library/math.html" rel="nofollow">math</a> library of python. <code>exp(x)</code> function this library is same as <code>e^x</code>. Hence you may write your code as:</p>
<p>I have modified the equation by replacing <code>1/2</code> as <code>0.5</code>. Else we have to expli... | 0 | 2016-08-25T21:02:01Z | [
"python",
"math",
"equation",
"exp"
] |
Use of hdf5 library in Python with ctypes | 39,154,663 | <p>I would like to use <code>hdf5</code> library directly from <code>Python</code> with <code>ctypes</code>. I know that <code>h5py</code> and <code>PyTables</code> do the job perfectly. The reason I want to do this: I need to work with <code>hdf5</code> files with a <code>Python</code> interpreter where I can not inst... | 0 | 2016-08-25T21:01:28Z | 39,158,110 | <p>You shouldn't need to define argtypes as <code>H5Fopen</code> doesn't appear to take arguments. Just call like a regular function:</p>
<pre><code>herr_t = lib.H5Fopen()
</code></pre>
<p><strong>Edit:</strong> for the version with args try:</p>
<pre><code>lib.H5Fopen.restype = c_int
lib.H5Fopen.argtypes = (c_char_... | 1 | 2016-08-26T04:04:06Z | [
"python",
"ctypes",
"hdf5"
] |
Use of hdf5 library in Python with ctypes | 39,154,663 | <p>I would like to use <code>hdf5</code> library directly from <code>Python</code> with <code>ctypes</code>. I know that <code>h5py</code> and <code>PyTables</code> do the job perfectly. The reason I want to do this: I need to work with <code>hdf5</code> files with a <code>Python</code> interpreter where I can not inst... | 0 | 2016-08-25T21:01:28Z | 39,167,930 | <p>I haven't (yet) done any Hdf5 programming, but looking through <a href="https://www.hdfgroup.org/HDF5/doc/RM/RM_H5F.html#File-Open" rel="nofollow">the documentation</a>, I see a few things to tell you.</p>
<p>What arguments you would pass to H5Fopen: the name is the filename you want to open. flags will be either ... | 1 | 2016-08-26T13:49:11Z | [
"python",
"ctypes",
"hdf5"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.